Fix INF-378 inventory subscription filter upgrade
[pti/o2.git] / o2ims / service / auditor / pserver_mem_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
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 Resource, ResourceType
26
27 from o2common.helper import o2logging
28 logger = o2logging.get_logger(__name__)
29
30
31 class InvalidResourceType(Exception):
32     pass
33
34
35 def update_pserver_mem(
36     cmd: commands.UpdatePserverMem,
37     uow: AbstractUnitOfWork
38 ):
39     stxobj = cmd.data
40     with uow:
41         p_resource = uow.resources.get(cmd.parentid)
42         # resourcepool = uow.resource_pools.get(p_resource.resourcePoolId)
43
44         res = uow.session.execute(
45             '''
46             SELECT "resourceTypeId", "name"
47             FROM "resourceType"
48             WHERE "resourceTypeEnum" = :resource_type_enum
49             ''',
50             dict(resource_type_enum=stxobj.type.name)
51         )
52         first = res.first()
53         if first is None:
54             res_type_name = 'pserver_mem'
55             resourcetype_id = str(uuid.uuid3(
56                 uuid.NAMESPACE_URL, res_type_name))
57             res_type = ResourceType(
58                 resourcetype_id,
59                 res_type_name, stxobj.type,
60                 description='A Memory resource type of Physical Server')
61             dict_id = str(uuid.uuid3(
62                 uuid.NAMESPACE_URL,
63                 str(f"{res_type_name}_alarmdictionary")))
64             alarm_dictionary = uow.alarm_dictionaries.get(dict_id)
65             if alarm_dictionary:
66                 res_type.alarmDictionary = alarm_dictionary
67             res_type.events.append(events.ResourceTypeChanged(
68                 id=res_type.resourceTypeId,
69                 notificationEventType=NotificationEventEnum.CREATE,
70                 updatetime=stxobj.updatetime))
71             uow.resource_types.add(res_type)
72         else:
73             resourcetype_id = first['resourceTypeId']
74
75         resource = uow.resources.get(stxobj.id)
76         if not resource:
77             logger.info("add the memory of pserver:" + stxobj.name
78                         + " update_at: " + str(stxobj.updatetime)
79                         + " id: " + str(stxobj.id)
80                         + " hash: " + str(stxobj.hash))
81             localmodel = create_by(stxobj, p_resource, resourcetype_id)
82             uow.resources.add(localmodel)
83
84             logger.info("Add the memory of pserver: " + stxobj.id
85                         + ", name: " + stxobj.name)
86         else:
87             localmodel = resource
88             if is_outdated(localmodel, stxobj):
89                 logger.info("update memory of pserver:" + stxobj.name
90                             + " update_at: " + str(stxobj.updatetime)
91                             + " id: " + str(stxobj.id)
92                             + " hash: " + str(stxobj.hash))
93                 update_by(localmodel, stxobj, p_resource)
94                 uow.resources.update(localmodel)
95
96             logger.info("Update the memory of pserver: " + stxobj.id
97                         + ", name: " + stxobj.name)
98         uow.commit()
99
100
101 def is_outdated(resource: Resource, stxobj: StxGenericModel):
102     return True if resource.hash != stxobj.hash else False
103
104
105 def create_by(stxobj: StxGenericModel, parent: Resource, resourcetype_id: str)\
106         -> Resource:
107     # content = json.loads(stxobj.content)
108     resourcetype_id = resourcetype_id
109     resourcepool_id = parent.resourcePoolId
110     parent_id = parent.resourceId
111     gAssetId = ''  # TODO: global ID
112     # description = "%s : A memory resource of the physical server"\
113     #     % stxobj.name
114     content = json.loads(stxobj.content)
115     selected_keys = [
116         "memtotal_mib", "memavail_mib", "vm_hugepages_use_1G",
117         "vm_hugepages_possible_1G", "hugepages_configured",
118         "vm_hugepages_avail_1G", "vm_hugepages_nr_1G",
119         "vm_hugepages_nr_4K", "vm_hugepages_nr_2M",
120         "vm_hugepages_possible_2M", "vm_hugepages_avail_2M",
121         "platform_reserved_mib", "numa_node"
122     ]
123     filtered = dict(
124         filter(lambda item: item[0] in selected_keys, content.items()))
125     extensions = json.dumps(filtered)
126     description = ";".join([f"{k}:{v}" for k, v in filtered.items()])
127     resource = Resource(stxobj.id, resourcetype_id, resourcepool_id,
128                         parent_id, gAssetId, stxobj.content, description,
129                         extensions)
130     resource.createtime = stxobj.createtime
131     resource.updatetime = stxobj.updatetime
132     resource.hash = stxobj.hash
133
134     return resource
135
136
137 def update_by(target: Resource, stxobj: StxGenericModel,
138               parentid: str) -> None:
139     if target.resourceId != stxobj.id:
140         raise MismatchedModel("Mismatched Id")
141     target.createtime = stxobj.createtime
142     target.updatetime = stxobj.updatetime
143     target.hash = stxobj.hash
144     target.version_number = target.version_number + 1
145     target.events.append(events.ResourceChanged(
146         id=stxobj.id,
147         resourcePoolId=target.resourcePoolId,
148         notificationEventType=NotificationEventEnum.MODIFY,
149         updatetime=stxobj.updatetime
150     ))