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