| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162 |
- #!/usr/bin/env python
- import errno
- import json
- import os
- from os import path
- import struct
- import gevent.pywsgi
- DATA_DIR = path.expanduser('~/sysvitals_data')
- def application(environ, start_response):
- split = environ['PATH_INFO'][1:].split('/')
- if split[0] == 'v1':
- handler = handlers.get(split[2])
- if handler:
- start_response('200 OK', [('Content-type', 'text/plain')])
- return [handler(split, environ)]
- else:
- print 'no handler for', split
- else:
- print 'split was', split
- formats = {
- 'cpu': 'f',
- 'mem': 'l',
- 'net': 'l',
- 'disk': 'l',
- }
- def datum(split, environ):
- group = int(split[1])
- body = json.load(environ['wsgi.input'])
- client_id = body['client_id']
- group_dir = path.join(DATA_DIR, str(group))
- try:
- os.makedirs(group_dir)
- except OSError as e:
- if e.errno != errno.EEXIST:
- raise
- with open(path.join(group_dir, str(client_id)), 'w') as f:
- for stat_group, stats in body.items():
- if stat_group == 'client_id':
- continue
- format_code = formats[stat_group]
- for stat, data in stats.items():
- key = '%s.%s' % (stat_group, stat)
- write_stat(f, key.encode('utf-8'), format_code, data)
- return '{"status": "ok"}'
- def write_stat(f, key, format_code, data):
- fmt = '%dp 1440%s' % (len(key) + 1, format_code)
- array = [0] * 1440
- array[0] = data
- f.write(struct.pack(fmt, key, *array))
- handlers = {
- 'datum': datum,
- }
- server = gevent.pywsgi.WSGIServer(('0.0.0.0', 8892), application)
- server.serve_forever()
|