-
Notifications
You must be signed in to change notification settings - Fork 5
/
app.py
executable file
·3250 lines (2777 loc) · 121 KB
/
app.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/env python
# -*- coding: utf-8 -*-
"""
``alignak_backend.app`` module
This module manages the backend, its configuration and starts the backend
Default date format is:
'%a, %d %b %Y %H:%M:%S GMT'
"""
from __future__ import print_function
import json
import os
import re
import sys
import time
import uuid
import socket
from collections import OrderedDict
from datetime import datetime, timedelta
import logging
from logging.config import dictConfig as logger_dictConfig
import requests
from dateutil import parser
from future.utils import iteritems
from eve import Eve
from eve.auth import TokenAuth
from eve.io.mongo import Validator
from eve.methods.delete import deleteitem_internal
from eve.methods.patch import patch_internal
from eve.methods.post import post_internal
from eve.utils import debug_error_message
from eve_swagger import swagger
from flask import current_app, g, request, abort, jsonify, make_response, send_from_directory, \
redirect
from flask_apscheduler import APScheduler
from flask_bootstrap import Bootstrap
from werkzeug.security import check_password_hash, generate_password_hash
from bson.objectid import ObjectId
import alignak_backend
from alignak_backend import manifest
from alignak_backend.grafana import Grafana
from alignak_backend.livesynthesis import Livesynthesis
from alignak_backend.models import register_models
from alignak_backend.template import Template
from alignak_backend.timeseries import Timeseries
_subcommands = OrderedDict()
class MyTokenAuth(TokenAuth):
"""
Class to manage authentication
"""
children_realms = {}
parent_realms = {}
"""Authentication token class"""
def check_auth(self, token, allowed_roles, resource, method):
# pylint: disable=too-many-locals
"""
Check if account exist and get roles for this user
:param token: token for auth
:type token: str
:param allowed_roles:
:type allowed_roles:
:param resource: name of the resource requested by user
:type resource: str
:param method: method used: GET | POST | PATCH | DELETE
:type method: str
:return: True if user exist and password is ok or if no roles defined, otherwise False
:rtype: bool
"""
user = current_app.data.driver.db['user'].find_one({'token': token})
if user:
# We get all resources we have in the backend for the userrestrictrole with *
resource_list = list(current_app.config['DOMAIN'])
g.updateRealm = False
g.updateGroup = False
g.user_realm = user['_realm']
# get children of realms for rights
realmsdrv = current_app.data.driver.db['realm']
allrealms = realmsdrv.find()
self.children_realms = {}
self.parent_realms = {}
for realm in allrealms:
self.children_realms[realm['_id']] = realm['_all_children']
self.parent_realms[realm['_id']] = realm['_tree_parents']
g.back_role_super_admin = user['back_role_super_admin']
g.can_submit_commands = user['can_submit_commands']
userrestrictroles = current_app.data.driver.db['userrestrictrole']
userrestrictrole = userrestrictroles.find({'user': user['_id']})
g.resources_get = {}
g.resources_get_parents = {}
get_parents = {}
g.resources_get_custom = {}
g.resources_post = {}
g.resources_post_parents = {}
g.resources_patch = {}
g.resources_patch_parents = {}
g.resources_patch_custom = {}
g.resources_delete = {}
g.resources_delete_parents = {}
g.resources_delete_custom = {}
for rights in userrestrictrole:
self.add_resources_realms('read', rights, False, g.resources_get, resource_list,
get_parents)
self.add_resources_realms('read', rights, True, g.resources_get_custom,
resource_list)
self.add_resources_realms('create', rights, False, g.resources_post, resource_list)
self.add_resources_realms('update', rights, False, g.resources_patch,
resource_list)
self.add_resources_realms('update', rights, True, g.resources_patch_custom,
resource_list)
self.add_resources_realms('delete', rights, False, g.resources_delete,
resource_list)
self.add_resources_realms('delete', rights, True, g.resources_delete_custom,
resource_list)
for res in g.resources_get:
g.resources_get[res] = list(set(g.resources_get[res]))
if res in g.resources_get_custom:
g.resources_get_custom[res] = list(set(g.resources_get_custom[res]))
g.resources_get_parents[res] = [item for item in get_parents[res]
if item not in g.resources_get[res]]
for res in g.resources_post:
g.resources_post[res] = list(set(g.resources_post[res]))
for res in g.resources_patch:
g.resources_patch[res] = list(set(g.resources_patch[res]))
for res in g.resources_delete:
g.resources_delete[res] = list(set(g.resources_delete[res]))
g.users_id = user['_id']
self.set_request_auth_value(user['_id'])
return user
def add_resources_realms(self, right, data, custom, resource, resource_list, parents=None):
"""
Add realms found for rights. it's used to fill rights when connect to app
:param right: right in list: create, read, update, delete
:type right: str
:param data: data (one record) from userrestrictrole (from mongo)
:type data: dict
:param custom: True if it's a custom right, otherwise False
:type custom: bool
:param resource: variable where store realm rights
:type resource: dict
:param resource_list: list of all resources of the backend
:type resource_list: list
:param parents: variable where store parents realms (required only for read right)
:type parents: dict or None
:return: None
"""
# pylint: disable=too-many-arguments
search_field = right
if custom:
search_field = 'custom'
if data['resource'] == '*':
my_resources = resource_list
else:
my_resources = [data['resource']]
if search_field in data['crud']:
for my_resource in my_resources:
if my_resource not in resource:
resource[my_resource] = []
if right == 'read' and not custom and my_resource not in parents:
parents[my_resource] = []
resource[my_resource].append(data['realm'])
if right == 'read' and not custom:
parents[my_resource].extend(self.parent_realms[data['realm']])
if data['sub_realm']:
resource[my_resource].extend(self.children_realms[data['realm']])
class MyValidator(Validator):
"""Specific validator for data model fields types extension"""
# pylint: disable=unused-argument
def _validate_skill_level(self, skill_level, field, value):
"""Validate 'skill_level' field (always valid)"""
return
# pylint: disable=unused-argument
def _validate_title(self, title, field, value):
"""Validate 'title' field (always valid)"""
return
# pylint: disable=unused-argument
def _validate_comment(self, comment, field, value):
"""Validate 'comment' field (always valid)"""
return
# pylint: disable=unused-argument
def _validate_schema_version(self, schema_version, field, value):
"""Validate 'schema_version' field (always valid)"""
return
def notify_alignak(event=None, parameters=None, notification=None):
"""Send a notification to the Alignak arbiter if configured"""
if not settings['ALIGNAK_URL'] or not event:
return
try:
current_app.logger.info("Logging an Alignak notification: %s / %s (%s)"
% (event, parameters, notification))
data = {'event': event}
if parameters:
data['parameters'] = parameters
if notification:
data['notification'] = notification
response, _, _, _, _ = post_internal('alignak_notifications', data, True)
current_app.logger.debug("Notification: %s" % response)
except Exception as exp:
current_app.logger.error("Alignak notification log failed: %s" % str(exp))
# Hooks used to check user's rights
def pre_get(resource, user_request, lookup):
"""Hook before get data. Add filter depend on roles of user
:param resource: name of the resource requested by user
:type resource: str
:param user_request: request of the user
:type user_request: object
:param lookup: values to get (filter in the request)
:type lookup: dict
:return: None
"""
# pylint: disable=unused-argument
if g.get('back_role_super_admin', False):
return
# Only if not super-admin
if resource not in ['user']:
# Get all resources we can have rights for reading
resources_get = g.get('resources_get', {})
resources_get_parents = g.get('resources_get_parents', {})
resources_get_custom = g.get('resources_get_custom', {})
users_id = g.get('users_id', {})
if resource not in resources_get and resource not in resources_get_custom:
lookup["_id"] = ''
else:
if resource not in resources_get:
resources_get[resource] = []
if resource not in resources_get_parents:
resources_get_parents[resource] = []
if resource not in resources_get_custom:
resources_get_custom[resource] = []
if resource in ['realm']:
lookup['$or'] = [{'_id': {'$in': resources_get[resource]}}]
else:
lookup['$or'] = [{'_realm': {'$in': resources_get[resource]}},
{'$and': [{'_sub_realm': True},
{'_realm': {'$in': resources_get_parents[resource]}}]},
{'$and': [{'_users_read': users_id},
{'_realm': {'$in': resources_get_custom[resource]}}]}]
def pre_post(resource, user_request):
"""Hook before posting data.
Check if the user restrictions match the request
:param resource: name of the resource requested by user
:type resource: str
:param user_request: request of the user
:type user_request: object
:return: None
"""
# pylint: disable=unused-argument
if g.get('back_role_super_admin', False):
return
# Only for some resources ...
if resource not in ['user', 'actionacknowledge', 'actiondowntime', 'actionforcecheck']:
# Get all resources we can have rights for creation
resources_post = g.get('resources_post', {})
resources_post_custom = g.get('resources_post_custom', {})
if resource not in resources_post and resource not in resources_post_custom:
abort(401, description='Not allowed to POST on this endpoint / resource.')
def pre_patch(resource, user_request, lookup):
"""Hook before updating data.
Check if the user restrictions match the request
:param resource: name of the resource requested by user
:type resource: str
:param user_request: request of the user
:type user_request: object
:param lookup: values to get (filter in the request)
:type lookup: dict
:return: None
"""
# pylint: disable=unused-argument
if g.get('back_role_super_admin', False):
return
# Only for some resources ...
if resource not in ['user', 'actionacknowledge', 'actiondowntime', 'actionforcecheck']:
# Get all resources we can have rights for updating
resources_patch = g.get('resources_patch', {})
resources_patch_parents = g.get('resources_patch_parents', {})
resources_patch_custom = g.get('resources_patch_custom', {})
users_id = g.get('users_id', {})
if resource not in resources_patch and resource not in resources_patch_custom:
abort(401, description='Not allowed to PATCH on this endpoint / resource.')
else:
if resource not in resources_patch:
resources_patch[resource] = []
if resource not in resources_patch_parents:
resources_patch_parents[resource] = []
if resource not in resources_patch_custom:
resources_patch_custom[resource] = []
if resource in ['realm']:
lookup['$or'] = [{'_id': {'$in': resources_patch[resource]}}]
else:
lookup['$or'] = [{'_realm': {'$in': resources_patch[resource]}},
{'$and': [{'_sub_realm': True},
{'_realm': {'$in': resources_patch_parents[resource]}}]},
{'$and': [{'_users_update': users_id},
{'_realm': {'$in': resources_patch_custom[resource]}}]}]
def pre_delete(resource, user_request, lookup):
"""Hook before deleting data.
Check if the user restrictions match the request
:param resource: name of the resource requested by user
:type resource: str
:param user_request: request of the user
:type user_request: object
:param lookup: values to get (filter in the request)
:type lookup: dict
:return: None
"""
# pylint: disable=unused-argument
if g.get('back_role_super_admin', False):
return
# Only if not super-admin
if resource not in ['user']:
# Get all resources we can have rights for delation
resources_delete = g.get('resources_delete', {})
resources_delete_parents = g.get('resources_delete_parents', {})
resources_delete_custom = g.get('resources_delete_custom', {})
users_id = g.get('users_id', {})
if resource not in resources_delete and resource not in resources_delete_custom:
abort(401, description='Not allowed to DELETE on this endpoint / resource.')
else:
if resource not in resources_delete:
resources_delete[resource] = []
if resource not in resources_delete_parents:
resources_delete_parents[resource] = []
if resource not in resources_delete_custom:
resources_delete_custom[resource] = []
if resource in ['realm']:
lookup['$or'] = [{'_id': {'$in': resources_delete[resource]}}]
else:
lookup['$or'] = [{'_realm': {'$in': resources_delete[resource]}},
{'$and': [{'_sub_realm': True},
{'_realm': {
'$in': resources_delete_parents[resource]}}]},
{'$and': [{'_users_delete': users_id},
{'_realm': {
'$in': resources_delete_custom[resource]}}]}]
# Escalations
def pre_hostescalation_post(items):
"""Hook before adding new serviceescalation element
If no escalation_period is provided then the 24x7 default TP will be used.
:param items: provided serviceescalation elements
:type items: list of dict
:return: None
"""
for dummy, item in enumerate(items):
if 'escalation_period' not in item:
tps = app.data.driver.db['timeperiod']
tp_always = tps.find_one({'name': '24x7'})
item['escalation_period'] = tp_always['_id']
def pre_serviceescalation_post(items):
"""Hook before adding new serviceescalation element
If no escalation_period is provided then the 24x7 default TP will be used.
:param items: provided serviceescalation elements
:type items: list of dict
:return: None
"""
for dummy, item in enumerate(items):
if 'escalation_period' not in item:
tps = app.data.driver.db['timeperiod']
tp_always = tps.find_one({'name': '24x7'})
item['escalation_period'] = tp_always['_id']
# History
def pre_history_post(items):
"""
Hook before adding new history element
If host _id is not provided, search for an host with host_name. Same for service and user.
:param items: history fields
:type items: dict
:return: None
"""
hosts_drv = current_app.data.driver.db['host']
services_drv = current_app.data.driver.db['service']
users_drv = current_app.data.driver.db['user']
for dummy, item in enumerate(items):
if 'host' in item and item['host']:
host = hosts_drv.find_one({'_id': item['host']})
if host:
item['host_name'] = host['name']
else:
continue
elif 'host_name' in item and item['host_name']:
host = hosts_drv.find_one({'name': item['host_name']})
if host:
item['host'] = host['_id']
else:
continue
else:
continue
host = hosts_drv.find_one({'_id': item['host']})
# Set _realm as host's _realm
item['_realm'] = host['_realm']
item['_sub_realm'] = host['_sub_realm']
# Find service and service_name
if 'service' in item and item['service']:
service = services_drv.find_one({'_id': item['service']})
if service:
item['service_name'] = service['name']
elif 'service_name' in item and item['service_name']:
service = services_drv.find_one({'host': item['host'], 'name': item['service_name']})
if service:
item['service'] = service['_id']
# Find user and user_name
if 'user' in item and item['user']:
user = users_drv.find_one({'_id': item['user']})
if user:
item['user_name'] = user['name']
elif 'user_name' in item and item['user_name']:
user = users_drv.find_one({'name': item['user_name']})
if user:
item['user'] = user['_id']
else:
item['user_name'] = 'Alignak'
item['user'] = None
# Log checks results
def pre_logcheckresult_post(items):
"""
Hook before adding new logcheckresult
:param items: logcheckresult fields
:type items: dict
:return: None
"""
hosts_drv = current_app.data.driver.db['host']
services_drv = current_app.data.driver.db['service']
for dummy, item in enumerate(items):
current_app.logger.debug("LCR - got a check result: %s" % item)
if not item.get('host') and not item.get('host_name'):
abort(make_response("Posting LCR without host information is not accepted.", 412))
# Find the concerned host
if not item.get('host'):
host = hosts_drv.find_one({'name': item['host_name']})
item['host'] = host['_id']
else:
host = hosts_drv.find_one({'_id': item['host']})
item['host_name'] = host['name']
item_last_check = host['ls_last_check']
if not item.get('service') and not item.get('service_name'):
# This is valid for an host check result
item['service'] = None
item['service_name'] = ''
else:
# We got a service check result
if item.get('service_name') and not item.get('service'):
service = services_drv.find_one(
{'host': item['host'], 'name': item['service_name']})
item['service'] = service['_id']
if item.get('service') and not item.get('service_name'):
service = services_drv.find_one({'_id': item['service']})
item['service_name'] = service['name']
item_last_check = service['ls_last_check']
# Set _realm as host's _realm
item['_realm'] = host['_realm']
g.updateLivestate = True
# If the log check result is older than the item last check, do not update the livestate
if item_last_check and item['last_check'] < item_last_check:
current_app.logger.debug("LCR - will not update the livestate: %s / %s",
item['last_check'], item_last_check)
g.updateLivestate = False
current_app.logger.debug("LCR - inserting an LCR for %s/%s...",
item['host_name'], item['service_name'])
def after_insert_logcheckresult(items):
"""
Hook after logcheckresult inserted.
:param items: realm fields
:type items: dict
:return: None
"""
for dummy, item in enumerate(items):
current_app.logger.debug("LCR - inserted an LCR for %s/%s...",
item['host_name'], item['service_name'])
current_app.logger.debug(" -> %s..." % item)
if g.updateLivestate:
# Update the livestate...
if item['service']:
# ...for a service
lookup = {"_id": item['service']}
data = {
'ls_state': item['state'],
'ls_state_type': item['state_type'],
'ls_state_id': item['state_id'],
'ls_acknowledged': item['acknowledged'],
'ls_acknowledgement_type': item['acknowledgement_type'],
'ls_downtimed': item['downtimed'],
'ls_last_check': item['last_check'],
'ls_last_state': item['last_state'],
'ls_last_state_type': item['last_state_type'],
'ls_output': item['output'],
'ls_long_output': item['long_output'],
'ls_perf_data': item['perf_data'],
'ls_current_attempt': item['current_attempt'],
'ls_latency': item['latency'],
'ls_execution_time': item['execution_time'],
'ls_passive_check': item['passive_check'],
'ls_state_changed': item.get('state_changed'),
'ls_last_state_changed': item['last_state_changed'],
'ls_last_hard_state_changed': item['last_hard_state_changed'],
'ls_last_time_ok': item['last_time_0'],
'ls_last_time_warning': item['last_time_1'],
'ls_last_time_critical': item['last_time_2'],
'ls_last_time_unknown': item['last_time_3'],
'ls_last_time_unreachable': item['last_time_4']
}
(pi_a, pi_b, pi_c, pi_d) = patch_internal('service', data, False, False, **lookup)
else:
# ...for an host
lookup = {"_id": item['host']}
data = {
'ls_state': item['state'],
'ls_state_type': item['state_type'],
'ls_state_id': item['state_id'],
'ls_acknowledged': item['acknowledged'],
'ls_acknowledgement_type': item['acknowledgement_type'],
'ls_downtimed': item['downtimed'],
'ls_last_check': item['last_check'],
'ls_last_state': item['last_state'],
'ls_last_state_type': item['last_state_type'],
'ls_output': item['output'],
'ls_long_output': item['long_output'],
'ls_perf_data': item['perf_data'],
'ls_current_attempt': item['current_attempt'],
'ls_latency': item['latency'],
'ls_execution_time': item['execution_time'],
'ls_passive_check': item['passive_check'],
'ls_state_changed': item.get('state_changed'),
'ls_last_state_changed': item['last_state_changed'],
'ls_last_hard_state_changed': item['last_hard_state_changed'],
'ls_last_time_up': item['last_time_0'],
'ls_last_time_down': item['last_time_1'],
'ls_last_time_unreachable': item['last_time_4']
}
(pi_a, pi_b, pi_c, pi_d) = patch_internal('host', data, False, False, **lookup)
current_app.logger.debug("LCR - updated the livestate: %s, %s, %s, %s",
pi_a, pi_b, pi_c, pi_d)
# Create an history event for the new logcheckresult
message = "%s[%s] (%s/%s): %s" % (item['state'], item['state_type'],
item['acknowledged'], item['downtimed'],
item['output'])
data = {
'host': item['host'],
'host_name': item['host_name'],
'service': item['service'],
'service_name': item['service_name'],
'user': None,
'type': 'check.result',
'message': message,
'logcheckresult': item['_id']
}
post_internal("history", data, True)
# Actions
def pre_post_action_right(actrequestp):
"""Deny post on action* endpoint if the logged-in user do not have can_submit_commands
:param actrequestp:
:return:
"""
# pylint: disable=unused-argument
if not g.get('can_submit_commands', False):
abort(403)
def pre_submit_action_right(actrequest, lookup):
# pylint: disable=unused-argument
"""Deny patch or delete action* endpoint if the logged-in user do not have can_submit_commands
:param actrequest:
:param lookup:
:return:
"""
if not g.get('can_submit_commands', False):
abort(403)
# Actions acknowledge
def pre_actionacknowledge_post(items):
"""
Hook before adding new acknowledge
:param items: actionacknowledge fields
:type items: dict
:return: None
"""
hosts_drv = current_app.data.driver.db['host']
for dummy, item in enumerate(items):
# Set _realm as host's _realm
host = hosts_drv.find_one({'_id': item['host']})
item['_realm'] = host['_realm']
item['_sub_realm'] = host['_sub_realm']
def after_insert_actionacknowledge(items):
"""
Hook after action acknowledge inserted.
:param items: realm fields
:type items: dict
:return: None
"""
hosts_drv = current_app.data.driver.db['host']
services_drv = current_app.data.driver.db['service']
for dummy, item in enumerate(items):
# Get concerned host
host = hosts_drv.find_one({'_id': item['host']})
service_name = ''
if item['service']:
service = services_drv.find_one({'_id': item['service']})
service_name = service['name']
# Create an history event for the new acknowledge
data = {
'host': item['host'],
'host_name': host['name'],
'service': item['service'],
'service_name': service_name,
'user': item['user'],
'type': 'ack.' + item['action'],
'message': item['comment']
}
post_internal("history", data, True)
def after_update_actionacknowledge(updated, original):
"""
Hook update on actionacknowledge
:param updated: modified fields
:type updated: dict
:param original: original fields
:type original: dict
:return: None
"""
if 'processed' in updated and updated['processed']:
hosts_drv = current_app.data.driver.db['host']
services_drv = current_app.data.driver.db['service']
# Get concerned host
host = hosts_drv.find_one({'_id': original['host']})
service_name = ''
if original['service']:
service = services_drv.find_one({'_id': original['service']})
service_name = service['name']
# Create an history event for the changed acknowledge
data = {
'host': original['host'],
'host_name': host['name'],
'service': original['service'],
'service_name': service_name,
'user': original['user'],
'type': 'ack.processed',
'message': original['comment'],
'content': {
}
}
post_internal("history", data, True)
# Actions downtime
def pre_actiondowntime_post(items):
"""
Hook before adding new downtime
:param items: actiondowntime fields
:type items: dict
:return: None
"""
hosts_drv = current_app.data.driver.db['host']
for dummy, item in enumerate(items):
# Set _realm as host's _realm
host = hosts_drv.find_one({'_id': item['host']})
item['_realm'] = host['_realm']
item['_sub_realm'] = host['_sub_realm']
def after_insert_actiondowntime(items):
"""
Hook after action downtime inserted.
:param items: realm fields
:type items: dict
:return: None
"""
hosts_drv = current_app.data.driver.db['host']
services_drv = current_app.data.driver.db['service']
for dummy, item in enumerate(items):
# Get concerned host
host = hosts_drv.find_one({'_id': item['host']})
service_name = ''
if item['service']:
service = services_drv.find_one({'_id': item['service']})
service_name = service['name']
# Create an history event for the new downtime
data = {
'host': item['host'],
'host_name': host['name'],
'service': item['service'],
'service_name': service_name,
'user': item['user'],
'type': 'downtime.' + item['action'],
'message': item['comment']
}
post_internal("history", data, True)
def after_update_actiondowntime(updated, original):
"""
Hook update on actiondowntime
:param updated: modified fields
:type updated: dict
:param original: original fields
:type original: dict
:return: None
"""
if 'processed' in updated and updated['processed']:
hosts_drv = current_app.data.driver.db['host']
services_drv = current_app.data.driver.db['service']
# Get concerned host
host = hosts_drv.find_one({'_id': original['host']})
service_name = ''
if original['service']:
service = services_drv.find_one({'_id': original['service']})
service_name = service['name']
# Create an history event for the changed downtime
data = {
'host': original['host'],
'host_name': host['name'],
'service': original['service'],
'service_name': service_name,
'user': original['user'],
'type': 'downtime.processed',
'message': original['comment'],
'content': {
}
}
post_internal("history", data, True)
# Actions forcecheck
def pre_actionforcecheck_post(items):
"""
Hook before adding new forcecheck
:param items: actionforcecheck fields
:type items: dict
:return: None
"""
hosts_drv = current_app.data.driver.db['host']
for dummy, item in enumerate(items):
# Set _realm as host's _realm
host = hosts_drv.find_one({'_id': item['host']})
item['_realm'] = host['_realm']
item['_sub_realm'] = host['_sub_realm']
def after_insert_actionforcecheck(items):
"""
Hook after action forcecheck inserted.
:param items: realm fields
:type items: dict
:return: None
"""
hosts_drv = current_app.data.driver.db['host']
services_drv = current_app.data.driver.db['service']
for dummy, item in enumerate(items):
# Get concerned host
host = hosts_drv.find_one({'_id': item['host']})
service_name = ''
if item['service']:
service = services_drv.find_one({'_id': item['service']})
service_name = service['name']
# Create an history event for the new forcecheck
data = {
'host': item['host'],
'host_name': host['name'],
'service': item['service'],
'service_name': service_name,
'user': item['user'],
'type': 'check.request',
'message': item['comment']
}
post_internal("history", data, True)
def after_update_actionforcecheck(updated, original):
"""
Hook update on actionforcecheck
:param updated: modified fields
:type updated: dict
:param original: original fields
:type original: dict
:return: None
"""
if 'processed' in updated and updated['processed']:
hosts_drv = current_app.data.driver.db['host']
services_drv = current_app.data.driver.db['service']
# Get concerned host
host = hosts_drv.find_one({'_id': original['host']})
service_name = ''
if original['service']:
service = services_drv.find_one({'_id': original['service']})
service_name = service['name']
# Create an history event for the changed forcecheck
data = {
'host': original['host'],
'host_name': host['name'],
'service': original['service'],
'service_name': service_name,
'user': original['user'],
'type': 'check.requested',
'message': original['comment'],
'content': {
}
}
post_internal("history", data, True)
# Hosts groups
def pre_hostgroup_post(items):
"""
Hook before adding a new hostgroup
Manage hostgroup level and parents tree.
:param items: hostgroup fields
:type items: dict
:return: None
"""
hgs_drv = current_app.data.driver.db['hostgroup']
for dummy, item in enumerate(items):
# Default parent
if '_parent' not in item or not item['_parent']:
# Use default hostgroup as a parent
def_hg = hgs_drv.find_one({'name': 'All'})
if def_hg:
item['_parent'] = def_hg['_id']
# Make sure hosts and hostgroups are a unique list (avoid duplicates)
if 'hosts' in item:
item['hosts'] = list(set(item['hosts']))
if 'hostgroups' in item:
item['hostgroups'] = list(set(item['hostgroups']))
# Compute _level
parent_hg = hgs_drv.find_one({'_id': item['_parent']})
item['_level'] = parent_hg['_level'] + 1
# Add parent in _tree_parents
item['_tree_parents'] = parent_hg['_tree_parents']
item['_tree_parents'].append(parent_hg['_id'])
def pre_hostgroup_patch(updates, original):
"""
Hook before updating existing hostgroup
:param updates: modified fields
:type updates: dict
:param original: original fields
:type original: dict
:return: None
"""
if not g.updateGroup:
if '_tree_parents' in updates:
abort(make_response("Updating _tree_parents is forbidden", 412))
# Make sure hosts and hostgroups are a unique list (avoid duplicates)
if 'hosts' in updates:
updates['hosts'] = list(set(updates['hosts']))
if 'hostgroups' in updates:
updates['hostgroups'] = list(set(updates['hostgroups']))
if '_parent' in updates and updates['_parent'] != original['_parent']:
hgs_drv = current_app.data.driver.db['hostgroup']
# Find parent
parent_hg = hgs_drv.find_one({'_id': updates['_parent']})
if not parent_hg:
abort(make_response("Error: parent not found: %s" % updates['_parent'], 412))
# Compute _level
updates['_level'] = parent_hg['_level'] + 1
# Add parent in _tree_parents
updates['_tree_parents'] = parent_hg['_tree_parents']
updates['_tree_parents'].append(parent_hg['_id'])
# Services groups
def pre_servicegroup_post(items):
"""
Hook before adding a new servicegroup
Manage servicegroup level and parents tree.
:param items: servicegroup fields
:type items: dict
:return: None
"""
sgs_drv = current_app.data.driver.db['servicegroup']
for dummy, item in enumerate(items):
# Default parent
if '_parent' not in item or not item['_parent']:
# Use default servicegroup as a parent
def_sg = sgs_drv.find_one({'name': 'All'})
if def_sg:
item['_parent'] = def_sg['_id']
# Make sure services and servicegroups are a unique list (avoid duplicates)