77ab28b9633976899783a8055b6d593082af905e
[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 import ssl
21 from urllib.parse import urlparse
22 from retry import retry
23
24 from o2common.service.unit_of_work import AbstractUnitOfWork
25 from o2common.config import config, conf
26
27 from o2ims.domain import commands
28 from o2ims.domain.subscription_obj import NotificationEventEnum
29
30 from o2common.helper import o2logging
31 logger = o2logging.get_logger(__name__)
32
33
34 def registry_to_smo(
35     cmd: commands.Register2SMO,
36     uow: AbstractUnitOfWork,
37 ):
38     logger.info('In registry_to_smo')
39     data = cmd.data
40     logger.info('The Register2SMO notificationEventType is {}'.format(
41         data.notificationEventType))
42     with uow:
43         ocloud = uow.oclouds.get(data.id)
44         if ocloud is None:
45             return
46         logger.debug('O-Cloud Global UUID: {}'.format(ocloud.globalCloudId))
47         ocloud_dict = ocloud.serialize()
48         if data.notificationEventType == NotificationEventEnum.CREATE:
49             register_smo(uow, ocloud_dict)
50
51
52 class RegIMSToSMOExp(Exception):
53     def __init__(self, value):
54         self.value = value
55
56
57 def register_smo(uow, ocloud_data):
58     call_res = call_smo(ocloud_data)
59     logger.debug('Call SMO response is {}'.format(call_res))
60     if call_res is not True:
61         raise RegIMSToSMOExp('Register o2ims to SMO failed')
62     # TODO: record the result for the smo register
63
64
65 # def retry(fun, max_tries=2):
66 #     for i in range(max_tries):
67 #         try:
68 #             time.sleep(5*i)
69 #             # await asyncio.sleep(5*i)
70 #             res = fun()
71 #             logger.debug('retry function result: {}'.format(res))
72 #             return res
73 #         except Exception:
74 #             continue
75
76
77 @retry((ConnectionRefusedError), tries=2, delay=2)
78 def call_smo(reg_data: dict):
79     smo_token = conf.DEFAULT.smo_token_data
80     smo_token_info = {
81         'iss': 'o2ims',
82         'aud': 'smo',
83         'smo_token_payload': smo_token,
84         'smo_token_type': 'jwt',
85         'smo_token_expiration': '',
86         'smo_token_algo': 'RS256'
87     }
88
89     callback_data = json.dumps({
90         'globalCloudId': reg_data['globalCloudId'],
91         'oCloudId': reg_data['oCloudId'],
92         'IMS_EP': config.get_api_url(),
93         'smo_token_data': smo_token_info
94     })
95     logger.info('URL: {}, data: {}'.format(
96         conf.DEFAULT.smo_register_url, callback_data))
97     o = urlparse(conf.DEFAULT.smo_register_url)
98     if o.scheme == 'https':
99         sslctx = ssl.create_default_context(purpose=ssl.Purpose.SERVER_AUTH)
100         sslctx.check_hostname = True
101         sslctx.verify_mode = ssl.CERT_REQUIRED
102         sslctx.load_default_certs()
103         conn = http.client.HTTPSConnection(o.netloc, context=sslctx)
104     else:
105         conn = http.client.HTTPConnection(o.netloc)
106
107     try:
108         return post_data(conn, o.path, callback_data)
109     except ssl.SSLCertVerificationError as e:
110         logger.info('post data except: {}'.format(e))
111         if 'self signed' in str(e):
112             sslctx = ssl.create_default_context(
113                 purpose=ssl.Purpose.SERVER_AUTH)
114             smo_ca_path = config.get_smo_ca_config_path()
115             sslctx.load_verify_locations(smo_ca_path)
116             sslctx.check_hostname = False
117             sslctx.verify_mode = ssl.CERT_REQUIRED
118             conn = http.client.HTTPSConnection(o.netloc, context=sslctx)
119             return post_data(conn, o.path, callback_data)
120     except Exception as e:
121         logger.info('except: {}'.format(e))
122         return False
123
124
125 def post_data(conn, path, data):
126     headers = {'Content-type': 'application/json'}
127     conn.request('POST', path, data, headers)
128     resp = conn.getresponse()
129     data = resp.read().decode('utf-8')
130     # json_data = json.loads(data)
131     if resp.status == 202 or resp.status == 200:
132         logger.info('Registrer to SMO successed, response code {} {}, data {}'.
133                     format(resp.status, resp.reason, data))
134         return True
135     logger.error('Response code is: {}'.format(resp.status))
136     return False