Add oAuth2 for subscription and registration with SMO
[pti/o2.git] / o2ims / service / command / registration_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 json
16
17 from o2common.config import config, conf
18 from o2common.domain.filter import gen_orm_filter
19 from o2common.service.unit_of_work import AbstractUnitOfWork
20 from o2common.adapter.notifications import AbstractNotifications
21
22 from o2ims.domain import commands, ocloud as cloud
23 from o2ims.domain.subscription_obj import Message2SMO, NotificationEventEnum
24
25 from .notify_handler import handle_filter, callback_smo
26
27 from o2common.helper import o2logging
28 logger = o2logging.get_logger(__name__)
29
30 apibase = config.get_o2ims_api_base()
31 api_monitoring_base = config.get_o2ims_monitoring_api_base()
32 inventory_api_version = config.get_o2ims_inventory_api_v1()
33
34
35 def registry_to_smo(
36     cmd: commands.Register2SMO,
37     uow: AbstractUnitOfWork,
38     notifications: AbstractNotifications,
39 ):
40     logger.debug('In registry_to_smo')
41     data = cmd.data
42     logger.info('The Register2SMO notificationEventType is {}'.format(
43         data.notificationEventType))
44     with uow:
45         ocloud = uow.oclouds.get(data.id)
46         if ocloud is None:
47             logger.warning('Ocloud {} does not exists.'.format(data.id))
48             return
49         logger.debug('O-Cloud Global UUID: {}'.format(ocloud.globalCloudId))
50         # ocloud_dict = ocloud.serialize()
51         ocloud_dict = {
52             'oCloudId': ocloud.oCloudId,
53             'globalcloudId': ocloud.globalCloudId,
54             'globalCloudId': ocloud.globalCloudId,
55             'name': ocloud.name,
56             'description': ocloud.description,
57             'serviceUri': ocloud.serviceUri
58         }
59         if data.notificationEventType == NotificationEventEnum.CREATE:
60             register_smo(notifications, ocloud_dict)
61         elif data.notificationEventType in [NotificationEventEnum.MODIFY,
62                                             NotificationEventEnum.DELETE]:
63             _notify_ocloud(uow, data, ocloud_dict)
64
65
66 class RegIMSToSMOExp(Exception):
67     def __init__(self, value):
68         self.value = value
69
70
71 def register_smo(notifications, ocloud_data):
72     call_res = call_smo(notifications, ocloud_data)
73     logger.debug('Call SMO response is {}'.format(call_res))
74     if call_res is True:
75         logger.info('Register to smo success response')
76     else:
77         raise RegIMSToSMOExp('Register o2ims to SMO failed')
78     # TODO: record the result for the smo register
79
80
81 def _notify_ocloud(uow, data, ocloud_dict):
82     ref = api_monitoring_base + inventory_api_version
83     msg = Message2SMO(
84         eventtype=data.notificationEventType, id=data.id,
85         ref=ref, updatetime=data.updatetime)
86     ocloud_dict.pop('globalCloudId')
87     subs = uow.subscriptions.list()
88     for sub in subs:
89         sub_data = sub.serialize()
90         logger.debug('Subscription: {}'.format(sub_data['subscriptionId']))
91         filters = handle_filter(sub_data['filter'], 'CloudInfo')
92         if not filters:
93             callback_smo(sub, msg, ocloud_dict)
94             continue
95         filter_hit = False
96         for filter in filters:
97             try:
98                 args = gen_orm_filter(cloud.Ocloud, filter)
99             except KeyError:
100                 logger.warning(
101                     'Subscription {} filter {} has wrong attribute '
102                     'name or value. Ignore the filter.'.format(
103                         sub_data['subscriptionId'],
104                         sub_data['filter']))
105                 continue
106             if len(args) == 0 and 'objectType' in filter:
107                 filter_hit = True
108                 break
109             args.append(cloud.Ocloud.oCloudId == data.id)
110             ret = uow.oclouds.list(*args)
111             if ret.count() > 0:
112                 filter_hit = True
113                 break
114         if filter_hit:
115             logger.info('Subscription {} filter hit, skip oCloud {}.'
116                         .format(sub_data['subscriptionId'], data.id))
117         else:
118             callback_smo(sub, msg, ocloud_dict)
119
120
121 def call_smo(notifications: AbstractNotifications, reg_data: dict):
122     smo_token = conf.DEFAULT.smo_token_data
123     smo_token_info = {
124         'iss': 'o2ims',
125         'aud': 'smo',
126         'smo_token_payload': smo_token,
127         'smo_token_type': 'jwt',
128         'smo_token_expiration': '',
129         'smo_token_algo': 'RS256'
130     }
131
132     callback_data = json.dumps({
133         'globalCloudId': reg_data['globalCloudId'],
134         'oCloudId': reg_data['oCloudId'],
135         'IMS_EP': config.get_api_url(),
136         'smo_token_data': smo_token_info
137     })
138     logger.info('callback URL: {}'.format(conf.DEFAULT.smo_register_url))
139     logger.debug('callback data: {}'.format(callback_data))
140     return notifications.send(conf.DEFAULT.smo_register_url, callback_data)