INF-417 InfrastructureInventoryObject implemented
[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.get_notification_dict()
51         if data.notificationEventType == NotificationEventEnum.CREATE:
52             register_smo(notifications, ocloud_dict)
53         elif data.notificationEventType in [NotificationEventEnum.MODIFY,
54                                             NotificationEventEnum.DELETE]:
55             _notify_ocloud(uow, data, ocloud_dict)
56
57
58 class RegIMSToSMOExp(Exception):
59     def __init__(self, value):
60         self.value = value
61
62
63 def register_smo(notifications, ocloud_data):
64     call_res = call_smo(notifications, ocloud_data)
65     logger.debug('Call SMO response is {}'.format(call_res))
66     if call_res is True:
67         logger.info('Register to smo success response')
68     else:
69         raise RegIMSToSMOExp('Register o2ims to SMO failed')
70     # TODO: record the result for the smo register
71
72
73 def _notify_ocloud(uow, data, ocloud_dict):
74     ref = api_monitoring_base + inventory_api_version
75     msg = Message2SMO(
76         eventtype=data.notificationEventType, id=data.id,
77         ref=ref, updatetime=data.updatetime)
78     ocloud_dict.pop('globalCloudId')
79     subs = uow.subscriptions.list()
80     for sub in subs:
81         sub_data = sub.serialize()
82         logger.debug('Subscription: {}'.format(sub_data['subscriptionId']))
83         filters = handle_filter(sub_data['filter'], 'CloudInfo')
84         if not filters:
85             callback_smo(sub, msg, ocloud_dict)
86             continue
87         filter_hit = False
88         for filter in filters:
89             try:
90                 args = gen_orm_filter(cloud.Ocloud, filter)
91             except KeyError:
92                 logger.warning(
93                     'Subscription {} filter {} has wrong attribute '
94                     'name or value. Ignore the filter.'.format(
95                         sub_data['subscriptionId'],
96                         sub_data['filter']))
97                 continue
98             if len(args) == 0 and 'objectType' in filter:
99                 filter_hit = True
100                 break
101             args.append(cloud.Ocloud.oCloudId == data.id)
102             ret = uow.oclouds.list(*args)
103             if ret.count() > 0:
104                 filter_hit = True
105                 break
106         if filter_hit:
107             logger.info('Subscription {} filter hit, skip oCloud {}.'
108                         .format(sub_data['subscriptionId'], data.id))
109         else:
110             callback_smo(sub, msg, ocloud_dict)
111
112
113 def call_smo(notifications: AbstractNotifications, reg_data: dict):
114     smo_token = conf.DEFAULT.smo_token_data
115     smo_token_info = {
116         'iss': 'o2ims',
117         'aud': 'smo',
118         'smo_token_payload': smo_token,
119         'smo_token_type': 'jwt',
120         'smo_token_expiration': '',
121         'smo_token_algo': 'RS256'
122     }
123
124     callback = {
125         'globalCloudId': reg_data['globalCloudId'],
126         'oCloudId': reg_data['oCloudId'],
127         'IMS_EP': config.get_api_url(),
128         'smo_token_data': smo_token_info
129     }
130     logger.info('callback URL: {}'.format(conf.DEFAULT.smo_register_url))
131     logger.debug('callback data: {}'.format(json.dumps(callback)))
132     return notifications.send(conf.DEFAULT.smo_register_url, callback)