50c40994c6c2f55e4eef3f9be7750e024ff0180e
[pti/o2.git] / o2ims / service / command / notify_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 json
18 import ssl
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, ocloud
30 from o2ims.domain.subscription_obj import Subscription, Message2SMO
31
32 from o2common.helper import o2logging
33 logger = o2logging.get_logger(__name__)
34
35
36 # # Maybe another MQ server
37 # r = redis.Redis(**config.get_redis_host_and_port())
38
39
40 def notify_change_to_smo(
41     cmd: commands.PubMessage2SMO,
42     uow: AbstractUnitOfWork,
43 ):
44     logger.debug('In notify_change_to_smo')
45     data = cmd.data
46     with uow:
47         resource = uow.resources.get(data.id)
48         if resource is None:
49             logger.debug('Resource {} does not exists.'.format(data.id))
50             return
51         res_pool_id = resource.serialize()['resourcePoolId']
52         logger.debug('res pool id is {}'.format(res_pool_id))
53
54         subs = uow.subscriptions.list()
55         for sub in subs:
56             sub_data = sub.serialize()
57             logger.debug('Subscription: {}'.format(sub_data['subscriptionId']))
58             if not sub_data.get('filter', None):
59                 callback_smo(sub, data)
60                 continue
61             try:
62                 args = gen_orm_filter(ocloud.Resource, sub_data['filter'])
63             except KeyError:
64                 logger.error(
65                     'Subscription {} filter {} has wrong attribute name '
66                     'or value. Ignore the filter.'.format(
67                         sub_data['subscriptionId'], sub_data['filter']))
68                 callback_smo(sub, data)
69                 continue
70             args.append(ocloud.Resource.resourceId == data.id)
71             ret = uow.resources.list_with_count(res_pool_id, *args)
72             if ret[0] != 0:
73                 logger.debug(
74                     'Resource {} skip for subscription {} because of the '
75                     'filter.'
76                     .format(data.id, sub_data['subscriptionId']))
77                 continue
78             callback_smo(sub, data)
79
80
81 def callback_smo(sub: Subscription, msg: Message2SMO):
82     sub_data = sub.serialize()
83     callback = {
84         'consumerSubscriptionId': sub_data['consumerSubscriptionId'],
85         'notificationEventType': msg.notificationEventType,
86         'objectRef': msg.objectRef,
87         'updateTime': msg.updatetime
88     }
89     # if msg.notificationEventType in [NotificationEventEnum.DELETE,
90     #                                  NotificationEventEnum.MODIFY]:
91     #     callback['priorObjectState'] = {}
92     # if msg.notificationEventType in [NotificationEventEnum.CREATE,
93     #                                  NotificationEventEnum.MODIFY]:
94     #     callback['postObjectState'] = {}
95     # logger.warning(callback)
96     callback_data = json.dumps(callback)
97     logger.info('URL: {}, data: {}'.format(
98         sub_data['callback'], callback_data))
99
100     # Call SMO through the SMO callback url
101     o = urlparse(sub_data['callback'])
102     if o.scheme == 'https':
103         conn = get_https_conn_default(o.netloc)
104     else:
105         conn = get_http_conn(o.netloc)
106     try:
107         rst, status = post_data(conn, o.path, callback_data)
108         if rst is True:
109             logger.info(
110                 'Notify to SMO successed with status: {}'.format(status))
111             return
112         logger.error('Notify Response code is: {}'.format(status))
113     except ssl.SSLCertVerificationError as e:
114         logger.debug(
115             'Notify try to post data with trusted ca failed: {}'.format(e))
116         if 'self signed' in str(e):
117             conn = get_https_conn_selfsigned(o.netloc)
118             try:
119                 return post_data(conn, o.path, callback_data)
120             except Exception as e:
121                 logger.info(
122                     'Notify post data with self-signed ca \
123                     failed: {}'.format(e))
124                 # TODO: write the status to extension db table.
125                 return False
126         return False
127     except Exception as e:
128         logger.critical('Notify except: {}'.format(e))
129         return False