本文整理汇总了Python中pynag.Plugins.PluginHelper.add_metric方法的典型用法代码示例。如果您正苦于以下问题:Python PluginHelper.add_metric方法的具体用法?Python PluginHelper.add_metric怎么用?Python PluginHelper.add_metric使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类pynag.Plugins.PluginHelper
的用法示例。
在下文中一共展示了PluginHelper.add_metric方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: testPluginHelper
# 需要导入模块: from pynag.Plugins import PluginHelper [as 别名]
# 或者: from pynag.Plugins.PluginHelper import add_metric [as 别名]
class testPluginHelper(unittest.TestCase):
def setUp(self):
self.argv_store = sys.argv
from pynag.Plugins import PluginHelper
self.my_plugin = PluginHelper()
self.my_plugin.parser.add_option('-F',
dest='fakedata',
help='fake data to test thresholds')
sys.stdout = StringIO()
def tearDown(self):
sys.argv = self.argv_store
sys.stdout = original_stdout
def run_expect(self, case, value, expected_exit):
sys.argv = [sys.argv[0]] + case.split() + ('-F %s' % value).split()
self.my_plugin.parse_arguments()
self.my_plugin.add_status(pynag.Plugins.ok)
self.my_plugin.add_summary(self.my_plugin.options.fakedata)
self.my_plugin.add_metric('fakedata', self.my_plugin.options.fakedata)
try:
self.my_plugin.check_all_metrics()
self.my_plugin.exit()
except SystemExit, e:
self.assertEquals(type(e), type(SystemExit()))
self.assertEquals(e.code, expected_exit)
except Exception, e:
self.fail('unexpected exception: %s' % e)
示例2:
# 需要导入模块: from pynag.Plugins import PluginHelper [as 别名]
# 或者: from pynag.Plugins.PluginHelper import add_metric [as 别名]
except Exception, e:
helper.exit(summary="Could not read /proc/loadavg", long_output=str(e), exit_code=unknown, perfdata='')
# We have read the contents of loadavg file. Lets put it in the summary of our plugin output:
helper.add_summary("Load: %s" % content)
# Read metrics from /proc/loadavg and add them as performance metrics
load1,load5,load15,processes,last_proc_id = content.split()
running,total = processes.split('/')
# If we so desire we can set default thresholds by adding warn attribute here
# However we decide that there are no thresholds by default and they have to be
# applied on runtime with the --threshold option
helper.add_metric(label='load1',value=load1)
helper.add_metric(label='load5',value=load5)
helper.add_metric(label='load15',value=load15)
helper.add_metric(label='running_processes',value=running)
helper.add_metric(label='total_processes',value=total)
# By default assume everything is ok. Any thresholds specified with --threshold can overwrite this status:
helper.status(ok)
# Here all metrics will be checked against thresholds that are either
# built-in or added via --threshold from the command-line
helper.check_all_metrics()
# Print out plugin information and exit nagios-style
helper.exit()
示例3: PluginHelper
# 需要导入模块: from pynag.Plugins import PluginHelper [as 别名]
# 或者: from pynag.Plugins.PluginHelper import add_metric [as 别名]
class PluginHelper(unittest.TestCase):
def setUp(self):
self.argv_store = sys.argv
from pynag.Plugins import PluginHelper
self.my_plugin = PluginHelper()
self.my_plugin.parser.add_option('-F',
dest='fakedata',
help='fake data to test thresholds')
sys.stdout = StringIO()
def tearDown(self):
sys.argv = self.argv_store
sys.stdout = original_stdout
def run_expect(self, case, value, expected_exit):
sys.argv = [sys.argv[0]] + case.split() + ('-F %s' % value).split()
self.my_plugin.parse_arguments()
self.my_plugin.add_status(pynag.Plugins.ok)
self.my_plugin.add_summary(self.my_plugin.options.fakedata)
self.my_plugin.add_metric('fakedata', self.my_plugin.options.fakedata)
try:
self.my_plugin.check_all_metrics()
self.my_plugin.exit()
except SystemExit as e:
self.assertEquals(type(e), type(SystemExit()))
self.assertEquals(e.code, expected_exit)
except Exception as e:
self.fail('unexpected exception: %s' % e)
else:
self.fail('SystemExit exception expected')
finally:
signal.alarm(0)
# Critical if "stuff" is over 20, else warn if over 10
# (will be critical if "stuff" is less than 0)
def test_number_1(self):
case = '--th=metric=fakedata,ok=0..10,warn=10..20'
self.run_expect(case, -23, 2)
def test_number_2(self):
case = '--th=metric=fakedata,ok=0..10,warn=10..20'
self.run_expect(case, 3, 0)
def test_number_3(self):
case = '--th=metric=fakedata,ok=0..10,warn=10..20'
self.run_expect(case, 13, 1)
def test_number_4(self):
case = '--th=metric=fakedata,ok=0..10,warn=10..20'
self.run_expect(case, 23, 2)
# Same as above. Negative "stuff" is OK
def test_number_5(self):
case = '--th=metric=fakedata,ok=inf..10,warn=10..20'
self.run_expect(case, '-23', 0)
def test_number_6(self):
case = '--th=metric=fakedata,ok=inf..10,warn=10..20'
self.run_expect(case, '3', 0)
def test_number_7(self):
case = '--th=metric=fakedata,ok=inf..10,warn=10..20'
self.run_expect(case, '13', 1)
def test_number_8(self):
case = '--th=metric=fakedata,ok=inf..10,warn=10..20'
self.run_expect(case, '23', 2)
# Critical if "stuff" is over 20, else warn if "stuff" is below 10
# (will be critical if "stuff" is less than 0)
def test_number_9(self):
case = '--th=metric=fakedata,warn=0..10,crit=20..inf'
self.run_expect(case, '-23', 0)
def test_number_10(self):
case = '--th=metric=fakedata,warn=0..10,crit=20..inf'
self.run_expect(case, '3', 1)
def test_number_11(self):
case = '--th=metric=fakedata,warn=0..10,crit=20..inf'
self.run_expect(case, '13', 0)
def test_number_12(self):
case = '--th=metric=fakedata,warn=0..10,crit=20..inf'
self.run_expect(case, '23', 2)
# Critical if "stuff" is less than 1
def test_number_13(self):
case = '--th=metric=fakedata,ok=1..inf'
self.run_expect(case, '-23', 2)
def test_number_14(self):
case = '--th=metric=fakedata,ok=1..inf'
self.run_expect(case, '0', 2)
def test_number_15(self):
case = '--th=metric=fakedata,ok=1..inf'
self.run_expect(case, '13', 0)
#.........这里部分代码省略.........
示例4: PluginHelper
# 需要导入模块: from pynag.Plugins import PluginHelper [as 别名]
# 或者: from pynag.Plugins.PluginHelper import add_metric [as 别名]
# check_stuff.py Takes any arguments from the command_line and treats them as performance metrics.
from pynag.Plugins import PluginHelper
my_plugin = PluginHelper()
my_plugin.parse_arguments()
# Any perfdatastring added as argument will be treated as a performance metric
for i in my_plugin.arguments:
my_plugin.add_metric(perfdatastring=i)
my_plugin.check_all_metrics()
my_plugin.exit()
示例5:
# 需要导入模块: from pynag.Plugins import PluginHelper [as 别名]
# 或者: from pynag.Plugins.PluginHelper import add_metric [as 别名]
now=time.time()
commandstr='m.'+valuesKey+"[%s]" % interfaceKey
labelstr=str(m.ifDescr[interfaceKey])+'-'+valuesKey
counthash=str(hash('checkinterfaces'+helper.options.host+labelstr))
timehash=str(hash('now'+helper.options.host+labelstr))
oldcounter=mc.get(str(counthash))
oldtime=mc.get(str(timehash))
if oldcounter is None:
oldcounter = 0
if oldtime is None:
oldtime = now-30
counter=eval(commandstr)
mc.set(counthash,counter)
mc.set(timehash, now)
mbps=((counter-oldcounter)*(8))/(now-oldtime)
#mbps=((counter-oldcounter)*(8/1000000))/(now-oldtime)
helper.add_metric(label=labelstr, value=mbps)
# print " %s: %i" % (labelstr, counter)
# By default assume everything is ok. Any thresholds specified with --threshold can overwrite this status:
helper.status(ok)
# Here all metrics will be checked against thresholds that are either
# built-in or added via --threshold from the command-line
helper.check_all_metrics()
# Print out plugin information and exit nagios-style
helper.exit()
示例6: parse
# 需要导入模块: from pynag.Plugins import PluginHelper [as 别名]
# 或者: from pynag.Plugins.PluginHelper import add_metric [as 别名]
distance = columns[7].text.strip()
direction = columns[8].text
location = columns[9].text
depth = depth.replace(',','.')
scale = scale.replace(',','.')
quality = quality.replace(',','.')
latitude = latitude.replace(',','.')
longitude = longitude.replace(',','.')
distance = distance.replace(',','.')
# manipulate location, well.. at least remove spaces
location = location.replace(' ','_')
datetimestr = str_date + " " + str_time.split(',',1)[0]
timestamp = time.mktime( parse(datetimestr).timetuple() )
timestamp = int(timestamp)
timesince = now-timestamp
if timesince > 60*60: # Less than one hour since earthquake
continue
if row.find('ATHUGI') > 0:
major_earthquakes += 1
recent_earthquakes += 1
helper.add_long_output("%s %s: scale=%s depth=%s quality=%s %s %s" % (str_date, str_time, scale, depth, quality, distance, location))
helper.add_summary('%s major earthquakes. %s total earthquakes' % (major_earthquakes, recent_earthquakes))
helper.add_metric('major earthquakes', value=major_earthquakes, crit='1..inf')
helper.add_metric('recent earthquakes', value=recent_earthquakes, warn='3..inf')
helper.check_all_metrics()
helper.exit()
示例7: main
# 需要导入模块: from pynag.Plugins import PluginHelper [as 别名]
# 或者: from pynag.Plugins.PluginHelper import add_metric [as 别名]
def main():
helper = PluginHelper()
helper.parser.add_option('-w', help='warning free (X% or XM)', dest='warning')
helper.parser.add_option('-c', help='critical free (X% or XM)', dest='critical')
helper.parse_arguments()
warn = helper.options.warning
crit = helper.options.critical
memory = getMemory()
if helper.options.warning is not None:
warn = helper.options.warning
if re.match('.*%$', warn):
warn = str(memory['total'] * int(re.search('\d*', warn).group(0)) / 100)
else:
warn = '0'
if helper.options.critical is not None:
crit = helper.options.critical
if re.match('.*%$', crit):
crit = str(memory['total'] * int(re.search('\d*', crit).group(0)) / 100)
else:
crit = '0'
helper.status(ok)
status = "OK"
if memory['totalfree'] <= int(warn):
helper.status(warning)
status = "WARNING"
if memory['totalfree'] <= int(crit):
helper.status(critical)
status = "CRITICAL"
helper.add_summary(status + ': Memory free: %(totalfree)s %% (%(free)s %% including buffers/cached)' % {'totalfree': (round((float(memory['totalfree']) / float(memory['total']) * 100), 1 )), 'free': (round((float(memory['free']) / float(memory['total']) * 100), 1 ))})
helper.add_metric(label='total',value=memory['total'])
helper.add_metric(label='free',value=memory['free'])
helper.add_metric(label='totalfree',value=memory['totalfree'], warn=warn+'..0', crit=crit+'..0')
helper.add_metric(label='used',value=memory['used'])
helper.add_metric(label='buffers',value=memory['buffers'])
helper.add_metric(label='cached',value=memory['cached'])
helper.add_metric(label='swapcached',value=memory['swapcached'])
helper.check_all_metrics()
helper.exit()
示例8: check_all_metrics
# 需要导入模块: from pynag.Plugins import PluginHelper [as 别名]
# 或者: from pynag.Plugins.PluginHelper import add_metric [as 别名]
# Here comes the specific check logic
try:
start_time = time.time()
result = socket.gethostbyname( hostname ) # result will contain the ip address resolved
end_time = time.time()
# If no address was specified with -a, then we return
# OK if hostname resolved to anything at all
if address is None or address == result:
my_plugin.status(ok)
my_plugin.add_summary("%s resolves to %s" % (hostname, result))
else:
my_plugin.status(critical)
my_plugin.add_summary("%s resolves to %s but should resolve to %s" % (hostname,result,address))
# Add run_time metric, so we can also alert if lookup takes to long
run_time = end_time - start_time
my_plugin.add_metric('run_time', run_time)
except gaierror:
# If any exceptions happened in the code above, lets return a critical status
my_plugin.status(critical)
my_plugin.add_summary('Could not resolve host "%s"' % hostname )
# when check_all_metrics() is run, any metrics we have added with add_metric() will be processed against
# Thresholds (like --threshold). This part will allow our plugin users to alert on lookup_time
my_plugin.check_all_metrics()
# Print status output and exit
my_plugin.exit()
示例9: PluginHelper
# 需要导入模块: from pynag.Plugins import PluginHelper [as 别名]
# 或者: from pynag.Plugins.PluginHelper import add_metric [as 别名]
p = PluginHelper()
chars = string.letters + string.digits
randomstring= ''.join([random.choice(chars) for i in xrange(4)]) # avoid cache
default_url = 'http://landspitali.is'
p.parser.add_option('--url', dest='url', default=default_url)
p.parse_arguments()
p.check_all_metrics()
p.show_legacy = True
html = requests.get(p.options.url).content
soup = BeautifulSoup(html)
activitylist = soup.find('div', {'class':'activityNumbers activityNumbersNew'})
activities = activitylist.findAll('div', recursive=False)
p.add_metric('metrics_found', value=len(activities), warn='0..1')
p.add_summary('%s metrics found on landspitali website' % (len(activities)))
for i in activities:
metric_name = i.get('class')
metric_value = i.find('div', {'class': "todaysCount"}).text
heading = i.find('div', {'class': 'heading'})
text = i.find('div', {'class': 'todaysText'})
# If string dag... is found, this is a counter for the whole day
if 'dag...' in heading.text:
uom = 'c'
else:
uom = ''
p.add_metric(metric_name, metric_value, uom=uom)
p.add_long_output("%s: %s %s %s" % (metric_name, heading.text, metric_value, text.text))
示例10: show_response
# 需要导入模块: from pynag.Plugins import PluginHelper [as 别名]
# 或者: from pynag.Plugins.PluginHelper import add_metric [as 别名]
auth = (plugin.options.user, plugin.options.password)
# Build the metric URL.
api = 'http://{}:{}/api/overview'.format(plugin.options.hostname, plugin.options.port)
payload = {
'msg_rates_age': '3600',
'msg_rates_incr': '10',
'columns': 'message_stats.deliver_get_details.avg_rate',
}
# No need to specify a timeout: pynag has --timeout option for the whole plugin.
r = requests.get(api, params=payload, auth=auth)
if plugin.options.show_debug:
show_response()
if r.status_code == 401:
plugin.add_summary("Login failed")
plugin.exit()
try:
deliver_rate = r.json()["message_stats"]["deliver_get_details"]["avg_rate"]
except ValueError:
plugin.add_summary("Can't decode server's response")
plugin.exit()
plugin.add_metric('deliver_rate', deliver_rate)
plugin.add_summary('message.deliver.avg_rate: {}'.format(deliver_rate))
plugin.check_all_metrics()
plugin.exit()
示例11: time
# 需要导入模块: from pynag.Plugins import PluginHelper [as 别名]
# 或者: from pynag.Plugins.PluginHelper import add_metric [as 别名]
remote_timestamp += datetime.timedelta(hours=remote_time_hours_offset, minutes=remote_time_minutes_offset)
try:
# Windows will return the local time (not UTC), so we need to use the local time to compare
# Force this this if '-l' or '--localtime' is set in commandline
if windows or use_local:
local_timestamp = datetime.datetime.now()
time_type = 'Remote (Local)'
else:
# usually the we need the UTC time
local_timestamp = datetime.datetime.utcnow()
time_type = 'Remote (UTC)'
# Calculate the offset between local and remote time
offset = time.mktime(local_timestamp.timetuple()) - time.mktime(remote_timestamp.timetuple()) + 60 * o_tzoff
helper.add_metric(label='offset', value=offset, uom='s')
helper.check_all_metrics()
except IndexError:
helper.exit(summary='remote device does not return a time value', exit_code=unknown, perfdata='')
# Print out plugin information and exit nagios-style
helper.add_summary(
'%s: ' % (time_type) + datetime.datetime.fromtimestamp(time.mktime(remote_timestamp.timetuple())).strftime(
'%H:%M:%S') + '. Offset = %d s' % offset)
helper.add_long_output(
'%s: ' % (time_type) + datetime.datetime.fromtimestamp(time.mktime(remote_timestamp.timetuple())).strftime(
'%Y.%m.%d %H:%M:%S'))
helper.exit()
示例12: len
# 需要导入模块: from pynag.Plugins import PluginHelper [as 别名]
# 或者: from pynag.Plugins.PluginHelper import add_metric [as 别名]
json = simplejson.loads(html)
total_bars = len(json)
open_bars = 0
now = datetime.datetime.now()
current_day = now.weekday()
current_hour = now.hour
for i in json:
fields = i['fields']
start = fields.get('happy_hour_start')
end = fields.get('happy_hour_end')
days = fields.get('happy_hour_days')
# format the data a little bit
start = int(start)
end = int(end)
days = days.split(',')
days = map(lambda x: int(x), days)
if current_day in days and start <= current_hour < end:
open_bars += 1
p.add_metric('total bars', value=total_bars)
p.add_metric('ongoing happy hours', value=open_bars)
p.status(ok)
p.add_summary('%s out of %s bars have an ongoing happy hour' % (open_bars,total_bars))
p.check_all_metrics()
p.exit()
示例13:
# 需要导入模块: from pynag.Plugins import PluginHelper [as 别名]
# 或者: from pynag.Plugins.PluginHelper import add_metric [as 别名]
formatstring=helper.options.value+': %s'
commandstring="m."+helper.options.value
content=eval(commandstring)
helper.add_summary(formatstring % content)
# Read metrics from /proc/loadavg and add them as performance metrics
#load1,load5,load15,processes,last_proc_id = content.split()
#running,total = processes.split('/')
# If we so desire we can set default thresholds by adding warn attribute here
# However we decide that there are no thresholds by default and they have to be
# applied on runtime with the --threshold option
helper.add_metric(label=helper.options.value,value=content)
#helper.add_metric(label='load5',value=load5)
#helper.add_metric(label='load15',value=load15)
#helper.add_metric(label='running_processes',value=running)
#helper.add_metric(label='total_processes',value=total)
# By default assume everything is ok. Any thresholds specified with --threshold can overwrite this status:
helper.status(ok)
# Here all metrics will be checked against thresholds that are either
# built-in or added via --threshold from the command-line
helper.check_all_metrics()
# Print out plugin information and exit nagios-style
helper.exit()
示例14: int
# 需要导入模块: from pynag.Plugins import PluginHelper [as 别名]
# 或者: from pynag.Plugins.PluginHelper import add_metric [as 别名]
current_traffic = i[86:90].strip()
total_traffic = i[90:].strip()
if max_wind:
max_winds.append( int(max_wind) )
if average_wind:
average_winds.append( int(average_wind) )
if road_temperature:
road_temperatures.append( int(road_temperature))
if air_temperature:
air_temperatures.append( int(air_temperature))
if humidity:
humidities.append( int(humidity) )
if current_traffic:
current_traffics.append( int(current_traffic))
if total_traffic:
total_traffics.append( int(total_traffic) )
p.add_metric('Average Wind Speed', value=np.mean(average_winds),uom='m_per_s')
p.add_metric('Max Gust measured', value=max(max_winds),uom='m_per_s')
p.add_metric('Air temperature', value=np.mean(air_temperatures), uom='celcius')
p.add_metric('Road temperature', value=np.mean(road_temperatures), uom='celcius')
p.add_metric('traffic today', value=sum(total_traffics), uom='c')
p.add_metric('current traffic', value=sum(current_traffics), uom='cars')
p.add_summary('Got metrics from %s weather stations' % ( len(average_winds) ))
p.status(ok)
p.exit()
示例15:
# 需要导入模块: from pynag.Plugins import PluginHelper [as 别名]
# 或者: from pynag.Plugins.PluginHelper import add_metric [as 别名]
except Exception, e:
helper.exit(summary="Could not read MIB file.", long_output=str(e), exit_code=unknown, perfdata='')
m=Manager(helper.options.host,helper.options.community,int(helper.options.version))
values={'systemCurrent':'','systemUsedCapacity':'','psBatteryVoltage':'','psBatteryCurrent':'','psInputLineAVoltage':''}
formatstring='systemUsedCapacity: %s'
content=m.systemUsedCapacity
helper.add_summary(formatstring % content)
for key in values:
commandstring="m."+key
values[key]=eval(commandstring)
# print key,values[key]
helper.add_metric(label=key,value=values[key])
#formatstring=helper.options.value+': %s'
#commandstring="m."+helper.options.value
#content=eval(commandstring)
content='foo'
#helper.add_summary(formatstring % content)
# Read metrics from /proc/loadavg and add them as performance metrics
#load1,load5,load15,processes,last_proc_id = content.split()
#running,total = processes.split('/')
# If we so desire we can set default thresholds by adding warn attribute here