Skip to content

Instantly share code, notes, and snippets.

@yottatsa
Last active October 6, 2016 14:07
Show Gist options
  • Save yottatsa/0450a18fc059b35c10945e59f6331016 to your computer and use it in GitHub Desktop.
Save yottatsa/0450a18fc059b35c10945e59f6331016 to your computer and use it in GitHub Desktop.
import requests
import logging
import os.path
class Graphite(object):
def __init__(self, url):
self.url = url
self.session = requests.Session()
def json(self, targets, f='-24hours', t='now'):
params = {}
params['from'] = f
params['to'] = t
params['target'] = targets
params['format'] = 'json'
response = self.session.get(self.url, params=params)
return response.json()
def availability(client, line, bucket='15min', period='-24hours'):
"""
Calculate service avaiability based on non-zero value of line
:param client: Graphite client
:param line: Line name
:param bucket: Bucket to aggregate data
:param period: Time-slot to query-data
:return: List of tuples with values and timestamps
"""
targets = []
signal = 'hitcount(transformNull(removeAboveValue(transformNull({}, 0), 0), 1), "{}")'.format(line, bucket)
all = 'hitcount(transformNull(removeAboveValue(transformNull({}, 1), 0), 1), "{}")'.format(line, bucket)
response = client.json(['divideSeries({},{})'.format(signal, all)], period)
if response:
return response[0]['datapoints']
if __name__ == '__main__':
logging.basicConfig(level=logging.DEBUG)
client = Graphite('http://graphite-server.iot.tcpcloud.eu/render/')
# artifical function with positive values and nulls
line = 'removeBelowValue(offset(movingAverage(support_prd.graphite-stg-mtr01_iot_tcpcloud_eu.carbon.agents.graphite-stg-mtr01-a.cpuUsage,50),-0.2),0)'
print availability(client, line, bucket='24hours', period='-24hours')
# [[0.33194444444444443, 1475676060]]
print availability(client, line)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment