Fix INF-346 and INF-347 subscription filter
[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 config
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         subs = uow.alarm_subscriptions.list()
45         for sub in subs:
46             sub_data = sub.serialize()
47             logger.debug('Alarm Subscription: {}'.format(
48                 sub_data['alarmSubscriptionId']))
49
50             alarm = uow.alarm_event_records.get(data.id)
51             if alarm is None:
52                 logger.debug('Alarm Event {} does not exists.'.format(data.id))
53                 continue
54             if sub_data.get('filter', None):
55                 try:
56                     args = gen_orm_filter(AlarmEventRecord, sub_data['filter'])
57                 except KeyError:
58                     logger.warning(
59                         'Alarm Subscription {} filter {} has wrong attribute '
60                         'name or value. Ignore the filter'.format(
61                             sub_data['alarmSubscriptionId'],
62                             sub_data['filter']))
63                     callback_smo(sub, data)
64                     continue
65                 args.append(AlarmEventRecord.alarmEventRecordId == data.id)
66                 ret = uow.alarm_event_records.list_with_count(*args)
67                 if ret[0] != 0:
68                     logger.debug(
69                         'Alarm Event {} skip for subscription {} because of '
70                         'the filter.'
71                         .format(data.id, sub_data['alarmSubscriptionId']))
72                     continue
73
74             callback_smo(sub, data)
75
76
77 def callback_smo(sub: AlarmSubscription, msg: AlarmEvent2SMO):
78     sub_data = sub.serialize()
79     callback_data = json.dumps({
80         'consumerSubscriptionId': sub_data['consumerSubscriptionId'],
81         'notificationEventType': msg.notificationEventType,
82         'objectRef': msg.objectRef,
83         'updateTime': msg.updatetime
84     })
85     logger.info('URL: {}, data: {}'.format(
86         sub_data['callback'], callback_data))
87     o = urlparse(sub_data['callback'])
88     if o.scheme == 'https':
89         conn = get_https_conn_default(o.netloc)
90     else:
91         conn = get_http_conn(o.netloc)
92     try:
93         rst, status = post_data(conn, o.path, callback_data)
94         if rst is True:
95             logger.info(
96                 'Notify alarm to SMO successed with status: {}'.format(status))
97             return
98         logger.error('Notify alarm Response code is: {}'.format(status))
99     except ssl.SSLCertVerificationError as e:
100         logger.debug(
101             'Notify alarm try to post data with trusted ca \
102                 failed: {}'.format(e))
103         if 'self signed' in str(e):
104             conn = get_https_conn_selfsigned(o.netloc)
105             try:
106                 return post_data(conn, o.path, callback_data)
107             except Exception as e:
108                 logger.info(
109                     'Notify alarm with self-signed ca failed: {}'.format(e))
110                 # TODO: write the status to extension db table.
111                 return False
112         return False
113     except Exception as e:
114         logger.critical('Notify alarm except: {}'.format(e))
115         return False