forked from nicolargo/checkglances
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcheckglances.py
executable file
·527 lines (463 loc) · 19.2 KB
/
checkglances.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
#!/usr/bin/env python
#
# CheckGlances
# Get stats from a Glances server
#
# Copyright (C) Nicolargo 2012 <[email protected]>
#
# This script is distributed
# under the terms of the GNU Lesser General Public License as published
# by the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This script is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
# See the GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.";
#
__appname__ = 'CheckGlances'
__version__ = "0.4"
__author__ = "Nicolas Hennion <[email protected]>"
__licence__ = "LGPL"
# Import libs
#############
import sys
import getopt
import xmlrpclib
import json
import gettext
gettext.install(__appname__)
# Classes
#########
class nagiospluginskeleton(object):
"""
A top level skeleton for a Nagios plugin
Do NOT use this class
USE the child class nagiosplugin to define your plugin (see below)
"""
# http://nagiosplug.sourceforge.net/developer-guidelines.html
return_codes = {'OK': 0,
'WARNING': 1,
'CRITICAL': 2,
'UNKNOWN': 3 }
def __init__(self):
"""
Init the class
"""
self.verbose = False
def version(self):
"""
Returns the plugin syntax
"""
print(_("%s version %s") % (__appname__, __version__))
def syntax(self):
"""
Returns the plugin syntax
"""
print(_("Syntax: %s -Vhv -H <host> [-p <port>] [-P <password>] -s <stat> [-e <param>] -w <warning> -c <critical>") % (format(sys.argv[0])))
print("")
print(" "+_("-V Display version and exit"))
print(" "+_("-h Display syntax and exit"))
print(" "+_("-v Set verbose mode on (default is off)"))
print(" "+_("-H <hosts> Glances server hostname or IP address"))
print(" "+_("-w <warning> Warning threshold"))
print(" "+_("-c <critical> Critical threshold"))
def setverbose(self, verbose = True):
self.verbose = verbose
def log(self, message):
if (self.verbose):
print(message)
def exit(self, code):
"""
The end...
"""
sys.exit(self.return_codes[code])
class nagiosplugin(nagiospluginskeleton):
"""
These class defines your Nagios Plugin
"""
statslist = ('cpu', 'load', 'mem', 'swap', 'process', 'net', 'diskio', 'fs')
statsparamslist = ( 'net' , 'diskio' , 'fs')
def syntax(self):
# Display the standard syntax
super(nagiosplugin, self).syntax()
# Display the specific syntax
print(" "+_("-p <port> Glances server TCP port (default 61209)"))
print(" "+_("-P <password> Glances server password (optional)"))
print(" "+_("-s <stat> Select stat to grab: %s")
% ", ".join(self.statslist))
print(" "+_("-e <param> Extended parameter for stat: %s")
% ", ".join(self.statsparamslist))
def methodexist(self, server, method):
# Check if a method exist on the RCP server
return method in server.system.listMethods()
def check(self, host, warning, critical, **args):
"""
INPUT
host: hostname or IP address to check
warning: warning value
critical: critical value
args: optional arguments
OUTPUT
One line text message on STDOUT
Return code
self.exit('OK') if check is OK
self.exit('WARNING') if check is WARNING
self.exit('CRITICAL') if check is WARNING
self.exit('UNKNOWN') if check ERROR
"""
# Connect to the Glances server
self.log(_("Check host: %s") % host)
if (args['password'] != ''):
gs = xmlrpclib.ServerProxy('http://%s:%s@%s:%d' % \
('glances', args['password'], host, int(args['port'])))
else:
gs = xmlrpclib.ServerProxy('http://%s:%d' % (host, int(args['port'])))
self.log(_("Others args: %s") % args)
# Test RCP server connection
try:
# getSystem() was born in the 1.5.2 version of Glances
gs.getSystem()
except xmlrpclib.Fault as err:
# getSystem method unknown ?... mmhhh...
self.log(_("Warning: %s works better with Glances server 1.5.2 or higher") % __appname__)
pass
except:
print(_("Connection to Glances server failed"))
self.exit('UNKNOWN')
# DEBUG
#~ print gs.system.listMethods()
#~ print eval(gs.getSystem())
# END DEBUG
if (args['stat'] == "cpu"):
# Get and eval CPU stat
if (self.methodexist(gs, "getCpu")):
try:
cpu = json.loads(gs.getCpu())
except xmlrpclib.Fault as err:
print(_("Can not run the Glances method: getCpu"))
self.exit('UNKNOWN')
else:
self.log(cpu)
else:
print(_("Unknown method on the Glances server: getCpu"))
self.exit('UNKNOWN')
#~ print cpu
#~ If user|kernel|nice CPU is > 70%, then status is set to "WARNING".
#~ If user|kernel|nice CPU is > 90%, then status is set to "CRITICAL".
if (warning is None): warning = 70
if (critical is None): critical = 90
checked_value = 100 - cpu['idle']
# Plugin output
checked_message = _("CPU consumption: %.2f%%") % checked_value
# Performance data
checked_message += _(" | 'percent'=%.2f") % checked_value
for key in cpu:
checked_message += " '%s'=%.2f" % (key, cpu[key])
elif (args['stat'] == "load"):
# Get and eval CORE and LOAD stat
if (self.methodexist(gs, "getCore")):
try:
core = gs.getCore()
except xmlrpclib.Fault as err:
print(_("Can not run the Glances method: getLoad"))
self.exit('UNKNOWN')
else:
self.log(core)
else:
print(_("Can not run the Glances method: getCore"))
self.exit('UNKNOWN')
if (self.methodexist(gs, "getLoad")):
try:
load = eval(gs.getLoad())
except xmlrpclib.Fault as err:
print(_("Can not run the Glances method: getLoad"))
self.exit('UNKNOWN')
else:
self.log(load)
else:
print(_("Unknown method on the Glances server: getLoad"))
self.exit('UNKNOWN')
#~ If average load is > 1*Core, then status is set to "WARNING".
#~ If average load is > 5*Core, then status is set to "CRITICAL".
if (warning is None): warning = 1
if (critical is None): critical = 5
warning *= core
critical *= core
checked_value = load['min5']
# Plugin output
checked_message = _("LOAD last 5 minutes: %.2f") % checked_value
# Performance data
checked_message += _(" |")
for key in load:
checked_message += " '%s'=%.2f" % (key, load[key])
elif (args['stat'] == "mem"):
# Get and eval MEM stat
if (self.methodexist(gs, "getMem")):
try:
mem = json.loads(gs.getMem())
except xmlrpclib.Fault as err:
print(_("Can not run the Glances method: getMem"))
self.exit('UNKNOWN')
else:
self.log(mem)
else:
print(_("Unknown method on the Glances server: getMem"))
self.exit('UNKNOWN')
#~ If memory is > 70%, then status is set to "WARNING".
#~ If memory is > 90%, then status is set to "CRITICAL"
if (warning is None): warning = 70
if (critical is None): critical = 90
checked_value = mem['percent']
# Plugin output
checked_message = _("MEM consumption: %.2f%%") % checked_value
# Performance data
checked_message += _(" |")
for key in mem:
checked_message += " '%s'=%.2f" % (key, mem[key])
elif (args['stat'] == "swap"):
# Get and eval MEM stat
if (self.methodexist(gs, "getMemSwap")):
try:
swap = json.loads(gs.getMemSwap())
except xmlrpclib.Fault as err:
print(_("Can not run the Glances method: getMemSwap"))
self.exit('UNKNOWN')
else:
self.log(swap)
else:
print(_("Unknown method on the Glances server: getMemSwap"))
self.exit('UNKNOWN')
#~ If memory is > 70%, then status is set to "WARNING".
#~ If memory is > 90%, then status is set to "CRITICAL"
if (warning is None): warning = 70
if (critical is None): critical = 90
checked_value = swap['percent']
# Plugin output
checked_message = _("SWAP consumption: %.2f%%") % checked_value
# Performance data
checked_message += _(" |")
for key in swap:
checked_message += " '%s'=%.2f" % (key, swap[key])
elif (args['stat'] == "process"):
# Get and eval Process stat
if (self.methodexist(gs, "getProcessCount")):
try:
process = json.loads(gs.getProcessCount())
except xmlrpclib.Fault as err:
print(_("Can not run the Glances method: getProcessCount"))
self.exit('UNKNOWN')
else:
self.log(process)
else:
print(_("Unknown method on the Glances server: getProcessCount"))
self.exit('UNKNOWN')
#~ If running process is > 50, then status is set to "WARNING".
#~ If running process is > 100, then status is set to "CRITICAL"
if (warning is None): warning = 50
if (critical is None): critical = 100
checked_value = process['running']
# Plugin output
checked_message = _("Running processes: %d") % checked_value
# Performance data
checked_message += _(" |")
for key in process:
checked_message += " '%s'=%d" % (key, process[key])
elif (args['stat'] == "net"):
# Get and eval Network stat
if (self.methodexist(gs, "getNetwork")):
try:
net = json.loads(gs.getNetwork())
except xmlrpclib.Fault as err:
print(_("Can not run the Glances method: getNetwork"))
self.exit('UNKNOWN')
else:
self.log(net)
else:
print(_("Unknown method on the Glances server: getNetwork"))
self.exit('UNKNOWN')
#~ If net[param] > 60 Mbps, then status is set to "WARNING".
#~ If net[param] > 80 Mbps, then status is set to "CRITICAL"
# Values are in Kbyte/second
if (warning is None): warning = 7500000
if (critical is None): critical = 10000000
checked_value = -1
for interface in net:
if interface['interface_name'] == args['statparam']:
checked_value = max(interface["tx"], interface["rx"])
break
if (checked_value == -1):
print(_("Unknown network interface: %s") % args['statparam'])
self.exit('UNKNOWN')
# Plugin output
checked_message = _("Network rate: %d") % checked_value
# Performance data
checked_message += _(" |")
for key in interface:
checked_message += " '%s'=%s" % (key, interface[key])
elif (args['stat'] == "diskio"):
# Get and eval Network stat
# !!! Not yet available
# Need to implement "read_rate" and "write_rate" In Glances
print(_("Not yet available. Sorry, had to wait next version"))
self.exit('UNKNOWN')
if (self.methodexist(gs, "getDiskIO")):
try:
diskio = json.loads(gs.getDiskIO())
except xmlrpclib.Fault as err:
print(_("Can not run the Glances method: getDiskIO"))
self.exit('UNKNOWN')
else:
self.log(diskio)
else:
print(_("Unknown method on the Glances server: getDiskIO"))
self.exit('UNKNOWN')
#~ If diskio[param] > 30 Mbytes/sec, then status is set to "WARNING".
#~ If diskio[param] > 40 MBytes/sec, then status is set to "CRITICAL"
if (warning is None): warning = 30000000
if (critical is None): critical = 40000000
checked_value = -1
for disk in diskio:
if disk['disk_name'] == args['statparam']:
checked_value = max(disk["read_rate"], disk["write_rate"])
break
if (checked_value == -1):
print(_("Unknown disk: %s") % args['statparam'])
self.exit('UNKNOWN')
# Plugin output
checked_message = _("Disk IO: %d") % checked_value
# Performance data
checked_message += _(" |")
for key in disk:
checked_message += " '%s'=%s" % (key, disk[key])
elif (args['stat'] == "fs"):
# Get and eval Network stat
if (self.methodexist(gs, "getFs")):
try:
fs = json.loads(gs.getFs())
except xmlrpclib.Fault as err:
print(_("Can not run the Glances method: getFs"))
self.exit('UNKNOWN')
else:
self.log(fs)
else:
print(_("Unknown method on the Glances server: getFs"))
self.exit('UNKNOWN')
#~ If fs[param] > %, then status is set to "WARNING".
#~ If fs[param] > %, then status is set to "CRITICAL"
if (warning is None): warning = 70
if (critical is None): critical = 90
checked_value = -1
for disk in fs:
if disk['mnt_point'] == args['statparam']:
checked_value = 100 - (100 * disk["avail"] / disk["size"])
break
if (checked_value == -1):
print(_("Unknown mounting point: %s") % args['statparam'])
self.exit('UNKNOWN')
# Plugin output
checked_message = _("FS using space: %d%%") % checked_value
# Performance data
checked_message += _(" |")
for key in disk:
checked_message += " '%s'=%s" % (key, disk[key])
else:
# Else...
print(_("Unknown stat: %s") % args['stat'])
self.exit('UNKNOWN')
# Display the message
self.log(_("Warning threshold: %s" % warning))
self.log(_("Critical threshold: %s" % critical))
print(checked_message)
# Return code
if (checked_value < warning):
self.exit('OK')
elif (checked_value < critical):
self.exit('WARNING')
elif (checked_value < critical):
self.exit('CRITICAL')
# Main function
###############
def main():
# Create an instance of the your plugin
plugin = nagiosplugin()
# Manage command line arguments
if len(sys.argv) < 2:
plugin.syntax()
plugin.exit('UNKNOWN')
try:
# Add optional tag definition here
# ...
opts, args = getopt.getopt(sys.argv[1:], "VhvH:p:P:w:c:s:e:")
except getopt.GetoptError, err:
plugin.syntax()
plugin.exit('UNKNOWN')
# Default parameters
warning = None
critical = None
port = 61209
password = ""
statparam = ""
for opt, arg in opts:
# Standard tag definition
if opt in ("-V", "--version"):
plugin.version()
plugin.exit('OK')
elif opt in ("-h", "--help"):
plugin.syntax()
plugin.exit('OK')
elif opt in ("-v", "--verbose"):
plugin.setverbose()
print(_("Verbose mode ON"))
elif opt in ("-H", "--hostname"):
host = arg
elif opt in ("-p", "--port"):
port = arg
elif opt in ("-P", "--password"):
password = arg
elif opt in ("-w", "--warning"):
warning = arg
elif opt in ("-c", "--critical"):
critical = arg
elif opt in ("-s", "--stat"):
stat = arg
elif opt in ("-e", "--statparam"):
statparam = arg
else:
# Tag is UNKNOW
plugin.syntax()
plugin.exit('UNKNOWN')
# Check args
try:
host
except:
print(_("Need to specified an hostname or IP address"))
plugin.exit('UNKNOWN')
try:
stat
except:
print(_("Need to specified the stat to grab (use the -s tag)"))
plugin.exit('UNKNOWN')
else:
if stat not in plugin.statslist:
print(_("Use -s with value in %s") % ", ".join(plugin.statslist))
plugin.exit('UNKNOWN')
if (stat == "net") and (statparam == ""):
print(_("You need to specified the interface name with -e <interface>"))
plugin.exit('UNKNOWN')
if (stat == "diskio") and (statparam == ""):
print(_("You need to specified the disk name with -e <disk>"))
plugin.exit('UNKNOWN')
if (stat == "fs") and (statparam == ""):
print(_("You need to specified the mounting point with -e <fs>"))
plugin.exit('UNKNOWN')
# Do the check
plugin.check(host, warning, critical, port = port, password = password, \
stat = stat, statparam = statparam)
# Main program
##############
if __name__ == "__main__":
main()