monitoringplugin.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626
  1. __version__ = '0.0.100802'
  2. __all__ = ['MonitoringPlugin', 'SNMPMonitoringPlugin']
  3. import optparse, os, re, sys
  4. try:
  5. import netsnmp
  6. except ImportError:
  7. pass
  8. class MonitoringPlugin(object):
  9. RETURNSTRINGS = { 0: "OK", 1: "WARNING", 2: "CRITICAL", 3: "UNKNOWN", 127: "UNKNOWN" }
  10. RETURNCODE = { 'OK': 0, 'WARNING': 1, 'CRITICAL': 2, 'UNKNOWN': 3 }
  11. returncode_priority = [2, 1, 3, 0]
  12. powers_binary = ['', 'Ki', 'Mi', 'Gi', 'Ti', 'Pi', 'Ei', 'Zi']
  13. powers_binary_lower = [ p.lower() for p in powers_binary]
  14. powers_si = ['', 'k', 'M', 'G', 'T', 'P', 'E', 'Z']
  15. powers_si_lower = [ p.lower() for p in powers_si]
  16. def __init__(self, *args, **kwargs):
  17. self.__pluginname = kwargs.get('pluginname') or ''
  18. self.__version = kwargs.get('version') or None
  19. self.__tagforstatusline = kwargs.get('tagforstatusline') or ''
  20. self.__tagforstatusline = self.__tagforstatusline.replace('|', ' ')
  21. self.__description = kwargs.get('description') or None
  22. self.__output = []
  23. self.__multilineoutput = []
  24. self.__performancedata = []
  25. self.__returncode = []
  26. self.__brain_checks = []
  27. self.__brain_perfdata = []
  28. self.__brain_perfdatalabels = []
  29. self.__optparser = optparse.OptionParser(version=self.__version, description=self.__description)
  30. self._cmdlineoptions_parsed = False
  31. def add_cmdlineoption(self, shortoption, longoption, dest, help, **kwargs):
  32. self.__optparser.add_option(shortoption, longoption, dest=dest, help=help, **kwargs)
  33. def parse_cmdlineoptions(self):
  34. if self._cmdlineoptions_parsed:
  35. return
  36. # self.__optparser.add_option('-V', '--version', action='version', help='show version number and exit')
  37. self.__optparser.add_option('-v', '--verbose', dest='verbose', help='Verbosity, more for more ;-)', action='count')
  38. (self.options, self.args) = self.__optparser.parse_args()
  39. self._cmdlineoptions_parsed = True
  40. def range_to_limits(self, range):
  41. # Check if we must negate result
  42. if len(range) > 0 and range[0] == '@':
  43. negate = True
  44. range = range[1:]
  45. else:
  46. negate = False
  47. # Look for a ':'...
  48. if range.find(':') >= 0:
  49. # ... this is a range
  50. (low, high) = range.split(':')
  51. if not low:
  52. low = float(0.0)
  53. elif low[0] == '~':
  54. low = float('-infinity')
  55. else:
  56. low = float(low)
  57. if high:
  58. high = float(high)
  59. else:
  60. high = float('infinity')
  61. elif len(range) == 0:
  62. low = float('-infinity')
  63. high = float('infinity')
  64. else:
  65. # ... this is just a number
  66. low = float(0.0)
  67. high = float(range)
  68. return (low, high, negate)
  69. def value_in_range(self, value, range):
  70. (low, high, negate) = self.range_to_limits(range)
  71. if value < low or value > high:
  72. result = False
  73. else:
  74. result = True
  75. if negate:
  76. result = not result
  77. return result
  78. def value_wc_to_returncode(self, value, range_warn, range_crit):
  79. if not self.value_in_range(value, range_crit):
  80. return 2
  81. elif not self.value_in_range(value, range_warn):
  82. return 1
  83. return 0
  84. def is_float(self, string):
  85. try:
  86. float(string)
  87. return True
  88. except ValueError:
  89. return False
  90. def special_value_wc_to_returncode(self, value, warn, crit):
  91. # Special add on: WARN > CRIT
  92. if self.is_float(warn) and self.is_float(crit) and float(warn) > float(crit):
  93. # Test if value is *smaller* than thresholds
  94. warn = '@0:' + warn
  95. crit = '@0:' + crit
  96. return self.value_wc_to_returncode(value, warn, crit)
  97. def add_output(self, value):
  98. self.__output.append(value)
  99. def add_multilineoutput(self, value):
  100. self.__multilineoutput.append(value)
  101. def format_performancedata(self, label, value, unit, *args, **kwargs):
  102. label = label.lstrip().rstrip()
  103. if re.search('[=\' ]', label):
  104. label = '\'' + label + '\''
  105. perfdata = label + '=' + str(value)
  106. if unit:
  107. perfdata += str(unit).lstrip().rstrip()
  108. for key in ['warn', 'crit', 'min', 'max']:
  109. perfdata += ';'
  110. if key in kwargs and kwargs[key]!=None:
  111. perfdata += str(kwargs[key])
  112. return perfdata
  113. def add_performancedata(self, perfdata):
  114. self.__performancedata.append(perfdata)
  115. def format_add_performancedata(self, label, value, unit, *args, **kwargs):
  116. self.add_performancedata(self.format_performancedata(label, value, unit, *args, **kwargs))
  117. def add_returncode(self, value):
  118. self.__returncode.append(value)
  119. def tagtarget(self, tag, target):
  120. if target:
  121. return str(tag) + ':' + str(target)
  122. else:
  123. return str(tag)
  124. def remember_check(self, tag, returncode, output, multilineoutput=None, perfdata=None, target=None):
  125. check = {}
  126. check['tag'] = tag
  127. check['returncode'] = returncode
  128. check['output'] = output
  129. check['multilineoutout'] = multilineoutput
  130. check['perfdata'] = perfdata
  131. check['target'] = target
  132. self.remember_perfdata(perfdata)
  133. self.__brain_checks.append(check)
  134. return check
  135. def remember_perfdata(self, perfdata=None):
  136. if perfdata:
  137. for pd in perfdata:
  138. if pd['label'] in self.__brain_perfdatalabels:
  139. pdidx = self.__brain_perfdatalabels.index(pd['label'])
  140. self.__brain_perfdata[pdidx] = pd
  141. else:
  142. self.__brain_perfdata.append(pd)
  143. self.__brain_perfdatalabels.append(pd['label'])
  144. def dump_brain(self):
  145. return (self.__brain_checks, self.__brain_perfdata)
  146. def brain2output(self):
  147. out = [[], [], [], []]
  148. for check in self.__brain_checks:
  149. tagtarget = self.tagtarget(check['tag'], check.get('target'))
  150. returncode = check.get('returncode') or 0
  151. self.add_returncode(returncode)
  152. out[returncode].append(tagtarget)
  153. #if returncode == 0:
  154. # self.add_output(tagtarget)
  155. #else:
  156. # self.add_output(tagtarget + '(' + check.get('output') + ') ')
  157. self.add_multilineoutput(self.RETURNSTRINGS[returncode] + ' ' + tagtarget + ' - ' + check.get('output'))
  158. if check.get('multilineoutput'):
  159. self.add_multilineoutput(check.get('multilineoutput'))
  160. statusline = []
  161. for retcode in [2, 1, 3, 0]:
  162. if len(out[retcode]):
  163. statusline.append(str(len(out[retcode])) + ' ' + self.RETURNSTRINGS[retcode] + ': ' + '/'.join(out[retcode]))
  164. statusline = ', '.join(statusline)
  165. self.add_output(statusline)
  166. for pd in self.__brain_perfdata:
  167. self.format_add_performancedata(**pd)
  168. def value_to_human_binary(self, value, unit=''):
  169. for power in self.powers_binary:
  170. if value < 1024.0:
  171. return "%3.1f%s%s" % (value, power, unit)
  172. value /= 1024.0
  173. if float(value) not in [float('inf'), float('-inf')]:
  174. return "%3.1fYi%s" % (value, unit)
  175. else:
  176. return value
  177. def value_to_human_si(self, value, unit=''):
  178. for power in self.powers_si:
  179. if value < 1000.0:
  180. return "%3.1f%s%s" % (value, power, unit)
  181. value /= 1000.0
  182. if float(value) not in [float('inf'), float('-inf')]:
  183. return "%3.1fY%s" % (value, unit)
  184. else:
  185. return value
  186. def human_to_number(self, value, total=None):
  187. if total:
  188. if not self.is_float(total):
  189. total = self.human_to_number(total)
  190. if self.is_float(value):
  191. return float(value)
  192. elif value[-1] == '%':
  193. if total:
  194. return float(value[:-1])/100.0 * float(total)
  195. else:
  196. return float(value[:-1])
  197. elif value[-1].lower() in self.powers_si_lower:
  198. return 1000.0 ** self.powers_si_lower.index(value[-1].lower()) * float(value[:-1])
  199. elif value[-2:].lower() in self.powers_binary_lower:
  200. return 1024.0 ** self.powers_binary_lower.index(value[-2:].lower()) * float(value[:-2])
  201. else:
  202. return value
  203. def range_dehumanize(self, range, total=None):
  204. newrange = ''
  205. if len(range):
  206. if range[0] == '@':
  207. newrange += '@'
  208. range = range[1:]
  209. parts = range.split(':')
  210. newrange += str(self.human_to_number(parts[0], total))
  211. if len(parts) > 1:
  212. newrange += ':' + str(self.human_to_number(parts[1], total))
  213. if range != newrange:
  214. self.verbose(3, 'Changed range/thresold from "' + range + '" to "' + newrange + '"')
  215. return newrange
  216. else:
  217. return ''
  218. def verbose(self, level, output):
  219. if level <= self.options.verbose:
  220. print 'V' + str(level) + ': ' + output
  221. def exit(self):
  222. for returncode in self.returncode_priority:
  223. if returncode in self.__returncode:
  224. break
  225. self.back2nagios(returncode, statusline=self.__output, multiline=self.__multilineoutput, performancedata=self.__performancedata)
  226. def back2nagios(self, returncode, statusline=None, multiline=None, performancedata=None, subtag=None, exit=True):
  227. # FIXME: Make 'returncode' also accept strings
  228. # Build status line
  229. out = self.__tagforstatusline
  230. if subtag:
  231. out += '(' + subtag.replace('|', ' ') + ')'
  232. out += ' ' + self.RETURNSTRINGS[returncode]
  233. # Check if there's a status line text and build it
  234. if statusline:
  235. out += ' - '
  236. if type(statusline) == str:
  237. out += statusline
  238. elif type(statusline) in [list, tuple]:
  239. out += ', '.join(statusline).replace('|', ' ')
  240. # Check if we have multi line output and build it
  241. if multiline:
  242. if type(multiline) == str:
  243. out += '\n' + multiline.replace('|', ' ')
  244. elif type(multiline) in [list, tuple]:
  245. out += '\n' + '\n'.join(multiline).replace('|', ' ')
  246. # Check if there's perfdata
  247. if performancedata:
  248. out += '|'
  249. if type(performancedata) == str:
  250. out += performancedata
  251. elif type(performancedata) in [list, tuple]:
  252. out += ' '.join(performancedata).replace('|', ' ')
  253. # Exit program or return output line(s)
  254. if exit:
  255. print out
  256. sys.exit(returncode)
  257. else:
  258. return (returncode, out)
  259. ##############################################################################
  260. class SNMPMonitoringPlugin(MonitoringPlugin):
  261. def __init__(self, *args, **kwargs):
  262. # Same as "MonitoringPlugin.__init__(*args, **kwargs)" but a little bit more flexible
  263. #super(MonitoringPlugin, self).__init__(*args, **kwargs)
  264. MonitoringPlugin.__init__(self, *args, **kwargs)
  265. self.add_cmdlineoption('-H', '', 'host', 'Host to check', default='127.0.0.1')
  266. self.add_cmdlineoption('-P', '', 'snmpversion', 'SNMP protocol version', default='1')
  267. self.add_cmdlineoption('-C', '', 'snmpauth', 'SNMP v1/v2c community OR SNMP v3 quadruple', default='public')
  268. self.add_cmdlineoption('', '--snmpcmdlinepath', 'snmpcmdlinepath', 'Path to "snmpget" and "snmpwalk"', default='/usr/bin')
  269. # FIXME
  270. self.add_cmdlineoption('', '--nonetsnmp', 'nonetsnmp', 'Do not use NET-SNMP python bindings', action='store_true')
  271. # self.__optparser.add_option('', '--nonetsnmp', dest='nonetsnmp', help='Do not use NET-SNMP python bindings', action='store_true')
  272. self.__SNMP_Cache = {}
  273. self.__use_netsnmp = False
  274. self.__prepared_snmp = False
  275. def prepare_snmp(self):
  276. if not self._cmdlineoptions_parsed:
  277. self.parse_cmdlineoptions()
  278. if not self.options.nonetsnmp:
  279. try:
  280. import netsnmp
  281. self.__use_netsnmp = True
  282. except ImportError:
  283. pass
  284. if self.__use_netsnmp:
  285. self.verbose(1, 'Using NET-SNMP Python bindings')
  286. self.SNMPGET_wrapper = self.__SNMPGET_netsnmp
  287. self.SNMPWALK_wrapper = self.__SNMPWALK_netsnmp
  288. if self.options.snmpversion == '2c':
  289. self.options.snmpversion = '2'
  290. else:
  291. self.verbose(1, 'Using NET-SNMP command line tools')
  292. self.SNMPGET_wrapper = self.__SNMPGET_cmdline
  293. self.SNMPWALK_wrapper = self.__SNMPWALK_cmdline
  294. # Building command lines
  295. self.__CMDLINE_get = os.path.join(self.options.snmpcmdlinepath, 'snmpget') + ' -OqevtU '
  296. self.__CMDLINE_walk = os.path.join(self.options.snmpcmdlinepath, 'snmpwalk') + ' -OqevtU '
  297. if self.options.snmpversion in [1, 2, '1', '2', '2c']:
  298. if self.options.snmpversion in [2, '2']:
  299. self.options.snmpversion = '2c'
  300. self.__CMDLINE_get += ' -v' + str(self.options.snmpversion) + ' -c' + self.options.snmpauth + ' '
  301. self.__CMDLINE_walk += ' -v' + str(self.options.snmpversion) + ' -c' + self.options.snmpauth + ' '
  302. elif options.snmpversion == [3, '3']:
  303. # FIXME: Better error handling
  304. try:
  305. snmpauth = self.options.snmpauth.split(':')
  306. self.__CMDLINE_get += ' -v3 -l' + snmpauth[0] + ' -u' + snmpauth[1] + ' -a' + snmpauth[2] + ' -A' + snmpauth[3] + ' '
  307. self.__CMDLINE_walk += ' -v3 -l' + snmpauth[0] + ' -u' + snmpauth[1] + ' -a' + snmpauth[2] + ' -A' + snmpauth[3] + ' '
  308. except:
  309. self.back2nagios(3, 'Could not build SNMPv3 command line, need "SecLevel:SecName:AuthProtocol:AuthKey"')
  310. else:
  311. self.back2nagios(3, 'Unknown SNMP version "' + str(self.options.snmpversion) + '"')
  312. self.__CMDLINE_get += ' ' + self.options.host + ' %s 2>/dev/null'
  313. self.__CMDLINE_walk += ' ' + self.options.host + ' %s 2>/dev/null'
  314. self.verbose(3, 'Using commandline: ' + self.__CMDLINE_get)
  315. self.verbose(3, 'Using commandline: ' + self.__CMDLINE_walk)
  316. self.__prepared_snmp = True
  317. def find_index_for_value(self, list_indexes, list_values, wanted):
  318. self.verbose(2, 'Look for "' + str(wanted) + '"')
  319. index = None
  320. if len(list_indexes) != len(list_values):
  321. self.verbose(1, 'Length of index and value lists do not match!')
  322. return None
  323. try:
  324. index = list_values.index(wanted)
  325. index = list_indexes[index]
  326. except ValueError:
  327. pass
  328. if index:
  329. self.verbose(2, 'Found "' + str(wanted) +'" with index "' + str(index) + '"')
  330. else:
  331. self.verbose(2, 'Nothing found!')
  332. return str(index)
  333. def find_in_table(self, oid_index, oid_values, wanted):
  334. self.verbose(2, 'Look for "' + str(wanted) + '" in "' + str(oid_values) +'"')
  335. index = None
  336. indexes = list(self.SNMPWALK(oid_index))
  337. values = list(self.SNMPWALK(oid_values))
  338. if len(indexes) != len(values):
  339. self.back2nagios(3, 'Different data from 2 SNMP Walks!')
  340. return str(self.find_index_for_value(indexes, values, wanted))
  341. def SNMPGET(self, baseoid, idx=None, exitonerror=True):
  342. if type(baseoid) in (list, tuple) and idx != None:
  343. idx = str(idx)
  344. if self.options.snmpversion in [1, '1']:
  345. value_low = long(self.SNMPGET_wrapper(baseoid[1] + '.' + idx, exitonerror=exitonerror))
  346. if value_low < 0L:
  347. value_low += 2 ** 32
  348. value_hi = long(self.SNMPGET_wrapper(baseoid[2] + '.' + idx, exitonerror=exitonerror))
  349. if value_hi < 0L:
  350. value_hi += 2 ** 32
  351. return value_hi * 2L ** 32L + value_low
  352. elif self.options.snmpversion in [2, 3, '2', '2c', '3']:
  353. return long(self.SNMPGET_wrapper(baseoid[0] + '.' + idx, exitonerror=exitonerror))
  354. elif type(baseoid) in (str, ) and idx != None:
  355. return self.SNMPGET_wrapper(baseoid + str(idx), exitonerror=exitonerror)
  356. else:
  357. return self.SNMPGET_wrapper(baseoid, exitonerror=exitonerror)
  358. def SNMPWALK(self, baseoid, exitonerror=True):
  359. return self.SNMPWALK_wrapper(baseoid, exitonerror=exitonerror)
  360. def __SNMPGET_netsnmp(self, oid, exitonerror=True):
  361. if not self.__prepared_snmp:
  362. self.prepare_snmp()
  363. if oid in self.__SNMP_Cache:
  364. self.verbose(2, "%40s -> (CACHED) %s" % (oid, self.__SNMP_Cache[oid]))
  365. return self.__SNMP_Cache[oid]
  366. result = netsnmp.snmpget(oid, Version=int(self.options.snmpversion), DestHost=self.options.host, Community=self.options.snmpauth)[0]
  367. if not result:
  368. if exitonerror:
  369. self.back2nagios(3, 'Timeout or no answer from "%s" looking for "%s"' % (self.options.host, oid))
  370. else:
  371. return None
  372. self.__SNMP_Cache[oid] = result
  373. self.verbose(2, "%40s -> %s" % (oid, result))
  374. return result
  375. def __SNMPWALK_netsnmp(self, oid, exitonerror=True):
  376. if not self.__prepared_snmp:
  377. self.prepare_snmp()
  378. if oid in self.__SNMP_Cache:
  379. self.verbose(2, "%40s -> (CACHED) %s" % (oid, self.__SNMP_Cache[oid]))
  380. return self.__SNMP_Cache[oid]
  381. result = netsnmp.snmpwalk(oid, Version=int(self.options.snmpversion), DestHost=self.options.host, Community=self.options.snmpauth)
  382. if not result:
  383. if exitonerror:
  384. self.back2nagios(3, 'Timeout or no answer from "%s" looking for "%s"' % (self.options.host, oid))
  385. else:
  386. return None
  387. self.__SNMP_Cache[oid] = result
  388. self.verbose(2, "%40s -> %s" % (oid, result))
  389. return result
  390. def __SNMPGET_cmdline(self, oid, exitonerror=True):
  391. if not self.__prepared_snmp:
  392. self.prepare_snmp()
  393. cmdline = self.__CMDLINE_get % oid
  394. self.verbose(2, cmdline)
  395. cmd = os.popen(cmdline)
  396. out = cmd.readline().rstrip().replace('"','')
  397. retcode = cmd.close()
  398. if retcode:
  399. if not exitonerror:
  400. return None
  401. if retcode == 256:
  402. self.back2nagios(3, 'Timeout - no SNMP answer from "' + self.options.host + '"')
  403. elif retcode ==512:
  404. self.back2nagios(3, 'OID "' + oid + '" not found')
  405. else:
  406. self.back2nagios(3, 'Unknown error code "' + str(retcode) + '" from command line utils')
  407. self.verbose(1, out)
  408. return out
  409. def __SNMPWALK_cmdline(self, oid, exitonerror=True):
  410. if not self.__prepared_snmp:
  411. self.prepare_snmp()
  412. cmdline = self.__CMDLINE_walk % oid
  413. self.verbose(2, cmdline)
  414. cmd = os.popen(cmdline)
  415. out = cmd.readlines()
  416. retcode = cmd.close()
  417. if retcode:
  418. if not exitonerror:
  419. return None
  420. if retcode == 256:
  421. self.back2nagios(3, 'Timeout - no SNMP answer from "' + self.options.host + '"')
  422. elif retcode ==512:
  423. self.back2nagios(3, 'OID "' + oid + '" not found')
  424. else:
  425. self.back2nagios(3, 'Unknown error code "' + str(retcode) + '" from command line utils')
  426. for line in range(0,len(out)):
  427. out[line] = out[line].rstrip().replace('"','')
  428. self.verbose(1, out)
  429. return out
  430. ##############################################################################
  431. def main():
  432. myplugin = MonitoringPlugin(pluginname='check_testplugin', tagforstatusline='TEST')
  433. from pprint import pprint
  434. pprint(myplugin.back2nagios(0, 'Nr. 01: Simple plugin', exit=False) )
  435. pprint(myplugin.back2nagios(0, 'Nr. 02: Simple plugin with sub tag', subtag='MySubTag', exit=False) )
  436. pprint(myplugin.back2nagios(0, 'Nr. 10: Exit Code OK', exit=False) )
  437. pprint(myplugin.back2nagios(1, 'Nr. 11: Exit Code WARNING', exit=False) )
  438. pprint(myplugin.back2nagios(2, 'Nr. 12: Exit Code CRITICAL', exit=False) )
  439. pprint(myplugin.back2nagios(3, 'Nr. 13: Exit Code UNKNOWN', exit=False) )
  440. ret = myplugin.back2nagios(0, 'Nr. 20: Plugin with string-based multiline output', 'Line 2\nLine 3\nLine4', exit=False)
  441. print ret[1]
  442. print 'Returncode: ' + str(ret[0])
  443. ret = myplugin.back2nagios(0, 'Nr. 21: Plugin with list-based multiline output', ['Line 2', 'Line 3', 'Line4'], exit=False)
  444. print ret[1]
  445. print 'Returncode: ' + str(ret[0])
  446. ret = myplugin.back2nagios(0, 'Nr. 22: Plugin with tuple-based multiline output', ('Line 2', 'Line 3', 'Line4'), exit=False)
  447. print ret[1]
  448. print 'Returncode: ' + str(ret[0])
  449. myplugin.add_performancedata('Val1', 42, '')
  450. myplugin.add_performancedata('Val2', 23, 'c', warn=10, crit=20, min=0, max=100)
  451. myplugin.add_performancedata('Val 3', '2342', 'c', warn=10, crit=20, min=0, max=100)
  452. pprint(myplugin.back2nagios(0, 'Nr. 30: With perfdatas', exit=False) )
  453. myplugin.back2nagios(0, 'Nr. 99: Exit test suite with OK')
  454. if __name__ == '__main__':
  455. main()
  456. #vim: ts=4 sw=4