c9e1e95cf531f941009942200fda39c388adb7c4
[pti/o2.git] / o2ims / adapter / clients / fault_client.py
1 # Copyright (C) 2022-2024 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 # client talking to Stx standalone
16
17 from typing import List  # Optional,  Set
18 import uuid as uuid
19
20 from cgtsclient.client import get_client as get_stx_client
21 from cgtsclient.exc import EndpointException
22 from dcmanagerclient.api.client import client as get_dc_client
23 from fmclient.client import get_client as get_fm_client
24 from fmclient.common.exceptions import HTTPNotFound
25
26 from o2app.adapter import unit_of_work
27 from o2common.config import config
28 from o2common.service.client.base_client import BaseClient
29 from o2ims.domain import alarm_obj as alarmModel
30
31 from o2common.helper import o2logging
32 logger = o2logging.get_logger(__name__)
33
34
35 CGTSCLIENT_ENDPOINT_ERROR_MSG = \
36     'Must provide Keystone credentials or user-defined endpoint and token'
37
38
39 class StxAlarmClient(BaseClient):
40     def __init__(self, uow: unit_of_work.AbstractUnitOfWork, driver=None):
41         super().__init__()
42         self.driver = driver if driver else StxFaultClientImp()
43         self.uow = uow
44
45     def _get(self, id) -> alarmModel.FaultGenericModel:
46         return self.driver.getAlarmInfo(id)
47
48     def _list(self, **filters) -> List[alarmModel.FaultGenericModel]:
49         newmodels = self.driver.getAlarmList(**filters)
50         uow = self.uow
51         exist_alarms = {}
52         with uow:
53             rs = uow.session.execute(
54                 '''
55                 SELECT "alarmEventRecordId"
56                 FROM "alarmEventRecord"
57                 WHERE "perceivedSeverity" != :perceived_severity_enum
58                 ''',
59                 dict(perceived_severity_enum=alarmModel.PerceivedSeverityEnum.
60                      CLEARED)
61             )
62             for row in rs:
63                 id = row[0]
64                 # logger.debug('Exist alarm: ' + id)
65                 exist_alarms[id] = False
66
67         ret = []
68         for m in newmodels:
69             try:
70                 if exist_alarms[m.id]:
71                     ret.append(m)
72                     exist_alarms[m.id] = True
73             except KeyError:
74                 logger.debug('alarm new: ' + m.id)
75                 ret.append(m)
76
77         for alarm in exist_alarms:
78             logger.debug('exist alarm: ' + alarm)
79             if exist_alarms[alarm]:
80                 # exist alarm is active
81                 continue
82             try:
83                 event = self._get(alarm)
84             except HTTPNotFound:
85                 logger.debug('alarm {} not in this resource pool {}'
86                              .format(alarm, self._pool_id))
87                 continue
88             ret.append(event)
89
90         return ret
91
92     def _set_stx_client(self):
93         self.driver.setFaultClient(self._pool_id)
94
95
96 class StxEventClient(BaseClient):
97     def __init__(self, uow: unit_of_work.AbstractUnitOfWork, driver=None):
98         super().__init__()
99         self.driver = driver if driver else StxFaultClientImp()
100         self.uow = uow
101
102     def _get(self, id) -> alarmModel.FaultGenericModel:
103         return self.driver.getEventInfo(id)
104
105     def _list(self, **filters) -> List[alarmModel.FaultGenericModel]:
106         return self.driver.getEventList(**filters)
107
108     def _set_stx_client(self):
109         self.driver.setFaultClient(self._pool_id)
110
111     def suppression_list(self, alarm_id) -> List[alarmModel.FaultGenericModel]:
112         return self.driver.getSuppressionList(alarm_id)
113
114     def suppress(self, id) -> alarmModel.FaultGenericModel:
115         return self.driver.suppressEvent(id)
116
117
118 # internal driver which implement client call to Stx Fault Management instance
119 class StxFaultClientImp(object):
120     def __init__(self, fm_client=None, stx_client=None, dc_client=None):
121         super().__init__()
122         self.fmclient = fm_client if fm_client else self.getFmClient()
123         self.stxclient = stx_client if stx_client else self.getStxClient()
124         self.dcclient = dc_client if dc_client else self.getDcmanagerClient()
125
126     def getStxClient(self):
127         os_client_args = config.get_stx_access_info()
128         config_client = get_stx_client(**os_client_args)
129         return config_client
130
131     def getDcmanagerClient(self):
132         os_client_args = config.get_dc_access_info()
133         config_client = get_dc_client(**os_client_args)
134         return config_client
135
136     def getFmClient(self):
137         os_client_args = config.get_fm_access_info()
138         config_client = get_fm_client(1, **os_client_args)
139         return config_client
140
141     def getSubcloudList(self):
142         self.dcclient = self.getDcmanagerClient()
143         subs = self.dcclient.subcloud_manager.list_subclouds()
144         known_subs = [sub for sub in subs if sub.sync_status != 'unknown']
145         return known_subs
146
147     def getSubcloudFaultClient(self, subcloud_id):
148         subcloud = self.dcclient.subcloud_manager.\
149             subcloud_additional_details(subcloud_id)
150         logger.debug('subcloud name: %s, oam_floating_ip: %s' %
151                      (subcloud[0].name, subcloud[0].oam_floating_ip))
152         try:
153             sub_is_https = False
154             os_client_args = config.get_stx_access_info(
155                 region_name=subcloud[0].name,
156                 subcloud_hostname=subcloud[0].oam_floating_ip)
157             stx_client = get_stx_client(**os_client_args)
158         except EndpointException as e:
159             msg = e.format_message()
160             if CGTSCLIENT_ENDPOINT_ERROR_MSG in msg:
161                 sub_is_https = True
162                 os_client_args = config.get_stx_access_info(
163                     region_name=subcloud[0].name, sub_is_https=sub_is_https,
164                     subcloud_hostname=subcloud[0].oam_floating_ip)
165                 stx_client = get_stx_client(**os_client_args)
166             else:
167                 raise ValueError('Stx endpoint exception: %s' % msg)
168         except Exception:
169             raise ValueError('cgtsclient get subcloud client failed')
170
171         os_client_args = config.get_fm_access_info(
172             sub_is_https=sub_is_https,
173             subcloud_hostname=subcloud[0].oam_floating_ip)
174         fm_client = get_fm_client(1, **os_client_args)
175
176         return stx_client, fm_client
177
178     def setFaultClient(self, resource_pool_id):
179         systems = self.stxclient.isystem.list()
180         if resource_pool_id == systems[0].uuid:
181             logger.debug('Fault Client not change: %s' % resource_pool_id)
182             self.fmclient = self.getFmClient()
183             return
184
185         subclouds = self.getSubcloudList()
186         for subcloud in subclouds:
187             substxclient, subfaultclient = self.getSubcloudFaultClient(
188                 subcloud.subcloud_id)
189             systems = substxclient.isystem.list()
190             if resource_pool_id == systems[0].uuid:
191                 self.fmclient = subfaultclient
192
193     def getAlarmList(self, **filters) -> List[alarmModel.FaultGenericModel]:
194         alarms = self.fmclient.alarm.list(expand=True)
195         if len(alarms) == 0:
196             return []
197         logger.debug('alarm 1:' + str(alarms[0].to_dict()))
198         # [print('alarm:' + str(alarm.to_dict())) for alarm in alarms if alarm]
199         return [alarmModel.FaultGenericModel(
200             alarmModel.EventTypeEnum.ALARM, self._alarmconverter(alarm))
201             for alarm in alarms if alarm]
202
203     def getAlarmInfo(self, id) -> alarmModel.FaultGenericModel:
204         try:
205             alarm = self.fmclient.alarm.get(id)
206             logger.debug('get alarm id ' + id + ':' + str(alarm.to_dict()))
207         except HTTPNotFound:
208             event = self.fmclient.event_log.get(id)
209             return alarmModel.FaultGenericModel(
210                 alarmModel.EventTypeEnum.ALARM, self._eventconverter(event,
211                                                                      True))
212         return alarmModel.FaultGenericModel(
213             alarmModel.EventTypeEnum.ALARM, self._alarmconverter(alarm))
214
215     def getEventList(self, **filters) -> List[alarmModel.FaultGenericModel]:
216         events = self.fmclient.event_log.list(alarms=True, expand=True)
217         logger.debug('event 1:' + str(events[0].to_dict()))
218         # [print('alarm:' + str(event.to_dict())) for event in events if event]
219         return [alarmModel.FaultGenericModel(
220             alarmModel.EventTypeEnum.EVENT, self._eventconverter(event))
221             for event in events if event]
222
223     def getEventInfo(self, id) -> alarmModel.FaultGenericModel:
224         event = self.fmclient.event_log.get(id)
225         logger.debug('get event id ' + id + ':' + str(event.to_dict()))
226         return alarmModel.FaultGenericModel(
227             alarmModel.EventTypeEnum.EVENT, self._eventconverter(event))
228
229     def suppressEvent(self, id) -> alarmModel.FaultGenericModel:
230         patch = [dict(path='/' + 'suppression_status', value='suppressed',
231                       op='replace')]
232         event = self.fmclient.event_suppression.update(id, patch)
233         logger.debug('suppressed event id ' + id + ':' + str(event.to_dict()))
234         return alarmModel.FaultGenericModel(
235             alarmModel.EventTypeEnum.EVENT, self._suppression_converter(event))
236
237     def getSuppressionList(self, alarm_id) -> alarmModel.FaultGenericModel:
238         suppression_list = []
239         queryAsArray = []
240         events = self.fmclient.event_suppression.list(q=queryAsArray)
241         for event in events:
242             if event.alarm_id == alarm_id:
243                 # logger.debug('suppression event:' + str(event.to_dict()))
244                 suppression_list.append(
245                     alarmModel.FaultGenericModel(
246                         alarmModel.EventTypeEnum.EVENT,
247                         self._suppression_converter(event)))
248         return suppression_list
249
250     @ staticmethod
251     def _alarmconverter(alarm):
252         selected_keys = [
253             'alarm_id', 'alarm_state', 'entity_type_id', 'entity_instance_id',
254             'reason_text', 'alarm_type', 'probable_cause',
255             'proposed_repair_action', 'service_affecting', 'suppression',
256             'suppression_status', 'mgmt_affecting', 'degrade_affecting'
257         ]
258         content = alarm.to_dict()
259         filtered = dict(
260             filter(lambda item: item[0] in selected_keys, content.items()))
261         setattr(alarm, 'filtered', filtered)
262         # setattr(alarm, 'alarm_def_id', uuid.uuid3(
263         #         uuid.NAMESPACE_URL, alarm.alarm_id))
264         setattr(alarm, 'state', alarm.alarm_state)
265
266         setattr(alarm, 'alarm_def_id', str(uuid.uuid3(
267                 uuid.NAMESPACE_URL, alarm.alarm_id)))
268         setattr(alarm, 'probable_cause_id', str(uuid.uuid3(
269                 uuid.NAMESPACE_URL, alarm.probable_cause)))
270         return alarm
271
272     @ staticmethod
273     def _eventconverter(event, clear=False):
274         selected_keys = [
275             'event_log_id', 'state', 'entity_type_id',
276             'entity_instance_id', 'reason_text', 'event_log_type',
277             'probable_cause', 'proposed_repair_action',
278             'service_affecting', 'suppression', 'suppression_status'
279         ]
280         content = event.to_dict()
281         filtered = dict(
282             filter(lambda item: item[0] in selected_keys, content.items()))
283         setattr(event, 'filtered', filtered)
284         setattr(event, 'alarm_id', event.event_log_id)
285         setattr(event, 'alarm_type', event.event_log_type)
286         if clear:
287             logger.debug('alarm is clear')
288             event.state = 'clear'
289         setattr(event, 'alarm_def_id', str(uuid.uuid3(
290                 uuid.NAMESPACE_URL, event.alarm_id)))
291         setattr(event, 'probable_cause_id', str(uuid.uuid3(
292                 uuid.NAMESPACE_URL, event.probable_cause)))
293         return event
294
295     @ staticmethod
296     def _suppression_converter(event, clear=False):
297         selected_keys = [
298             'alarm_id', 'description', 'suppression_status',
299             'links'
300         ]
301         content = event.to_dict()
302         filtered = dict(
303             filter(lambda item: item[0] in selected_keys, content.items()))
304         setattr(event, 'filtered', filtered)
305         setattr(event, 'uuid', event.uuid)
306         setattr(event, 'alarm_id', event.alarm_id)
307         setattr(event, 'description', event.description)
308         setattr(event, 'suppression_status', event.suppression_status)
309         setattr(event, 'alarm_type', None)
310         setattr(event, 'alarm_def_id', None)
311         setattr(event, 'probable_cause_id', None)
312         setattr(event, 'state', None)
313         setattr(event, 'timestamp', None)
314         return event
315
316     @ staticmethod
317     def _alarmeventhasher(event, state=''):
318         # The event model and the alarm model have different parameter name
319         # of the state. alarm model is alarm_state, event model is state.
320         status = event.alarm_state if state == '' else state
321         return str(hash((event.uuid, event.timestamp, status)))