Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import argparse
import requests
__version__ = '0.1'
class KubeStatus(object):
def __init__(self, args):
self.args = args
def _get(self, url):
try:
resp = requests.get(url, timeout=int(self.args.timeout))
except requests.exceptions.Timeout:
resp = object()
resp.timeout = True
except requests.exceptions.RequestException:
resp = object()
resp.error = True
finally:
return resp
def get_component_status(self):
metrics = {}
tags = {}
resp = self._get('{0}/api/v1/componentstatuses'.format(self.args.url))
if getattr(resp, 'timeout', False):
metrics['timeout'] = True
elif getattr(resp, 'error', False):
metrics['error'] = True
else:
data = resp.json()
for component in data['items']:
tags['name'] = component['metadata']['name']
metrics['healthy'] = component['conditions'][0]['status']
yield self._influxline('kube_components', metrics, tags)
def get_namespace_status(self):
metrics = {}
tags = {}
resp = self._get('{0}/api/v1/namespaces'.format(self.args.url))
if getattr(resp, 'timeout', False):
metrics['timeout'] = True
elif getattr(resp, 'error', False):
metrics['error'] = True
else:
data = resp.json()
for component in data['items']:
tags['name'] = component['metadata']['name']
metrics['uid'] = component['metadata']['uid']
metrics['status'] = component['status']['phase']
yield self._influxline('kube_namespaces', metrics, tags)
def get_node_status(self):
metrics = {}
tags = {}
resp = self._get('{0}/api/v1/nodes'.format(self.args.url))
if getattr(resp, 'timeout', False):
metrics['timeout'] = True
elif getattr(resp, 'error', False):
metrics['error'] = True
else:
data = resp.json()
for component in data['items']:
tags['name'] = component['metadata']['name']
tags['uid'] = component['metadata']['uid']
tags['zone'] = component['metadata']['labels'].get('zone', None)
metrics['name'] = component['metadata']['name']
metrics['n_cpu'] = component['status']['capacity']['cpu']
metrics['total_memory'] = int(component['status']['capacity']['memory'].strip('Ki')) * 1024
for condition in component['status']['conditions']:
metrics['condition_{0}'.format(condition['type'].lower())] = condition['status']
metrics['condition_{0}_msg'.format(condition['type'].lower())] = condition['message']
yield self._influxline('kube_nodes', metrics, tags)
def get_pod_status(self):
metrics = {}
tags = {}
resp = self._get('{0}/api/v1/pods'.format(self.args.url))
if getattr(resp, 'timeout', False):
metrics['timeout'] = True
elif getattr(resp, 'error', False):
metrics['error'] = True
else:
data = resp.json()
for component in data['items']:
tags['name'] = component['metadata']['name']
tags['namespace'] = component['metadata']['namespace']
metrics['uid'] = component['metadata']['uid']
metrics['phase'] = component['status']['phase']
for condition in component['status']['conditions']:
metrics['condition_{0}'.format(condition['type'].lower())] = condition['status']
for container_status in component['status'].get('containerStatuses', []):
cmetrics = {}
ctags = {}
cmetrics['name'] = container_status['name']
cmetrics['ready'] = container_status['ready']
cmetrics['restartcount'] = container_status['restartCount']
ctags['pod'] = component['metadata']['name']
ctags['name'] = container_status['name']
yield self._influxline('kube_container', cmetrics, ctags)
yield self._influxline('kube_pods', metrics, tags)
def _influxline(self, measurement, metrics, tags):
values = []
mtags = []
for key, value in metrics.iteritems():
if isinstance(value, basestring):
fmt_str = '{0}="{1}"'.format(key, value)
else:
fmt_str = '{0}={1}'.format(key, value)
values.append(fmt_str)
for key, value in tags.iteritems():
fmt_str = '{0}={1}'.format(key, value)
mtags.append(fmt_str)
return "{0},{1} {2}".format(measurement, ','.join(mtags), ','.join(values))
def main():
parser = argparse.ArgumentParser()
parser.add_argument('-v', '--version', action='version', version=__version__)
parser.add_argument('-u', '--url', help='url to query', default='http://localhost:8080')
parser.add_argument('-t', '--timeout', help='timeout in seconds', default=5)
args = parser.parse_args()
kubestatus = KubeStatus(args)
for metric in kubestatus.get_component_status():
print(metric)
for metric in kubestatus.get_node_status():
print(metric)
for metric in kubestatus.get_namespace_status():
print(metric)
for metric in kubestatus.get_pod_status():
print(metric)
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment