Fix INF-381 another issue cause this case still failed
[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, ocloud
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                 args = [ocloud.Resource.resourceTypeId ==
61                         restype.resourceTypeId]
62                 hosts = uow.resources.list(resourcepool.resourcePoolId, *args)
63                 for host in hosts:
64                     logger.debug('host extensions: ' + host.extensions)
65                     extensions = json.loads(host.extensions)
66                     if extensions['hostname'] == hostname:
67                         localmodel.resourceId = host.resourceId
68                 uow.alarm_event_records.add(localmodel)
69                 logger.info("Add the alarm event record: " + fmobj.id
70                             + ", name: " + fmobj.name)
71             else:
72                 restype = uow.resource_types.get_by_name('undefined_aggregate')
73                 localmodel.resourceTypeId = restype.resourceTypeId
74
75                 args = [ocloud.Resource.resourceTypeId ==
76                         restype.resourceTypeId]
77                 undefined_res = uow.resources.list(
78                     resourcepool.resourcePoolId, *args)
79                 localmodel.resourceId = undefined_res[0].resourceId
80                 uow.alarm_event_records.add(localmodel)
81                 logger.info("Add the alarm event record: " + fmobj.id
82                             + ", name: " + fmobj.name)
83
84         else:
85             localmodel = alarm_event_record
86             if is_outdated(localmodel, fmobj):
87                 logger.info("update alarm event record:" + fmobj.name
88                             + " update_at: " + str(fmobj.updatetime)
89                             + " id: " + str(fmobj.id)
90                             + " hash: " + str(fmobj.hash))
91                 update_by(localmodel, fmobj)
92                 uow.alarm_event_records.update(localmodel)
93
94             logger.info("Update the alarm event record: " + fmobj.id
95                         + ", name: " + fmobj.name)
96         uow.commit()
97
98
99 def is_outdated(alarm_event_record: AlarmEventRecord,
100                 fmobj: FaultGenericModel):
101     return True if alarm_event_record.hash != fmobj.hash else False
102
103
104 def create_by(fmobj: FaultGenericModel) -> AlarmEventRecord:
105     content = json.loads(fmobj.content)
106     # globalcloudId = fmobj.id  # to be updated
107     alarm_definition_id = fmobj.alarm_def_id
108     alarm_event_record = AlarmEventRecord(
109         fmobj.id, "", "",
110         alarm_definition_id, "",
111         fmobj.timestamp)
112
113     def severity_switch(val):
114         if val == 'critical':
115             return alarm_obj.PerceivedSeverityEnum.CRITICAL
116         elif val == 'major':
117             return alarm_obj.PerceivedSeverityEnum.MAJOR
118         elif val == 'minor':
119             return alarm_obj.PerceivedSeverityEnum.MINOR
120         else:
121             return alarm_obj.PerceivedSeverityEnum.WARNING
122     alarm_event_record.perceivedSeverity = severity_switch(content['severity'])
123     alarm_event_record.probableCauseId = fmobj.probable_cause_id
124     alarm_event_record.hash = fmobj.hash
125     # logger.info('severity: ' + content['severity'])
126     # logger.info('perceived severity: '
127     # + alarm_event_record.perceivedSeverity)
128     alarm_event_record.events.append(events.AlarmEventChanged(
129         id=fmobj.id,
130         notificationEventType=AlarmNotificationEventEnum.NEW,
131         updatetime=fmobj.updatetime
132     ))
133
134     return alarm_event_record
135
136
137 def update_by(target: AlarmEventRecord, fmobj: FaultGenericModel
138               ) -> None:
139     # content = json.loads(fmobj.content)
140     target.hash = fmobj.hash
141     if fmobj.status == 'clear':
142         target.perceivedSeverity = alarm_obj.PerceivedSeverityEnum.CLEARED
143     target.events.append(events.AlarmEventChanged(
144         id=fmobj.id,
145         notificationEventType=AlarmNotificationEventEnum.CLEAR,
146         updatetime=fmobj.updatetime
147     ))
148
149
150 def check_restype_id(uow: AbstractUnitOfWork, fmobj: FaultGenericModel) -> str:
151     content = json.loads(fmobj.content)
152     entity_type_id = content['entity_type_id']
153     # Entity_Instance_ID: <hostname>.lvmthinpool=<VG name>/<Pool name>
154     # Entity_Instance_ID: ["image=<image-uuid>, instance=<instance-uuid>",
155     # Entity_Instance_ID: [host=<hostname>.command=provision,
156     # Entity_Instance_ID: [host=<hostname>.event=discovered,
157     # Entity_Instance_ID: [host=<hostname>.state=disabled,
158     # Entity_Instance_ID: [subcloud=<subcloud>.resource=<compute | network
159     # | platform | volumev2>]
160     # Entity_Instance_ID: cinder_io_monitor
161     # Entity_Instance_ID: cluster=<dist-fs-uuid>
162     # Entity_Instance_ID: cluster=<dist-fs-uuid>.peergroup=<group-x>
163     # Entity_Instance_ID: fs_name=<image-conversion>
164     # Entity_Instance_ID: host=<host_name>
165     # Entity_Instance_ID: host=<host_name>.network=<network>
166     # Entity_Instance_ID: host=<host_name>.services=compute
167     # Entity_Instance_ID: host=<hostname>
168     # Entity_Instance_ID: host=<hostname>,agent=<agent-uuid>,
169     # bgp-peer=<bgp-peer>
170     # Entity_Instance_ID: host=<hostname>.agent=<agent-uuid>
171     # Entity_Instance_ID: host=<hostname>.interface=<if-name>
172     # Entity_Instance_ID: host=<hostname>.interface=<if-uuid>
173     # Entity_Instance_ID: host=<hostname>.ml2driver=<driver>
174     # Entity_Instance_ID: host=<hostname>.network=<mgmt | oam | cluster-host>
175     # Entity_Instance_ID: host=<hostname>.openflow-controller=<uri>
176     # Entity_Instance_ID: host=<hostname>.openflow-network=<name>
177     # Entity_Instance_ID: host=<hostname>.port=<port-name>
178     # Entity_Instance_ID: host=<hostname>.port=<port-uuid>
179     # Entity_Instance_ID: host=<hostname>.process=<processname>
180     # Entity_Instance_ID: host=<hostname>.processor=<processor>
181     # Entity_Instance_ID: host=<hostname>.sdn-controller=<uuid>
182     # Entity_Instance_ID: host=<hostname>.sensor=<sensorname>
183     # Entity_Instance_ID: host=<hostname>.service=<service>
184     # Entity_Instance_ID: host=<hostname>.service=networking.providernet=
185     # <pnet-uuid>
186     # Entity_Instance_ID: host=controller
187     # Entity_Instance_ID: itenant=<tenant-uuid>.instance=<instance-uuid>
188     # Entity_Instance_ID: k8s_application=<appname>
189     # Entity_Instance_ID: kubernetes=PV-migration-failed
190     # Entity_Instance_ID: orchestration=fw-update
191     # Entity_Instance_ID: orchestration=kube-rootca-update
192     # Entity_Instance_ID: orchestration=kube-upgrade
193     # Entity_Instance_ID: orchestration=sw-patch
194     # Entity_Instance_ID: orchestration=sw-upgrade
195     # Entity_Instance_ID: resource=<crd-resource>,name=<resource-name>
196     # Entity_Instance_ID: server-group<server-group-uuid>
197     # Entity_Instance_ID: service=networking.providernet=<pnet-uuid>
198     # Entity_Instance_ID: service_domain=<domain>.service_group=<group>
199     # Entity_Instance_ID: service_domain=<domain>.service_group=<group>.
200     # host=<host_name>
201     # Entity_Instance_ID: service_domain=<domain_name>.service_group=
202     # <group_name>
203     # Entity_Instance_ID: service_domain=<domain_name>.service_group=
204     # <group_name>.host=<hostname>
205     # Entity_Instance_ID: storage_backend=<storage-backend-name>
206     # Entity_Instance_ID: subcloud=<subcloud>
207     # Entity_Instance_ID: subsystem=vim
208     # Entity_Instance_ID: tenant=<tenant-uuid>.instance=<instance-uuid>
209     if 'host' == entity_type_id:
210         with uow:
211             restype = uow.resource_types.get_by_name('pserver')
212             return restype.resourceTypeId
213     else:
214         return ""
215
216
217 def check_res_id(uow: AbstractUnitOfWork, fmobj: FaultGenericModel) -> str:
218     content = json.loads(fmobj.content)
219     entity_type_id = content['entity_type_id']
220     entity_instance_id = content['entity_instance_id']
221     if 'host' == entity_type_id:
222         logger.info('host: ' + entity_instance_id)
223         hostname = entity_instance_id.split('.')[0].split('=')[1]
224         with uow:
225             respools = uow.resource_pools.list()
226             respoolids = [respool.resourcePoolId for respool in respools
227                           if respool.oCloudId == respool.resourcePoolId]
228             restype = uow.resource_types.get_by_name('pserver')
229             hosts = uow.resources.list(respoolids[0], **{
230                 'resourceTypeId': restype.resourceTypeId
231             })
232             for host in hosts:
233                 if host.name == hostname:
234                     return host.resourceId
235     else:
236         return ""