+ # Check for a specified list
+ try:
+ # Check if the metric_name was specified for the list
+ metric_name = values['metric_name'].lower()
+ if metric_name not in METRIC_MAPPINGS.keys():
+ log.warn("This metric is not supported, won't be listed.")
+ metric_name = None
+ except KeyError as exc:
+ log.info("Metric name is not specified: %s", exc)
+ metric_name = None
+
+ try:
+ resource = values['resource_uuid']
+ except KeyError as exc:
+ log.info("Resource is not specified:%s", exc)
+ resource = None
+
+ try:
+ result = self._common._perform_request(
+ url, auth_token, req_type="get")
+ metrics = json.loads(result.text)
+
+ if metrics is not None:
+ # Format the list response
+ if metric_name is not None and resource is not None:
+ metric_list = self.response_list(
+ metrics, metric_name=metric_name, resource=resource)
+ log.info("Returning an %s resource list for %s metrics",
+ metric_name, resource)
+ elif metric_name is not None:
+ metric_list = self.response_list(
+ metrics, metric_name=metric_name)
+ log.info("Returning a list of %s metrics", metric_name)
+ elif resource is not None:
+ metric_list = self.response_list(
+ metrics, resource=resource)
+ log.info("Return a list of %s resource metrics", resource)
+ else:
+ metric_list = self.response_list(metrics)
+ log.info("Returning a complete list of metrics")
+
+ return metric_list
+ else:
+ log.info("There are no metrics available")
+ return []
+ except Exception as exc:
+ log.warn("Failed to generate any metric list. %s", exc)
+ return None
+
+ def get_metric_id(self, endpoint, auth_token, metric_name, resource_id):
+ """Check if the desired metric already exists for the resource."""
+ url = "{}/v1/resource/generic/%s".format(endpoint) % resource_id
+
+ try:
+ # Try return the metric id if it exists
+ result = self._common._perform_request(
+ url, auth_token, req_type="get")
+ return json.loads(result.text)['metrics'][metric_name]
+ except Exception:
+ log.info("Metric doesn't exist. No metric_id available")
+ return None
+
+ def get_metric_name(self, values):
+ """Check metric name configuration and normalize."""
+ try:
+ # Normalize metric name
+ metric_name = values['metric_name'].lower()
+ return metric_name, METRIC_MAPPINGS[metric_name]
+ except KeyError:
+ log.info("Metric name %s is invalid.", metric_name)
+ return metric_name, None
+
+ def read_metric_data(self, endpoint, auth_token, values):
+ """Collectd metric measures over a specified time period."""
+ timestamps = []
+ data = []
+ try:
+ # Try and collect measures
+ metric_id = values['metric_uuid']
+ collection_unit = values['collection_unit'].upper()
+ collection_period = values['collection_period']
+
+ # Define the start and end time based on configurations
+ stop_time = time.strftime("%Y-%m-%d") + "T" + time.strftime("%X")
+ end_time = int(round(time.time() * 1000))
+ if collection_unit == 'YEAR':
+ diff = PERIOD_MS[collection_unit]
+ else:
+ diff = collection_period * PERIOD_MS[collection_unit]
+ s_time = (end_time - diff) / 1000.0
+ start_time = datetime.datetime.fromtimestamp(s_time).strftime(
+ '%Y-%m-%dT%H:%M:%S.%f')
+ base_url = "{}/v1/metric/%(0)s/measures?start=%(1)s&stop=%(2)s"
+ url = base_url.format(endpoint) % {
+ "0": metric_id, "1": start_time, "2": stop_time}
+
+ # Perform metric data request
+ metric_data = self._common._perform_request(
+ url, auth_token, req_type="get")
+
+ # Generate a list of the requested timestamps and data
+ for r in json.loads(metric_data.text):
+ timestamp = r[0].replace("T", " ")
+ timestamps.append(timestamp)
+ data.append(r[2])
+
+ return timestamps, data
+ except Exception as exc:
+ log.warn("Failed to gather specified measures: %s", exc)
+ return timestamps, data
+
+ def authenticate(self):
+ """Generate an authentication token and endpoint for metric request."""
+ try:
+ # Check for a tenant_id
+ auth_token = self._common._authenticate()
+ endpoint = self._common.get_endpoint("metric")
+ return auth_token, endpoint
+ except Exception as exc:
+ log.warn("Authentication to Keystone failed: %s", exc)
+
+ return None, None
+
+ def response_list(self, metric_list, metric_name=None, resource=None):
+ """Create the appropriate lists for a list response."""
+ resp_list, name_list, res_list = [], [], []
+
+ # Create required lists
+ for row in metric_list:
+ # Only list OSM metrics
+ if row['name'] in METRIC_MAPPINGS.keys():
+ metric = {"metric_name": row['name'],
+ "metric_uuid": row['id'],
+ "metric_unit": row['unit'],
+ "resource_uuid": row['resource_id']}
+ resp_list.append(str(metric))
+ # Generate metric_name specific list
+ if metric_name is not None:
+ if row['name'] == metric_name:
+ metric = {"metric_name": row['name'],
+ "metric_uuid": row['id'],
+ "metric_unit": row['unit'],
+ "resource_uuid": row['resource_id']}
+ name_list.append(str(metric))
+ # Generate resource specific list
+ if resource is not None:
+ if row['resource_id'] == resource:
+ metric = {"metric_name": row['name'],
+ "metric_uuid": row['id'],
+ "metric_unit": row['unit'],
+ "resource_uuid": row['resource_id']}
+ res_list.append(str(metric))
+
+ # Join required lists
+ if metric_name is not None and resource is not None:
+ return list(set(res_list).intersection(name_list))
+ elif metric_name is not None:
+ return name_list
+ elif resource is not None:
+ return list(set(res_list).intersection(resp_list))
+ else:
+ return resp_list