code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
if not self._apikey or not self._secret:
raise PoloniexCredentialsException('missing apikey/secret')
with self.nonce_lock:
params.update({'command': command, 'nonce': next(self.nonce_iter)})
response = self.session.post(
self._private_url, data=params,
auth=Poloniex._PoloniexAuth(self._apikey, self._secret))
return response | def _private(self, command, **params) | Invoke the 'command' public API with optional params. | 4.823817 | 4.603068 | 1.047957 |
return self._private('returnDepositsWithdrawals', start=start, end=end) | def returnDepositsWithdrawals(self, start=0, end=2**32-1) | Returns your deposit and withdrawal history within a range,
specified by the "start" and "end" POST parameters, both of which
should be given as UNIX timestamps. | 4.419915 | 6.205903 | 0.712211 |
return self._private('returnTradeHistory', currencyPair=currencyPair,
start=start, end=end, limit=limit) | def returnTradeHistory(self, currencyPair='all', start=None, end=None, limit=500) | Returns your trade history for a given market, specified by the
"currencyPair" POST parameter. You may specify "all" as the
currencyPair to receive your trade history for all markets. You may
optionally specify a range via "start" and/or "end" POST parameters,
given in UNIX timestamp format; if you do not specify a range, it will
be limited to one day. | 3.069577 | 3.436397 | 0.893254 |
return super(Poloniex, self).returnTradeHistory(currencyPair, start, end) | def returnTradeHistoryPublic(self, currencyPair, start=None, end=None) | Returns the past 200 trades for a given market, or up to 50,000
trades between a range specified in UNIX timestamps by the "start"
and "end" GET parameters. | 4.209635 | 5.690827 | 0.739723 |
return self._private('buy', currencyPair=currencyPair, rate=rate,
amount=amount, fillOrKill=fillOrKill,
immediateOrCancel=immediateOrCancel,
postOnly=postOnly) | def buy(self, currencyPair, rate, amount, fillOrKill=None,
immediateOrCancel=None, postOnly=None) | Places a limit buy order in a given market. Required POST parameters
are "currencyPair", "rate", and "amount". If successful, the method
will return the order number.
You may optionally set "fillOrKill", "immediateOrCancel", "postOnly"
to 1. A fill-or-kill order will either fill in its entirety or be
completely aborted. An immediate-or-cancel order can be partially or
completely filled, but any portion of the order that cannot be filled
immediately will be canceled rather than left on the order book.
A post-only order will only be placed if no portion of it fills
immediately; this guarantees you will never pay the taker fee on any
part of the order that fills. | 1.979539 | 2.359878 | 0.838831 |
return self._private('moveOrder', orderNumber=orderNumber, rate=rate,
amount=amount, postOnly=postOnly,
immediateOrCancel=immediateOrCancel) | def moveOrder(self, orderNumber, rate, amount=None, postOnly=None,
immediateOrCancel=None) | Cancels an order and places a new one of the same type in a single
atomic transaction, meaning either both operations will succeed or both
will fail. Required POST parameters are "orderNumber" and "rate"; you
may optionally specify "amount" if you wish to change the amount of
the new order. "postOnly" or "immediateOrCancel" may be specified for
exchange orders, but will have no effect on margin orders. | 2.481347 | 2.699249 | 0.919273 |
return self._private('withdraw', currency=currency, amount=amount,
address=address, paymentId=paymentId) | def withdraw(self, currency, amount, address, paymentId=None) | Immediately places a withdrawal for a given currency, with no email
confirmation. In order to use this method, the withdrawal privilege
must be enabled for your API key. Required POST parameters are
"currency", "amount", and "address". For XMR withdrawals, you may
optionally specify "paymentId". | 3.711507 | 3.948267 | 0.940034 |
return self._private('transferBalance', currency=currency,
amount=amount, fromAccount=fromAccount,
toAccount=toAccount) | def transferBalance(self, currency, amount, fromAccount, toAccount) | Transfers funds from one account to another (e.g. from your exchange
account to your margin account). Required POST parameters are
"currency", "amount", "fromAccount", and "toAccount". | 3.601743 | 3.659622 | 0.984184 |
return self._private('marginBuy', currencyPair=currencyPair, rate=rate,
amount=amount, lendingRate=lendingRate) | def marginBuy(self, currencyPair, rate, amount, lendingRate=None) | Places a margin buy order in a given market. Required POST
parameters are "currencyPair", "rate", and "amount". You may optionally
specify a maximum lending rate using the "lendingRate" parameter.
If successful, the method will return the order number and any trades
immediately resulting from your order. | 3.238556 | 3.289639 | 0.984472 |
return self._private('marginSell', currencyPair=currencyPair, rate=rate,
amount=amount, lendingRate=lendingRate) | def marginSell(self, currencyPair, rate, amount, lendingRate=None) | Places a margin sell order in a given market. Parameters and output
are the same as for the marginBuy method. | 3.219036 | 3.318059 | 0.970156 |
return self._private('createLoanOffer', currency=currency,
amount=amount, duration=duration,
autoRenew=autoRenew, lendingRate=lendingRate) | def createLoanOffer(self, currency, amount, duration, autoRenew,
lendingRate) | Creates a loan offer for a given currency. Required POST parameters
are "currency", "amount", "duration", "autoRenew" (0 or 1), and
"lendingRate". | 2.571611 | 2.985174 | 0.861461 |
return self._private('returnLendingHistory', start=start, end=end,
limit=limit) | def returnLendingHistory(self, start=0, end=2**32-1, limit=None) | Returns your lending history within a time range specified by the
"start" and "end" POST parameters as UNIX timestamps. "limit" may also
be specified to limit the number of rows returned. | 4.850216 | 5.694941 | 0.851671 |
cid = getattr(_thread_locals, 'CID', None)
if cid is None and getattr(settings, 'CID_GENERATE', False):
cid = str(uuid.uuid4())
set_cid(cid)
return cid | def get_cid() | Return the currently set correlation id (if any).
If no correlation id has been set and ``CID_GENERATE`` is enabled
in the settings, a new correlation id is set and returned.
FIXME (dbaty): in version 2, just `return getattr(_thread_locals, 'CID', None)`
We want the simplest thing here and let `generate_new_cid` do the job. | 3.869093 | 2.12864 | 1.817636 |
if upstream_cid is None:
return str(uuid.uuid4()) if getattr(settings, 'CID_GENERATE', False) else None
if (
getattr(settings, 'CID_CONCATENATE_IDS', False)
and getattr(settings, 'CID_GENERATE', False)
):
return '%s, %s' % (upstream_cid, str(uuid.uuid4()))
return upstream_cid | def generate_new_cid(upstream_cid=None) | Generate a new correlation id, possibly based on the given one. | 3.314572 | 3.191466 | 1.038573 |
try:
# Nod to tastypie's use of importlib.
parts = val.split('.')
module_path, class_name = '.'.join(parts[:-1]), parts[-1]
module = importlib.import_module(module_path)
return getattr(module, class_name)
except (ImportError, AttributeError) as e:
msg = "Could not import '%s' for Graph Auth setting '%s'. %s: %s." % (val, setting_name, e.__class__.__name__, e)
raise ImportError(msg) | def import_from_string(val, setting_name) | Attempt to import a class from a string representation. | 2.701828 | 2.540163 | 1.063644 |
the_helper.add_metric(
label=the_helper.options.type,
value=the_snmp_value,
uom="minutes")
the_helper.set_summary("Remaining runtime on battery is {} minutes".format(the_snmp_value)) | def check_ups_estimated_minutes_remaining(the_session, the_helper, the_snmp_value) | OID .1.3.6.1.2.1.33.1.2.3.0
MIB excerpt
An estimate of the time to battery charge depletion
under the present load conditions if the utility power
is off and remains off, or if it were to be lost and
remain off. | 7.860748 | 7.07409 | 1.111203 |
a_frequency = calc_frequency_from_snmpvalue(the_snmp_value)
the_helper.add_metric(
label=the_helper.options.type,
value=a_frequency,
uom='Hz')
the_helper.set_summary("Input Frequency is {} Hz".format(a_frequency)) | def check_ups_input_frequency(the_session, the_helper, the_snmp_value) | OID .1.3.6.1.2.1.33.1.3.3.1.2.1
MIB excerpt
The present input frequency. | 6.023959 | 6.55393 | 0.919137 |
a_current = calc_output_current_from_snmpvalue(the_snmp_value)
the_helper.add_metric(
label=the_helper.options.type,
value=a_current,
uom='A')
the_helper.set_summary("Output Current is {} A".format(a_current)) | def check_ups_output_current(the_session, the_helper, the_snmp_value) | OID .1.3.6.1.2.1.33.1.4.4.1.3.1
MIB excerpt
The present output current. | 5.969111 | 6.246923 | 0.955528 |
if the_snmp_value != '0':
the_helper.add_status(pynag.Plugins.critical)
else:
the_helper.add_status(pynag.Plugins.ok)
the_helper.set_summary("{} active alarms ".format(the_snmp_value)) | def check_ups_alarms_present(the_session, the_helper, the_snmp_value) | OID .1.3.6.1.2.1.33.1.6.1.0
MIB excerpt
The present number of active alarm conditions. | 5.28747 | 4.511717 | 1.171942 |
the_helper.add_metric(
label=the_helper.options.type,
value=a_snmp_value,
uom='%')
the_helper.set_summary("Remaining Battery Capacity {} %".format(the_snmp_value)) | def check_xups_bat_capacity(the_session, the_helper, the_snmp_value) | OID .1.3.6.1.4.1.534.1.2.4.0
MIB Excerpt
Battery percent charge. | 8.644216 | 8.859332 | 0.975719 |
the_helper.add_metric(
label=the_helper.options.type,
value=the_snmp_value,
uom='degree')
the_helper.set_summary("Environment Temperature is {} degree".format(the_snmp_value)) | def check_xups_env_ambient_temp(the_session, the_helper, the_snmp_value, the_unit=1) | OID .1.3.6.1.4.1.534.1.6.1.0
MIB Excerpt
The reading of the ambient temperature in the vicinity of the
UPS or SNMP agent. | 7.375834 | 7.417946 | 0.994323 |
# get the data
cpu_value = get_data(sess, cpu_oid, helper)
memory_value = get_data(sess, memory_oid, helper)
filesystem_value = get_data(sess, filesystem_oid, helper)
helper.add_summary("Controller Status")
helper.add_long_output("Controller Ressources - CPU: %s%%" % cpu_value)
helper.add_metric("CPU", cpu_value, "0:90", "0:90", "", "", "%%")
if int(cpu_value) > 90:
helper.status(critical)
helper.add_summary("Controller Ressources - CPU: %s%%" % cpu_value)
helper.add_long_output("Memory: %s%%" % memory_value)
helper.add_metric("Memory", memory_value, "0:90", "0:90", "", "", "%%")
if int(memory_value) > 90:
helper.add_summary("Memory: %s%%" % memory_value)
helper.status(critical)
helper.add_long_output("Filesystem: %s%%" % filesystem_value)
helper.add_metric("Filesystem", filesystem_value, "0:90", "0:90", "", "", "%%")
if int(filesystem_value) > 90:
helper.add_summary("Filesystem: %s%%" % filesystem_value)
helper.status(critical) | def check_ressources(sess) | check the Ressources of the Fortinet Controller
all thresholds are currently hard coded. should be fine. | 2.398872 | 2.277704 | 1.053197 |
controller_operational = get_data(sess, operational_oid, helper)
controller_availability = get_data(sess, availability_oid, helper)
controller_alarm = get_data(sess, alarm_oid, helper)
# Add summary
helper.add_summary("Controller Status")
# Add all states to the long output
helper.add_long_output("Controller Operational State: %s" % operational_states[int(controller_operational)])
helper.add_long_output("Controller Availability State: %s" % availability_states[int(controller_availability)])
helper.add_long_output("Controller Alarm State: %s" % alarm_states[int(controller_alarm)])
# Operational State
if controller_operational != "1" and controller_operational != "4":
helper.status(critical)
helper.add_summary("Controller Operational State: %s" % operational_states[int(controller_operational)])
# Avaiability State
if controller_availability != "3":
helper.status(critical)
helper.add_summary("Controller Availability State: %s" % availability_states[int(controller_availability)])
# Alarm State
if controller_alarm == "2":
helper.status(warning)
helper.add_summary("Controller Alarm State: %s" % alarm_states[int(controller_alarm)])
if controller_alarm == "3" or controller_alarm == "4":
helper.status(critical)
helper.add_summary("Controller Alarm State: %s" % alarm_states[int(controller_alarm)]) | def check_controller(sess) | check the status of the controller | 2.28375 | 2.282917 | 1.000365 |
ap_names = walk_data(sess, name_ap_oid, helper)[0]
ap_operationals = walk_data(sess, operational_ap_oid, helper)[0]
ap_availabilitys = walk_data(sess, availability_ap_oid, helper)[0]
ap_alarms = walk_data(sess, alarm_ap_oid, helper)[0]
#ap_ip = walk_data(sess, ip_ap_oid, helper) # no result
helper.add_summary("Access Points Status")
for x in range(len(ap_names)):
ap_name = ap_names[x]
ap_operational = ap_operationals[x]
ap_availability = ap_availabilitys[x]
ap_alarm = ap_alarms[x]
# Add all states to the long output
helper.add_long_output("%s - Operational: %s - Availabilty: %s - Alarm: %s" % (ap_name, operational_states[int(ap_operational)], availability_states[int(ap_availability)], alarm_states[int(ap_alarm)]))
# Operational State
if ap_operational != "1" and ap_operational != "4":
helper.status(critical)
helper.add_summary("%s Operational State: %s" % (ap_name, operational_states[int(ap_operational)]))
# Avaiability State
if ap_availability != "3":
helper.status(critical)
helper.add_summary("%s Availability State: %s" % (ap_name, availability_states[int(ap_availability)]))
# Alarm State
if ap_alarm == "2":
helper.status(warning)
helper.add_summary("%s Controller Alarm State: %s" % (ap_name, alarm_states[int(ap_alarm)]))
if ap_alarm == "3" or ap_alarm == "4":
helper.status(critical)
helper.add_summary("%s Controller Alarm State: %s" % (ap_name, alarm_states[int(ap_alarm)])) | def check_accesspoints(sess) | check the status of all connected access points | 2.481285 | 2.466954 | 1.005809 |
status_string = NORMAL_STATE.get(int(status), "unknown")
if status_string == "ok":
return ok, "{} '{}': {}".format(device_type, name, status_string)
elif status_string == "unknown":
return unknown, "{} '{}': {}".format(device_type, name, status_string)
return critical, "{} '{}': {}".format(device_type, name, status_string) | def normal_check(name, status, device_type) | if the status is "ok" in the NORMAL_STATE dict, return ok + string
if the status is not "ok", return critical + string | 2.850653 | 2.296528 | 1.241288 |
status_string = PROBE_STATE.get(int(status), "unknown")
if status_string == "ok":
return ok, "{} '{}': {}".format(device_type, name, status_string)
if status_string == "unknown":
return unknown, "{} '{}': {}".format(device_type, name, status_string)
return critical, "{} '{}': {}".format(device_type, name, status_string) | def probe_check(name, status, device_type) | if the status is "ok" in the PROBE_STATE dict, return ok + string
if the status is not "ok", return critical + string | 2.775318 | 2.233126 | 1.242795 |
host_name_data = helper.get_snmp_value(session, helper,
DEVICE_INFORMATION_OIDS['oid_host_name'])
product_type_data = helper.get_snmp_value(session, helper,
DEVICE_INFORMATION_OIDS['oid_product_type'])
service_tag_data = helper.get_snmp_value(session, helper,
DEVICE_INFORMATION_OIDS['oid_service_tag'])
helper.add_summary('Name: {} - Typ: {} - Service tag: {}'.format(
host_name_data, product_type_data, service_tag_data)) | def add_device_information(helper, session) | add general device information to summary | 3.24882 | 3.068274 | 1.058843 |
snmp_result_status = helper.get_snmp_value(session, helper, DEVICE_GLOBAL_OIDS['oid_' + check])
if check == "system_lcd":
helper.update_status(helper, normal_check("global", snmp_result_status, "LCD status"))
elif check == "global_storage":
helper.update_status(helper, normal_check("global", snmp_result_status, "Storage status"))
elif check == "system_power":
helper.update_status(helper, self.check_system_power_status(snmp_result_status))
elif check == "global_system":
helper.update_status(helper,
normal_check("global", snmp_result_status, "Device status")) | def process_status(self, helper, session, check) | process a single status | 4.157546 | 4.101896 | 1.013567 |
snmp_result_status = helper.walk_snmp_values(session, helper,
DEVICE_STATES_OIDS["oid_" + check],
check)
snmp_result_names = helper.walk_snmp_values(session, helper,
DEVICE_NAMES_OIDS["oid_" + check],
check)
for i, _result in enumerate(snmp_result_status):
if check == "power_unit":
helper.update_status(
helper,
normal_check(snmp_result_names[i], snmp_result_status[i], "Power unit"))
elif check == "drive":
helper.update_status(
helper,
self.check_drives(snmp_result_names[i], snmp_result_status[i]))
elif check == "power_unit_redundancy":
helper.update_status(
helper,
self.check_power_unit_redundancy(snmp_result_names[i], snmp_result_status[i]))
elif check == "chassis_intrusion":
helper.update_status(
helper,
normal_check(snmp_result_names[i], snmp_result_status[i],
"Chassis intrusion sensor"))
elif check == "cooling_unit":
helper.update_status(
helper,
normal_check(snmp_result_names[i], snmp_result_status[i], "Cooling unit")) | def process_states(self, helper, session, check) | process status values from a table | 2.634996 | 2.617748 | 1.006589 |
snmp_result_temp_sensor_names = helper.walk_snmp_values(
session, helper,
DEVICE_TEMPERATURE_OIDS['oid_temperature_probe_location'], "temperature sensors")
snmp_result_temp_sensor_states = helper.walk_snmp_values(
session, helper,
DEVICE_TEMPERATURE_OIDS['oid_temperature_probe_status'], "temperature sensors")
snmp_result_temp_sensor_values = helper.walk_snmp_values(
session, helper,
DEVICE_TEMPERATURE_OIDS['oid_temperature_probe_reading'], "temperature sensors")
for i, _result in enumerate(snmp_result_temp_sensor_states):
helper.update_status(
helper, probe_check(snmp_result_temp_sensor_names[i],
snmp_result_temp_sensor_states[i], "Temperature sensor"))
if i < len(snmp_result_temp_sensor_values):
helper.add_metric(label=snmp_result_temp_sensor_names[i] + " -Celsius-",
value=float(snmp_result_temp_sensor_values[i]) / 10) | def process_temperature_sensors(helper, session) | process the temperature sensors | 3.132464 | 3.096251 | 1.011696 |
return DISK_STATES[int(drivestatus)]["icingastatus"], "Drive '{}': {}".format(
drivename, DISK_STATES[int(drivestatus)]["result"]) | def check_drives(drivename, drivestatus) | check the drive status | 9.702594 | 9.505945 | 1.020687 |
return (POWER_UNIT_REDUNDANCY_STATE[int(power_unit_redundancy_data)]["icingastatus"],
"Power unit '{}' redundancy: {}".format(power_unit_name_data,
POWER_UNIT_REDUNDANCY_STATE[
int(power_unit_redundancy_data)]
["result"])) | def check_power_unit_redundancy(power_unit_name_data, power_unit_redundancy_data) | check the status of the power units | 4.671419 | 4.35201 | 1.073393 |
# only check the status, if the "no" flag is not set
if flag:
# get the data via snmp
myData = get_data(sess, oid, helper)
data_summary_output, data_long_output = state_summary(myData, name, normal_state, helper)
add_output(data_summary_output, data_long_output, helper) | def check_global_status(flag, name, oid) | check a global status
check_global_status(True, "Global Storage", '.1.3.6.1.4.1.232.3.1.3.0') | 9.321136 | 8.721627 | 1.068738 |
if power_state_flag:
power_state = get_data(sess, oid_power_state, helper)
power_state_summary_output, power_state_long_output = state_summary(power_state, 'Server power', server_power_state, helper, server_power_state[3])
add_output(power_state_summary_output, power_state_long_output, helper) | def check_server_power() | Check if the server is powered on
Skip this check, if the --noPowerState is set | 6.371577 | 6.021426 | 1.058151 |
if ctrl_flag:
ctrl = walk_data(sess, oid_ctrl, helper)[0]
for x, data in enumerate(ctrl, 1):
ctrl_summary_output, ctrl_long_output = state_summary(data, 'Controller %d' % x, normal_state, helper)
add_output(ctrl_summary_output, ctrl_long_output, helper) | def check_storage_controllers() | Check the status of the storage controllers
Skip this check, if --noController is set | 10.537853 | 10.119424 | 1.041349 |
# walk all temperature sensor values and thresholds
env_temp = walk_data(sess, oid_env_temp, helper)[0]
env_temp_thresh = walk_data(sess, oid_env_temp_thres, helper)[0]
env_temp_zipped = zip(env_temp, env_temp_thresh)
for x, data in enumerate(env_temp_zipped, 1):
# skip the check if -99 or 0 is in the value or threshold, because these data we can not use
if '-99' not in data and '0' not in data:
#check if the value is over the treshold
if int(data[0]) > int(data[1]):
helper.add_summary('Temperature at sensor %d above threshold (%s / %s)' % (x, data[0], data[1]))
helper.status(critical)
# always add the sensor to the output
helper.add_long_output('Temperature %d: %s Celsius (threshold: %s Celsius)' % (x, data[0], data[1]))
# for the first sensor (envirnoment temperature, we add performance data)
if x == 1:
helper.add_metric("Environment Temperature", data[0], '', ":" + data[1], "", "", "Celsius") | def check_temperature_sensors() | Check all temperature sensors of the server
All sensors with the value or threshold is -99 or 0 are ignored | 6.301178 | 5.787725 | 1.088714 |
# human readable status
hr_status = normal_state[int(state)]
if hr_status != "ok":
# if the power supply is ok, we will set a critical status and add it to the summary
helper.add_summary('Power supply status %s: %s' % (x, hr_status))
helper.status(critical)
else:
# if everything is ok, we increase the ps_ok_count
ps_ok_count += 1
# we always want to see the status in the long output
helper.add_long_output('Power supply status %s: %s' % (x, hr_status))
helper.add_long_output('')
if int(input_pwr_sply) != ps_ok_count:
# if the confiugred power supplies and power supplies in ok state are different
helper.add_summary('%s power supplies expected - %s power supplies ok ' % (input_pwr_sply, ps_ok_count))
helper.status(critical) | def check_ps():
if int(input_pwr_sply) != 0:
ps_data = walk_data(sess, oid_ps, helper)[0]
ps_ok_count = 0
for x, state in enumerate(ps_data, 1) | Check if the power supplies are ok, and we have the configured amount
The check is skipped if --ps=0 | 4.635969 | 4.448979 | 1.04203 |
# skip the check if --noPowerRedundancy is set
if power_redundancy_flag:
# walk the data
ps_redundant_data = walk_data(sess, oid_ps_redundant, helper)[0]
for x, state in enumerate(ps_redundant_data, 1):
# human readable status
hr_status = ps_redundant_state[int(state)]
if hr_status != "redundant":
# if the power supply is not redundant, we will set a critical status and add it to the summary
helper.add_summary('Power supply %s: %s' % (x, hr_status))
helper.status(critical)
# we always want to see the redundancy status in the long output
helper.add_long_output('Power supply %s: %s' % (x, hr_status))
helper.add_long_output('') | def check_power_redundancy() | Check if the power supplies are redundant
The check is skipped if --noPowerRedundancy is set | 6.867061 | 6.090133 | 1.127572 |
# get a list of all fans
fan_data = walk_data(sess, oid_fan, helper)[0]
fan_count = 0
summary_output = ''
long_output = ''
for x, fan in enumerate(fan_data, 1):
fan = int(fan)
if normal_state[fan] == 'ok':
# if the fan is ok, we increase the fan_count varaible
fan_count += 1
# we always want to the the status in the long output
long_output += 'Fan %d: %s.\n' % (x, normal_state[fan])
# check we have the correct amount ok fans in OK state, otherwise set status to critical and print the fan in the summary
if int(fan_count) != int(input_fan):
summary_output += '%s fan(s) expected - %s fan(s) ok. ' % (input_fan, fan_count)
helper.status(critical)
return (summary_output, long_output) | def check_fan(input_fan) | check the fans | 6.607224 | 6.502388 | 1.016123 |
response = self.snmp1.get_oids(ps1_oid, ps2_oid, fan1_oid, fan2_oid, bat_oid, temp_oid, activity_oid, logfill_oid)
self.ps1_value = states[int(response[0])]
self.ps2_value = states[int(response[1])]
self.fan1_value = states[int(response[2])]
self.fan2_value = states[int(response[3])]
self.bat_value = states[int(response[4])]
self.temp_value = states[int(response[5])]
self.activity_value1 = activity[int(response[6])]
self.logfill_value = str(response[7]) | def get_snmp_from_host1(self) | Get SNMP values from 1st host. | 2.834059 | 2.727268 | 1.039157 |
if not self.snmp2:
self.activity_value2 = None
else:
response = self.snmp2.get_oids(activity_oid)
self.activity_value2 = activity[int(response[0])] | def get_snmp_from_host2(self) | Get SNMP values from 2nd host. | 7.828594 | 6.977427 | 1.121989 |
try:
self.get_snmp_from_host1()
self.get_snmp_from_host2()
except (health_monitoring_plugins.SnmpException, TypeError, KeyError):
self.helper.status(unknown)
self.helper.add_summary("SNMP response incomplete or invalid")
return
self.helper.add_summary("Filter Status")
self.helper.add_long_output("Power Supply 1: %s" % self.ps1_value)
if self.ps1_value != "ok":
self.helper.status(critical)
self.helper.add_summary("Power Supply 1: %s" % self.ps1_value)
self.helper.add_long_output("Power Supply 2: %s" % self.ps2_value)
if self.ps2_value != "ok":
self.helper.status(critical)
self.helper.add_summary("Power Supply 2: %s" % self.ps2_value)
self.helper.add_long_output("Fan 1: %s" % self.fan1_value)
if self.fan1_value != "ok":
self.helper.status(critical)
self.helper.add_summary("Fan 1: %s" % self.fan1_value)
self.helper.add_long_output("Fan 2: %s" % self.fan2_value)
if self.fan2_value != "ok":
self.helper.status(critical)
self.helper.add_summary("Fan 2: %s" % self.fan2_value)
self.helper.add_long_output("Battery: %s" % self.bat_value)
if self.bat_value != "ok":
self.helper.status(critical)
self.helper.add_summary("Battery: %s" % self.bat_value)
self.helper.add_long_output("Temperature: %s" % self.temp_value)
if self.temp_value != "ok":
self.helper.status(critical)
self.helper.add_summary("Temperature: %s" % self.temp_value)
self.helper.add_metric(label='logfill',value=self.logfill_value, uom="%%")
self.helper.add_long_output("Fill Level internal log: %s%%" % self.logfill_value)
self.helper.add_long_output("Activity State: %s" % self.activity_value1)
if self.activity_value1 == "error":
self.helper.status(critical)
self.helper.add_summary("Activity State: %s" % self.activity_value1)
if self.activity_value2:
self.helper.add_long_output("Activity State 2: %s" % self.activity_value2)
if self.activity_value1 == "active" and self.activity_value2 == "active":
self.helper.status(critical)
self.helper.add_summary("Filter 1 and Filter 2 active!")
if self.activity_value1 == "standby" and self.activity_value2 == "standby":
self.helper.status(critical)
self.helper.add_summary("Filter 1 and Filter 2 standby!")
self.helper.check_all_metrics() | def check(self) | Evaluate health status from device parameters. | 1.934983 | 1.899736 | 1.018554 |
if status:
self.status(status[0])
# if the status is ok, add it to the long output
if status[0] == 0:
self.add_long_output(status[1])
# if the status is not ok, add it to the summary
else:
self.add_summary(status[1]) | def update_status(self, helper, status) | update the helper | 3.999428 | 3.931042 | 1.017396 |
snmp_result = sess.get_oids(oid)[0]
if snmp_result is None:
helper.exit(summary="No response from device for oid " + oid, exit_code=unknown, perfdata='')
else:
return snmp_result | def get_snmp_value(sess, helper, oid) | return a snmp value or exits the plugin with unknown | 8.030851 | 7.353323 | 1.092139 |
try:
snmp_walk = sess.walk_oid(oid)
result_list = []
for x in range(len(snmp_walk)):
result_list.append(snmp_walk[x].val)
if result_list != []:
return result_list
else:
raise SnmpException("No content")
except SnmpException:
helper.exit(summary="No response from device for {} ({})".format(check, oid),
exit_code=unknown, perfdata='') | def walk_snmp_values(sess, helper, oid, check) | return a snmp value or exits the plugin with unknown | 5.468391 | 5.252662 | 1.04107 |
var = netsnmp.Varbind(oid)
varlist = netsnmp.VarList(var)
data = self.walk(varlist)
if len(data) == 0:
raise SnmpException("SNMP walk response incomplete")
return varlist | def walk_oid(self, oid) | Get a list of SNMP varbinds in response to a walk for oid.
Each varbind in response list has a tag, iid, val and type attribute. | 5.227837 | 5.183191 | 1.008614 |
all_disks = walk_data(sess, oid_hrStorageDescr, helper)[0]
print "All available disks at: " + host
for disk in all_disks:
print "Disk: \t'" + disk + "'"
quit() | def run_scan() | show all available partitions | 31.273645 | 27.236437 | 1.148228 |
# if we want to have a linux partition (/) we use the full path (startswith "/" would result in / /var /dev etc).
# if we start with something else, we use the startswith function
if "/" in partition:
use_fullcompare = True
else:
use_fullcompare = False
if use_fullcompare and (partition == description):
return True
elif not use_fullcompare and description.startswith(partition):
return True
else:
return False | def partition_found(partition, description) | returns True, if the partition (--partition) is in the description we received from the host | 8.537322 | 7.83147 | 1.09013 |
all_index = walk_data(sess, oid_hrStorageIndex, helper)[0]
all_descriptions = walk_data(sess, oid_hrStorageDescr, helper)[0]
# we need the sucess flag for the error handling (partition found or not found)
sucess = False
# here we zip all index and descriptions to have a list like
# [('Physical memory', '1'), ('Virtual memory', '3'), ('/', '32'), ('/proc/xen', '33')]
zipped = zip(all_index, all_descriptions)
for partition in zipped:
index = partition[0]
description = partition[1]
if partition_found(disk, description):
# we found the partition
sucess = True
# receive all values we need
unit = float(get_data(sess, oid_hrStorageAllocationUnits + "." + index, helper))
size = float(get_data(sess, oid_hrStorageSize + "." + index, helper))
used = float(get_data(sess, oid_hrStorageUsed + "." + index, helper))
if size == 0 or used == 0:
# if the host return "0" as used or size, then we have a problem with the calculation (devision by zero)
helper.exit(summary="Received value 0 as StorageSize or StorageUsed: calculation error", exit_code=unknown, perfdata='')
# calculate the real size (size*unit) and convert the results to the target unit the user wants to see
used_result = convert_to_XX(calculate_real_size(used), unit, targetunit)
size_result = convert_to_XX(calculate_real_size(size), unit, targetunit)
# calculation of the used percentage
percent_used = used_result / size_result * 100
# we need a string and want only two decimals
used_string = str(float("{0:.2f}".format(used_result)))
size_string = str(float("{0:.2f}".format(size_result)))
percent_string = str(float("{0:.2f}".format(percent_used)))
if percent_used < 0 or percent_used > 100:
# just a validation that percent_used is not smaller then 0% or lager then 100%
helper.exit(summary="Calculation error - second counter overrun?", exit_code=unknown, perfdata='')
# show the summary
helper.add_summary("%s%% used (%s%s of %s%s) at '%s'" % (percent_string, used_string, targetunit, size_string, targetunit, description))
# add the metric in percent.
helper.add_metric(label='percent used',value=percent_string, min="0", max="100", uom="%")
else:
if not sucess:
# if the partition was not found in the data output, we return an error
helper.exit(summary="Partition '%s' not found" % disk, exit_code=unknown, perfdata='') | def check_partition() | check the defined partition | 5.326064 | 5.319936 | 1.001152 |
all_sensors = walk_data(sess, oid_description, helper)[0]
all_status = walk_data(sess, oid_status, helper)[0]
# here we zip all index and descriptions to have a list like
# [('Fan Sensor', '2'), ('Power Supply Sensor', '4')]
# we are doomed if the lists do not have the same length ... but that should never happen ... hopefully
zipped = zip(all_sensors, all_status)
for sensor in zipped:
description = sensor[0]
status = sensor[1]
# translate the value to human readable
try:
status_string = senor_status_table[status]
except KeyError:
# if we receive an invalid value, we don't want to crash...
helper.exit(summary="received an undefined value from device: " + status, exit_code=unknown, perfdata='')
# for each sensor the summary is added like: Fan Sensor: good
helper.add_summary("%s: %s" % (description, status_string))
# set the status
if status == "2":
helper.status(critical)
if status == "3":
helper.status(warning) | def check_sensors() | collect and check all available sensors | 8.626835 | 8.449339 | 1.021007 |
apc_battery_states = {
'1' : 'unknown',
'2' : 'batteryNormal',
'3' : 'batteryLow',
'4' : 'batteryInFaultCondition'
}
a_state = apc_battery_states.get(the_snmp_value, 'unknown')
if the_snmp_value == '2':
the_helper.add_status(pynag.Plugins.ok)
elif the_snmp_value == '3':
the_helper.add_status(pynag.Plugins.warning)
else:
the_helper.add_status(pynag.Plugins.critical)
the_helper.set_summary("UPS batteries state is {}".format(a_state)) | def check_basic_battery_status(the_session, the_helper, the_snmp_value) | OID .1.3.6.1.4.1.318.1.1.1.2.1.1.0
MIB Excerpt
The status of the UPS batteries. A batteryLow(3)
value indicates the UPS will be unable to sustain the
current load, and its services will be lost if power is
not restored. The amount of run time in reserve at the
time of low battery can be configured by the
upsAdvConfigLowBatteryRunTime.
Value List
unknown (1)
batteryNormal (2)
batteryLow (3)
batteryInFaultCondition (4) | 3.367209 | 2.550884 | 1.320016 |
a_minute_value = calc_minutes_from_ticks(the_snmp_value)
the_helper.add_metric(
label=the_helper.options.type,
value=a_minute_value,
warn=the_helper.options.warning,
crit=the_helper.options.critical,
uom="Minutes")
the_helper.check_all_metrics()
the_helper.set_summary("Remaining runtime on battery is {} minutes".format(a_minute_value)) | def check_runtime_remaining(the_session, the_helper, the_snmp_value) | OID .1.3.6.1.4.1.318.1.1.1.2.2.3.0
MIB excerpt
The UPS battery run time remaining before battery
exhaustion.
SNMP value is in TimeTicks aka hundredths of a second | 5.004765 | 5.110333 | 0.979342 |
apc_states = {
'1' : 'Battery does not need to be replaced',
'2' : 'Battery needs to be replaced!'}
a_state = apc_states.get(the_snmp_value, "Unknown battery replacement state!")
if the_snmp_value == '1':
the_helper.add_status(pynag.Plugins.ok)
else:
the_helper.add_status(pynag.Plugins.critical)
the_helper.set_summary(a_state) | def check_battery_replace_indicator(the_session, the_helper, the_snmp_value) | OID .1.3.6.1.4.1.318.1.1.1.2.2.4.0
MIB Excerpt
Indicates whether the UPS batteries need replacing.
Value List
noBatteryNeedsReplacing (1)
batteryNeedsReplacing (2) | 4.692577 | 4.211464 | 1.114239 |
a_snmp_unit = snmpSessionBaseClass.get_data(
the_session,
apc_oid_environment_temperature_unit,
the_helper)
snmp_units = {
'1' : 'C',
'2' : 'F'
}
a_unit = snmp_units.get(a_snmp_unit, 'UNKNOWN_UNIT')
the_helper.add_metric(
label=the_helper.options.type,
value=the_snmp_value,
warn=the_helper.options.warning,
crit=the_helper.options.critical,
uom=a_unit)
the_helper.check_all_metrics()
the_helper.set_summary("Current environmental temperature is {}{}".format(the_snmp_value, a_unit)) | def check_environment_temperature(the_session, the_helper, the_snmp_value, the_unit=1) | OID .1.3.6.1.4.1.318.1.1.10.2.3.2.1.4.1
MIB Excerpt
The current temperature reading from the probe displayed
in the units shown in the 'iemStatusProbeTempUnits' OID
(Celsius or Fahrenheit).
Description of unit OID
OID .1.3.6.1.4.1.318.1.1.10.2.3.2.1.5
The temperature scale used to display the temperature
thresholds of the probe, Celsius(1) or Fahrenheit(2).
This setting is based on the system preferences
configuration in the agent. | 4.301061 | 4.691186 | 0.916839 |
if typ != "tcp" and typ != "udp":
helper.exit(summary="Type (-t) must be udp or tcp.", exit_code=unknown, perfdata='') | def check_typ(helper, typ) | check if typ parameter is TCP or UDP | 21.87722 | 16.353886 | 1.337738 |
try:
int(port)
except ValueError:
helper.exit(summary="Port (-p) must be a integer value.", exit_code=unknown, perfdata='') | def check_port(helper, port) | check if the port parameter is really a port or "scan" | 20.149775 | 15.656949 | 1.286954 |
open_ports = walk_data(session, '.1.3.6.1.2.1.7.5.1.2', helper)[0] # the udpLocaLPort from UDP-MIB.mib (deprecated)
# here we show all open UDP ports
if scan:
print "All open UDP ports at host " + host
for port in open_ports:
print "UDP: \t" + port
quit()
if port in open_ports:
udp_status = "OPEN"
else:
udp_status = "CLOSED"
helper.status(critical)
return ("Current status for UDP port " + port + " is: " + udp_status) | def check_udp(helper, host, port, session) | the check logic for UDP ports | 8.97002 | 8.734875 | 1.02692 |
# from tcpConnState from TCP-MIB
tcp_translate = {
"1" : "closed",
"2" : "listen",
"3" : "synSent",
"4" : "synReceived",
"5" : "established",
"6" : "finWait1",
"7" : "finWait2",
"8" : "closeWait",
"9" : "lastAck",
"10": "closing",
"11": "timeWait",
"12": "deleteTCB"
}
# collect all open local ports
open_ports = walk_data(session, '.1.3.6.1.2.1.6.13.1.3', helper)[0] #tcpConnLocalPort from TCP-MIB (deprecated)
# collect all status information about the open ports
port_status = walk_data(session, '.1.3.6.1.2.1.6.13.1.1', helper)[0] #tcpConnState from TCP-MIB (deprecated)
# make a dict out of the two lists
port_and_status = dict(zip(open_ports, port_status))
# here we show all open TCP ports and it's status
if scan:
print "All open TCP ports: " + host
for port in open_ports:
tcp_status = port_and_status[port]
tcp_status = tcp_translate[tcp_status]
print "TCP: \t" + port + "\t Status: \t" + tcp_status
quit()
#here we have the real check logic for TCP ports
if port in open_ports:
# if the port is available in the list of open_ports, then extract the status
tcp_status = port_and_status[port]
# translate the status from the integer value to a human readable string
tcp_status = tcp_translate[tcp_status]
# now let's set the status according to the warning / critical "threshold" parameter
if tcp_status in warning_param:
helper.status(warning)
elif tcp_status in critical_param:
helper.status(critical)
else:
helper.status(ok)
else:
# if there is no value in the list => the port is closed for sure
tcp_status = "CLOSED"
helper.status(critical)
return ("Current status for TCP port " + port + " is: " + tcp_status) | def check_tcp(helper, host, port, warning_param, critical_param, session) | the check logic for check TCP ports | 3.608452 | 3.578121 | 1.008477 |
i = StringIO.StringIO()
w = Writer(i, encoding='UTF-8')
w.write_value(obj)
return i.getvalue() | def to_json(obj) | Return a json string representing the python object obj. | 4.915572 | 4.170927 | 1.178532 |
"Get SNMP values from host"
alarm_oids = [netsnmp.Varbind(alarms[alarm_id]['oid']) for alarm_id in self.models[self.modem_type]['alarms']]
metric_oids = [netsnmp.Varbind(metrics[metric_id]['oid']) for metric_id in self.models[self.modem_type]['metrics']]
response = self.snmp_session.get(netsnmp.VarList(*alarm_oids + metric_oids))
return (
response[0:len(alarm_oids)],
response[len(alarm_oids):]
) | def get_data(self) | Get SNMP values from host | 4.090848 | 3.461751 | 1.181728 |
"Build list with active alarms"
self.active_alarms = []
for i in range(0, len(self.models[self.modem_type]['alarms'])):
if bool(int(snmp_data[i])) == True:
self.active_alarms.append(self.models[self.modem_type]['alarms'][i]) | def process_alarms(self, snmp_data) | Build list with active alarms | 3.442329 | 2.90268 | 1.185914 |
"Build list with metrics"
self.metrics = {}
for i in range(0, len(snmp_data)):
metric_id = self.models[self.modem_type]['metrics'][i]
value = int(snmp_data[i])
self.metrics[metric_id] = value | def process_metrics(self, snmp_data) | Build list with metrics | 4.763526 | 3.934083 | 1.210835 |
s = service_name
# convert the service_name to ascci
service_ascii = [ord(c) for c in s]
# we need the length of the service name
length = str(len(s))
# make the oid
oid = base_oid + "." + length + "." + ".".join(str(x) for x in service_ascii)
return oid | def convert_in_oid(service_name) | calculate the correct OID for the service name | 4.71648 | 4.309472 | 1.094445 |
"Return one SNMP response list for all status OIDs, and one list for all metric OIDs."
alarm_oids = [netsnmp.Varbind(status_mib[alarm_id]['oid']) for alarm_id in self.models[self.modem_type]['alarms']]
metric_oids = [netsnmp.Varbind(metric_mib[metric_id]['oid']) for metric_id in self.models[self.modem_type]['metrics']]
response = self.snmp_session.get(netsnmp.VarList(*alarm_oids + metric_oids))
return (
response[0:len(alarm_oids)],
response[len(alarm_oids):]
) | def get_data(self) | Return one SNMP response list for all status OIDs, and one list for all metric OIDs. | 4.610816 | 2.960561 | 1.557413 |
"Build list with active alarms"
self.active_alarms = {}
for i in range(0, len(self.models[self.modem_type]['alarms'])):
mib_name = self.models[self.modem_type]['alarms'][i]
conv = status_mib[mib_name]['conv']
self.active_alarms[mib_name] = conv(snmp_data[i]) | def process_alarms(self, snmp_data) | Build list with active alarms | 4.218602 | 3.696186 | 1.141339 |
"Build list with metrics"
self.metrics = {}
for i in range(0, len(snmp_data)):
mib_name = self.models[self.modem_type]['metrics'][i]
conv = metric_mib[mib_name]['conv']
self.metrics[mib_name] = conv(snmp_data[i]) | def process_metrics(self, snmp_data) | Build list with metrics | 5.463266 | 4.64543 | 1.176052 |
return str(float(value) / math.pow(10, float(digit))) | def real_value(value, digit) | function to calculate the real value
we need to devide the value by the digit
e.g.
value = 100
digit = 2
return: "1.0" | 5.424316 | 5.388329 | 1.006679 |
# walk the data
try:
inlet_values = self.sess.walk_oid(self.oids['oid_inlet_value'])
inlet_units = self.sess.walk_oid(self.oids['oid_inlet_unit'])
inlet_digits = self.sess.walk_oid(self.oids['oid_inlet_digits'])
inlet_states = self.sess.walk_oid(self.oids['oid_inlet_state'])
inlet_warning_uppers = self.sess.walk_oid(self.oids['oid_inlet_warning_upper'])
inlet_critical_uppers = self.sess.walk_oid(self.oids['oid_inlet_critical_upper'])
inlet_critical_lowers = self.sess.walk_oid(self.oids['oid_inlet_critical_lower'])
inlet_warning_lowers = self.sess.walk_oid(self.oids['oid_inlet_warning_lower'])
except health_monitoring_plugins.SnmpException as e:
helper.exit(summary=str(e), exit_code=unknown, perfdata='')
# just print the summary, that the inlet sensors are checked
helper.add_summary("Inlet")
# all list must have the same length, if not something went wrong. that makes it easier and we need less loops
# translate the data in human readable units with help of the dicts
for x in range(len(inlet_values)):
inlet_unit = units[int(inlet_units[x].val)]
inlet_digit = inlet_digits[x].val
inlet_state = states[int(inlet_states[x].val)]
inlet_value = real_value(inlet_values[x].val, inlet_digit)
inlet_warning_upper = real_value(inlet_warning_uppers[x].val, inlet_digit)
inlet_critical_upper = real_value(inlet_critical_uppers[x].val, inlet_digit)
inlet_warning_lower = real_value(inlet_warning_lowers[x].val, inlet_digit)
inlet_critical_lower = real_value(inlet_critical_lowers[x].val, inlet_digit)
if inlet_state != "normal":
# we don't want to use the thresholds. we rely on the state value of the device
helper.add_summary("%s %s is %s" % (inlet_value, inlet_unit, inlet_state))
helper.status(critical)
# we always want to see the values in the long output and in the perf data
helper.add_summary("%s %s" % (inlet_value, inlet_unit))
helper.add_long_output("%s %s: %s" % (inlet_value, inlet_unit, inlet_state))
helper.add_metric("Sensor " + str(x) + " -%s-" % inlet_unit, inlet_value,
inlet_warning_lower +\
":" + inlet_warning_upper, inlet_critical_lower + ":" +\
inlet_critical_upper, "", "", "") | def check_inlet(self, helper) | check the Inlets of Raritan PDUs | 3.015291 | 2.964131 | 1.01726 |
try:
outlet_name, outlet_state = self.sess.get_oids(self.oids['oid_outlet_name'], self.oids['oid_outlet_state'])
except health_monitoring_plugins.SnmpException as e:
helper.exit(summary=str(e), exit_code=unknown, perfdata='')
outlet_real_state = states[int(outlet_state)]
# here we check if the outlet is powered on
if outlet_real_state != "on":
helper.status(critical)
# print the status
helper.add_summary("Outlet %s - '%s' is: %s" % (self.number, outlet_name, outlet_real_state.upper())) | def check_outlet(self, helper) | check the status of the specified outlet | 7.127317 | 6.917686 | 1.030304 |
try:
sensor_name, sensor_state, sensor_type = self.sess.get_oids(
self.oids['oid_sensor_name'], self.oids['oid_sensor_state'], self.oids['oid_sensor_type'])
except health_monitoring_plugins.SnmpException as e:
helper.exit(summary=str(e), exit_code=unknown, perfdata='')
try:
sensor_state_string = states[int(sensor_state)]
except KeyError as e:
helper.exit(summary="Invalid sensor response " + sensor_state, exit_code=unknown, perfdata='')
sensor_unit = "" # if it's a onOff Sensor or something like that, we need an empty string for the summary
sensor_unit_string = ""
sensor_value = ""
sensor_digit = ""
real_sensor_value = ""
sensor_warning_upper = ""
sensor_critical_upper = ""
sensor_warning_lower = ""
sensor_critical_lower = ""
if int(sensor_type) not in [14, 16, 17, 18, 19, 20]:
# for all sensors except these, we want to calculate the real value and show the metric.
# 14: onOff
# 16: vibration
# 17: waterDetection
# 18: smokeDetection
# 19: binary
# 20: contact
try:
sensor_unit, sensor_digit, sensor_warning_upper, sensor_critical_upper, sensor_warning_lower, sensor_critical_lower, sensor_value = self.sess.get_oids(
self.oids['oid_sensor_unit'], self.oids['oid_sensor_digit'],
self.oids['oid_sensor_warning_upper'], self.oids['oid_sensor_critical_upper'],
self.oids['oid_sensor_warning_lower'], self.oids['oid_sensor_critical_lower'],
self.oids['oid_sensor_value'])
except health_monitoring_plugins.SnmpException as e:
helper.exit(summary=str(e), exit_code=unknown, perfdata='')
sensor_unit_string = units[int(sensor_unit)]
real_sensor_value = real_value(int(sensor_value), sensor_digit)
real_sensor_warning_upper = real_value(sensor_warning_upper, sensor_digit)
real_sensor_critical_upper = real_value(sensor_critical_upper, sensor_digit)
real_sensor_warning_lower = real_value(sensor_warning_lower, sensor_digit)
real_sensor_critical_lower = real_value(sensor_critical_lower, sensor_digit)
# metrics are only possible for these sensors
helper.add_metric(sensor_name + " -%s- " % sensor_unit_string, real_sensor_value,
real_sensor_warning_lower +\
":" + real_sensor_warning_upper, real_sensor_critical_lower +\
":" + real_sensor_critical_upper, "", "", "")
# "OK" state
if sensor_state_string in ["closed", "normal", "on", "notDetected", "ok", "yes", "one", "two", "inSync"]:
helper.status(ok)
# "WARNING" state
elif sensor_state_string in ["open", "belowLowerWarning", "aboveUpperWarning", "marginal", "standby"]:
helper.status(warning)
# "CRITICAL" state
elif sensor_state_string in ["belowLowerCritical", "aboveUpperCritical", "off", "detected", "alarmed", "fail", "no", "outOfSync"]:
helper.status(critical)
# "UNKOWN" state
elif sensor_state_string in ["unavailable"]:
helper.status(unknown)
# received an undefined state
else:
helper.exit(summary="Something went wrong - received undefined state", exit_code=unknown, perfdata='')
# summary is shown for all sensors
helper.add_summary("Sensor %s - '%s' %s%s is: %s" % (self.number, sensor_name, real_sensor_value, sensor_unit_string, sensor_state_string)) | def check_sensor(self, helper) | check the status of the specified sensor | 3.03639 | 3.031094 | 1.001747 |
os.dup2(dev_null, sys.stdout.fileno())
return_object = func(*a, **kwargs)
sys.stdout.flush()
os.dup2(tmp_stdout, sys.stdout.fileno())
return return_object | def dev_null_wrapper(func, *a, **kwargs) | Temporarily swap stdout with /dev/null, and execute given function while stdout goes to /dev/null.
This is useful because netsnmp writes to stdout and disturbes Icinga result in some cases. | 2.532971 | 2.372957 | 1.067432 |
# translate the value (integer) we receive to a human readable value (e.g. ok, critical etc.) with the given state_list
state_value = state_list[int(value)]
summary_output = ''
long_output = ''
if not info:
info = ''
if state_value != ok_value:
summary_output += ('%s status: %s %s ' % (name, state_value, info))
helper.status(pynag.Plugins.critical)
long_output += ('%s status: %s %s\n' % (name, state_value, info))
return (summary_output, long_output) | def state_summary(value, name, state_list, helper, ok_value = 'ok', info = None) | Always add the status to the long output, and if the status is not ok (or ok_value),
we show it in the summary and set the status to critical | 4.776985 | 4.154297 | 1.14989 |
if summary_output != '':
helper.add_summary(summary_output)
helper.add_long_output(long_output) | def add_output(summary_output, long_output, helper) | if the summary output is empty, we don't add it as summary, otherwise we would have empty spaces (e.g.: '. . . . .') in our summary report | 2.955859 | 2.406068 | 1.228502 |
gps_position = helper.get_snmp_value(sess, helper, self.oids['oid_gps_position'])
if gps_position:
helper.add_summary(gps_position)
else:
helper.add_summary("Could not retrieve GPS position")
helper.status(unknown) | def process_gps_position(self, helper, sess) | just print the current GPS position | 6.549944 | 6.215285 | 1.053845 |
if check == 'ntp_current_state':
ntp_status_int = helper.get_snmp_value(sess, helper, self.oids['oid_ntp_current_state_int'])
result = self.check_ntp_status(ntp_status_int)
elif check == 'gps_mode':
gps_status_int = helper.get_snmp_value(sess, helper, self.oids['oid_gps_mode_int'])
result = self.check_gps_status(gps_status_int)
else:
return
helper.update_status(helper, result) | def process_status(self, helper, sess, check) | get the snmp value, check the status and update the helper | 3.507588 | 3.118188 | 1.12488 |
# convert the ntp_status integer value in a human readable value
ntp_status_string = self.ntp_status.get(ntp_status_int, "unknown")
if ntp_status_string == "unknown":
return unknown, ("NTP status: " + ntp_status_string)
# the ntp status should be synchronized (new MIB) or normalOperation (old mib)
elif ntp_status_string != "synchronized" and ntp_status_string != "normalOperationPPS":
# that is a critical condition, because the time reference will not be reliable anymore
return critical, ("NTP status: " + ntp_status_string)
return None | def check_ntp_status(self, ntp_status_int) | check the NTP status | 5.840716 | 5.755957 | 1.014725 |
gps_mode_string = self.gps_mode.get(gps_status_int, "unknown")
if gps_mode_string == "unknown":
return unknown, ("GPS status: " + gps_mode_string)
elif gps_mode_string != "normalOperation" \
and gps_mode_string != "gpsSync":
# that is a warning condition, NTP could still work without the GPS antenna
return warning, ("GPS status: " + gps_mode_string)
return None | def check_gps_status(self, gps_status_int) | check the GPS status | 6.510482 | 6.383772 | 1.019849 |
good_satellites = helper.get_snmp_value(sess, helper, self.oids['oid_gps_satellites_good'])
# Show the summary and add the metric and afterwards check the metric
helper.add_summary("Good satellites: {}".format(good_satellites))
helper.add_metric(label='satellites', value=good_satellites) | def process_satellites(self, helper, sess) | check and show the good satellites | 8.603396 | 7.307813 | 1.177287 |
password = self.selenium.find_element(*self._password_input_locator)
password.clear()
password.send_keys(value) | def login_password(self, value) | Set the value of the login password field. | 3.452539 | 3.031427 | 1.138915 |
email = self.wait.until(expected.visibility_of_element_located(
self._email_input_locator))
email.clear()
email.send_keys(value) | def email(self, value) | Set the value of the email field. | 4.489799 | 3.923407 | 1.144362 |
self.email = email
self.login_password = password
if self.is_element_present(*self._next_button_locator):
self.wait.until(expected.visibility_of_element_located(
self._next_button_locator))
self.click_next()
self.click_sign_in() | def sign_in(self, email, password) | Signs in using the specified email address and password. | 3.548126 | 3.476602 | 1.020573 |
from .pages.sign_in import SignIn
sign_in = SignIn(self.selenium, self.timeout)
sign_in.sign_in(email, password) | def sign_in(self, email=None, password=None) | Signs in a user, either with the specified email address and password, or a returning user. | 3.701967 | 3.452035 | 1.072401 |
csvwriter = csv.writer(fileobj, dialect=dialect)
csv_writerows(csvwriter, rows, encoding) | def write_csv(fileobj, rows, encoding=ENCODING, dialect=DIALECT) | Dump rows to ``fileobj`` with the given ``encoding`` and CSV ``dialect``. | 3.50222 | 4.324467 | 0.809862 |
global pandas
if pandas is None: # pragma: no cover
import pandas
with contextlib.closing(CsvBuffer()) as fd:
write_csv(fd, rows, encoding, dialect)
fd.seek(0)
df = read_csv(pandas, fd, encoding, dialect, kwargs)
return df | def write_dataframe(rows, encoding=ENCODING, dialect=DIALECT, **kwargs) | Dump ``rows`` to string buffer and load with ``pandas.read_csv()`` using ``kwargs``. | 4.634285 | 4.418762 | 1.048775 |
ma = cls._pattern.search(link)
if ma is None:
raise ValueError(link)
id = ma.group('id')
return cls(id) | def from_string(cls, link) | Return a new SheetUrl instance from parsed URL string.
>>> SheetUrl.from_string('https://docs.google.com/spreadsheets/d/spam')
<SheetUrl id='spam' gid=0> | 4.444136 | 6.032089 | 0.736749 |
def decorator(func):
func.__doc__ = func.__doc__ % tuple(args)
return func
return decorator | def doctemplate(*args) | Return a decorator putting ``args`` into the docstring of the decorated ``func``.
>>> @doctemplate('spam', 'spam')
... def spam():
... '''Returns %s, lovely %s.'''
... return 'Spam'
>>> spam.__doc__
'Returns spam, lovely spam.' | 3.761762 | 5.847863 | 0.643271 |
result = collections.defaultdict(list)
for i in items:
key = keyfunc(i)
result[key].append(i)
return result | def group_dict(items, keyfunc) | Return a list defaultdict with ``items`` grouped by ``keyfunc``.
>>> sorted(group_dict('eggs', lambda x: x).items())
[('e', ['e']), ('g', ['g', 'g']), ('s', ['s'])] | 2.150496 | 3.208002 | 0.670354 |
seen = set()
return [item for item in iterable if item not in seen and not seen.add(item)] | def uniqued(iterable) | Return unique list of ``iterable`` items preserving order.
>>> uniqued('spameggs')
['s', 'p', 'a', 'm', 'e', 'g'] | 2.240298 | 3.383788 | 0.662068 |
if name is not None:
for kw, value in iteritems(SERVICES[name]):
kwargs.setdefault(kw, value)
return apiclient.discovery.build(**kwargs) | def build_service(name=None, **kwargs) | Return a service endpoint for interacting with a Google API. | 5.937461 | 4.730668 | 1.2551 |
params = {'orderBy': order, 'pageToken': None}
q = []
if name is not None:
q.append("name='%s'" % name)
if mimeType is not None:
q.append("mimeType='%s'" % mimeType)
if q:
params['q'] = ' and '.join(q)
while True:
response = service.files().list(**params).execute()
for f in response['files']:
yield f['id'], f['name']
try:
params['pageToken'] = response['nextPageToken']
except KeyError:
return | def iterfiles(service, name=None, mimeType=SHEET, order=FILEORDER) | Fetch and yield ``(id, name)`` pairs for Google drive files. | 1.855214 | 1.79126 | 1.035703 |
request = service.spreadsheets().get(spreadsheetId=id)
try:
response = request.execute()
except apiclient.errors.HttpError as e:
if e.resp.status == 404:
raise KeyError(id)
else: # pragma: no cover
raise
return response | def spreadsheet(service, id) | Fetch and return spreadsheet meta data with Google sheets API. | 2.257386 | 2.21271 | 1.020191 |
params = {'majorDimension': 'ROWS', 'valueRenderOption': 'UNFORMATTED_VALUE',
'dateTimeRenderOption': 'FORMATTED_STRING'}
params.update(spreadsheetId=id, ranges=ranges)
response = service.spreadsheets().values().batchGet(**params).execute()
return response['valueRanges'] | def values(service, id, ranges) | Fetch and return spreadsheet cell values with Google sheets API. | 3.08274 | 2.317926 | 1.329956 |
scopes = Scopes.get(scopes)
if secrets is None:
secrets = SECRETS
if storage is None:
storage = STORAGE
secrets, storage = map(os.path.expanduser, (secrets, storage))
store = file.Storage(storage)
creds = store.get()
if creds is None or creds.invalid:
flow = client.flow_from_clientsecrets(secrets, scopes)
args = ['--noauth_local_webserver'] if no_webserver else []
flags = tools.argparser.parse_args(args)
creds = tools.run_flow(flow, store, flags)
return creds | def get_credentials(scopes=None, secrets=None, storage=None, no_webserver=False) | Make OAuth 2.0 credentials for scopes from ``secrets`` and ``storage`` files.
Args:
scopes: scope URL(s) or ``'read'``, ``'write'`` (default: ``%r``)
secrets: location of secrets file (default: ``%r``)
storage: location of storage file (default: ``%r``)
no_webserver: url/code prompt instead of webbrowser based auth
see https://developers.google.com/sheets/quickstart/python
see https://developers.google.com/api-client-library/python/guide/aaa_client_secrets | 2.204759 | 2.223904 | 0.991391 |
if scope is None:
scope = cls.default
if isinstance(scope, string_types) and scope in cls._keywords:
return getattr(cls, scope)
return scope | def get(cls, scope=None) | Return default or predefined URLs from keyword, pass through ``scope``. | 4.221542 | 3.352852 | 1.25909 |
''' Returns a single list containing up to 'limit' Result objects'''
desired_limit = limit
results = self._search(limit, format)
limit = limit - len(results)
while len(results) < desired_limit:
more_results = self._search(limit, format)
if not more_results:
break
results += more_results
limit = limit - len(more_results)
time.sleep(1)
return results | def search_all(self, limit=50, format='json') | Returns a single list containing up to 'limit' Result objects | 3.404618 | 2.820013 | 1.207306 |
'''
Returns a list of result objects, with the url for the next page bing search url.
'''
url = self.QUERY_URL.format(requests.utils.quote("'{}'".format(self.query)), min(50, limit), self.current_offset, format)
r = requests.get(url, auth=("", self.api_key))
try:
json_results = r.json()
except ValueError as vE:
if not self.safe:
raise PyBingVideoException("Request returned with code %s, error msg: %s" % (r.status_code, r.text))
else:
print ("[ERROR] Request returned with code %s, error msg: %s. \nContinuing in 5 seconds." % (r.status_code, r.text))
time.sleep(5)
packaged_results = [VideoResult(single_result_json) for single_result_json in json_results['d']['results']]
self.current_offset += min(50, limit, len(packaged_results))
return packaged_results | def _search(self, limit, format) | Returns a list of result objects, with the url for the next page bing search url. | 4.396599 | 3.414553 | 1.287606 |
return sum((_start + ord(c)) * 26**i for i, c in enumerate(reversed(s))) | def base26int(s, _start=1 - ord('A')) | Return string ``s`` as ``int`` in bijective base26 notation.
>>> base26int('SPAM')
344799 | 3.216736 | 5.678343 | 0.566492 |
result = []
while x:
x, digit = divmod(x, 26)
if not digit:
x -= 1
digit = 26
result.append(_alphabet[digit - 1])
return ''.join(result[::-1]) | def base26(x, _alphabet=string.ascii_uppercase) | Return positive ``int`` ``x`` as string in bijective base26 notation.
>>> [base26(i) for i in [0, 1, 2, 26, 27, 28, 702, 703, 704]]
['', 'A', 'B', 'Z', 'AA', 'AB', 'ZZ', 'AAA', 'AAB']
>>> base26(344799) # 19 * 26**3 + 16 * 26**2 + 1 * 26**1 + 13 * 26**0
'SPAM'
>>> base26(256)
'IV' | 2.225719 | 2.89698 | 0.768289 |
try:
return _match(coord).groups()
except AttributeError:
raise ValueError(coord) | def _parse(coord, _match=_regex.match) | Return match groups from single sheet coordinate.
>>> Coordinates._parse('A1')
('A', '1', None, None)
>>> Coordinates._parse('A'), Coordinates._parse('1')
((None, None, 'A', None), (None, None, None, '1'))
>>> Coordinates._parse('spam')
Traceback (most recent call last):
...
ValueError: spam | 4.085256 | 7.091166 | 0.576105 |
try:
return _map[col.upper()]
except KeyError:
raise ValueError(col) | def _cint(col, _map={base26(i): i - 1 for i in range(1, 257)}) | Return zero-based column index from bijective base26 string.
>>> Coordinates._cint('Ab')
27
>>> Coordinates._cint('spam')
Traceback (most recent call last):
...
ValueError: spam | 3.720353 | 7.114764 | 0.522906 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.