Skip to content

Instantly share code, notes, and snippets.

@stanaka
Created December 20, 2015 13:27
Show Gist options
  • Save stanaka/00d20c3f3d5d66bd375c to your computer and use it in GitHub Desktop.
Save stanaka/00d20c3f3d5d66bd375c to your computer and use it in GitHub Desktop.
Regression analysis with Mackerel
# -*- coding: utf-8 -*-
import requests
import time
import json
from StringIO import StringIO
import re
import sys
import os
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import logging
logging.basicConfig()
logger = logging.getLogger(__name__)
logger.setLevel(level=logging.DEBUG)
MACKEREL_APIKEY = os.environ.get("MACKEREL_APIKEY")
BASEURL="https://mackerel.io"
HOSTNAME="testserver"
epoch_time = int(time.time())
duration = 60 * 60 * 24
def fetch_hosts():
headers = {'X-Api-Key': MACKEREL_APIKEY}
payload = {'name': HOSTNAME}
r = requests.get(BASEURL+"/api/v0/hosts", headers=headers, params=payload)
hosts = json.load(StringIO(r.content))
return hosts['hosts']
def fetch_metrics(hostid, name, time_from, time_to):
payload = {'name': name, 'from': time_from, 'to': time_to}
headers = {'X-Api-Key': MACKEREL_APIKEY}
r = requests.get(BASEURL+"/api/v0/hosts/"+hostid+"/metrics", params=payload, headers=headers)
metrics = json.load(StringIO(r.content))
if metrics.has_key('metrics'):
return metrics['metrics']
else:
return []
def import_df(metrics):
# {u'metrics': [{u'value': 6.85, u'time': 1450575540}, {u'value': 7.03, u'time': 1450575600}]}
times = []
values = []
for metric in metrics:
times.append(metric['time'] - (epoch_time - duration))
values.append(metric['value'])
df = pd.DataFrame({'time': times, 'value': values})
plt.plot(times, values, 'bo')
model = pd.ols(y=df['value'], x=df['time'], intercept=True)
print model
plt.plot(model.x['x'], model.y_fitted, 'g-')
plt.show()
return model
def prepare_targets():
dat = {}
hosts = fetch_hosts()
for host in hosts:
if not dat.has_key(host['name']):
dat[host['name']] = {'id': host['id']}
meta = host['meta']
if meta.has_key('filesystem'):
dat[host['name']]['filesystem'] = meta['filesystem'].keys()
return dat
def process_targets(dat):
for hostname in dat.keys():
logger.info('fetching %s', hostname)
record = {'hostname': hostname, 'fs': [], 'nearest': sys.maxint}
if not dat[hostname].has_key('filesystem'):
continue
for fs in dat[hostname]['filesystem']:
(fs, count) = re.subn(r"^/dev/", "", fs)
if count == 0:
continue
metric_name = "filesystem." + fs + ".used"
metrics = fetch_metrics(dat[hostname]['id'], metric_name, epoch_time, epoch_time - duration)
if len(metrics) == 0:
logger.info("skip the fs: %s" % (metric_name))
continue
import_df(metrics)
if __name__ == "__main__":
dat = prepare_targets()
res = process_targets(dat)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment