/
alarmgen.py
2189 lines (2007 loc) · 91.5 KB
/
alarmgen.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
#
# Copyright (c) 2013 Juniper Networks, Inc. All rights reserved.
#
#
# Opserver
#
# Operational State Server for VNC
#
from gevent import monkey
monkey.patch_all()
import sys
import json
import socket
import time
import copy
import traceback
import signal
import logging
logging.getLogger('kafka').addHandler(logging.StreamHandler())
logging.getLogger('kafka').setLevel(logging.WARNING)
try:
from collections import OrderedDict
except ImportError:
# python 2.6 or earlier, use backport
from ordereddict import OrderedDict
from pysandesh.sandesh_base import *
from pysandesh.connection_info import ConnectionState
from pysandesh.sandesh_logger import SandeshLogger
from pysandesh.gen_py.sandesh_alarm.ttypes import SandeshAlarmAckResponseCode
from sandesh.alarmgen_ctrl.sandesh_alarm_base.ttypes import AlarmTrace, \
UVEAlarms, UVEAlarmInfo, UVEAlarmConfig, AlarmOperand2, AlarmCondition, \
AlarmMatch, AlarmConditionMatch, AlarmAndList, AlarmRules
from sandesh.analytics.ttypes import *
from sandesh.nodeinfo.ttypes import NodeStatusUVE, NodeStatus
from sandesh.nodeinfo.cpuinfo.ttypes import *
from sandesh.nodeinfo.process_info.ttypes import *
from sandesh_common.vns.ttypes import Module, NodeType
from sandesh_common.vns.constants import ModuleNames, CategoryNames,\
ModuleCategoryMap, Module2NodeType, NodeTypeNames, ModuleIds,\
INSTANCE_ID_DEFAULT, COLLECTOR_DISCOVERY_SERVICE_NAME,\
ALARM_GENERATOR_SERVICE_NAME
from alarmgen_cfg import CfgParser
from uveserver import UVEServer
from partition_handler import PartitionHandler, UveStreamProc
from alarmgen_config_handler import AlarmGenConfigHandler
from sandesh.alarmgen_ctrl.ttypes import PartitionOwnershipReq, \
PartitionOwnershipResp, PartitionStatusReq, UVECollInfo, UVEGenInfo, \
PartitionStatusResp, UVETableAlarmReq, UVETableAlarmResp, \
AlarmgenTrace, UVEKeyInfo, UVETypeCount, UVETypeInfo, AlarmgenStatusTrace, \
AlarmgenStatus, AlarmgenStats, AlarmgenPartitionTrace, \
AlarmgenPartition, AlarmgenPartionInfo, AlarmgenUpdate, \
UVETableInfoReq, UVETableInfoResp, UVEObjectInfo, UVEStructInfo, \
UVETablePerfReq, UVETablePerfResp, UVETableInfo, UVETableCount, \
UVEAlarmStateMachineInfo, UVEAlarmState, UVEAlarmOperState,\
AlarmStateChangeTrace, UVEQTrace
from sandesh.discovery.ttypes import CollectorTrace
from cpuinfo import CpuInfoData
from opserver_util import ServicePoller
from stevedore import hook, extension
from pysandesh.util import UTCTimestampUsec
from libpartition.libpartition import PartitionClient
import discoveryclient.client as client
from kafka import KafkaClient, SimpleProducer
import redis
from collections import namedtuple
OutputRow = namedtuple("OutputRow",["key","typ","val"])
class AGTabStats(object):
""" This class is used to store per-UVE-table information
about the time taken and number of instances when
a UVE was retrieved, published or evaluated for alarms
"""
def __init__(self):
self.reset()
def record_get(self, get_time):
self.get_time += get_time
self.get_n += 1
def record_pub(self, get_time):
self.pub_time += get_time
self.pub_n += 1
def record_call(self, get_time):
self.call_time += get_time
self.call_n += 1
def get_result(self):
if self.get_n:
return self.get_time / self.get_n
else:
return 0
def pub_result(self):
if self.pub_n:
return self.pub_time / self.pub_n
else:
return 0
def call_result(self):
if self.call_n:
return self.call_time / self.call_n
else:
return 0
def reset(self):
self.call_time = 0
self.call_n = 0
self.get_time = 0
self.get_n = 0
self.pub_time = 0
self.pub_n = 0
class AGKeyInfo(object):
""" This class is used to maintain UVE contents
"""
def __init__(self, part):
self._part = part
# key of struct name, value of content dict
self.current_dict = {}
self.update({})
def update_single(self, typ, val):
# A single UVE struct has changed
# If the UVE has gone away, the val is passed in as None
self.set_removed = set()
self.set_added = set()
self.set_changed = set()
self.set_unchanged = self.current_dict.keys()
if typ in self.current_dict:
# the "added" set must stay empty in this case
if val is None:
self.set_unchanged.remove(typ)
self.set_removed.add(typ)
del self.current_dict[typ]
else:
# both "added" and "removed" will be empty
if val != self.current_dict[typ]:
self.set_unchanged.remove(typ)
self.set_changed.add(typ)
self.current_dict[typ] = val
else:
if val != None:
self.set_added.add(typ)
self.current_dict[typ] = val
def update(self, new_dict):
# A UVE has changed, and we have the entire new
# content of the UVE available in new_dict
set_current = set(new_dict.keys())
set_past = set(self.current_dict.keys())
set_intersect = set_current.intersection(set_past)
self.set_added = set_current - set_intersect
self.set_removed = set_past - set_intersect
self.set_changed = set()
self.set_unchanged = set()
for o in set_intersect:
if new_dict[o] != self.current_dict[o]:
self.set_changed.add(o)
else:
self.set_unchanged.add(o)
self.current_dict = new_dict
def values(self):
return self.current_dict
def added(self):
return self.set_added
def removed(self):
return self.set_removed
def changed(self):
return self.set_changed
def unchanged(self):
return self.set_unchanged
class AlarmProcessor(object):
def __init__(self, logger):
self.uve_alarms = {}
self._logger = logger
self.ActiveTimer = {}
self.IdleTimer = {}
self.FreqExceededCheck = {}
self.FreqCheck_Times = {}
self.FreqCheck_Seconds = {}
def process_alarms(self, alarm_fqname, alarm, uv, local_uve):
if not alarm.is_enabled():
return
alarm_name = alarm_fqname.rsplit(':', 1)[1]
sev = alarm.severity()
if not uv in self.ActiveTimer:
self.ActiveTimer[uv] = {}
self.ActiveTimer[uv][alarm_name] = alarm.ActiveTimer()
if not uv in self.IdleTimer:
self.IdleTimer[uv] = {}
self.IdleTimer[uv][alarm_name] = alarm.IdleTimer()
if not uv in self.FreqExceededCheck:
self.FreqExceededCheck[uv] = {}
self.FreqExceededCheck[uv][alarm_name] = alarm.FreqExceededCheck()
if not uv in self.FreqCheck_Times:
self.FreqCheck_Times[uv] = {}
self.FreqCheck_Times[uv][alarm_name] = alarm.FreqCheck_Times()
if not uv in self.FreqCheck_Seconds:
self.FreqCheck_Seconds[uv] = {}
self.FreqCheck_Seconds[uv][alarm_name] = alarm.FreqCheck_Seconds()
try:
# __call__ method overrides the generic alarm processing code.
if hasattr(alarm, '__call__'):
or_list = alarm.__call__(uv, local_uve)
else:
or_list = self._evaluate_uve_for_alarms(
alarm.config(), uv, local_uve)
self._logger.debug("Alarm[%s] %s: %s" %
(uv, alarm_name, str(or_list)))
if or_list:
self.uve_alarms[alarm_name] = UVEAlarmInfo(type=alarm_name,
severity=sev, timestamp=0, token="",
alarm_rules=AlarmRules(or_list),
description=alarm.description(), ack=False)
except Exception as ex:
template = "Exception {0} in Alarm Processing. Arguments:\n{1!r}"
messag = template.format(type(ex).__name__, ex.args)
self._logger.error("%s : traceback %s" % \
(messag, traceback.format_exc()))
self.uve_alarms[alarm_name] = UVEAlarmInfo(type=alarm_name,
severity=sev, timestamp=0, token="",
alarm_rules=AlarmRules(None),
description=alarm.description(), ack=False)
# end process_alarms
def _get_uve_attribute(self, tuve, puve, attr_list):
if tuve is None or not attr_list:
return {'value': tuve, 'parent_attr': puve,
'status': False if len(attr_list) else True}
if isinstance(tuve, dict):
return self._get_uve_attribute(tuve.get(attr_list[0]),
tuve, attr_list[1:])
elif isinstance(tuve, list):
return [self._get_uve_attribute(elem, tuve, attr_list) \
for elem in tuve]
elif isinstance(tuve, str):
try:
json_elem = json.loads(tuve)
except ValueError:
return {'value': None, 'parent_attr': tuve, 'status': False}
else:
return self._get_uve_attribute(json_elem, tuve, attr_list)
# end _get_uve_attribute
def _get_operand_value(self, uve, operand):
attr_list = operand.split('.')
return self._get_uve_attribute(uve, uve, attr_list)
# end _get_operand_value
def _get_json_value(self, val):
try:
tval = json.loads(val)
except (ValueError, TypeError):
return json.dumps(val)
else:
return val
# end _get_json_value
def _get_json_variables(self, uve, exp, operand1_val,
operand2_val, is_operand2_json_val):
json_vars = {}
for var in exp.variables:
# If var and operand1/operand2 are at the same hirerarchy in
# the uve struture, then get the value of var from parent_attr of
# the corresponding operand_val
# TODO: Handle the case len(var.rsplit) != len(operand.rsplit)
if var.rsplit('.', 1)[0] == exp.operand1.rsplit('.', 1)[0]:
var_val = \
operand1_val['parent_attr'].get(var.rsplit('.', 1)[1])
elif not is_operand2_json_val and \
var.rsplit('.', 1)[0] == exp.operand2.uve_attribute.rsplit(
'.', 1)[0]:
var_val = \
operand2_val['parent_attr'].get(var.rsplit('.', 1)[1])
else:
var_val = self._get_operand_value(uve, var)['value']
json_vars[var] = self._get_json_value(var_val)
return json_vars
# end _get_json_variables
def _compare_operand_vals(self, val1, val2, operation):
try:
val1 = json.loads(val1)
except (TypeError, ValueError):
pass
try:
val2 = json.loads(val2)
except (TypeError, ValueError):
pass
if operation == '==':
return val1 == val2
elif operation == '!=':
return val1 != val2
elif operation == '<=':
return val1 <= val2
elif operation == '>=':
return val1 >= val2
elif operation == 'in':
if not isinstance(val2, list):
return False
return val1 in val2
elif operation == 'not in':
if not isinstance(val2, list):
return True
return val1 not in val2
elif operation == 'size==':
if not isinstance(val1, list):
return False
return len(val1) == val2
elif operation == 'size!=':
if not isinstance(val1, list):
return True
return len(val1) != val2
# end _compare_operand_vals
def _get_alarm_match(self, uve, exp, operand1_val, operand2_val,
is_operand2_json_val):
json_vars = self._get_json_variables(uve, exp, operand1_val,
operand2_val, is_operand2_json_val)
json_operand1_val = self._get_json_value(operand1_val['value'])
if not is_operand2_json_val:
json_operand2_val = self._get_json_value(operand2_val['value'])
else:
json_operand2_val = None
return AlarmMatch(json_operand1_value=json_operand1_val,
json_operand2_value=json_operand2_val, json_variables=json_vars)
# end _get_alarm_match
def _get_alarm_condition_match(self, uve, exp, operand1_val, operand2_val,
is_operand2_json_val, match_list=None):
if not match_list:
match_list = [self._get_alarm_match(uve, exp, operand1_val,
operand2_val, is_operand2_json_val)]
return AlarmConditionMatch(
condition=AlarmCondition(operation=exp.operation,
operand1=exp.operand1, operand2=AlarmOperand2(
uve_attribute=exp.operand2.uve_attribute,
json_value=exp.operand2.json_value),
variables=exp.variables),
match=match_list)
# end _get_alarm_condition_match
def _evaluate_uve_for_alarms(self, alarm_cfg, uve_key, uve):
table, uve_name = uve_key.split(':', 1)
# For alarms configured under project, the parent fq_name of the uve
# should match with that of the alarm config
if alarm_cfg.parent_type == 'project':
uve_parent_fqname = uve_name.rsplit(':', 1)[0]
if uve_parent_fqname != alarm_cfg.get_parent_fq_name_str():
return None
or_list = []
for cfg_and_list in alarm_cfg.alarm_rules.or_list:
and_list = []
and_list_fail = False
for exp in cfg_and_list.and_list:
operand1_val = self._get_operand_value(uve, exp.operand1)
if isinstance(operand1_val, dict) and \
operand1_val['status'] is False:
and_list_fail = True
break
if exp.operand2.json_value is not None:
operand2_val = json.loads(exp.operand2.json_value)
is_operand2_json_val = True
else:
operand2_val = self._get_operand_value(uve,
exp.operand2.uve_attribute)
if isinstance(operand2_val, dict) and \
operand2_val['status'] is False:
and_list_fail = True
break
is_operand2_json_val = False
if isinstance(operand1_val, list) or \
(is_operand2_json_val is False and \
isinstance(operand2_val, list)):
match_list = []
# both operand1_val and operand2_val are list
if isinstance(operand1_val, list) and \
(is_operand2_json_val is False and \
isinstance(operand2_val, list)):
if len(operand1_val) != len(operand2_val):
and_list_fail = True
break
for i in range(0, len(operand1_val)):
if self._compare_operand_vals(
operand1_val[i]['value'],
operand2_val[i]['value'],
exp.operation):
match_list.append(
self._get_alarm_match(
uve, exp, operand1_val[i],
operand2_val[i],
is_operand2_json_val))
# operand1_val is list and operand2_val is not list
elif isinstance(operand1_val, list):
val2 = operand2_val
if not is_operand2_json_val:
val2 = operand2_val['value']
for val1 in operand1_val:
if self._compare_operand_vals(val1['value'],
val2, exp.operation):
match_list.append(self._get_alarm_match(
uve, exp, val1, operand2_val,
is_operand2_json_val))
# operand1_val is not list and operand2_val is list
elif is_operand2_json_val is False and \
isinstance(operand2_val, list):
for val2 in operand2_val:
if self._compare_operand_vals(
operand1_val['value'], val2['value'],
exp.operation):
match_list.append(self._get_alarm_match(
uve, exp, operand1_val, val2,
is_operand2_json_val))
if match_list:
and_list.append(self._get_alarm_condition_match(
uve, exp, operand1_val, operand2_val,
is_operand2_json_val, match_list))
else:
and_list_fail = True
break
# Neither operand1_val nor operand2_val is a list
else:
val1 = operand1_val['value']
val2 = operand2_val
if not is_operand2_json_val:
val2 = operand2_val['value']
if self._compare_operand_vals(val1, val2, exp.operation):
and_list.append(self._get_alarm_condition_match(
uve, exp, operand1_val, operand2_val,
is_operand2_json_val))
else:
and_list_fail = True
break
if not and_list_fail:
or_list.append(AlarmAndList(and_list))
if or_list:
return or_list
return None
# end _evaluate_uve_for_alarms
class AlarmStateMachine:
tab_alarms_timer = {}
def __init__(self, tab, uv, nm, sandesh, activeTimer, idleTimer,
freqCheck_Times, freqCheck_Seconds, freqExceededCheck):
self._sandesh = sandesh
self._logger = sandesh._logger
self.tab = tab
self.uv = uv
self.nm = nm
self.uac = UVEAlarmConfig(ActiveTimer = activeTimer, IdleTimer = \
idleTimer, FreqCheck_Times = freqCheck_Times, FreqCheck_Seconds
= freqCheck_Seconds, FreqExceededCheck = freqExceededCheck)
self.uas = UVEAlarmOperState(state = UVEAlarmState.Idle,
head_timestamp = 0, alarm_timestamp = [])
self.uai = None
self.activeTimeout = None
self.deleteTimeout = None
self.idleTimeout = None
def get_uai(self, forced=False):
"""
This functions returns all the alarms which are in Active or
Soak_Idle state, all other alarms are not yet asserted or cleared
"""
if forced:
return self.uai
if self.uas.state == UVEAlarmState.Active or \
self.uas.state == UVEAlarmState.Soak_Idle:
return self.uai
return None
def get_uac(self):
return self.uac
def get_uas(self):
return self.uas
def set_uai(self, uai):
self.uai = uai
def is_new_alarm_same(self, new_uai):
uai2 = copy.deepcopy(self.uai)
uai2.timestamp = 0
uai2.token = ""
uai2.ack = False
if (uai2 == new_uai) and \
self.uas.state == UVEAlarmState.Active:
return True
return False
def _remove_timer_from_list(self, index):
AlarmStateMachine.tab_alarms_timer[index].discard((self.tab,\
self.uv, self.nm))
if len(AlarmStateMachine.tab_alarms_timer[index]) == 0:
del AlarmStateMachine.tab_alarms_timer[index]
def set_alarms(self):
"""
This function runs the state machine code for setting an alarm
If a timer becomes Active, caller should send out updated AlarmUVE
"""
old_state = self.uas.state
curr_time = int(time.time())
if self.uas.state == UVEAlarmState.Soak_Idle:
self.uas.state = UVEAlarmState.Active
self._remove_timer_from_list(self.idleTimeout)
elif self.uas.state == UVEAlarmState.Idle:
if self.deleteTimeout and (self.deleteTimeout in \
AlarmStateMachine.tab_alarms_timer):
self._remove_timer_from_list(self.deleteTimeout)
if self.uac.FreqExceededCheck:
# log the timestamp
ts = int(self.uai.timestamp/1000000.0)
if len(self.uas.alarm_timestamp) <= self.uas.head_timestamp:
self.uas.alarm_timestamp.append(ts)
else:
self.uas.alarm_timestamp[self.uas.head_timestamp] = ts
self.uas.head_timestamp = (self.uas.head_timestamp + 1) % \
(self.uac.FreqCheck_Times + 1)
if not self.uac.ActiveTimer or self.is_alarm_frequency_exceeded():
self.uas.state = UVEAlarmState.Active
else:
# put it on the timer
self.uas.state = UVEAlarmState.Soak_Active
self.activeTimeout = curr_time + self.uac.ActiveTimer
timeout_value = self.activeTimeout
if not timeout_value in AlarmStateMachine.tab_alarms_timer:
AlarmStateMachine.tab_alarms_timer[timeout_value] = set()
AlarmStateMachine.tab_alarms_timer[timeout_value].add\
((self.tab, self.uv, self.nm))
self.send_state_change_trace(old_state, self.uas.state)
#end set_alarms
def send_state_change_trace(self, os, ns):
# No need to send if old and new states are same
if os == ns:
return
state_trace = AlarmStateChangeTrace()
state_trace.table = str(self.tab)
state_trace.uv = str(self.uv)
state_trace.alarm_type = str(self.nm)
state_trace.old_state = os
state_trace.new_state = ns
state_trace.trace_msg(name="AlarmStateChangeTrace", \
sandesh=self._sandesh)
def clear_alarms(self):
"""
This function runs the state machine code for clearing an alarm
If a timer becomes Idle with no soaking enabled,
caller should delete corresponding alarm and send out updated AlarmUVE
"""
cur_time = int(time.time())
old_state = self.uas.state
delete_alarm = False
if self.uas.state == UVEAlarmState.Soak_Active:
# stop the active timer and start idle timer
self.uas.state = UVEAlarmState.Idle
self._remove_timer_from_list(self.activeTimeout)
if self.uac.FreqCheck_Seconds:
self.deleteTimeout = cur_time + self.uac.FreqCheck_Seconds
to_value = self.deleteTimeout
if not to_value in AlarmStateMachine.tab_alarms_timer:
AlarmStateMachine.tab_alarms_timer[to_value] = set()
AlarmStateMachine.tab_alarms_timer[to_value].add\
((self.tab, self.uv, self.nm))
else:
delete_alarm = True
elif self.uas.state == UVEAlarmState.Active:
if not self.uac.IdleTimer:
# Move to Idle state, caller should delete it
self.uas.state = UVEAlarmState.Idle
if self.uac.FreqCheck_Seconds:
self.deleteTimeout = cur_time + self.uac.FreqCheck_Seconds
to_value = self.deleteTimeout
if not to_value in AlarmStateMachine.tab_alarms_timer:
AlarmStateMachine.tab_alarms_timer[to_value] = set()
AlarmStateMachine.tab_alarms_timer[to_value].add\
((self.tab, self.uv, self.nm))
else:
delete_alarm = True
else:
self.uas.state = UVEAlarmState.Soak_Idle
self.idleTimeout = cur_time + self.uac.IdleTimer
to_value = self.idleTimeout
if not to_value in AlarmStateMachine.tab_alarms_timer:
AlarmStateMachine.tab_alarms_timer[to_value] = set()
AlarmStateMachine.tab_alarms_timer[to_value].add\
((self.tab, self.uv, self.nm))
self.send_state_change_trace(old_state, self.uas.state)
return delete_alarm
def is_alarm_frequency_exceeded(self):
if not self.uac.FreqExceededCheck or \
not self.uac.FreqCheck_Times or \
not self.uac.FreqCheck_Seconds:
return False
if len(self.uas.alarm_timestamp) < self.uac.FreqCheck_Times + 1:
return False
freqCheck_times = self.uac.FreqCheck_Times
head = self.uas.head_timestamp
start = (head + freqCheck_times + 1) % freqCheck_times
end = (head + freqCheck_times) % freqCheck_times
if (self.uas.alarm_timestamp[end] - self.uas.alarm_timestamp[start]) \
<= self.uac.FreqCheck_Seconds:
self._logger.info("alarm frequency is exceeded, raising alarm")
return True
return False
def run_active_timer(self, curr_time):
update_alarm = False
timeout_value = None
if curr_time >= self.activeTimeout:
self.send_state_change_trace(self.uas.state,
UVEAlarmState.Active)
self.uas.state = UVEAlarmState.Active
timeout_value = -1
update_alarm = True
return timeout_value, update_alarm
def run_idle_timer(self, curr_time):
"""
This is the handler function for checking timer in Soak_Idle state.
State Machine should be deleted by the caller if this timer fires
"""
idleTimerExpired = 0
update_alarm = False
timeout_value = None
delete_alarm = False
if self.idleTimeout:
idleTimerExpired = curr_time - self.idleTimeout
if idleTimerExpired >= 0:
self.send_state_change_trace(self.uas.state, UVEAlarmState.Idle)
self.uas.state = UVEAlarmState.Idle
if self.uac.FreqCheck_Seconds:
self.deleteTimeout = curr_time + self.uac.FreqCheck_Seconds
timeout_value = self.deleteTimeout
update_alarm = True
else:
delete_alarm = True
return timeout_value, update_alarm, delete_alarm
def run_delete_timer(self, curr_time):
"""
This is the handler function for checking timer in Idle state.
State Machine should be deleted by the caller if this timer fires
"""
delete_alarm = False
idleTimerExpired = 0
if self.deleteTimeout > 0:
idleTimerExpired = curr_time - self.deleteTimeout
if idleTimerExpired >= 0:
delete_alarm = True
return delete_alarm
def run_uve_soaking_timer(self, curr_time):
"""
This function goes through the list of alarms which were raised
or set to delete but not soaked yet.
If an alarm is soaked for corresponding soak_time then it is asserted
or deleted
"""
update_alarm = False
delete_alarm = False
timeout_value = None
if self.uas.state == UVEAlarmState.Soak_Active:
timeout_value, update_alarm = self.run_active_timer(curr_time)
elif self.uas.state == UVEAlarmState.Soak_Idle:
timeout_value, update_alarm, delete_alarm = self.run_idle_timer(curr_time)
elif self.uas.state == UVEAlarmState.Idle:
delete_alarm = self.run_delete_timer(curr_time)
return delete_alarm, update_alarm, timeout_value
#end run_uve_soaking_timer
def delete_timers(self):
if self.uas.state == UVEAlarmState.Idle:
if self.deleteTimeout and self.deleteTimeout > 0:
self._remove_timer_from_list(self.deleteTimeout)
elif self.uas.state == UVEAlarmState.Soak_Active:
if self.activeTimeout and self.activeTimeout > 0:
self._remove_timer_from_list(self.activeTimeout)
elif self.uas.state == UVEAlarmState.Soak_Idle:
if self.idleTimeout and self.idleTimeout > 0:
self._remove_timer_from_list(self.idleTimeout)
@staticmethod
def run_timers(curr_time, tab_alarms):
inputs = namedtuple('inputs', ['tab', 'uv', 'nm',
'delete_alarm', 'timeout_val', 'old_to'])
delete_alarms = []
update_alarms = []
if curr_time in AlarmStateMachine.tab_alarms_timer:
update_timers = []
for (tab, uv, nm) in AlarmStateMachine.tab_alarms_timer[curr_time]:
asm = tab_alarms[tab][uv][nm]
delete_alarm, update_alarm, timeout_val = \
asm.run_uve_soaking_timer(curr_time)
if delete_alarm:
delete_alarms.append((asm.tab, asm.uv, asm.nm))
if update_alarm:
update_alarms.append((asm.tab, asm.uv, asm.nm))
update_timers.append(inputs(tab=asm.tab, uv=asm.uv, nm=asm.nm,
delete_alarm=delete_alarm,
timeout_val=timeout_val, old_to=curr_time))
for timer in update_timers:
if timer.timeout_val is not None or timer.delete_alarm:
AlarmStateMachine.update_tab_alarms_timer(timer.tab,
timer.uv, timer.nm, timer.old_to,
timer.timeout_val, tab_alarms)
return delete_alarms, update_alarms
@staticmethod
def update_tab_alarms_timer(tab, uv, nm, curr_index, timeout_val,
tab_alarms):
del_timers = []
if curr_index is not None and curr_index > 0:
timers = AlarmStateMachine.tab_alarms_timer[curr_index]
if (tab, uv, nm) in timers:
asm = tab_alarms[tab][uv][nm]
timers.discard((tab, uv, nm))
if len(timers) == 0:
del_timers.append(curr_index)
for timeout in del_timers:
del AlarmStateMachine.tab_alarms_timer[timeout]
if timeout_val >= 0:
if not timeout_val in AlarmStateMachine.tab_alarms_timer:
AlarmStateMachine.tab_alarms_timer[timeout_val] = set()
if (tab, uv, nm) in AlarmStateMachine.tab_alarms_timer\
[timeout_val]:
self._logger.error("Timer error for (%s,%s,%s)" % \
(tab, uv, nm))
raise SystemExit
AlarmStateMachine.tab_alarms_timer[timeout_val].add\
((asm.tab, asm.uv, asm.nm))
class Controller(object):
@staticmethod
def token(sandesh, timestamp):
token = {'host_ip': sandesh.host_ip(),
'http_port': sandesh._http_server.get_port(),
'timestamp': timestamp}
return base64.b64encode(json.dumps(token))
def fail_cb(self, manager, entrypoint, exception):
self._sandesh._logger.info("Load failed for %s with exception %s" % \
(str(entrypoint),str(exception)))
def __init__(self, conf, test_logger=None):
self._conf = conf
module = Module.ALARM_GENERATOR
self._moduleid = ModuleNames[module]
node_type = Module2NodeType[module]
self._node_type_name = NodeTypeNames[node_type]
self.table = "ObjectCollectorInfo"
self._hostname = socket.gethostname()
self._instance_id = self._conf.worker_id()
self.disc = None
self._libpart_name = self._conf.host_ip() + ":" + self._instance_id
self._libpart = None
self._partset = set()
if self._conf.discovery()['server']:
self._max_out_rows = 20
self.disc = client.DiscoveryClient(
self._conf.discovery()['server'],
self._conf.discovery()['port'],
ModuleNames[Module.ALARM_GENERATOR],
'%s-%s' % (self._hostname, self._instance_id))
is_collector = True
if test_logger is not None:
is_collector = False
self._sandesh = Sandesh()
# Reset the sandesh send rate limit value
if self._conf.sandesh_send_rate_limit() is not None:
SandeshSystem.set_sandesh_send_rate_limit( \
self._conf.sandesh_send_rate_limit())
self._sandesh.init_generator(self._moduleid, self._hostname,
self._node_type_name, self._instance_id,
self._conf.collectors(),
self._node_type_name,
self._conf.http_port(),
['opserver.sandesh', 'sandesh'],
host_ip=self._conf.host_ip(),
discovery_client=self.disc,
connect_to_collector = is_collector,
alarm_ack_callback=self.alarm_ack_callback)
if test_logger is not None:
self._logger = test_logger
else:
self._sandesh.set_logging_params(
enable_local_log=self._conf.log_local(),
category=self._conf.log_category(),
level=self._conf.log_level(),
file=self._conf.log_file(),
enable_syslog=self._conf.use_syslog(),
syslog_facility=self._conf.syslog_facility())
self._logger = self._sandesh._logger
# Trace buffer list
self.trace_buf = [
{'name':'DiscoveryMsg', 'size':1000},
{'name':'AlarmStateChangeTrace', 'size':1000},
{'name':'UVEQTrace', 'size':10000}
]
# Create trace buffers
for buf in self.trace_buf:
self._sandesh.trace_buffer_create(name=buf['name'], size=buf['size'])
tables = set()
mgrlist = extension.ExtensionManager('contrail.analytics.alarms')
for elem in mgrlist:
tables.add(elem.name)
self._logger.error('Found extenstions for %s' % str(tables))
self.mgrs = {}
self.tab_alarms = {}
self.ptab_info = {}
self.tab_perf = {}
self.tab_perf_prev = {}
for table in tables:
self.mgrs[table] = hook.HookManager(
namespace='contrail.analytics.alarms',
name=table,
invoke_on_load=True,
invoke_args=(),
on_load_failure_callback=self.fail_cb
)
for extn in self.mgrs[table][table]:
self._logger.info('Loaded extensions for %s: %s,%s doc %s' % \
(table, extn.name, extn.entry_point_target, extn.obj.__doc__))
self.tab_alarms[table] = {}
self.tab_perf[table] = AGTabStats()
ConnectionState.init(self._sandesh, self._hostname, self._moduleid,
self._instance_id,
staticmethod(ConnectionState.get_process_state_cb),
NodeStatusUVE, NodeStatus, self.table)
self._us = UVEServer(None, self._logger, self._conf.redis_password())
if not self.disc:
self._max_out_rows = 2
# If there is no discovery service, use fixed redis_uve list
redis_uve_list = []
try:
for redis_uve in self._conf.redis_uve_list():
redis_ip_port = redis_uve.split(':')
redis_elem = (redis_ip_port[0], int(redis_ip_port[1]),0)
redis_uve_list.append(redis_elem)
except Exception as e:
print('Failed to parse redis_uve_list: %s' % e)
else:
self._us.update_redis_uve_list(redis_uve_list)
# If there is no discovery service, use fixed alarmgen list
self._libpart = self.start_libpart(self._conf.alarmgen_list())
self._workers = {}
self._uvestats = {}
self._uveq = {}
self._uveqf = {}
self._alarm_config_change_map = {}
# Create config handler to read/update alarm config
rabbitmq_params = self._conf.rabbitmq_params()
self._config_handler = AlarmGenConfigHandler(self._moduleid,
self._instance_id, self.config_log, self.disc,
self._conf.keystone_params(), rabbitmq_params, self.mgrs,
self.alarm_config_change_callback)
if rabbitmq_params['servers'] and self.disc:
self._config_handler.start()
else:
self._logger.error('Rabbitmq server and/or Discovery server '
'not configured')
PartitionOwnershipReq.handle_request = self.handle_PartitionOwnershipReq
PartitionStatusReq.handle_request = self.handle_PartitionStatusReq
UVETableAlarmReq.handle_request = self.handle_UVETableAlarmReq
UVETableInfoReq.handle_request = self.handle_UVETableInfoReq
UVETablePerfReq.handle_request = self.handle_UVETablePerfReq
def config_log(self, msg, level):
self._sandesh.logger().log(
SandeshLogger.get_py_logger_level(level), msg)
# end config_log
def libpart_cb(self, part_list):
agpi = AlarmgenPartionInfo()
agpi.instance = self._instance_id
agpi.partitions = part_list
agp = AlarmgenPartition()
agp.name = self._hostname
agp.inst_parts = [agpi]
agp_trace = AlarmgenPartitionTrace(data=agp, sandesh=self._sandesh)
agp_trace.send(sandesh=self._sandesh)
newset = set(part_list)
oldset = self._partset
self._partset = newset
self._logger.error('Partition List : new %s old %s' % \
(str(newset),str(oldset)))
for addpart in (newset-oldset):
self._logger.error('Partition Add : %s' % addpart)
self.partition_change(addpart, True)
for delpart in (oldset-newset):
self._logger.error('Partition Del : %s' % delpart)
if not self.partition_change(delpart, False):
self._logger.error('Partition Del : %s failed!' % delpart)
raise SystemExit
self._logger.error('Partition List done : new %s old %s' % \
(str(newset),str(oldset)))
def start_libpart(self, ag_list):
if not self._conf.zk_list():
self._logger.error('Could not import libpartition: No zookeeper')
return None
if not ag_list:
self._logger.error('Could not import libpartition: No alarmgen list')
return None
try:
self._logger.error('Starting PC')
agpi = AlarmgenPartionInfo()
agpi.instance = self._instance_id
agpi.partitions = []
agp = AlarmgenPartition()
agp.name = self._hostname
agp.inst_parts = [agpi]
agp_trace = AlarmgenPartitionTrace(data=agp, sandesh=self._sandesh)
agp_trace.send(sandesh=self._sandesh)
pc = PartitionClient(self._conf.kafka_prefix() + "-alarmgen",
self._libpart_name, ag_list,
self._conf.partitions(), self.libpart_cb,
','.join(self._conf.zk_list()), self._logger)
self._logger.error('Started PC %s' % self._conf.kafka_prefix() + "-alarmgen")
return pc
except Exception as e:
self._logger.error('Could not import libpartition: %s' % str(e))
return None
def handle_uve_notifq(self, part, uves):
"""
uves :
This is a dict of UVEs that have changed, as per the following scheme:
<UVE-Key> : None # Any of the types may have changed
# Used during stop_partition and GenDelete
<UVE-Key> : { <Struct>: {} } # The given struct may have changed
<UVE-Key> : { <Struct>: None } # The given struct may have gone
Our treatment of the 2nd and 3rd case above is the same
"""
uveq_trace = UVEQTrace()
uveq_trace.uves = uves.keys()
uveq_trace.part = part
if part not in self._uveq:
self._uveq[part] = {}
self._logger.error('Created uveQ for part %s' % str(part))
uveq_trace.oper = "create"
else:
uveq_trace.oper = "update"
uveq_trace.trace_msg(name="UVEQTrace",\
sandesh=self._sandesh)
for uv,types in uves.iteritems():
if types is None: