-
Notifications
You must be signed in to change notification settings - Fork 19
/
Copy pathexternal_command.py
4026 lines (3414 loc) · 167 KB
/
external_command.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
# -*- coding: utf-8 -*-
#
# Copyright (C) 2015-2018: Alignak team, see AUTHORS.txt file for contributors
#
# This file is part of Alignak.
#
# Alignak 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.
#
# Alignak 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 Alignak. If not, see <http://www.gnu.org/licenses/>.
#
#
# This file incorporates work covered by the following copyright and
# permission notice:
#
# Copyright (C) 2009-2014:
# andrewmcgilvray, a.mcgilvray@gmail.com
# Guillaume Bour, guillaume@bour.cc
# Alexandre Viau, alexandre@alexandreviau.net
# Frédéric MOHIER, frederic.mohier@ipmfrance.com
# aviau, alexandre.viau@savoirfairelinux.com
# xkilian, fmikus@acktomic.com
# Nicolas Dupeux, nicolas@dupeux.net
# Hartmut Goebel, h.goebel@goebel-consult.de
# Grégory Starck, g.starck@gmail.com
# Arthur Gautier, superbaloo@superbaloo.net
# Sebastien Coavoux, s.coavoux@free.fr
# Squiz, squiz@squiz.confais.org
# Olivier Hanesse, olivier.hanesse@gmail.com
# Jean Gabes, naparuba@gmail.com
# Zoran Zaric, zz@zoranzaric.de
# Gerhard Lausser, gerhard.lausser@consol.de
# 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/>.
"""This module provides ExternalCommand and ExternalCommandManager classes
Used to process command sent by users
"""
# Because some arguments are really not used:
# pylint: disable=unused-argument
# Because it is easier to keep all the source code in the same file:
# pylint: disable=too-many-lines
# pylint: disable=too-many-public-methods
# Because sometimes we have many arguments
# pylint: disable=too-many-arguments
import logging
import time
import re
import collections
# This import, despite not used, is necessary to include all Alignak objects modules
# pylint: disable=wildcard-import,unused-wildcard-import
from alignak.action import ACT_STATUS_DONE, ACT_STATUS_TIMEOUT, ACT_STATUS_WAIT_CONSUME
from alignak.objects import *
from alignak.util import to_int, to_bool, split_semicolon
from alignak.downtime import Downtime
from alignak.contactdowntime import ContactDowntime
from alignak.comment import Comment
from alignak.log import make_monitoring_log
from alignak.eventhandler import EventHandler
from alignak.brok import Brok
from alignak.misc.common import DICT_MODATTR
from alignak.stats import statsmgr
logger = logging.getLogger(__name__) # pylint: disable=invalid-name
class ExternalCommand(object):
"""ExternalCommand class is only an object with a cmd_line attribute.
All parsing and execution is done in manager
"""
my_type = 'externalcommand'
def __init__(self, cmd_line, timestamp=None):
self.cmd_line = cmd_line
try:
self.cmd_line = self.cmd_line.decode('utf8', 'ignore')
except UnicodeEncodeError:
pass
except AttributeError:
# Python 3 will raise an exception
pass
self.creation_timestamp = timestamp or time.time()
def serialize(self, no_json=True, printing=False):
"""This function serializes into a simple dict object.
It is used when transferring data to other daemons over the network (http)
Here we directly return all attributes
:return: json representation of a Brok
:rtype: dict
"""
return {"my_type": self.my_type, "cmd_line": self.cmd_line,
"creation_timestamp": self.creation_timestamp}
class ExternalCommandManager(object):
"""ExternalCommandManager manages all external commands sent to Alignak.
It basically parses arguments and executes the right function
"""
commands = {
'change_contact_modsattr':
{'global': True, 'args': ['contact', None]},
'change_contact_modhattr':
{'global': True, 'args': ['contact', None]},
'change_contact_modattr':
{'global': True, 'args': ['contact', None]},
'change_contact_host_notification_timeperiod':
{'global': True, 'args': ['contact', 'time_period']},
'add_svc_comment':
{'global': False, 'args': ['service', 'obsolete', 'author', None]},
'add_host_comment':
{'global': False, 'args': ['host', 'obsolete', 'author', None]},
'acknowledge_svc_problem':
{'global': False, 'args': ['service', 'to_int', 'to_bool', 'obsolete', 'author', None]},
'acknowledge_host_problem':
{'global': False, 'args': ['host', 'to_int', 'to_bool', 'obsolete', 'author', None]},
'acknowledge_svc_problem_expire':
{'global': False, 'args': ['service', 'to_int', 'to_bool',
'obsolete', 'to_int', 'author', None]},
'acknowledge_host_problem_expire':
{'global': False,
'args': ['host', 'to_int', 'to_bool', 'obsolete', 'to_int', 'author', None]},
'change_contact_svc_notification_timeperiod':
{'global': True, 'args': ['contact', 'time_period']},
'change_custom_contact_var':
{'global': True, 'args': ['contact', None, None]},
'change_custom_host_var':
{'global': False, 'args': ['host', None, None]},
'change_custom_svc_var':
{'global': False, 'args': ['service', None, None]},
'change_global_host_event_handler':
{'global': True, 'args': ['command']},
'change_global_svc_event_handler':
{'global': True, 'args': ['command']},
'change_host_check_command':
{'global': False, 'args': ['host', 'command']},
'change_host_check_timeperiod':
{'global': False, 'args': ['host', 'time_period']},
'change_host_event_handler':
{'global': False, 'args': ['host', 'command']},
'change_host_snapshot_command':
{'global': False, 'args': ['host', 'command']},
'change_host_modattr':
{'global': False, 'args': ['host', 'to_int']},
'change_max_host_check_attempts':
{'global': False, 'args': ['host', 'to_int']},
'change_max_svc_check_attempts':
{'global': False, 'args': ['service', 'to_int']},
'change_normal_host_check_interval':
{'global': False, 'args': ['host', 'to_int']},
'change_normal_svc_check_interval':
{'global': False, 'args': ['service', 'to_int']},
'change_retry_host_check_interval':
{'global': False, 'args': ['host', 'to_int']},
'change_retry_svc_check_interval':
{'global': False, 'args': ['service', 'to_int']},
'change_svc_check_command':
{'global': False, 'args': ['service', 'command']},
'change_svc_check_timeperiod':
{'global': False, 'args': ['service', 'time_period']},
'change_svc_event_handler':
{'global': False, 'args': ['service', 'command']},
'change_svc_snapshot_command':
{'global': False, 'args': ['service', 'command']},
'change_svc_modattr':
{'global': False, 'args': ['service', 'to_int']},
'change_svc_notification_timeperiod':
{'global': False, 'args': ['service', 'time_period']},
'delay_host_notification':
{'global': False, 'args': ['host', 'to_int']},
'delay_svc_notification':
{'global': False, 'args': ['service', 'to_int']},
'del_all_contact_downtimes':
{'global': False, 'args': ['contact']},
'del_all_host_comments':
{'global': False, 'args': ['host']},
'del_all_host_downtimes':
{'global': False, 'args': ['host']},
'del_all_svc_comments':
{'global': False, 'args': ['service']},
'del_all_svc_downtimes':
{'global': False, 'args': ['service']},
'del_contact_downtime':
{'global': True, 'args': [None]},
'del_host_comment':
{'global': True, 'args': [None]},
'del_host_downtime':
{'global': True, 'args': [None]},
'del_svc_comment':
{'global': True, 'args': [None]},
'del_svc_downtime':
{'global': True, 'args': [None]},
'disable_all_notifications_beyond_host':
{'global': False, 'args': ['host']},
'disable_contactgroup_host_notifications':
{'global': True, 'args': ['contact_group']},
'disable_contactgroup_svc_notifications':
{'global': True, 'args': ['contact_group']},
'disable_contact_host_notifications':
{'global': True, 'args': ['contact']},
'disable_contact_svc_notifications':
{'global': True, 'args': ['contact']},
'disable_event_handlers':
{'global': True, 'args': []},
'disable_failure_prediction':
{'global': True, 'args': []},
'disable_flap_detection':
{'global': True, 'args': []},
'disable_hostgroup_host_checks':
{'global': True, 'args': ['host_group']},
'disable_hostgroup_host_notifications':
{'global': True, 'args': ['host_group']},
'disable_hostgroup_passive_host_checks':
{'global': True, 'args': ['host_group']},
'disable_hostgroup_passive_svc_checks':
{'global': True, 'args': ['host_group']},
'disable_hostgroup_svc_checks':
{'global': True, 'args': ['host_group']},
'disable_hostgroup_svc_notifications':
{'global': True, 'args': ['host_group']},
'disable_host_and_child_notifications':
{'global': False, 'args': ['host']},
'disable_host_check':
{'global': False, 'args': ['host']},
'disable_host_event_handler':
{'global': False, 'args': ['host']},
'disable_host_flap_detection':
{'global': False, 'args': ['host']},
'disable_host_freshness_check':
{'global': False, 'args': ['host']},
'disable_host_freshness_checks':
{'global': True, 'args': []},
'disable_host_notifications':
{'global': False, 'args': ['host']},
'disable_host_svc_checks':
{'global': False, 'args': ['host']},
'disable_host_svc_notifications':
{'global': False, 'args': ['host']},
'disable_notifications':
{'global': True, 'args': []},
'disable_passive_host_checks':
{'global': False, 'args': ['host']},
'disable_passive_svc_checks':
{'global': False, 'args': ['service']},
'disable_performance_data':
{'global': True, 'args': []},
'disable_servicegroup_host_checks':
{'global': True, 'args': ['service_group']},
'disable_servicegroup_host_notifications':
{'global': True, 'args': ['service_group']},
'disable_servicegroup_passive_host_checks':
{'global': True, 'args': ['service_group']},
'disable_servicegroup_passive_svc_checks':
{'global': True, 'args': ['service_group']},
'disable_servicegroup_svc_checks':
{'global': True, 'args': ['service_group']},
'disable_servicegroup_svc_notifications':
{'global': True, 'args': ['service_group']},
'disable_service_flap_detection':
{'global': False, 'args': ['service']},
'disable_service_freshness_checks':
{'global': True, 'args': []},
'disable_svc_check':
{'global': False, 'args': ['service']},
'disable_svc_event_handler':
{'global': False, 'args': ['service']},
'disable_svc_flap_detection':
{'global': False, 'args': ['service']},
'disable_svc_freshness_check':
{'global': False, 'args': ['service']},
'disable_svc_notifications':
{'global': False, 'args': ['service']},
'enable_all_notifications_beyond_host':
{'global': False, 'args': ['host']},
'enable_contactgroup_host_notifications':
{'global': True, 'args': ['contact_group']},
'enable_contactgroup_svc_notifications':
{'global': True, 'args': ['contact_group']},
'enable_contact_host_notifications':
{'global': True, 'args': ['contact']},
'enable_contact_svc_notifications':
{'global': True, 'args': ['contact']},
'enable_event_handlers':
{'global': True, 'args': []},
'enable_failure_prediction':
{'global': True, 'args': []},
'enable_flap_detection':
{'global': True, 'args': []},
'enable_hostgroup_host_checks':
{'global': True, 'args': ['host_group']},
'enable_hostgroup_host_notifications':
{'global': True, 'args': ['host_group']},
'enable_hostgroup_passive_host_checks':
{'global': True, 'args': ['host_group']},
'enable_hostgroup_passive_svc_checks':
{'global': True, 'args': ['host_group']},
'enable_hostgroup_svc_checks':
{'global': True, 'args': ['host_group']},
'enable_hostgroup_svc_notifications':
{'global': True, 'args': ['host_group']},
'enable_host_and_child_notifications':
{'global': False, 'args': ['host']},
'enable_host_check':
{'global': False, 'args': ['host']},
'enable_host_event_handler':
{'global': False, 'args': ['host']},
'enable_host_flap_detection':
{'global': False, 'args': ['host']},
'enable_host_freshness_check':
{'global': False, 'args': ['host']},
'enable_host_freshness_checks':
{'global': True, 'args': []},
'enable_host_notifications':
{'global': False, 'args': ['host']},
'enable_host_svc_checks':
{'global': False, 'args': ['host']},
'enable_host_svc_notifications':
{'global': False, 'args': ['host']},
'enable_notifications':
{'global': True, 'args': []},
'enable_passive_host_checks':
{'global': False, 'args': ['host']},
'enable_passive_svc_checks':
{'global': False, 'args': ['service']},
'enable_performance_data':
{'global': True, 'args': []},
'enable_servicegroup_host_checks':
{'global': True, 'args': ['service_group']},
'enable_servicegroup_host_notifications':
{'global': True, 'args': ['service_group']},
'enable_servicegroup_passive_host_checks':
{'global': True, 'args': ['service_group']},
'enable_servicegroup_passive_svc_checks':
{'global': True, 'args': ['service_group']},
'enable_servicegroup_svc_checks':
{'global': True, 'args': ['service_group']},
'enable_servicegroup_svc_notifications':
{'global': True, 'args': ['service_group']},
'enable_service_freshness_checks':
{'global': True, 'args': []},
'enable_svc_check':
{'global': False, 'args': ['service']},
'enable_svc_event_handler':
{'global': False, 'args': ['service']},
'enable_svc_flap_detection':
{'global': False, 'args': ['service']},
'enable_svc_freshness_check':
{'global': False, 'args': ['service']},
'enable_svc_notifications':
{'global': False, 'args': ['service']},
'process_file':
{'global': True, 'args': [None, 'to_bool']},
'process_host_check_result':
{'global': False, 'args': ['host', 'to_int', None]},
'process_host_output':
{'global': False, 'args': ['host', None]},
'process_service_check_result':
{'global': False, 'args': ['service', 'to_int', None]},
'process_service_output':
{'global': False, 'args': ['service', None]},
'read_state_information':
{'global': True, 'args': []},
'remove_host_acknowledgement':
{'global': False, 'args': ['host']},
'remove_svc_acknowledgement':
{'global': False, 'args': ['service']},
'restart_program':
{'global': True, 'internal': True, 'args': []},
'reload_config':
{'global': True, 'internal': True, 'args': []},
'save_state_information':
{'global': True, 'args': []},
'schedule_and_propagate_host_downtime':
{'global': False, 'args': ['host', 'to_int', 'to_int', 'to_bool',
'to_int', 'to_int', 'author', None]},
'schedule_and_propagate_triggered_host_downtime':
{'global': False, 'args': ['host', 'to_int', 'to_int', 'to_bool',
'to_int', 'to_int', 'author', None]},
'schedule_contact_downtime':
{'global': True, 'args': ['contact', 'to_int', 'to_int', 'author', None]},
'schedule_forced_host_check':
{'global': False, 'args': ['host', 'to_int']},
'schedule_forced_host_svc_checks':
{'global': False, 'args': ['host', 'to_int']},
'schedule_forced_svc_check':
{'global': False, 'args': ['service', 'to_int']},
'schedule_hostgroup_host_downtime':
{'global': True, 'args': ['host_group', 'to_int', 'to_int',
'to_bool', None, 'to_int', 'author', None]},
'schedule_hostgroup_svc_downtime':
{'global': True, 'args': ['host_group', 'to_int', 'to_int', 'to_bool',
None, 'to_int', 'author', None]},
'schedule_host_check':
{'global': False, 'args': ['host', 'to_int']},
'schedule_host_downtime':
{'global': False, 'args': ['host', 'to_int', 'to_int', 'to_bool',
None, 'to_int', 'author', None]},
'schedule_host_svc_checks':
{'global': False, 'args': ['host', 'to_int']},
'schedule_host_svc_downtime':
{'global': False, 'args': ['host', 'to_int', 'to_int', 'to_bool',
None, 'to_int', 'author', None]},
'schedule_servicegroup_host_downtime':
{'global': True, 'args': ['service_group', 'to_int', 'to_int', 'to_bool',
None, 'to_int', 'author', None]},
'schedule_servicegroup_svc_downtime':
{'global': True, 'args': ['service_group', 'to_int', 'to_int', 'to_bool',
None, 'to_int', 'author', None]},
'schedule_svc_check':
{'global': False, 'args': ['service', 'to_int']},
'schedule_svc_downtime':
{'global': False, 'args': ['service', 'to_int', 'to_int',
'to_bool', None, 'to_int', 'author', None]},
'send_custom_host_notification':
{'global': False, 'args': ['host', 'to_int', 'author', None]},
'send_custom_svc_notification':
{'global': False, 'args': ['service', 'to_int', 'author', None]},
'set_host_notification_number':
{'global': False, 'args': ['host', 'to_int']},
'set_svc_notification_number':
{'global': False, 'args': ['service', 'to_int']},
'shutdown_program':
{'global': True, 'args': []},
'start_accepting_passive_host_checks':
{'global': True, 'args': []},
'start_accepting_passive_svc_checks':
{'global': True, 'args': []},
'start_executing_host_checks':
{'global': True, 'args': []},
'start_executing_svc_checks':
{'global': True, 'args': []},
'stop_accepting_passive_host_checks':
{'global': True, 'args': []},
'stop_accepting_passive_svc_checks':
{'global': True, 'args': []},
'stop_executing_host_checks':
{'global': True, 'args': []},
'stop_executing_svc_checks':
{'global': True, 'args': []},
'launch_svc_event_handler':
{'global': False, 'args': ['service']},
'launch_host_event_handler':
{'global': False, 'args': ['host']},
# Now internal calls
'add_simple_host_dependency':
{'global': False, 'args': ['host', 'host']},
'del_host_dependency':
{'global': False, 'args': ['host', 'host']},
'add_simple_poller':
{'global': True, 'internal': True, 'args': [None, None, None, None]},
}
def __init__(self, conf, mode, daemon, accept_unknown=False, log_external_commands=False):
"""
The command manager is initialized with a `mode` parameter specifying what is to be done
with the managed commands. If mode is:
- applyer, the user daemon is a scheduler that will execute the command
- dispatcher, the user daemon only dispatches the command to an applyer
- receiver, the user daemon only receives commands, analyses and then dispatches
them to the schedulers
Note that the daemon parameter is really a Daemon object except for the scheduler where
it is a Scheduler object!
If `accept_passive_unknown_check_results` is True, then a Brok will be created even if
passive checks are received for unknown host/service else a Warning log will be emitted..
Note: the receiver mode has no configuration
:param conf: current configuration
:type conf: alignak.objects.Config
:param mode: command manager mode
:type mode: str
:param daemon:
:type daemon: alignak.Daemon
:param accept_unknown: accept or not unknown passive checks results
:type accept_unknown: bool
"""
self.daemon = daemon
self.mode = mode
# If we got a conf...
if self.mode == 'receiver':
self.my_conf = {
'schedulers': daemon.schedulers
}
else:
self.my_conf = conf
if conf:
self.my_conf = conf
self.hosts = conf.hosts
self.services = conf.services
self.contacts = conf.contacts
self.hostgroups = conf.hostgroups
self.commands = conf.commands
self.servicegroups = conf.servicegroups
self.contactgroups = conf.contactgroups
self.timeperiods = conf.timeperiods
self.cfg_parts = None
if self.mode == 'dispatcher':
self.cfg_parts = conf.parts
self.accept_passive_unknown_check_results = accept_unknown
self.log_external_commands = log_external_commands
logger.debug("External command manager, log commands: %s, accept unknown check: %s",
self.log_external_commands, self.accept_passive_unknown_check_results)
# Will change for each command read, so if a command need it,
# it can get it
self.current_timestamp = 0
def send_an_element(self, element):
"""Send an element (Brok, Comment,...) to our daemon
Use the daemon `add` function if it exists, else raise an error log
:param element: elementto be sent
:type: alignak.Brok, or Comment, or Downtime, ...
:return:
"""
# Comment this log because it raises an encoding exception on Travis CI with python 2.7!
# logger.debug("Sending to %s for %s", self.daemon, element)
if hasattr(self.daemon, "add"):
func = getattr(self.daemon, "add")
if isinstance(func, collections.Callable):
try:
func(element)
except Exception as exp: # pylint: disable=broad-except
logger.critical("Daemon report exception: %s", exp)
return
logger.critical("External command or Brok could not be sent to any daemon!")
def resolve_command(self, excmd):
"""Parse command and dispatch it (to schedulers for example) if necessary
If the command is not global it will be executed.
:param excmd: external command to handle
:type excmd: alignak.external_command.ExternalCommand
:return: result of command parsing. None for an invalid command.
"""
# Maybe the command is invalid. Bailout
try:
command = excmd.cmd_line
except AttributeError as exp: # pragma: no cover, simple protection
logger.warning("resolve_command, error with command %s", excmd)
logger.exception("Exception: %s", exp)
return None
# Parse command
command = command.strip()
cmd = self.get_command_and_args(command, excmd)
if cmd is None:
return cmd
# If we are a receiver, bail out here... do not try to execute the command
if self.mode == 'receiver' and not cmd.get('internal', False):
return cmd
if self.mode == 'applyer' and self.log_external_commands:
make_a_log = True
# #912: only log an external command if it is not a passive check
if self.my_conf.log_passive_checks and cmd['c_name'] \
in ['process_host_check_result', 'process_service_check_result']:
# Do not log the command
make_a_log = False
if make_a_log:
# I am a command dispatcher, notifies to my arbiter
self.send_an_element(make_monitoring_log('info', 'EXTERNAL COMMAND: ' + command))
if not cmd['global']:
# Execute the command
c_name = cmd['c_name']
args = cmd['args']
logger.debug("Execute command: %s %s", c_name, str(args))
logger.debug("Command time measurement: %s (%d s)",
excmd.creation_timestamp, time.time() - excmd.creation_timestamp)
statsmgr.timer('external-commands.latency', time.time() - excmd.creation_timestamp)
getattr(self, c_name)(*args)
else:
# Send command to all our schedulers
for scheduler_link in self.my_conf.schedulers:
logger.debug("Preparing an external command '%s' for the scheduler %s",
excmd, scheduler_link.name)
scheduler_link.pushed_commands.append(excmd.cmd_line)
return cmd
def search_host_and_dispatch(self, host_name, command, extcmd):
# pylint: disable=too-many-branches
"""Try to dispatch a command for a specific host (so specific scheduler)
because this command is related to a host (change notification interval for example)
:param host_name: host name to search
:type host_name: str
:param command: command line
:type command: str
:param extcmd: external command object (the object will be added to sched commands list)
:type extcmd: alignak.external_command.ExternalCommand
:return: None
"""
logger.debug("Calling search_host_and_dispatch for %s", host_name)
host_found = False
# If we are a receiver, just look in the receiver
if self.mode == 'receiver':
logger.debug("Receiver is searching a scheduler for the external command %s %s",
host_name, command)
scheduler_link = self.daemon.get_scheduler_from_hostname(host_name)
if scheduler_link:
host_found = True
logger.debug("Receiver pushing external command to scheduler %s",
scheduler_link.name)
scheduler_link.pushed_commands.append(extcmd)
else:
logger.warning("I did not found a scheduler for the host: %s", host_name)
else:
for cfg_part in list(self.cfg_parts.values()):
if cfg_part.hosts.find_by_name(host_name) is not None:
logger.debug("Host %s found in a configuration", host_name)
if cfg_part.is_assigned:
host_found = True
scheduler_link = cfg_part.scheduler_link
logger.debug("Sending command to the scheduler %s", scheduler_link.name)
scheduler_link.push_external_commands([command])
# scheduler_link.my_daemon.external_commands.append(command)
break
else:
logger.warning("Problem: the host %s was found in a configuration, "
"but this configuration is not assigned to any scheduler!",
host_name)
if not host_found:
if self.accept_passive_unknown_check_results:
brok = self.get_unknown_check_result_brok(command)
if brok:
self.send_an_element(brok)
else:
logger.warning("External command was received for the host '%s', "
"but the host could not be found! Command is: %s",
host_name, command)
else:
logger.warning("External command was received for host '%s', "
"but the host could not be found!", host_name)
@staticmethod
def get_unknown_check_result_brok(cmd_line):
"""Create unknown check result brok and fill it with command data
:param cmd_line: command line to extract data
:type cmd_line: str
:return: unknown check result brok
:rtype: alignak.objects.brok.Brok
"""
match = re.match(
r'^\[([0-9]{10})] PROCESS_(SERVICE)_CHECK_RESULT;'
r'([^\;]*);([^\;]*);([^\;]*);([^\|]*)(?:\|(.*))?', cmd_line)
if not match:
match = re.match(
r'^\[([0-9]{10})] PROCESS_(HOST)_CHECK_RESULT;'
r'([^\;]*);([^\;]*);([^\|]*)(?:\|(.*))?', cmd_line)
if not match:
return None
data = {
'time_stamp': int(match.group(1)),
'host_name': match.group(3),
}
if match.group(2) == 'SERVICE':
data['service_description'] = match.group(4)
data['return_code'] = match.group(5)
data['output'] = match.group(6)
data['perf_data'] = match.group(7)
else:
data['return_code'] = match.group(4)
data['output'] = match.group(5)
data['perf_data'] = match.group(6)
return Brok({'type': 'unknown_%s_check_result' % match.group(2).lower(), 'data': data})
def get_command_and_args(self, command, extcmd=None):
# pylint: disable=too-many-return-statements, too-many-nested-blocks
# pylint: disable=too-many-locals,too-many-branches,too-many-statements
"""Parse command and get args
:param command: command line to parse
:type command: str
:param extcmd: external command object (used to dispatch)
:type extcmd: None | object
:return: Dict containing command and arg ::
{'global': False, 'c_name': c_name, 'args': args}
:rtype: dict | None
"""
# danger!!! passive check results with perfdata
elts = split_semicolon(command)
try:
timestamp, c_name = elts[0].split()
except ValueError as exp:
splitted_command = elts[0].split()
if len(splitted_command) == 1:
# Assume no timestamp and only a command
timestamp = "[%s]" % int(time.time())
logger.warning("Missing timestamp in command '%s', using %s as a timestamp.",
elts[0], timestamp)
c_name = elts[0].split()[0]
else:
logger.warning("Malformed command '%s'", command)
# logger.exception("Malformed command exception: %s", exp)
if self.log_external_commands:
# The command failed, make a monitoring log to inform
self.send_an_element(make_monitoring_log(
'error', "Malformed command: '%s'" % command))
return None
c_name = c_name.lower()
# Is timestamp already an integer value?
try:
timestamp = int(timestamp)
except ValueError as exp:
# Else, remove enclosing characters: [], (), {}, ...
timestamp = timestamp[1:-1]
# Finally, check that the timestamp is really a timestamp
try:
self.current_timestamp = int(timestamp)
except ValueError as exp:
logger.warning("Malformed command '%s'", command)
# logger.exception("Malformed command exception: %s", exp)
if self.log_external_commands:
# The command failed, make a monitoring log to inform
self.send_an_element(make_monitoring_log(
'error', "Malformed command: '%s'" % command))
return None
if c_name not in ExternalCommandManager.commands:
logger.warning("External command '%s' is not recognized, sorry", c_name)
if self.log_external_commands:
# The command failed, make a monitoring log to inform
self.send_an_element(make_monitoring_log(
'error', "Command '%s' is not recognized, sorry" % command))
return None
# Split again based on the number of args we expect. We cannot split
# on every ; because this character may appear in the perfdata of
# passive check results.
entry = ExternalCommandManager.commands[c_name]
# Look if the command is purely internal (Alignak) or not
internal = False
if 'internal' in entry and entry['internal']:
internal = True
numargs = len(entry['args'])
if numargs and 'service' in entry['args']:
numargs += 1
elts = split_semicolon(command, numargs)
logger.debug("mode= %s, global= %s", self.mode, str(entry['global']))
if self.mode in ['dispatcher', 'receiver'] and entry['global']:
if not internal:
logger.debug("Command '%s' is a global one, we resent it to all schedulers", c_name)
return {'global': True, 'cmd': command}
args = []
i = 1
in_service = False
tmp_host = ''
obsolete_arg = 0
try:
for elt in elts[1:]:
try:
elt = elt.decode('utf8', 'ignore')
except AttributeError:
# Python 3 will raise an error...
pass
except UnicodeEncodeError:
pass
logger.debug("Searching for a new arg: %s (%d)", elt, i)
val = elt.strip()
if val.endswith('\n'):
val = val[:-1]
logger.debug("For command arg: %s", val)
if not in_service:
type_searched = entry['args'][i - 1]
logger.debug("Type searched: %s", type_searched)
if type_searched == 'host':
if self.mode == 'dispatcher' or self.mode == 'receiver':
self.search_host_and_dispatch(val, command, extcmd)
return None
host = self.hosts.find_by_name(val)
if host is None:
if self.accept_passive_unknown_check_results:
brok = self.get_unknown_check_result_brok(command)
if brok:
self.daemon.add_brok(brok)
else:
logger.warning("A command was received for the host '%s', "
"but the host could not be found!", val)
return None
args.append(host)
elif type_searched == 'contact':
contact = self.contacts.find_by_name(val)
if contact is not None:
args.append(contact)
elif type_searched == 'time_period':
timeperiod = self.timeperiods.find_by_name(val)
if timeperiod is not None:
args.append(timeperiod)
elif type_searched == 'obsolete':
obsolete_arg += 1
elif type_searched == 'to_bool':
args.append(to_bool(val))
elif type_searched == 'to_int':
args.append(to_int(val))
elif type_searched in ('author', None):
args.append(val)
elif type_searched == 'command':
command = self.commands.find_by_name(val)
if command is not None:
# the find will be redone by
# the commandCall creation, but != None
# is useful so a bad command will be caught
args.append(val)
elif type_searched == 'host_group':
hostgroup = self.hostgroups.find_by_name(val)
if hostgroup is not None:
args.append(hostgroup)
elif type_searched == 'service_group':
servicegroup = self.servicegroups.find_by_name(val)
if servicegroup is not None:
args.append(servicegroup)
elif type_searched == 'contact_group':
contactgroup = self.contactgroups.find_by_name(val)
if contactgroup is not None:
args.append(contactgroup)
# special case: service are TWO args host;service, so one more loop
# to get the two parts
elif type_searched == 'service':
in_service = True
tmp_host = elt.strip()
if tmp_host[-1] == '\n':
tmp_host = tmp_host[:-1]
if self.mode == 'dispatcher':
self.search_host_and_dispatch(tmp_host, command, extcmd)
return None
i += 1
else:
in_service = False
srv_name = elt
if srv_name[-1] == '\n':
srv_name = srv_name[:-1]
# If we are in a receiver, bailout now.
if self.mode == 'receiver':
self.search_host_and_dispatch(tmp_host, command, extcmd)
return None
serv = self.services.find_srv_by_name_and_hostname(tmp_host, srv_name)
if serv is None:
if self.accept_passive_unknown_check_results:
brok = self.get_unknown_check_result_brok(command)
self.send_an_element(brok)
else:
logger.warning("A command was received for the service '%s' on "
"host '%s', but the service could not be found!",
srv_name, tmp_host)
return None
args.append(serv)
logger.debug("Got args: %s", args)
except IndexError as exp:
logger.warning("Sorry, the arguments for the command '%s' are not correct")
logger.exception("Arguments parsing exception: %s", exp)
if self.log_external_commands:
# The command failed, make a monitoring log to inform
self.send_an_element(make_monitoring_log(
'error', "Arguments are not correct for the command: '%s'" % command))
else:
if len(args) == (len(entry['args']) - obsolete_arg):
return {
'global': False, 'internal': internal,
'c_name': c_name, 'args': args
}
logger.warning("Sorry, the arguments for the command '%s' are not correct (%s)",
command, (args))
if self.log_external_commands:
# The command failed, make a monitoring log to inform
self.send_an_element(make_monitoring_log(
'error', "Arguments are not correct for the command: '%s'" % command))
return None
@staticmethod
def change_contact_modsattr(contact, value):
"""Change contact modified service attribute value
Format of the line that triggers function call::
CHANGE_CONTACT_MODSATTR;<contact_name>;<value>
:param contact: contact to edit
:type contact: alignak.objects.contact.Contact
:param value: new value to set
:type value: str
:return: None
"""
# todo: deprecate this
contact.modified_service_attributes = int(value)
@staticmethod
def change_contact_modhattr(contact, value):
"""Change contact modified host attribute value
Format of the line that triggers function call::
CHANGE_CONTACT_MODHATTR;<contact_name>;<value>
:param contact: contact to edit
:type contact: alignak.objects.contact.Contact
:param value: new value to set
:type value:str
:return: None
"""
# todo: deprecate this
contact.modified_host_attributes = int(value)
@staticmethod
def change_contact_modattr(contact, value):
"""Change contact modified attribute value
Format of the line that triggers function call::
CHANGE_CONTACT_MODATTR;<contact_name>;<value>
:param contact: contact to edit
:type contact: alignak.objects.contact.Contact
:param value: new value to set
:type value: str
:return: None
"""
# todo: deprecate this
contact.modified_attributes = int(value)
def change_contact_host_notification_timeperiod(self, contact, notification_timeperiod):
"""Change contact host notification timeperiod value
Format of the line that triggers function call::