0c6bbefd3923a17d39df72fc13684147a037fdff
[pti/o2.git] / o2ims / service / command / registration_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 time
16 import json
17 # import asyncio
18 # import requests
19 import http.client
20 from urllib.parse import urlparse
21 from retry import retry
22
23 from o2common.service.unit_of_work import AbstractUnitOfWork
24 from o2common.config import config, conf
25
26 from o2ims.domain import commands
27 from o2ims.domain.subscription_obj import NotificationEventEnum
28
29 from o2common.helper import o2logging
30 logger = o2logging.get_logger(__name__)
31
32
33 def registry_to_smo(
34     cmd: commands.Register2SMO,
35     uow: AbstractUnitOfWork,
36 ):
37     logger.info('In registry_to_smo')
38     data = cmd.data
39     logger.info('The Register2SMO notificationEventType is {}'.format(
40         data.notificationEventType))
41     with uow:
42         ocloud = uow.oclouds.get(data.id)
43         if ocloud is None:
44             return
45         logger.debug('O-Cloud Global UUID: {}'.format(ocloud.globalCloudId))
46         ocloud_dict = ocloud.serialize()
47         if data.notificationEventType == NotificationEventEnum.CREATE:
48             register_smo(uow, ocloud_dict)
49
50
51 def register_smo(uow, ocloud_data):
52     call_res = call_smo(ocloud_data)
53     logger.debug('Call SMO response is {}'.format(call_res))
54     # TODO: record the result for the smo register
55
56
57 # def retry(fun, max_tries=2):
58 #     for i in range(max_tries):
59 #         try:
60 #             time.sleep(5*i)
61 #             # await asyncio.sleep(5*i)
62 #             res = fun()
63 #             logger.debug('retry function result: {}'.format(res))
64 #             return res
65 #         except Exception:
66 #             continue
67
68
69 @retry((ConnectionRefusedError), tries=2, delay=2)
70 def call_smo(reg_data: dict):
71     smo_token = conf.DEFAULT.smo_token_data
72     smo_token_info = {
73         'iss': 'o2ims',
74         'aud': 'smo',
75         'smo_token_payload': smo_token,
76         'smo_token_type': 'jwt',
77         'smo_token_expiration': '',
78         'smo_token_algo': 'RS256'
79     }
80
81     callback_data = json.dumps({
82         'globalCloudId': reg_data['globalCloudId'],
83         'oCloudId': reg_data['oCloudId'],
84         'IMS_EP': config.get_api_url(),
85         'smo_token_data': smo_token_info
86     })
87     logger.info('URL: {}, data: {}'.format(
88         conf.DEFAULT.smo_register_url, callback_data))
89     o = urlparse(conf.DEFAULT.smo_register_url)
90     conn = http.client.HTTPConnection(o.netloc)
91     headers = {'Content-type': 'application/json'}
92     conn.request('POST', o.path, callback_data, headers)
93     resp = conn.getresponse()
94     data = resp.read().decode('utf-8')
95     # json_data = json.loads(data)
96     if resp.status == 202 or resp.status == 200:
97         logger.info('Registrer to SMO successed, response code {} {}, data {}'.
98                     format(resp.status, resp.reason, data))
99         return True
100     logger.error('Response code is: {}'.format(resp.status))
101     return False