INF-303 Add Infrastructure Monitoring Fault Service; INF-305 update inventory api...
[pti/o2.git] / o2ims / service / command / notify_alarm_handler.py
1 # Copyright (C) 2021 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 json
16 # import redis
17 # import requests
18 import http.client
19 from urllib.parse import urlparse
20
21 # from o2common.config import config
22 from o2common.service.unit_of_work import AbstractUnitOfWork
23 from o2ims.domain import commands
24 from o2ims.domain.alarm_obj import AlarmSubscription, AlarmEvent2SMO
25
26 from o2common.helper import o2logging
27 logger = o2logging.get_logger(__name__)
28
29
30 def notify_alarm_to_smo(
31     cmd: commands.PubAlarm2SMO,
32     uow: AbstractUnitOfWork,
33 ):
34     logger.info('In notify_alarm_to_smo')
35     data = cmd.data
36     with uow:
37         subs = uow.alarm_subscriptions.list()
38         for sub in subs:
39             sub_data = sub.serialize()
40             logger.debug('Alarm Subscription: {}'.format(
41                 sub_data['alarmSubscriptionId']))
42
43             callback_smo(sub, data)
44
45
46 def callback_smo(sub: AlarmSubscription, msg: AlarmEvent2SMO):
47     sub_data = sub.serialize()
48     callback_data = json.dumps({
49         'consumerSubscriptionId': sub_data['consumerSubscriptionId'],
50         'notificationEventType': msg.notificationEventType,
51         'objectRef': msg.objectRef,
52         'updateTime': msg.updatetime
53     })
54     logger.info('URL: {}, data: {}'.format(
55         sub_data['callback'], callback_data))
56     o = urlparse(sub_data['callback'])
57     conn = http.client.HTTPConnection(o.netloc)
58     headers = {'Content-type': 'application/json'}
59     conn.request('POST', o.path, callback_data, headers)
60     resp = conn.getresponse()
61     data = resp.read().decode('utf-8')
62     # json_data = json.loads(data)
63     if resp.status == 202 or resp.status == 200:
64         logger.info('Notify to SMO successed, response code {} {}, data {}'.
65                     format(resp.status, resp.reason, data))
66         return
67     logger.error('Response code is: {}'.format(resp.status))