Fix INF-393 serviceUri in the DMS list query and detail query have different response
[pti/o2.git] / o2ims / service / auditor / dms_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 # pylint: disable=unused-argument
16 from __future__ import annotations
17 import base64
18 import json
19
20 from o2ims.domain import commands, events
21 from o2ims.domain.stx_object import StxGenericModel
22 from o2ims.domain.subscription_obj import NotificationEventEnum
23 from o2common.service.unit_of_work import AbstractUnitOfWork
24 from o2ims.domain.resource_type import MismatchedModel
25 from o2ims.domain.ocloud import DeploymentManager
26 # if TYPE_CHECKING:
27 #     from . import unit_of_work
28
29 from o2common.helper import o2logging
30 logger = o2logging.get_logger(__name__)
31
32
33 class InvalidResourceType(Exception):
34     pass
35
36
37 def update_dms(
38     cmd: commands.UpdateDms,
39     uow: AbstractUnitOfWork
40 ):
41     stxobj = cmd.data
42     with uow:
43         dms = uow.deployment_managers.get(stxobj.id)
44         if not dms:
45             logger.info("add dms: " + stxobj.name
46                         + " update_at: " + str(stxobj.updatetime)
47                         + " id: " + str(stxobj.id)
48                         + " hash: " + str(stxobj.hash))
49             # ocloud = uow.oclouds.get(cmd.parent.oCloudId)
50             localmodel = create_by(stxobj, cmd.parentid)
51             uow.deployment_managers.add(localmodel)
52
53             logger.info("Add a dms: " + stxobj.id
54                         + ", name: " + stxobj.name)
55         else:
56             localmodel = dms
57             if is_outdated(localmodel, stxobj):
58                 logger.info("update a dms: " + stxobj.name
59                             + " update_at: " + str(stxobj.updatetime)
60                             + " id: " + str(stxobj.id)
61                             + " hash: " + str(stxobj.hash))
62                 update_by(localmodel, stxobj, cmd.parentid)
63                 uow.deployment_managers.update(localmodel)
64
65             logger.info("Update a dms: " + stxobj.id
66                         + ", name: " + stxobj.name)
67         uow.commit()
68
69
70 def is_outdated(ocloud: DeploymentManager, stxobj: StxGenericModel):
71     # if stxobj.updatetime:
72     #     return True if Ocloud.updatetime < stxobj.updatetime else False
73     # else:
74     return True if ocloud.hash != stxobj.hash else False
75
76
77 def create_by(stxobj: StxGenericModel, parentid: str) -> DeploymentManager:
78     description = "A DMS"
79     ocloudid = parentid
80     supportedLocations = ''
81     capabilities = ''
82     capacity = ''
83     content = json.loads(stxobj.content)
84     dmsendpoint = content['cluster_api_endpoint']
85     profile = _convert_content(content)
86     localmodel = DeploymentManager(
87         stxobj.id, stxobj.name, ocloudid, dmsendpoint, description,
88         supportedLocations, capabilities, capacity, profile)
89     localmodel.createtime = stxobj.createtime
90     localmodel.updatetime = stxobj.updatetime
91     localmodel.hash = stxobj.hash
92
93     localmodel.events.append(events.DmsChanged(
94         id=stxobj.id,
95         notificationEventType=NotificationEventEnum.CREATE,
96         updatetime=stxobj.updatetime
97     ))
98
99     return localmodel
100
101
102 def update_by(target: DeploymentManager, stxobj: StxGenericModel,
103               parentid: str) -> None:
104     if target.deploymentManagerId != stxobj.id:
105         raise MismatchedModel("Mismatched Id")
106     target.name = stxobj.name
107     target.createtime = stxobj.createtime
108     target.updatetime = stxobj.updatetime
109     target.hash = stxobj.hash
110     target.oCloudId = parentid
111     target.version_number = target.version_number + 1
112     target.profile = _convert_content(stxobj.content)
113
114     target.events.append(events.DmsChanged(
115         id=stxobj.id,
116         notificationEventType=NotificationEventEnum.MODIFY,
117         updatetime=stxobj.updatetime
118     ))
119
120
121 def _convert_content(content: str):
122     # Convert api retrun content to dict object
123     # content = json.loads(stxobj_content)
124     admin_user = content["admin_user"]
125     cluster_api_endpoint = content["cluster_api_endpoint"]
126     cluster_ca_cert = _b64_encode_str(content["cluster_ca_cert"])
127     admin_client_cert = _b64_encode_str(content["admin_client_cert"])
128     admin_client_key = _b64_encode_str(content["admin_client_key"])
129     # admin_client_cert = base64.b64encode(
130     #     bytes(content["admin_client_cert"], "utf-8"))
131     # admin_client_key = base64.b64encode(
132     #     bytes(content["admin_client_key"], "utf-8"))
133     profile = {
134         "admin_user": admin_user,
135         "cluster_api_endpoint": cluster_api_endpoint,
136         "cluster_ca_cert": cluster_ca_cert,
137         "admin_client_cert": admin_client_cert,
138         "admin_client_key": admin_client_key
139     }
140
141     return json.dumps(profile)
142
143
144 def _b64_encode_str(msg: str, encode: str = 'utf-8') -> str:
145     msg_bytes = msg.encode('utf-8')
146     base64_bytes = base64.b64encode(msg_bytes)
147     base64_msg = base64_bytes.decode('utf-8')
148     return base64_msg