Convert file endlines to Unix (LF)
[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
25 from o2ims.domain import commands
26 from o2ims.domain.configuration_obj import ConfigurationTypeEnum, \
27     RegistrationStatusEnum
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 all is {}'.format(data.all))
40     if data.all:
41         confs = uow.configrations.list()
42         for conf in confs:
43             if conf.conftype != ConfigurationTypeEnum.SMO:
44                 continue
45             reg_data = conf.serialize()
46             logger.debug('Configuration: {}'.format(
47                 reg_data['configurationId']))
48
49             register_smo(uow, reg_data)
50     else:
51         with uow:
52             conf = uow.configurations.get(data.id)
53             if conf is None:
54                 return
55             logger.debug('Configuration: {}'.format(conf.configurationId))
56             conf_data = conf.serialize()
57             register_smo(uow, conf_data)
58
59
60 def register_smo(uow, reg_data):
61     call_res = call_smo(reg_data)
62     logger.debug('Call SMO response is {}'.format(call_res))
63     if call_res:
64         reg = uow.configurations.get(reg_data['configurationId'])
65         if reg is None:
66             return
67         reg.status = RegistrationStatusEnum.NOTIFIED
68         logger.debug('Updating Configurations: {}'.format(
69             reg.configurationId))
70         uow.configurations.update(reg)
71         uow.commit()
72
73
74 # def retry(fun, max_tries=2):
75 #     for i in range(max_tries):
76 #         try:
77 #             time.sleep(5*i)
78 #             # await asyncio.sleep(5*i)
79 #             res = fun()
80 #             logger.debug('retry function result: {}'.format(res))
81 #             return res
82 #         except Exception:
83 #             continue
84
85
86 @retry((ConnectionRefusedError), tries=2, delay=2)
87 def call_smo(reg_data: dict):
88     callback_data = json.dumps({
89         'consumerSubscriptionId': reg_data['configurationId'],
90         'imsUrl': config.get_api_url()
91     })
92     logger.info('URL: {}, data: {}'.format(
93         reg_data['callback'], callback_data))
94
95     o = urlparse(reg_data['callback'])
96     conn = http.client.HTTPConnection(o.netloc)
97     headers = {'Content-type': 'application/json'}
98     conn.request('POST', o.path, callback_data, headers)
99     resp = conn.getresponse()
100     data = resp.read().decode('utf-8')
101     # json_data = json.loads(data)
102     if resp.status == 202 or resp.status == 200:
103         logger.info('Registrer to SMO successed, response code {} {}, data {}'.
104                     format(resp.status, resp.reason, data))
105         return True
106     logger.error('Response code is: {}'.format(resp.status))
107     return False