e7b41e1de3d2f323d256efac15ceffe3352b2073
[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         subs = uow.subscriptions.list()
48         for sub in subs:
49             sub_data = sub.serialize()
50             logger.debug('Subscription: {}'.format(sub_data['subscriptionId']))
51             resource = uow.resources.get(data.id)
52             if resource is None:
53                 logger.debug('Resource {} does not exists.'.format(data.id))
54                 continue
55             res_pool_id = resource.serialize()['resourcePoolId']
56             logger.debug('res pool id is {}'.format(res_pool_id))
57             if sub_data.get('filter', None):
58                 try:
59                     args = gen_orm_filter(ocloud.Resource, sub_data['filter'])
60                 except KeyError:
61                     logger.error(
62                         'Subscription {} filter {} has wrong attribute name '
63                         'or value. Ignore the filter.'.format(
64                             sub_data['subscriptionId'], sub_data['filter']))
65                     callback_smo(sub, data)
66                     continue
67                 args.append(ocloud.Resource.resourceId == data.id)
68                 ret = uow.resources.list_with_count(res_pool_id, *args)
69                 if ret[0] != 0:
70                     logger.debug(
71                         'Resource {} skip for subscription {} because of the '
72                         'filter.'
73                         .format(data.id, sub_data['subscriptionId']))
74                     continue
75
76             callback_smo(sub, data)
77
78
79 def callback_smo(sub: Subscription, msg: Message2SMO):
80     sub_data = sub.serialize()
81     callback_data = json.dumps({
82         'consumerSubscriptionId': sub_data['consumerSubscriptionId'],
83         'notificationEventType': msg.notificationEventType,
84         'objectRef': msg.objectRef,
85         'updateTime': msg.updatetime
86     })
87     logger.info('URL: {}, data: {}'.format(
88         sub_data['callback'], callback_data))
89     # r.publish(sub_data['subscriptionId'], json.dumps({
90     #     'consumerSubscriptionId': sub_data['consumerSubscriptionId'],
91     #     'notificationEventType': msg.notificationEventType,
92     #     'objectRef': msg.objectRef
93     # }))
94     # try:
95     #     headers = {'User-Agent': 'Mozilla/5.0'}
96     #     resp = requests.post(sub_data['callback'], data=callback_data,
97     #                          headers=headers)
98     #     if resp.status_code == 202 or resp.status_code == 200:
99     #         logger.info('Notify to SMO successed')
100     #         return
101     #     logger.error('Response code is: {}'.format(resp.status_code))
102     # except requests.exceptions.HTTPError as err:
103     #     logger.error('request smo error: {}'.format(err))
104     o = urlparse(sub_data['callback'])
105     if o.scheme == 'https':
106         conn = get_https_conn_default(o.netloc)
107     else:
108         conn = get_http_conn(o.netloc)
109     try:
110         rst, status = post_data(conn, o.path, callback_data)
111         if rst is True:
112             logger.info(
113                 'Notify to SMO successed with status: {}'.format(status))
114             return
115         logger.error('Notify Response code is: {}'.format(status))
116     except ssl.SSLCertVerificationError as e:
117         logger.debug(
118             'Notify try to post data with trusted ca failed: {}'.format(e))
119         if 'self signed' in str(e):
120             conn = get_https_conn_selfsigned(o.netloc)
121             try:
122                 return post_data(conn, o.path, callback_data)
123             except Exception as e:
124                 logger.info(
125                     'Notify post data with self-signed ca \
126                     failed: {}'.format(e))
127                 # TODO: write the status to extension db table.
128                 return False
129         return False
130     except Exception as e:
131         logger.critical('Notify except: {}'.format(e))
132         return False