1ab1189ea9691eb0cd2811094ba026a524579712
[pti/o2.git] / o2ims / service / auditor / pserver_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 uuid
18 import json
19 from typing import Callable
20
21 from o2ims.domain import commands, events
22 from o2ims.domain.stx_object import StxGenericModel
23 from o2ims.domain.subscription_obj import NotificationEventEnum
24 from o2common.service.unit_of_work import AbstractUnitOfWork
25 from o2ims.domain.resource_type import MismatchedModel
26 from o2ims.domain.ocloud import Resource, ResourceType
27
28 from o2common.helper import o2logging
29 logger = o2logging.get_logger(__name__)
30
31
32 class InvalidResourceType(Exception):
33     pass
34
35
36 def update_pserver(
37     cmd: commands.UpdatePserver,
38     uow: AbstractUnitOfWork,
39     publish: Callable
40 ):
41     stxobj = cmd.data
42     with uow:
43         # resourcepool = uow.resource_pools.get(cmd.parentid)
44
45         # res = uow.session.execute(select(resourcetype).where(
46         #     resourcetype.c.resourceTypeEnum == stxobj.type))
47         res = uow.session.execute(
48             '''
49             SELECT "resourceTypeId", "name"
50             FROM "resourceType"
51             WHERE "resourceTypeEnum" = :resource_type_enum
52             ''',
53             dict(resource_type_enum=stxobj.type.name)
54         )
55         first = res.first()
56         if first is None:
57             res_type_name = 'pserver'
58             resourcetype_id = str(uuid.uuid3(
59                 uuid.NAMESPACE_URL, res_type_name))
60             res_type = ResourceType(
61                 resourcetype_id,
62                 res_type_name, stxobj.type,
63                 description='The Physical Server resource type')
64             dict_id = str(uuid.uuid3(
65                 uuid.NAMESPACE_URL,
66                 str(f"{res_type_name}_alarmdictionary")))
67             alarm_dictionary = uow.alarm_dictionaries.get(dict_id)
68             if alarm_dictionary:
69                 res_type.alarmDictionary = alarm_dictionary
70             uow.resource_types.add(res_type)
71         else:
72             resourcetype_id = first['resourceTypeId']
73
74         resource = uow.resources.get(stxobj.id)
75         if not resource:
76             logger.info("add pserver:" + stxobj.name
77                         + " update_at: " + str(stxobj.updatetime)
78                         + " id: " + str(stxobj.id)
79                         + " hash: " + str(stxobj.hash))
80             localmodel = create_by(stxobj, cmd.parentid, resourcetype_id)
81             uow.resources.add(localmodel)
82
83             logger.info("Add the pserver: " + stxobj.id
84                         + ", name: " + stxobj.name)
85         else:
86             localmodel = resource
87             if is_outdated(localmodel, stxobj):
88                 logger.info("update pserver:" + stxobj.name
89                             + " update_at: " + str(stxobj.updatetime)
90                             + " id: " + str(stxobj.id)
91                             + " hash: " + str(stxobj.hash))
92                 update_by(localmodel, stxobj, cmd.parentid)
93                 uow.resources.update(localmodel)
94
95             logger.info("Update the pserver: " + stxobj.id
96                         + ", name: " + stxobj.name)
97         uow.commit()
98
99
100 def is_outdated(resource: Resource, stxobj: StxGenericModel):
101     return True if resource.hash != stxobj.hash else False
102
103
104 def create_by(stxobj: StxGenericModel, parentid: str, resourcetype_id: str) \
105         -> Resource:
106     # content = json.loads(stxobj.content)
107     resourcetype_id = resourcetype_id
108     resourcepool_id = parentid
109     parent_id = None  # the root of the resource has no parent id
110     gAssetId = ''  # TODO: global ID
111     # description = "%s : A physical server resource" % stxobj.name
112     content = json.loads(stxobj.content)
113     selected_keys = [
114         "hostname", "personality", "id", "mgmt_ip", "mgmt_mac",
115         "software_load", "capabilities",
116         "operational", "availability", "administrative",
117         "boot_device", "rootfs_device", "install_state", "subfunctions",
118         "clock_synchronization", "max_cpu_mhz_allowed"
119         ]
120     filtered = dict(
121         filter(lambda item: item[0] in selected_keys, content.items()))
122     extensions = json.dumps(filtered)
123     description = ";".join([f"{k}:{v}" for k, v in filtered.items()])
124     resource = Resource(stxobj.id, resourcetype_id, resourcepool_id,
125                         parent_id, gAssetId, stxobj.content, description,
126                         extensions)
127     resource.createtime = stxobj.createtime
128     resource.updatetime = stxobj.updatetime
129     resource.hash = stxobj.hash
130
131     return resource
132
133
134 def update_by(target: Resource, stxobj: StxGenericModel,
135               parentid: str) -> None:
136     if target.resourceId != stxobj.id:
137         raise MismatchedModel("Mismatched Id")
138     target.createtime = stxobj.createtime
139     target.updatetime = stxobj.updatetime
140     target.hash = stxobj.hash
141     target.version_number = target.version_number + 1
142     target.events.append(events.ResourceChanged(
143         id=stxobj.id,
144         resourcePoolId=target.resourcePoolId,
145         notificationEventType=NotificationEventEnum.MODIFY,
146         updatetime=stxobj.updatetime
147     ))