Move registration API to configuration
[pti/o2.git] / o2ims / service / command / registration_handler.py
1 # Copyright (C) 2021 Wind River Systems, Inc.\r
2 #\r
3 #  Licensed under the Apache License, Version 2.0 (the "License");\r
4 #  you may not use this file except in compliance with the License.\r
5 #  You may obtain a copy of the License at\r
6 #\r
7 #      http://www.apache.org/licenses/LICENSE-2.0\r
8 #\r
9 #  Unless required by applicable law or agreed to in writing, software\r
10 #  distributed under the License is distributed on an "AS IS" BASIS,\r
11 #  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
12 #  See the License for the specific language governing permissions and\r
13 #  limitations under the License.\r
14 \r
15 # import time\r
16 import json\r
17 # import asyncio\r
18 # import requests\r
19 import http.client\r
20 from urllib.parse import urlparse\r
21 from retry import retry\r
22 \r
23 from o2common.service.unit_of_work import AbstractUnitOfWork\r
24 from o2common.config import config\r
25 from o2ims.domain import commands\r
26 from o2ims.domain.configuration_obj import ConfigurationTypeEnum, \\r
27     RegistrationStatusEnum\r
28 \r
29 from o2common.helper import o2logging\r
30 logger = o2logging.get_logger(__name__)\r
31 \r
32 \r
33 def registry_to_smo(\r
34     cmd: commands.Register2SMO,\r
35     uow: AbstractUnitOfWork,\r
36 ):\r
37     logger.info('In registry_to_smo')\r
38     data = cmd.data\r
39     logger.info('The Register2SMO all is {}'.format(data.all))\r
40     if data.all:\r
41         confs = uow.configrations.list()\r
42         for conf in confs:\r
43             if conf.conftype != ConfigurationTypeEnum.SMO:\r
44                 continue\r
45             reg_data = conf.serialize()\r
46             logger.debug('Configuration: {}'.format(\r
47                 reg_data['configurationId']))\r
48 \r
49             register_smo(uow, reg_data)\r
50     else:\r
51         with uow:\r
52             conf = uow.configurations.get(data.id)\r
53             if conf is None:\r
54                 return\r
55             logger.debug('Configuration: {}'.format(conf.configurationId))\r
56             conf_data = conf.serialize()\r
57             register_smo(uow, conf_data)\r
58 \r
59 \r
60 def register_smo(uow, reg_data):\r
61     call_res = call_smo(reg_data)\r
62     logger.debug('Call SMO response is {}'.format(call_res))\r
63     if call_res:\r
64         reg = uow.configurations.get(reg_data['configurationId'])\r
65         if reg is None:\r
66             return\r
67         reg.status = RegistrationStatusEnum.NOTIFIED\r
68         logger.debug('Updating Configurations: {}'.format(\r
69             reg.configurationId))\r
70         uow.configurations.update(reg)\r
71         uow.commit()\r
72 \r
73 \r
74 # def retry(fun, max_tries=2):\r
75 #     for i in range(max_tries):\r
76 #         try:\r
77 #             time.sleep(5*i)\r
78 #             # await asyncio.sleep(5*i)\r
79 #             res = fun()\r
80 #             logger.debug('retry function result: {}'.format(res))\r
81 #             return res\r
82 #         except Exception:\r
83 #             continue\r
84 \r
85 \r
86 @retry((ConnectionRefusedError), tries=2, delay=2)\r
87 def call_smo(reg_data: dict):\r
88     callback_data = json.dumps({\r
89         'consumerSubscriptionId': reg_data['configurationId'],\r
90         'imsUrl': config.get_api_url()\r
91     })\r
92     logger.info('URL: {}, data: {}'.format(\r
93         reg_data['callback'], callback_data))\r
94 \r
95     o = urlparse(reg_data['callback'])\r
96     conn = http.client.HTTPConnection(o.netloc)\r
97     headers = {'Content-type': 'application/json'}\r
98     conn.request('POST', o.path, callback_data, headers)\r
99     resp = conn.getresponse()\r
100     data = resp.read().decode('utf-8')\r
101     # json_data = json.loads(data)\r
102     if resp.status == 202 or resp.status == 200:\r
103         logger.info('Registrer to SMO successed, response code {} {}, data {}'.\r
104                     format(resp.status, resp.reason, data))\r
105         return True\r
106     logger.error('Response code is: {}'.format(resp.status))\r
107     return False\r