-
Notifications
You must be signed in to change notification settings - Fork 12
/
dockercontainer.py
99 lines (88 loc) · 3.43 KB
/
dockercontainer.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
#!/usr/bin/env python
import argparse
import re
import os
import docker
import pdb
import threading
import collections
import diamond.collector
try:
import json
except ImportError:
import simplejson as json
class DockerContainerCollector(diamond.collector.Collector):
def get_default_config_help(self):
config_help = super(DockerContainerCollector, self).get_default_config_help()
config_help.update({
'none': 'no options atm',
})
return config_help
def get_default_config(self):
"""
Returns the default collector settings
"""
config = super(DockerContainerCollector, self).get_default_config()
config.update({
'path': 'containers',
})
return config
def flatten_dict(self,d):
def items():
for key, value in d.items():
if isinstance(value, dict):
for subkey, subvalue in self.flatten_dict(value).items():
yield key + "." + subkey, subvalue
else:
yield key, value
return dict(items())
def collect(self):
def print_metric(cc,name):
data = cc.stats(name)
#self.log.debug(data)
metrics = json.loads(data.next())
#self.log.debug(metrics)
if name.find("/") != -1:
name = name.rsplit('/',1)[1]
#memory metrics
self.memory = self.flatten_dict (metrics['memory_stats'])
#self.log.debug(self.memory)
for key, value in self.memory.items():
if type(value) == int:
metric_name = name+".memory_stats."+key
#self.log.debug(metric_name)
#self.log.debug(value)
self.publish_gauge(metric_name, value)
#cpu metrics
self.cpu = self.flatten_dict (metrics['cpu_stats'])
for key, value in self.cpu.items():
#percpu_usage is a list, we'll deal with it after
if type(value) == int:
metric_name = name+".cpu_stats."+key
self.publish_counter(metric_name, value)
#dealing with percpu_usage
if type(value) == list:
self.length = len(value)
for i in range(self.length):
self.value = value
self.metric_name = name+".cpu_stats."+key+str(i)
self.publish_counter(self.metric_name, self.value[i])
#network metrics
self.network = self.flatten_dict (metrics['networks'])
for key, value in self.network.items():
metric_name = name+".networks."+key
self.publish_counter(metric_name, value)
#blkio metrics
self.blkio = self.flatten_dict (metrics['blkio_stats'])
for key, value in self.blkio.items():
metric_name = name+".blkio_stats."+key
self.publish_counter(metric_name, value)
cc = docker.Client(base_url='unix://var/run/docker.sock', version='auto')
dockernames=[i['Names'] for i in cc.containers()]
threads = []
for dname in dockernames:
t = threading.Thread(target=print_metric, args=(cc,dname[0][1:]))
threads.append(t)
t.start()
for thread in threads:
thread.join()