d5e049e1e905fbbf459f976324fd1fcb98736bb6
[pti/o2.git] / o2ims / service / command / notify_alarm_handler.py
1 # Copyright (C) 2021-2022 Wind River Systems, Inc.
2 #
3 #  Licensed under the Apache License, Version 2.0 (the "License");
4 #  you may not use this file except in compliance with the License.
5 #  You may obtain a copy of the License at
6 #
7 #      http://www.apache.org/licenses/LICENSE-2.0
8 #
9 #  Unless required by applicable law or agreed to in writing, software
10 #  distributed under the License is distributed on an "AS IS" BASIS,
11 #  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 #  See the License for the specific language governing permissions and
13 #  limitations under the License.
14
15 # import redis
16 # import requests
17 import ssl
18 import json
19 from urllib.parse import urlparse
20
21 from o2common.config import conf
22 from o2common.domain.filter import gen_orm_filter
23 from o2common.service.unit_of_work import AbstractUnitOfWork
24 from o2common.service.command.handler import get_https_conn_default
25 from o2common.service.command.handler import get_http_conn
26 from o2common.service.command.handler import get_https_conn_selfsigned
27 from o2common.service.command.handler import post_data
28
29 from o2ims.domain import commands
30 from o2ims.domain.alarm_obj import AlarmSubscription, AlarmEvent2SMO, \
31     AlarmEventRecord
32
33 from o2common.helper import o2logging
34 logger = o2logging.get_logger(__name__)
35
36
37 def notify_alarm_to_smo(
38     cmd: commands.PubAlarm2SMO,
39     uow: AbstractUnitOfWork,
40 ):
41     logger.debug('In notify_alarm_to_smo')
42     data = cmd.data
43     with uow:
44         alarm = uow.alarm_event_records.get(data.id)
45         if alarm is None:
46             logger.debug('Alarm Event {} does not exists.'.format(data.id))
47             return
48
49         subs = uow.alarm_subscriptions.list()
50         for sub in subs:
51             sub_data = sub.serialize()
52             logger.debug('Alarm Subscription: {}'.format(
53                 sub_data['alarmSubscriptionId']))
54
55             if not sub_data.get('filter', None):
56                 callback_smo(sub, data, alarm)
57                 continue
58             try:
59                 args = gen_orm_filter(AlarmEventRecord, sub_data['filter'])
60             except KeyError:
61                 logger.warning(
62                     'Alarm Subscription {} filter {} has wrong attribute '
63                     'name or value. Ignore the filter'.format(
64                         sub_data['alarmSubscriptionId'],
65                         sub_data['filter']))
66                 callback_smo(sub, data, alarm)
67                 continue
68             args.append(AlarmEventRecord.alarmEventRecordId == data.id)
69             ret = uow.alarm_event_records.list_with_count(*args)
70             if ret[0] != 0:
71                 logger.debug(
72                     'Alarm Event {} skip for subscription {} because of '
73                     'the filter.'
74                     .format(data.id, sub_data['alarmSubscriptionId']))
75                 continue
76             callback_smo(sub, data, alarm)
77
78
79 def callback_smo(sub: AlarmSubscription, msg: AlarmEvent2SMO,
80                  alarm: AlarmEventRecord):
81     sub_data = sub.serialize()
82     alarm_data = alarm.serialize()
83     callback = {
84         'globalCloudID': conf.DEFAULT.ocloud_global_id,
85         'consumerSubscriptionId': sub_data['consumerSubscriptionId'],
86         'notificationEventType': msg.notificationEventType,
87         'objectRef': msg.objectRef,
88         'alarmEventRecordId': alarm_data['alarmEventRecordId'],
89         'resourceTypeID': alarm_data['resourceTypeId'],
90         'resourceID': alarm_data['resourceId'],
91         'alarmDefinitionID': alarm_data['alarmDefinitionId'],
92         'probableCauseID': alarm_data['probableCauseId'],
93         'alarmRaisedTime': alarm_data['alarmRaisedTime'],
94         'alarmChangedTime': alarm_data['alarmChangedTime'],
95         'alarmAcknowledgeTime': alarm_data['alarmAcknowledgeTime'],
96         'alarmAcknowledged': alarm_data['alarmAcknowledged'],
97         'perceivedSeverity': alarm_data['perceivedSeverity'],
98         'extensions': json.loads(alarm_data['extensions'])
99     }
100     # logger.warning(callback)
101     callback_data = json.dumps(callback)
102     logger.info('URL: {}, data: {}'.format(
103         sub_data['callback'], callback_data))
104
105     o = urlparse(sub_data['callback'])
106     if o.scheme == 'https':
107         conn = get_https_conn_default(o.netloc)
108     else:
109         conn = get_http_conn(o.netloc)
110     try:
111         rst, status = post_data(conn, o.path, callback_data)
112         if rst is True:
113             logger.info(
114                 'Notify alarm to SMO successed with status: {}'.format(status))
115             return
116         logger.error('Notify alarm Response code is: {}'.format(status))
117     except ssl.SSLCertVerificationError as e:
118         logger.debug(
119             'Notify alarm try to post data with trusted ca \
120                 failed: {}'.format(e))
121         if 'self signed' in str(e):
122             conn = get_https_conn_selfsigned(o.netloc)
123             try:
124                 return post_data(conn, o.path, callback_data)
125             except Exception as e:
126                 logger.info(
127                     'Notify alarm with self-signed ca failed: {}'.format(e))
128                 # TODO: write the status to extension db table.
129                 return False
130         return False
131     except Exception as e:
132         logger.critical('Notify alarm except: {}'.format(e))
133         return False