+ a_list, name_list, sev_list, res_list = [], [], [], []
+
+ # TODO(mcgoughh): for now resource_id is a mandatory field
+ resource = list_details['resource_uuid']
+
+ # Checking what fields are specified for a list request
+ try:
+ name = list_details['alarm_name'].lower()
+ if name not in ALARM_NAMES.keys():
+ log.warn("This alarm is not supported, won't be used!")
+ name = None
+ except KeyError as exc:
+ log.info("Alarm name isn't specified.")
+ name = None
+
+ try:
+ severity = list_details['severity'].lower()
+ sev = SEVERITIES[severity]
+ except KeyError as exc:
+ log.info("Severity is unspecified/incorrectly configured")
+ sev = None
+
+ # Perform the request to get the desired list
+ try:
+ result = self._common._perform_request(
+ url, auth_token, req_type="get")
+
+ if result is not None:
+ # Get list based on resource id
+ for alarm in json.loads(result.text):
+ rule = alarm['gnocchi_resources_threshold_rule']
+ if resource == rule['resource_id']:
+ res_list.append(str(alarm))
+ if not res_list:
+ log.info("No alarms for this resource")
+ return a_list
+
+ # Generate specified listed if requested
+ if name is not None and sev is not None:
+ log.info("Return a list of %s alarms with %s severity.",
+ name, sev)
+ for alarm in json.loads(result.text):
+ if name == alarm['name']:
+ name_list.append(str(alarm))
+ for alarm in json.loads(result.text):
+ if sev == alarm['severity']:
+ sev_list.append(str(alarm))
+ name_sev_list = list(set(name_list).intersection(sev_list))
+ a_list = list(set(name_sev_list).intersection(res_list))
+ elif name is not None:
+ log.info("Returning a %s list of alarms.", name)
+ for alarm in json.loads(result.text):
+ if name == alarm['name']:
+ name_list.append(str(alarm))
+ a_list = list(set(name_list).intersection(res_list))
+ elif sev is not None:
+ log.info("Returning %s severity alarm list.", sev)
+ for alarm in json.loads(result.text):
+ if sev == alarm['severity']:
+ sev_list.append(str(alarm))
+ a_list = list(set(sev_list).intersection(res_list))
+ else:
+ log.info("Returning an entire list of alarms.")
+ a_list = res_list
+ else:
+ log.info("There are no alarms!")
+
+ except Exception as exc:
+ log.info("Failed to generate required list: %s", exc)
+ return None
+
+ return a_list
+
+ def update_alarm_state(self, endpoint, auth_token, alarm_id):
+ """Set the state of an alarm to ok when ack message is received."""
+ url = "{}/v2/alarms/%s/state".format(endpoint) % alarm_id
+ payload = json.dumps("ok")
+
+ try:
+ self._common._perform_request(
+ url, auth_token, req_type="put", payload=payload)
+ return True
+ except Exception as exc:
+ log.warn("Unable to update alarm state: %s", exc)
+ return False
+
+ def update_alarm(self, endpoint, auth_token, values):
+ """Get alarm name for an alarm configuration update."""
+ # Get already existing alarm details
+ url = "{}/v2/alarms/%s".format(endpoint) % values['alarm_uuid']
+
+ # Gets current configurations about the alarm
+ try:
+ result = self._common._perform_request(
+ url, auth_token, req_type="get")
+ alarm_name = json.loads(result.text)['name']
+ rule = json.loads(result.text)['gnocchi_resources_threshold_rule']
+ alarm_state = json.loads(result.text)['state']
+ resource_id = rule['resource_id']
+ metric_name = rule['metric']
+ except Exception as exc:
+ log.warn("Failed to retreive existing alarm info: %s.\
+ Can only update OSM alarms.", exc)
+ return None, False
+
+ # Generates and check payload configuration for alarm update
+ payload = self.check_payload(values, metric_name, resource_id,
+ alarm_name, alarm_state=alarm_state)
+
+ # Updates the alarm configurations with the valid payload
+ if payload is not None:
+ try:
+ update_alarm = self._common._perform_request(
+ url, auth_token, req_type="put", payload=payload)
+
+ return json.loads(update_alarm.text)['alarm_id'], True
+ except Exception as exc:
+ log.warn("Alarm update could not be performed: %s", exc)
+ return None, False
+ return None, False
+
+ def check_payload(self, values, metric_name, resource_id,
+ alarm_name, alarm_state=None):
+ """Check that the payload is configuration for update/create alarm."""
+ try:
+ # Check state and severity
+ severity = values['severity'].lower()
+ if severity == "indeterminate":
+ alarm_state = "insufficient data"
+ if alarm_state is None:
+ alarm_state = "ok"
+
+ statistic = values['statistic'].lower()
+ # Try to configure the payload for the update/create request
+ # Can only update: threshold, operation, statistic and
+ # the severity of the alarm
+ rule = {'threshold': values['threshold_value'],
+ 'comparison_operator': values['operation'].lower(),
+ 'metric': metric_name,
+ 'resource_id': resource_id,
+ 'resource_type': 'generic',
+ 'aggregation_method': STATISTICS[statistic]}
+ payload = json.dumps({'state': alarm_state,
+ 'name': alarm_name,
+ 'severity': SEVERITIES[severity],
+ 'type': 'gnocchi_resources_threshold',
+ 'gnocchi_resources_threshold_rule': rule, })
+ return payload
+ except KeyError as exc:
+ log.warn("Alarm is not configured correctly: %s", exc)
+ return None
+
+ def authenticate(self):
+ """Generate an authentication token and endpoint for alarm request."""
+ try:
+ # Check for a tenant_id
+ auth_token = self._common._authenticate()
+ endpoint = self._common.get_endpoint("alarming")
+ return auth_token, endpoint
+ except Exception as exc:
+ log.warn("Authentication to Keystone failed:%s", exc)
+ return None, None
+
+ def get_alarm_state(self, endpoint, auth_token, alarm_id):
+ """Get the state of the alarm."""
+ url = "{}/v2/alarms/%s/state".format(endpoint) % alarm_id
+
+ try:
+ alarm_state = self._common._perform_request(
+ url, auth_token, req_type="get")
+ return json.loads(alarm_state.text)
+ except Exception as exc:
+ log.warn("Failed to get the state of the alarm:%s", exc)
+ return None