本文整理汇总了Python中pynag.Plugins.PluginHelper.add_summary方法的典型用法代码示例。如果您正苦于以下问题:Python PluginHelper.add_summary方法的具体用法?Python PluginHelper.add_summary怎么用?Python PluginHelper.add_summary使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类pynag.Plugins.PluginHelper
的用法示例。
在下文中一共展示了PluginHelper.add_summary方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: main
# 需要导入模块: from pynag.Plugins import PluginHelper [as 别名]
# 或者: from pynag.Plugins.PluginHelper import add_summary [as 别名]
def main():
p = PluginHelper()
# Warn on inactive
level = 2
service_status = get_service_status(sys.argv[1])
if loaded(service_status)[0] is False:
p.exit(3,
"%s - %s" % (service_status['name'],
loaded(service_status)[1]),
"\n" + service_status['unparsed'])
active = service_status['headers']['Active'][0]
if active.startswith("inactive") or active.startswith('failed'):
p.add_status(level)
elif active.startswith("active"):
p.add_status(0)
else:
p.add_status(3)
p.add_summary("%s - %s" % ( service_status['name'], active))
p.add_long_output("\n" + service_status['unparsed'])
p.exit()
示例2: testPluginHelper
# 需要导入模块: from pynag.Plugins import PluginHelper [as 别名]
# 或者: from pynag.Plugins.PluginHelper import add_summary [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)
示例3: main
# 需要导入模块: from pynag.Plugins import PluginHelper [as 别名]
# 或者: from pynag.Plugins.PluginHelper import add_summary [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()
示例4: len
# 需要导入模块: from pynag.Plugins import PluginHelper [as 别名]
# 或者: from pynag.Plugins.PluginHelper import add_summary [as 别名]
if len(services) == 0:
# if there are no running services, print the message
print "no service running at host"
# we don't want to return a icinga output, so we just end the script here
quit()
else:
#############
# Here we check the service
#############
## convert the service name to a oid
service_oid = convert_in_oid(service)
# get the data
result = attempt_get_data(sess, service_oid)
if not result or result == "NOSUCHOBJECT":
service_status = "NOT RUNNING"
helper.status(critical)
else:
service_status = "RUNNING"
helper.status(ok)
helper.add_summary("Status of Service '" + service + "' is: " + service_status)
# Print out plugin information and exit nagios-style
helper.exit()
示例5: reload
# 需要导入模块: from pynag.Plugins import PluginHelper [as 别名]
# 或者: from pynag.Plugins.PluginHelper import add_summary [as 别名]
import string
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
from BeautifulSoup import BeautifulSoup
from pynag.Plugins import PluginHelper,ok,warning,critical,unknown
p = PluginHelper()
default_url = 'http://www.isanicelandicvolcanoerupting.com'
p.parser.add_option('--url', dest='url', default=default_url)
p.parse_arguments()
p.show_legacy = True
html = requests.get(p.options.url).content
soup = BeautifulSoup(html)
answer = soup.find('h3').text
p.add_summary('Source says: "%s"' % answer)
if 'yes' in answer.lower():
p.status(warning)
elif 'no' in answer.lower():
p.status(ok)
else:
p.status(unknown)
p.check_all_metrics()
p.exit()
示例6: parse
# 需要导入模块: from pynag.Plugins import PluginHelper [as 别名]
# 或者: from pynag.Plugins.PluginHelper import add_summary [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: PluginHelper
# 需要导入模块: from pynag.Plugins import PluginHelper [as 别名]
# 或者: from pynag.Plugins.PluginHelper import add_summary [as 别名]
#!/usr/bin/env python
import requests
from BeautifulSoup import BeautifulSoup
from pynag.Plugins import PluginHelper,ok,warning,critical,unknown
import simplejson as json
p = PluginHelper()
p.parser.add_option('--url', dest='url', default='http://api.gulur.is/buses/?geo=true&latitude=64.1251991&longitude=-21.8108419&accuracy=20&range=restOfDay&radius=750000')
p.parse_arguments()
html = requests.get(p.options.url).content
json_data = json.loads(html)
buses_running = len(json_data)
p.add_metric('buses running', buses_running)
p.add_summary('%s buses are currently running' % (buses_running))
print json.dumps(json_data[0], indent=4)
p.check_all_metrics()
p.exit()
示例8: Thresholds
# 需要导入模块: from pynag.Plugins import PluginHelper [as 别名]
# 或者: from pynag.Plugins.PluginHelper import add_summary [as 别名]
address = my_plugin.options.address
if hostname is None:
my_plugin.parser.error('-H argument is required')
# 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()
示例9: int
# 需要导入模块: from pynag.Plugins import PluginHelper [as 别名]
# 或者: from pynag.Plugins.PluginHelper import add_summary [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()
示例10: verify_host
# 需要导入模块: from pynag.Plugins import PluginHelper [as 别名]
# 或者: from pynag.Plugins.PluginHelper import add_summary [as 别名]
"1" : "Fault",
"2" : "N/A",
"3" : "Pos1",
"4" : "Pos2"
}
if __name__ == "__main__":
# verify that a hostname is set
verify_host(host, helper)
# The default return value should be always OK
helper.status(ok)
sess = netsnmp.Session(Version=version, DestHost=host, Community=community)
# here we check the status
for name in sorted(oids):
# get the snmp values
value = get_data(sess, oids[name], helper)
helper.add_summary("%s: %s" % (name, status[value]))
# if the value is 1 / Fault the status is set to critical
if value == "1":
helper.status(critical)
# Print out plugin information and exit nagios-style
helper.exit()
示例11: PluginHelper
# 需要导入模块: from pynag.Plugins import PluginHelper [as 别名]
# 或者: from pynag.Plugins.PluginHelper import add_summary [as 别名]
tn.write('{}\n'.format(word))
return tn.read_all()
if __name__ == '__main__':
plugin = PluginHelper()
plugin.parser.add_option("-H","--hostname", help="Zookeeper's host", default='127.0.0.1')
plugin.parser.add_option("-p","--port", help="Zookeeper's port", default='2181')
plugin.parse_arguments()
try:
zk = ZkClient(plugin.options.hostname, plugin.options.port)
except socket.error:
plugin.status(critical)
plugin.add_summary("Can't connect to {}:{}".format(plugin.options.hostname, plugin.options.port))
plugin.exit()
try:
if zk.cmd('ruok') != 'imok':
plugin.status(critical)
plugin.add_summary("Command 'ruok' failed")
plugin.exit()
except socket.error, socket.timeout:
plugin.status(critical)
plugin.add_summary("Can't connect to {}:{}".format(plugin.options.hostname, plugin.options.port))
plugin.exit()
try:
if zk.cmd('isro') != 'rw':
plugin.status(critical)
示例12: show_response
# 需要导入模块: from pynag.Plugins import PluginHelper [as 别名]
# 或者: from pynag.Plugins.PluginHelper import add_summary [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()
示例13: PluginHelper
# 需要导入模块: from pynag.Plugins import PluginHelper [as 别名]
# 或者: from pynag.Plugins.PluginHelper import add_summary [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))
示例14: time
# 需要导入模块: from pynag.Plugins import PluginHelper [as 别名]
# 或者: from pynag.Plugins.PluginHelper import add_summary [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()
示例15: PluginHelper
# 需要导入模块: from pynag.Plugins import PluginHelper [as 别名]
# 或者: from pynag.Plugins.PluginHelper import add_summary [as 别名]
from pynag.Plugins import PluginHelper, ok, unknown
p = PluginHelper()
default_url = 'http://appyhour.herokuapp.com/iceland/'
p.parser.add_option('--url', dest='url', default=default_url)
p.parse_arguments()
p.show_legacy = True
try:
html = requests.get(p.options.url).content
except Exception, e:
p.status(unknown)
p.add_summary("%s error encountered while trying to connect to api hour api: %s" % (type(e), e))
p.exit()
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')