Skip to content

Commit

Permalink
Merge pull request #34 from jacekszubert/default_metric
Browse files Browse the repository at this point in the history
Push default metric value for failed connection trials
  • Loading branch information
mtakaki committed Mar 12, 2017
2 parents 284ef97 + fd0cca2 commit 8ce89e4
Showing 1 changed file with 10 additions and 3 deletions.
13 changes: 10 additions & 3 deletions cachet_url_monitor/configuration.py
Expand Up @@ -88,6 +88,7 @@ def __init__(self, config_file):
self.api_url = os.environ.get('CACHET_API_URL') or self.data['cachet']['api_url']
self.component_id = os.environ.get('CACHET_COMPONENT_ID') or self.data['cachet']['component_id']
self.metric_id = os.environ.get('CACHET_METRIC_ID') or self.data['cachet'].get('metric_id')
self.default_metric_value = self.get_default_metric_value()

# We need the current status so we monitor the status changes. This is necessary for creating incidents.
self.status = get_current_status(self.api_url, self.component_id, self.headers)
Expand All @@ -100,6 +101,11 @@ def __init__(self, config_file):
for expectation in self.expectations:
self.logger.info('Registered expectation: %s' % (expectation,))

def get_default_metric_value(self):
"""Returns default value for configured metric."""
get_metric_request = requests.get('%s/metrics/%s' % (self.api_url, self.metric_id), headers=self.headers)
return get_metric_request.json()['data']['default_value']

def get_action(self):
"""Retrieves the action list from the configuration. If it's empty, returns an empty list.
:return: The list of actions, which can be an empty list.
Expand Down Expand Up @@ -198,17 +204,18 @@ def push_status(self):
def push_metrics(self):
"""Pushes the total amount of seconds the request took to get a response from the URL.
It only will send a request if the metric id was set in the configuration.
In case of failed connection trial pushes the default metric value.
"""
if 'metric_id' in self.data['cachet'] and hasattr(self, 'request'):
params = {'id': self.metric_id, 'value': self.request.elapsed.total_seconds(),
value = self.default_metric_value if self.status != 1 else self.request.elapsed.total_seconds()
params = {'id': self.metric_id, 'value': value,
'timestamp': self.current_timestamp}
metrics_request = requests.post('%s/metrics/%d/points' % (self.api_url, self.metric_id), params=params,
headers=self.headers)

if metrics_request.ok:
# Successful metrics upload
self.logger.info('Metric uploaded: %.6f seconds' %
(self.request.elapsed.total_seconds(),))
self.logger.info('Metric uploaded: %.6f seconds' % (value,))
else:
self.logger.warning('Metric upload failed with status [%d]' %
(metrics_request.status_code,))
Expand Down

0 comments on commit 8ce89e4

Please sign in to comment.