forked from shinken-solutions/shinken
-
Notifications
You must be signed in to change notification settings - Fork 2
/
snmp_poller.py
1460 lines (1296 loc) · 61 KB
/
snmp_poller.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
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright (C) 2009-2012:
# Gabes Jean, naparuba@gmail.com
# Gerhard Lausser, Gerhard.Lausser@consol.de
# Gregory Starck, g.starck@gmail.com
# Hartmut Goebel, h.goebel@goebel-consult.de
# Thibault Cohen, thibault.cohen@savoirfairelinux.com
#
# This file is part of Shinken.
#
# Shinken is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Shinken 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 Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with Shinken. If not, see <http://www.gnu.org/licenses/>.
import os
import re
import sys
import glob
import signal
import time
import socket
import struct
import copy
import binascii
import getopt
import shlex
import operator
import math
from datetime import datetime, timedelta
from Queue import Empty
from shinken.log import logger
try:
import memcache
from configobj import ConfigObj, Section
from pysnmp.carrier.asynsock.dispatch import AsynsockDispatcher
from pysnmp.carrier.asynsock.dgram import udp
from pyasn1.codec.ber import encoder, decoder
from pysnmp.proto.api import v2c
except ImportError, e:
logger.error("[SnmpBooster] Import error. Maybe one of this module is missing: memcache, configobj, pysnmp")
raise ImportError(e)
from shinken.basemodule import BaseModule
from shinken.check import Check
from shinken.macroresolver import MacroResolver
properties = {
'daemons': ['poller', 'scheduler', 'arbiter'],
'type': 'snmp_poller',
'external': False,
'phases': ['running', 'late_configuration'],
# To be a real worker module, you must set this
'worker_capable': True,
}
def get_instance(mod_conf):
"""called by the plugin manager to get a poller"""
logger.info("[SnmpBooster] Get a snmp poller module for plugin %s" % mod_conf.get_name())
instance = Snmp_poller(mod_conf)
return instance
def rpn_calculator(rpn_list):
""" Reverse Polish notation calculator
"""
try:
st = []
for el in rpn_list:
if el is None:
continue
if hasattr(operator, str(el)):
y, x = st.pop(),st.pop()
z = getattr(operator, el)(x, y)
else:
z = float(el)
st.append(z)
assert len(st) <= 1
if len(st) == 1:
return(st.pop())
except Exception, e:
logger.error('[SnmpBooster] RPN calculation Error: %s - %s' % (str(e),
str(rpn_list)))
return "Calc error"
def parse_args(cmd_args):
#Default params
host = None
community = 'public3'
version = '2c'
dstemplate = None
triggergroup = None
instance = 0
instance_name = None
#Manage the options
try:
options, args = getopt.getopt(cmd_args,
'H:C:V:i:t:T:n:',
['hostname=', 'community=', 'snmp-version=',
'dstemplate=', 'triggergroup=',
'instance=', 'instance-name=' ])
except getopt.GetoptError, err:
# TODO later - Use argparse
# If we got problem, bail out
logger.error("[SnmpBooster] Error in command: definition %s" % str(err))
return (host, community, version,
triggergroup, dstemplate, instance,
instance_name,)
for option_name, value in options:
if option_name in ("-H", "--hostname"):
host = value
elif option_name in ("-C", "--community"):
community = value
elif option_name in ("-t", "--dstemplate"):
dstemplate = value
elif option_name in ("-T", "--triggergroup"):
triggergroup = value
elif option_name in ("-i", "--instance"):
instance = value
elif option_name in ("-V", "--snmp-version"):
version = value
elif option_name in ("-n", "--instance-name"):
instance_name = value
if instance and (instance.startswith('-') or instance.lower() == 'none'):
instance = None
if dstemplate and (dstemplate.startswith('-') or dstemplate.lower() == 'none'):
dstemplate = None
logger.error("[SnmpBooster] Dstemplate is not define in the command line")
if triggergroup and (triggergroup.startswith('-') or triggergroup.lower() == 'none'):
triggergroup = None
if instance:
res = re.search("map\((.*),(.*)\)", instance)
if res:
instance_name = res.groups()[1]
return (host, community, version,
triggergroup, dstemplate, instance,
instance_name)
class SNMPHost(object):
""" Host with SNMP checks
frequences = {
'1' : <SNMPFrequence>
'5' : <SNMPFrequence>
}
instances = {
'wlan': 1,
'eth0': 0,
}
"""
def __init__(self, host, community, version):
self.host = host
self.community = community
self.version = version
# frequences == check_intervals
# frequences dict : sort services by check_interval
self.frequences = {}
# instance mapping
self.instances = {}
def update_service(self, service):
""" Add or modify a service in service list
"""
if service.check_interval in self.frequences:
# interval found
if not service.key in self.frequences[service.check_interval].services:
# service not found
self.frequences[service.check_interval].services[service.key] = service
else:
# service found, check if it needs update
if not self.frequences[service.check_interval].services[service.key] == service:
self.frequences[service.check_interval].services[service.key] = service
else:
# no changes
pass
# TODO search service in other interval !!!
else:
# Interval not found
self.frequences[service.check_interval] = {}
# Create new freq
new_freq = SNMPFrequence(service.check_interval)
new_freq.services[service.key] = service
self.frequences[service.check_interval] = new_freq
def find_frequences(self, service_key):
""" search service frequence
get a service key and return its frequence
"""
tmp = dict([(key, interval)
for interval,f in self.frequences.items()
for key in f.services.keys()])
if service_key in tmp:
return tmp[service_key]
else:
logger.error('[SnmpBooster] No frequences found for this key: %s' % str(service_key))
return None
def get_oids_by_frequence(self, interval):
""" Return all oids from an frequence
"""
return dict([(snmpoid.oid, snmpoid)
for s in self.frequences[interval].services.values()
for snmpoid in s.oids.values()
if s.instance != "NOTFOUND"])
def get_oids_for_instance_mapping(self, interval, datasource):
""" Return all oids from an frequence in order to map instances
"""
base_oids = {}
for s in self.frequences[interval].services.values():
if s.instance:
res = re.search("map\((.*),(.*)\)", s.instance)
if res:
base_oid_name = res.groups()[0]
if base_oid_name in datasource['MAP']:
oid = datasource['MAP'][base_oid_name]['base_oid']
base_oids[oid] = s.instance
else:
logger.error("[SnmpBooster] Map name `%s' not found in datasource INI file" % base_oid_name)
return base_oids
def get_oids_for_limits(self, interval):
""" Return all oids from an frequence in order to get data max values
"""
return dict([(snmpoid.max_, snmpoid)
for s in self.frequences[interval].services.values()
for snmpoid in s.oids.values()
if s.instance != "NOTFOUND" and isinstance(snmpoid.max_, str) and snmpoid.max_])
# TODO : Unreachable code, FIXME!!!
max_oids = []
for s in self.frequences[interval].services.values():
for snmpoid in s.oids.values():
if snmpoid.max_ and not isinstance(snmpoid.max_, float):
oid_max, _ = snmpoid.max_.rsplit(".", 1) # DELETE ME PLEASE! :)
max_oids.append(oid_max)
return max_oids
def format_output(self, frequence, key):
""" Prepare service output
"""
m, r = self.frequences[frequence].format_output(key)
return m, r
def map_instances(self, frequence):
""" Map instances
"""
for s in self.frequences[frequence].services.values():
s.map_instances(self.instances)
def set_limits(self, frequence, limits):
""" Set data max values
"""
for s in self.frequences[frequence].services.values():
s.set_limits(limits)
def __eq__(self, other):
""" equal reimplementation
"""
if isinstance(other, SNMPHost):
result = []
result.append(self.community == other.community)
result.append(self.version == other.version)
return all(result)
return NotImplemented
class SNMPFrequence(object):
""" Frequence
services = {
'(interface, map(interface,eth0), eth0)' : <SNMPService>
'(interface, map(interface,eth1), eth1)' : <SNMPService>
}
"""
def __init__(self, frequence):
self.frequence = frequence
self.check_time = None
self.old_check_time = None
# List services
self.services = {}
self.forced = None
self.checking = False
def format_output(self, key):
""" Prepare service output
"""
return self.services[key].format_output(self.check_time, self.old_check_time)
class SNMPService(object):
""" SNMP service
oids = {
'SysContact' : <SNMPOid>,
'SysName' : <SNMPOid>
}
"""
def __init__(self, service, host, triggergroup, dstemplate, instance, instance_name, name=None):
self.host = host
self.check_interval = service.check_interval
self.triggergroup = triggergroup
self.triggers = {}
self.dstemplate = dstemplate
self.instance = instance # If = 'NOTFOUND' means mapping failed
self.raw_instance = instance
self.instance_name = instance_name
self.name = name
self.oids = {}
self.key = (dstemplate, instance, instance_name)
def set_limits(self, limits):
""" Set data max values
"""
for snmpoid in self.oids.values():
if snmpoid.max_ in limits:
snmpoid.max_ = float(limits[snmpoid.max_])
def map_instances(self, instances):
""" Map instances
"""
# CHANGE IF FOR REGEXP
if self.instance_name in instances:
# Set instance
self.instance = instances[self.instance_name]
for snmpoid in self.oids.values():
snmpoid.oid = re.sub("map\(.*\)", self.instance, snmpoid.oid)
if snmpoid.max_ and isinstance(snmpoid.max_, str):
snmpoid.max_ = snmpoid.max_ % self.__dict__
return True # useless
return False # useless
def format_output(self, check_time, old_check_time):
""" Prepare service output
"""
for snmpoid in self.oids.values():
snmpoid.format_output(check_time, old_check_time)
# Get return code from trigger
rc = self.get_trigger_result()
# Get perf from all oids
perf = " ".join([snmpoid.perf for snmpoid in self.oids.values() if snmpoid.perf])
# Get output from all oids
out = " - ".join([snmpoid.out for snmpoid in self.oids.values() if snmpoid.out])
# Get name
if self.instance_name:
name = self.instance_name
elif self.instance:
name = self.instance
else:
name = self.dstemplate
if self.instance == "NOTFOUND":
out = "Instance mapping not found. Please check your config"
rc = 3
if not perf:
message = "%s: %s" % (name, out)
else:
message = "%s: %s" % (name, out)
message = "%s | %s" % (message, perf)
return message, rc
def get_trigger_result(self):
""" Get return code from trigger calculator
"""
errors = {'critical': 2,
'warning' : 1,
'ok' : 0}
try:
for error_name in ['critical', 'warning']:
error_code = errors[error_name]
for trigger_name, trigger in self.triggers.items():
rpn_list = []
if error_name in trigger:
for el in trigger[error_name]:
# function ?
tmp = el.split(".")
if len(tmp) > 1:
# detect oid with function
ds, fct = tmp
if self.oids[ds].value is None:
return int(trigger['default_status'])
fct, args = fct.split("(")
if hasattr(self.oids[ds], fct):
if args == ')':
value = getattr(self.oids[ds], fct)()
else:
args = args[:-1]
args = args.split(",")
value = getattr(self.oids[ds], fct)(**args)
else:
logger.error("[SnmpBooster] Trigger function not found: %s" % fct)
# return UNKNOW
return 3
elif el in self.oids:
# detect oid
value = self.oids[ds].value
else:
value = el
rpn_list.append(value)
error = rpn_calculator(rpn_list)
if error:
return error_code
return errors['ok']
except Exception, e:
logger.error("[SnmpBooster] Get Trigger error: %s" % str(e))
return int(trigger['default_status'])
def set_triggers(self, datasource):
""" Prepare trigger from triggroup and trigges definition
"""
if self.triggergroup in datasource['TRIGGERGROUP']:
triggers = datasource['TRIGGERGROUP'][self.triggergroup]
# if triggers is a str
if isinstance(triggers, str):
# Transform to list
triggers = [triggers,]
for trigger_name in triggers:
if trigger_name in datasource['TRIGGER']:
self.triggers[trigger_name] = {}
if 'warning' in datasource['TRIGGER'][trigger_name]:
self.triggers[trigger_name]['warning'] = datasource['TRIGGER'][trigger_name]['warning']
if 'critical' in datasource['TRIGGER'][trigger_name]:
self.triggers[trigger_name]['critical'] = datasource['TRIGGER'][trigger_name]['critical']
if 'default_status' in datasource['TRIGGER'][trigger_name]:
self.triggers[trigger_name]['default_status'] = datasource['TRIGGER'][trigger_name]['default_status']
elif 'default_status' in datasource['TRIGGER']:
self.triggers[trigger_name]['default_status'] = datasource['TRIGGER']['default_status']
def set_oids(self, datasource):
""" Get datas from datasource and set SNMPOid dict
"""
ds = datasource['DSTEMPLATE'][self.dstemplate]['ds']
if isinstance(ds, str):
ds = [d.strip() for d in ds.split(",")]
for source in ds:
try:
oid = datasource['DATASOURCE'][source]['ds_oid']
except:
logger.error("[SnmpBooster] ds_oid not found for source: %s" % source)
return
# Determining oid
oid = oid % self.__dict__
# Search type
ds_type = None
if 'ds_type' in datasource['DATASOURCE'][source]:
ds_type = datasource['DATASOURCE'][source]['ds_type']
elif 'ds_type' in datasource['DATASOURCE']:
ds_type = datasource['DATASOURCE']['ds_type']
else:
ds_type = 'TEXT'
logger.info("[SnmpBooster] ds_type not found for source: %s. TEXT type selected" % source)
# Search name
name = source
if 'ds_name' in datasource['DATASOURCE'][source]:
name = datasource['DATASOURCE'][source]['ds_name']
elif 'ds_name' in datasource['DATASOURCE']:
name = datasource['DATASOURCE']['ds_name']
# Search unit
unit = ''
if 'ds_unit' in datasource['DATASOURCE'][source]:
unit = datasource['DATASOURCE'][source]['ds_unit']
elif 'ds_unit' in datasource['DATASOURCE']:
unit = datasource['DATASOURCE']['ds_unit']
# Search ds_min
ds_min = ''
if 'ds_min' in datasource['DATASOURCE'][source]:
ds_min = datasource['DATASOURCE'][source]['ds_min']
elif 'ds_min' in datasource['DATASOURCE']:
ds_min = datasource['DATASOURCE']['ds_min']
# Search ds_max
ds_max = ''
if 'ds_max' in datasource['DATASOURCE'][source]:
ds_max = datasource['DATASOURCE'][source]['ds_max']
elif 'ds_max' in datasource['DATASOURCE']:
ds_max = datasource['DATASOURCE']['ds_max']
try:
ds_max = float(ds_max)
except:
pass
# Search calc
calc = None
if 'ds_calc' in datasource['DATASOURCE'][source]:
calc = datasource['DATASOURCE'][source]['ds_calc']
elif 'ds_calc' in datasource['DATASOURCE']:
calc = datasource['DATASOURCE']['ds_calc']
snmp_oid = SNMPOid(oid, ds_type, name, ds_max, ds_min, unit, calc)
self.oids[source] = snmp_oid
def __eq__(self, other):
""" equal reimplementation
"""
if isinstance(other, SNMPService):
result = []
result.append(self.host == other.host)
result.append(self.triggergroup == other.triggergroup)
result.append(self.triggers == other.triggers)
result.append(self.dstemplate == other.dstemplate)
result.append(self.instance_name == other.instance_name)
result.append(self.raw_instance == other.instance)
for key, snmpoid in self.oids.items():
if not key in other.oids:
result.append(False)
else:
result.append(other.oids[key] == snmpoid)
return all(result)
return NotImplemented
class SNMPOid(object):
""" OID created from datasource
contains oids, values, max, ...
"""
def __init__(self, oid, ds_type, name, ds_max='', ds_min='', unit='', calc=None):
self.oid = oid
self.raw_oid = oid
self.type_ = ds_type
self.name = name
self.max_ = ds_max
self.raw_max_ = ds_max
self.min_ = ds_min
self.unit = unit
self.calc = calc
# Message printed
self.out = None
# Raw value (before calculation)
self.raw_value = None
# Raw old value (before calculation)
self.raw_old_value = None
# Value (after calculation)
self.value = None
# Old value (after calculation)
self.old_value = None
self.perf = ""
# Zabbix functions
# AMELIORER LES MESSAGES D ERREUR SUR LE CALCUL DU TRIGGER
def diff(self):
return self.raw_value == self.raw_old_value
def prct(self):
return float(self.value) * 100 / float(self.max_)
def last(self):
return self.value
# End zabbix functions
def calculation(self, value):
""" Get result from self.calc
"""
return rpn_calculator([value,] + self.calc)
def format_output(self, check_time, old_check_time):
""" Prepare service output
"""
getattr(self, 'format_' + self.type_.lower() + '_output')(check_time, old_check_time)
def format_text_output(self, check_time, old_check_time):
""" Format output for text type
"""
self.value = "%(raw_value)s" % self.__dict__
self.out = "%(name)s: %(value)s%(unit)s" % self.__dict__
def format_derive64_output(self, check_time, old_check_time):
""" Format output for derive64 type
"""
self.format_derive_output(check_time, old_check_time, limit=18446744073709551615)
def format_derive_output(self, check_time, old_check_time, limit=4294967295):
""" Format output for derive type
"""
if self.raw_old_value == None:
# Need more data to get derive
self.out = "Waiting an additional check to calculate derive"
self.perf = ''
else:
raw_value = self.raw_value
# detect counter reset
if self.raw_value < self.raw_old_value:
# Counter reseted
raw_value = (float(limit) - float(self.raw_old_value)) + float(raw_value)
# Get derive
t_delta = check_time - old_check_time
if t_delta.seconds == 0:
logger.error("[SnmpBooster] Time delta is 0s. We can not get derive for this OID %s" % self.oid)
else:
if self.raw_value < self.raw_old_value:
d_delta = float(raw_value)
else:
d_delta = float(raw_value) - float(self.raw_old_value)
value = d_delta / t_delta.seconds
value = "%0.2f" % value
# Make calculation
if self.calc:
self.value = self.calculation(value)
else:
self.value = value
self.value = float(self.value)
self.out = "%(name)s: %(value)0.2f%(unit)s" % self.__dict__
self.perf = "%(name)s=%(value)0.2f%(unit)s;;;%(min_)s;%(max_)s" % self.__dict__
def format_counter64_output(self, check_time, old_check_time):
""" Format output for counter64 type
"""
self.format_counter_output(check_time, old_check_time, limit=18446744073709551615)
def format_counter_output(self, check_time, old_check_timei, limit=4294967295):
""" Format output for counter type
"""
if self.raw_value == None:
# No data, is it possible??
self.out = "No Data found ... maybe we have to wait ..."
self.perf = ''
else:
raw_value = self.raw_value
# detect counter reset
# USELESS FOR SIMPLE COUNTER
#if self.raw_value < self.raw_old_value:
# Counter reseted
# raw_value = (limit - self.old_value) + raw_value
# Make calculation
if self.calc:
self.value = self.calculation(raw_value)
else:
self.value = raw_value
self.value = float(self.value)
self.out = "%(name)s: %(value)0.2f%(unit)s" % self.__dict__
self.out = self.out % self.__dict__
def format_gauge_output(self, check_time, old_check_time):
""" Format output for gauge type
"""
if self.raw_value == None:
# No data, is it possible??
self.out = "No Data found ... maybe we have to wait ..."
self.perf = ''
else:
raw_value = self.raw_value
# Make calculation
if self.calc:
self.value = self.calculation(raw_value)
else:
self.value = raw_value
self.value = float(self.value)
self.out = "%(name)s: %(value)0.2f%(unit)s" % self.__dict__
self.perf = "%(name)s=%(out)s%(unit)s;;;%(min_)s;%(max_)s" % self.__dict__
def __eq__(self, other):
""" equal reimplementation
"""
if isinstance(other, SNMPOid):
result = []
result.append(self.raw_oid == other.raw_oid)
result.append(self.type_ == other.type_)
result.append(self.name == other.name)
result.append(self.raw_max_ == other.raw_max_)
result.append(self.min_ == other.min_)
result.append(self.calc == other.calc)
return all(result)
return NotImplemented
class SNMPAsyncClient(object):
"""SNMP asynchron Client.
Launch async SNMP request
"""
def __init__(self, host, community, version, datasource,
triggergroup, dstemplate, instance, instance_name,
memcached_address, max_repetitions=64):
self.hostname = host
self.community = community
self.version = version
self.dstemplate = dstemplate
self.instance = instance
self.instance_name = instance_name
self.triggergroup = triggergroup
self.max_repetitions = max_repetitions
self.serv_key = (dstemplate, instance, instance_name)
self.interval_length = 60
self.remaining_oids = None
self.remaining_tablerow = []
self.nb_next_requests = 0
self.memcached = memcache.Client([memcached_address], debug=0)
self.datasource = datasource
self.check_interval = None
self.state = 'creation'
self.start_time = datetime.now()
self.timeout = 5
self.obj = None
# Check if obj is in memcache
self.obj_key = str(self.hostname)
try:
# LOCKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKK
self.obj = self.memcached.get(self.obj_key)
except ValueError, e:
self.set_exit("Memcached error: `%s'"
% self.memcached.get(self.obj_key),
rc=3)
return
if not isinstance(self.obj, SNMPHost):
logger.error('[SnmpBooster] Host not found in memcache: %s' % self.hostname)
self.set_exit("Host not found in memcache: `%s'" % self.hostname,
rc=3)
return
# Find service check_interval
self.check_interval = self.obj.find_frequences(self.serv_key)
if self.check_interval is None:
# Possible ???
logger.error('[SnmpBooster] Interval not found in memcache: %s' % self.check_interval)
self.set_exit("Interval not found in memcache", rc=3)
return
# Check if map is done
s = self.obj.frequences[self.check_interval].services[self.serv_key]
if isinstance(s.instance, str):
self.mapping_done = not s.instance.startswith("map(")
else:
self.mapping_done = True
data_validity = False
# Check if the check is forced
if self.obj.frequences[self.check_interval].forced:
# Check forced !!
logger.debug("[SnmpBooster] Check forced : %s,%s" % (self.hostname, self.instance_name))
self.obj.frequences[self.check_interval].forced = False
data_validity = False
elif not self.mapping_done:
logger.debug("[SnmpBooster] Mapping not done : %s,%s" % (self.hostname, self.instance_name))
data_validity = False
# Check datas validity
elif self.obj.frequences[self.check_interval].check_time is None:
# Datas not valid : no data
logger.debug("[SnmpBooster] No old data : %s,%s" % (self.hostname, self.instance_name))
data_validity = False
# Don't send SNMP request if old check is younger than 20 sec
elif self.obj.frequences[self.check_interval].check_time and self.start_time - self.obj.frequences[self.check_interval].check_time < timedelta(seconds=20):
logger.debug("[SnmpBooster] Derive 0s protection : %s,%s" % (self.hostname, self.instance_name))
data_validity = True
# Don't send SNMP request if an other SNMP is on the way
elif self.obj.frequences[self.check_interval].checking:
logger.debug("[SnmpBooster] SNMP request already launched : %s,%s" % (self.hostname, self.instance_name))
data_validity = True
else:
# Compare last check time and check_interval and now
td = timedelta(seconds=(self.check_interval
*
self.interval_length))
# Just to be sure to invalidate datas ...
mini_td = timedelta(seconds=(5))
data_validity = self.obj.frequences[self.check_interval].check_time + td \
> self.start_time + mini_td
logger.debug("[SnmpBooster] Data validity : %s,%s => %s" % (self.hostname, self.instance_name, data_validity))
if data_validity:
# Datas valid
data_validity = True
message, rc = self.obj.format_output(self.check_interval, self.serv_key)
logger.info('[SnmpBooster] FROM CACHE : Return code: %s - Message: %s' % (rc, message))
message = "FROM CACHE: " + message
self.set_exit(message, rc=rc)
self.memcached.set(self.obj_key, self.obj, time=604800)
return
# Save old datas
#for oid in self.obj.frequences[self.check_interval].services[self.serv_key].oids.values():
for service in self.obj.frequences[self.check_interval].services.values():
for snmpoid in service.oids.values():
snmpoid.old_value = snmpoid.value
snmpoid.raw_old_value = snmpoid.raw_value
# One SNMP request is now running
self.obj.frequences[self.check_interval].checking = True
self.memcached.set(self.obj_key, self.obj, time=604800)
# UNLOCKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKK
self.headVars = []
# Prepare SNMP oid for mapping
self.mapping_oids = self.obj.get_oids_for_instance_mapping(self.check_interval, self.datasource)
tmp_oids = list(set([oid[1:] for oid in self.mapping_oids]))
for oid in tmp_oids:
try:
oid = tuple(int(i) for i in oid.split("."))
except ValueError:
logger.info("[SnmpBooster] Bad format for this oid: %s" % oid)
continue
self.headVars.append(v2c.ObjectIdentifier(oid))
self.limit_oids = {}
if not self.mapping_oids:
# Prepare SNMP oid for limits
self.limit_oids = self.obj.get_oids_for_limits(self.check_interval)
tmp_oids = list(set([oid[1:].rsplit(".", 1)[0] for oid in self.limit_oids]))
for oid in tmp_oids:
try:
oid = tuple(int(i) for i in oid.split("."))
except ValueError, e:
logger.info("[SnmpBooster] Bad format for this oid: %s" % oid)
continue
self.headVars.append(v2c.ObjectIdentifier(oid))
self.limits_done = not bool(self.limit_oids)
self.oids_to_check = {}
if not self.mapping_oids:
# Get all oids which have to be checked
self.oids_to_check = self.obj.get_oids_by_frequence(self.check_interval)
if self.oids_to_check == {}:
logger.error('[SnmpBooster] No OID found - %s - %s' % (self.obj_key, str(self.serv_key)))
self.set_exit("No OID found" + " - " + self.obj_key + " - "+ str(self.serv_key), rc=3)
return
# SNMP table header
tmp_oids = list(set([oid[1:].rsplit(".", 1)[0] for oid in self.oids_to_check]))
for oid in tmp_oids:
# TODO: FIND SOMETHING BETTER ??
# Launch : snmpbulkget .1.3.6.1.2.1.2.2.1.8
# to get.1.3.6.1.2.1.2.2.1.8.2
# Because : snmpbulkget .1.3.6.1.2.1.2.2.1.8.2
# returns value only for .1.3.6.1.2.1.2.2.1.8.3
# oid = oid.rsplit(".", 1)[0]
try:
oid = tuple(int(i) for i in oid.split("."))
except ValueError:
logger.info("[SnmpBooster] Bad format for this oid: %s" % oid)
continue
self.headVars.append(v2c.ObjectIdentifier(oid))
# prepare results dicts
self.results_limits_dict = {}
self.results_oid_dict = {}
# Build PDU
self.reqPDU = v2c.GetBulkRequestPDU()
v2c.apiBulkPDU.setDefaults(self.reqPDU)
v2c.apiBulkPDU.setNonRepeaters(self.reqPDU, 0)
v2c.apiBulkPDU.setMaxRepetitions(self.reqPDU, self.max_repetitions)
v2c.apiBulkPDU.setVarBinds(self.reqPDU,
[(x, v2c.null) for x in self.headVars])
# Build message
self.reqMsg = v2c.Message()
v2c.apiMessage.setDefaults(self.reqMsg)
v2c.apiMessage.setCommunity(self.reqMsg, self.community)
v2c.apiMessage.setPDU(self.reqMsg, self.reqPDU)
self.startedAt = time.time()
transportDispatcher = AsynsockDispatcher()
transportDispatcher.registerTransport(udp.domainName,
udp.UdpSocketTransport().openClientMode())
transportDispatcher.registerRecvCbFun(self.callback)
transportDispatcher.registerTimerCbFun(self.callback_timer)
transportDispatcher.sendMessage(encoder.encode(self.reqMsg),
udp.domainName,
(self.hostname, 161))
transportDispatcher.jobStarted(1)
# transportDispatcher.runDispatcher()
try:
transportDispatcher.runDispatcher()
except Exception, e:
logger.error('[SnmpBooster] SNMP Request error: %s' % str(e))
self.set_exit("SNMP Request error: " + str(e), rc=3)
# LOCKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKK
try:
self.obj = self.memcached.get(self.obj_key)
except ValueError, e:
self.set_exit("Memcached error: `%s'"
% self.memcached.get(self.obj_key),
rc=3)
return
if not isinstance(self.obj, SNMPHost):
logger.error('[SnmpBooster] Host not found in memcache: %s' % self.hostname)
self.set_exit("Host not found in memcache: `%s'" % self.hostname,
rc=3)
return
self.obj.frequences[self.check_interval].checking = False
self.memcached.set(self.obj_key, self.obj, time=604800)
# UNLOCKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKK
transportDispatcher.closeDispatcher()
def callback(self, transportDispatcher, transportDomain, transportAddress,
wholeMsg, reqPDU=None, headVars=None):
aBP = v2c.apiBulkPDU
# Get PDU
if reqPDU:
self.reqPDU = reqPDU
if headVars:
self.headVars = headVars
while wholeMsg:
self.rspMsg, wholeMsg = decoder.decode(wholeMsg,
asn1Spec=v2c.Message())
self.rspPDU = v2c.apiMessage.getPDU(self.rspMsg)
if aBP.getRequestID(self.reqPDU) == aBP.getRequestID(self.rspPDU):
# Check for SNMP errors reported
errorStatus = aBP.getErrorStatus(self.rspPDU)
if errorStatus and errorStatus != 2:
logger.error('[SnmpBooster] SNMP Request error: %s' % str(errorStatus))
self.set_exit("SNMP Request error: " + str(errorStatus), rc=3)
return wholeMsg
# Format var-binds table
varBindTable = aBP.getVarBindTable(self.reqPDU, self.rspPDU)
# Report SNMP table
mapping_instance = {}
for tableRow in varBindTable:
# VERIFIER QUE tableRow est dans la liste des tables que l on doit repecurere
# Si elle n'est pas dedans :
# continue ou return ????
for oid, val in tableRow:
oid = "." + oid.prettyPrint()
if oid in self.oids_to_check:
# Get values
self.results_oid_dict[oid] = str(val)
elif any([oid.startswith(m_oid + ".") for m_oid in self.mapping_oids]):
# Get mapping
for m_oid in self.mapping_oids:
if oid.startswith(m_oid + "."):
instance = oid.replace(m_oid + ".", "")
val = re.sub("[,:/ ]", "_", str(val))
mapping_instance[val] = instance
elif oid in self.limit_oids:
# get limits
try:
self.results_limits_dict[oid] = float(val)
except ValueError:
logger.error('[SnmpBooster] Bad limit for oid: %s - Skipping' % str(oid))
# SNPNEXT NEEDED ????
if self.mapping_done:
# trier `oids' par table, puis par oid => A faire avant le dispatcher
# oids = {'.1.3.6.1.2.1.2.2.1.11' : { '.1.3.6.1.2.1.2.2.1.11.10016': VALUE }, ... }
oids = set(self.oids_to_check.keys() + self.limit_oids.keys())
results_oids = set(self.results_oid_dict.keys() + self.results_limits_dict.keys())
self.remaining_oids = oids - results_oids
#COMMENTTTTTTTTTTT
tableRow = [oid.rsplit(".", 1)[0] + "." + str(int(oid.rsplit(".", 1)[1]) - 1) for oid in self.remaining_oids]
# LIMIT SNMP BULK to 120 OIDs in same request
if self.remaining_tablerow:
aBP.setVarBinds(self.reqPDU,
[(x, v2c.null) for x in self.remaining_tablerow])
self.remaining_tablerow = []
aBP.setRequestID(self.reqPDU, v2c.getNextRequestID())
transportDispatcher.sendMessage(encoder.encode(self.reqMsg),
transportDomain,
transportAddress)
self.nb_next_requests = self.nb_next_requests + 1
return wholeMsg
if oids != results_oids and self.nb_next_requests < 5:
# SNMP next needed
# LIMIT SNMP BULK to 120 OIDs in same request
if len(tableRow) > 100: