Merge "Fix the resource request handling with wrong resourcepoolId"
[pti/o2.git] / o2ims / service / auditor / alarm_handler.py
1 # Copyright (C) 2022 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 json
18
19 # from o2common.config import config
20 # from o2common.service.messagebus import MessageBus
21 from o2common.service.unit_of_work import AbstractUnitOfWork
22 from o2ims.domain import events, commands, alarm_obj
23 from o2ims.domain.alarm_obj import AlarmEventRecord, FaultGenericModel,\
24     AlarmNotificationEventEnum
25
26 from o2common.helper import o2logging
27 logger = o2logging.get_logger(__name__)
28
29
30 def update_alarm(
31     cmd: commands.UpdateAlarm,
32     uow: AbstractUnitOfWork
33 ):
34     fmobj = cmd.data
35     logger.info("add alarm event record:" + fmobj.name
36                 + " update_at: " + str(fmobj.updatetime)
37                 + " id: " + str(fmobj.id)
38                 + " hash: " + str(fmobj.hash))
39     with uow:
40         resourcepool = uow.resource_pools.get(cmd.parentid)
41
42         alarm_event_record = uow.alarm_event_records.get(fmobj.id)
43         if not alarm_event_record:
44             logger.info("add alarm event record:" + fmobj.name
45                         + " update_at: " + str(fmobj.updatetime)
46                         + " id: " + str(fmobj.id)
47                         + " hash: " + str(fmobj.hash))
48             localmodel = create_by(fmobj)
49             content = json.loads(fmobj.content)
50             entity_type_id = content['entity_type_id']
51             entity_instance_id = content['entity_instance_id']
52             logger.info('alarm entity instance id: ' + entity_instance_id)
53             if 'host' == entity_type_id:
54                 # TODO: handle different resource type
55                 hostname = entity_instance_id.split('.')[0].split('=')[1]
56                 logger.debug('hostname: ' + hostname)
57
58                 restype = uow.resource_types.get_by_name('pserver')
59                 localmodel.resourceTypeId = restype.resourceTypeId
60                 hosts = uow.resources.list(resourcepool.resourcePoolId, **{
61                     'resourceTypeId': restype.resourceTypeId
62                 })
63                 for host in hosts:
64                     if host.name == hostname:
65                         localmodel.resourceId = host.resourceId
66                 uow.alarm_event_records.add(localmodel)
67                 logger.info("Add the alarm event record: " + fmobj.id
68                             + ", name: " + fmobj.name)
69             # localmodel.resourceTypeId = check_restype_id(uow, fmobj)
70             # logger.debug("resource type ID: " + localmodel.resourceTypeId)
71             # localmodel.resourceId = check_res_id(uow, fmobj)
72             # logger.debug("resource ID: " + localmodel.resourceId)
73             # uow.alarm_event_records.add(localmodel)
74             else:
75                 restype = uow.resource_types.get_by_name('undefined_aggregate')
76                 localmodel.resourceTypeId = restype.resourceTypeId
77
78                 undefined_res = uow.resources.list(
79                     resourcepool.resourcePoolId, **{
80                         'resourceTypeId': restype.resourceTypeId
81                     })
82                 localmodel.resourceId = undefined_res[0].resourceId
83                 uow.alarm_event_records.add(localmodel)
84                 logger.info("Add the alarm event record: " + fmobj.id
85                             + ", name: " + fmobj.name)
86
87         else:
88             localmodel = alarm_event_record
89             if is_outdated(localmodel, fmobj):
90                 logger.info("update alarm event record:" + fmobj.name
91                             + " update_at: " + str(fmobj.updatetime)
92                             + " id: " + str(fmobj.id)
93                             + " hash: " + str(fmobj.hash))
94                 update_by(localmodel, fmobj)
95                 uow.alarm_event_records.update(localmodel)
96
97             logger.info("Update the alarm event record: " + fmobj.id
98                         + ", name: " + fmobj.name)
99         uow.commit()
100
101
102 def is_outdated(alarm_event_record: AlarmEventRecord,
103                 fmobj: FaultGenericModel):
104     return True if alarm_event_record.hash != fmobj.hash else False
105
106
107 def create_by(fmobj: FaultGenericModel) -> AlarmEventRecord:
108     content = json.loads(fmobj.content)
109     # globalcloudId = fmobj.id  # to be updated
110     alarm_definition_id = fmobj.alarm_def_id
111     alarm_event_record = AlarmEventRecord(
112         fmobj.id, "", "",
113         alarm_definition_id, "",
114         fmobj.timestamp)
115
116     def severity_switch(val):
117         if val == 'critical':
118             return alarm_obj.PerceivedSeverityEnum.CRITICAL
119         elif val == 'major':
120             return alarm_obj.PerceivedSeverityEnum.MAJOR
121         elif val == 'minor':
122             return alarm_obj.PerceivedSeverityEnum.MINOR
123         else:
124             return alarm_obj.PerceivedSeverityEnum.WARNING
125     alarm_event_record.perceivedSeverity = severity_switch(content['severity'])
126     alarm_event_record.probableCauseId = fmobj.probable_cause_id
127     alarm_event_record.hash = fmobj.hash
128     # logger.info('severity: ' + content['severity'])
129     # logger.info('perceived severity: '
130     # + alarm_event_record.perceivedSeverity)
131     alarm_event_record.events.append(events.AlarmEventChanged(
132         id=fmobj.id,
133         notificationEventType=AlarmNotificationEventEnum.NEW,
134         updatetime=fmobj.updatetime
135     ))
136
137     return alarm_event_record
138
139
140 def update_by(target: AlarmEventRecord, fmobj: FaultGenericModel
141               ) -> None:
142     # content = json.loads(fmobj.content)
143     target.hash = fmobj.hash
144     if fmobj.status == 'clear':
145         target.perceivedSeverity = alarm_obj.PerceivedSeverityEnum.CLEARED
146     target.events.append(events.AlarmEventChanged(
147         id=fmobj.id,
148         notificationEventType=AlarmNotificationEventEnum.CLEAR,
149         updatetime=fmobj.updatetime
150     ))
151
152
153 def check_restype_id(uow: AbstractUnitOfWork, fmobj: FaultGenericModel) -> str:
154     content = json.loads(fmobj.content)
155     entity_type_id = content['entity_type_id']
156     # Entity_Instance_ID: <hostname>.lvmthinpool=<VG name>/<Pool name>
157     # Entity_Instance_ID: ["image=<image-uuid>, instance=<instance-uuid>",
158     # Entity_Instance_ID: [host=<hostname>.command=provision,
159     # Entity_Instance_ID: [host=<hostname>.event=discovered,
160     # Entity_Instance_ID: [host=<hostname>.state=disabled,
161     # Entity_Instance_ID: [subcloud=<subcloud>.resource=<compute | network
162     # | platform | volumev2>]
163     # Entity_Instance_ID: cinder_io_monitor
164     # Entity_Instance_ID: cluster=<dist-fs-uuid>
165     # Entity_Instance_ID: cluster=<dist-fs-uuid>.peergroup=<group-x>
166     # Entity_Instance_ID: fs_name=<image-conversion>
167     # Entity_Instance_ID: host=<host_name>
168     # Entity_Instance_ID: host=<host_name>.network=<network>
169     # Entity_Instance_ID: host=<host_name>.services=compute
170     # Entity_Instance_ID: host=<hostname>
171     # Entity_Instance_ID: host=<hostname>,agent=<agent-uuid>,
172     # bgp-peer=<bgp-peer>
173     # Entity_Instance_ID: host=<hostname>.agent=<agent-uuid>
174     # Entity_Instance_ID: host=<hostname>.interface=<if-name>
175     # Entity_Instance_ID: host=<hostname>.interface=<if-uuid>
176     # Entity_Instance_ID: host=<hostname>.ml2driver=<driver>
177     # Entity_Instance_ID: host=<hostname>.network=<mgmt | oam | cluster-host>
178     # Entity_Instance_ID: host=<hostname>.openflow-controller=<uri>
179     # Entity_Instance_ID: host=<hostname>.openflow-network=<name>
180     # Entity_Instance_ID: host=<hostname>.port=<port-name>
181     # Entity_Instance_ID: host=<hostname>.port=<port-uuid>
182     # Entity_Instance_ID: host=<hostname>.process=<processname>
183     # Entity_Instance_ID: host=<hostname>.processor=<processor>
184     # Entity_Instance_ID: host=<hostname>.sdn-controller=<uuid>
185     # Entity_Instance_ID: host=<hostname>.sensor=<sensorname>
186     # Entity_Instance_ID: host=<hostname>.service=<service>
187     # Entity_Instance_ID: host=<hostname>.service=networking.providernet=
188     # <pnet-uuid>
189     # Entity_Instance_ID: host=controller
190     # Entity_Instance_ID: itenant=<tenant-uuid>.instance=<instance-uuid>
191     # Entity_Instance_ID: k8s_application=<appname>
192     # Entity_Instance_ID: kubernetes=PV-migration-failed
193     # Entity_Instance_ID: orchestration=fw-update
194     # Entity_Instance_ID: orchestration=kube-rootca-update
195     # Entity_Instance_ID: orchestration=kube-upgrade
196     # Entity_Instance_ID: orchestration=sw-patch
197     # Entity_Instance_ID: orchestration=sw-upgrade
198     # Entity_Instance_ID: resource=<crd-resource>,name=<resource-name>
199     # Entity_Instance_ID: server-group<server-group-uuid>
200     # Entity_Instance_ID: service=networking.providernet=<pnet-uuid>
201     # Entity_Instance_ID: service_domain=<domain>.service_group=<group>
202     # Entity_Instance_ID: service_domain=<domain>.service_group=<group>.
203     # host=<host_name>
204     # Entity_Instance_ID: service_domain=<domain_name>.service_group=
205     # <group_name>
206     # Entity_Instance_ID: service_domain=<domain_name>.service_group=
207     # <group_name>.host=<hostname>
208     # Entity_Instance_ID: storage_backend=<storage-backend-name>
209     # Entity_Instance_ID: subcloud=<subcloud>
210     # Entity_Instance_ID: subsystem=vim
211     # Entity_Instance_ID: tenant=<tenant-uuid>.instance=<instance-uuid>
212     if 'host' == entity_type_id:
213         with uow:
214             restype = uow.resource_types.get_by_name('pserver')
215             return restype.resourceTypeId
216     else:
217         return ""
218
219
220 def check_res_id(uow: AbstractUnitOfWork, fmobj: FaultGenericModel) -> str:
221     content = json.loads(fmobj.content)
222     entity_type_id = content['entity_type_id']
223     entity_instance_id = content['entity_instance_id']
224     if 'host' == entity_type_id:
225         logger.info('host: ' + entity_instance_id)
226         hostname = entity_instance_id.split('.')[0].split('=')[1]
227         with uow:
228             respools = uow.resource_pools.list()
229             respoolids = [respool.resourcePoolId for respool in respools
230                           if respool.oCloudId == respool.resourcePoolId]
231             restype = uow.resource_types.get_by_name('pserver')
232             hosts = uow.resources.list(respoolids[0], **{
233                 'resourceTypeId': restype.resourceTypeId
234             })
235             for host in hosts:
236                 if host.name == hostname:
237                     return host.resourceId
238     else:
239         return ""