1 # Copyright (C) 2022-2024 Wind River Systems, Inc.
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
7 # http://www.apache.org/licenses/LICENSE-2.0
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.
15 # client talking to Stx standalone
17 from typing import List # Optional, Set
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
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
31 from o2common.helper import o2logging
32 logger = o2logging.get_logger(__name__)
35 CGTSCLIENT_ENDPOINT_ERROR_MSG = \
36 'Must provide Keystone credentials or user-defined endpoint and token'
39 class StxAlarmClient(BaseClient):
40 def __init__(self, uow: unit_of_work.AbstractUnitOfWork, driver=None):
42 self.driver = driver if driver else StxFaultClientImp()
45 def _get(self, id) -> alarmModel.FaultGenericModel:
46 return self.driver.getAlarmInfo(id)
48 def _list(self, **filters) -> List[alarmModel.FaultGenericModel]:
49 newmodels = self.driver.getAlarmList(**filters)
53 rs = uow.session.execute(
55 SELECT "alarmEventRecordId"
56 FROM "alarmEventRecord"
57 WHERE "perceivedSeverity" != :perceived_severity_enum
59 dict(perceived_severity_enum=alarmModel.PerceivedSeverityEnum.
64 # logger.debug('Exist alarm: ' + id)
65 exist_alarms[id] = False
70 if exist_alarms[m.id]:
72 exist_alarms[m.id] = True
74 logger.debug('alarm new: ' + m.id)
77 for alarm in exist_alarms:
78 logger.debug('exist alarm: ' + alarm)
79 if exist_alarms[alarm]:
80 # exist alarm is active
83 event = self._get(alarm)
85 logger.debug('alarm {} not in this resource pool {}'
86 .format(alarm, self._pool_id))
92 def _set_stx_client(self):
93 self.driver.setFaultClient(self._pool_id)
96 class StxEventClient(BaseClient):
97 def __init__(self, uow: unit_of_work.AbstractUnitOfWork, driver=None):
99 self.driver = driver if driver else StxFaultClientImp()
102 def _get(self, id) -> alarmModel.FaultGenericModel:
103 return self.driver.getEventInfo(id)
105 def _list(self, **filters) -> List[alarmModel.FaultGenericModel]:
106 return self.driver.getEventList(**filters)
108 def _set_stx_client(self):
109 self.driver.setFaultClient(self._pool_id)
111 def suppression_list(self, alarm_id) -> List[alarmModel.FaultGenericModel]:
112 return self.driver.getSuppressionList(alarm_id)
114 def suppress(self, id) -> alarmModel.FaultGenericModel:
115 return self.driver.suppressEvent(id)
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):
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()
126 def getStxClient(self):
127 os_client_args = config.get_stx_access_info()
128 config_client = get_stx_client(**os_client_args)
131 def getDcmanagerClient(self):
132 os_client_args = config.get_dc_access_info()
133 config_client = get_dc_client(**os_client_args)
136 def getFmClient(self):
137 os_client_args = config.get_fm_access_info()
138 config_client = get_fm_client(1, **os_client_args)
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']
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))
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:
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)
167 raise ValueError('Stx endpoint exception: %s' % msg)
169 raise ValueError('cgtsclient get subcloud client failed')
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)
176 return stx_client, fm_client
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()
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
193 def getAlarmList(self, **filters) -> List[alarmModel.FaultGenericModel]:
194 alarms = self.fmclient.alarm.list(expand=True)
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]
203 def getAlarmInfo(self, id) -> alarmModel.FaultGenericModel:
205 alarm = self.fmclient.alarm.get(id)
206 logger.debug('get alarm id ' + id + ':' + str(alarm.to_dict()))
208 event = self.fmclient.event_log.get(id)
209 return alarmModel.FaultGenericModel(
210 alarmModel.EventTypeEnum.ALARM, self._eventconverter(event,
212 return alarmModel.FaultGenericModel(
213 alarmModel.EventTypeEnum.ALARM, self._alarmconverter(alarm))
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]
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))
229 def suppressEvent(self, id) -> alarmModel.FaultGenericModel:
230 patch = [dict(path='/' + 'suppression_status', value='suppressed',
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))
237 def getSuppressionList(self, alarm_id) -> alarmModel.FaultGenericModel:
238 suppression_list = []
240 events = self.fmclient.event_suppression.list(q=queryAsArray)
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
251 def _alarmconverter(alarm):
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'
258 content = alarm.to_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)
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)))
273 def _eventconverter(event, clear=False):
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'
280 content = event.to_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)
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)))
296 def _suppression_converter(event, clear=False):
298 'alarm_id', 'description', 'suppression_status',
301 content = event.to_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)
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)))