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