]> arthur.barton.de Git - netdata.git/blob - python.d/redis.chart.py
fixed context for python.d charts
[netdata.git] / python.d / redis.chart.py
1 # -*- coding: utf-8 -*-
2 # Description: redis netdata python.d module
3 # Author: Pawel Krupa (paulfantom)
4
5 from base import SocketService
6
7 # default module values (can be overridden per job in `config`)
8 #update_every = 2
9 priority = 60000
10 retries = 60
11
12 # default job configuration (overridden by python.d.plugin)
13 # config = {'local': {
14 #             'update_every': update_every,
15 #             'retries': retries,
16 #             'priority': priority,
17 #             'host': 'localhost',
18 #             'port': 6379,
19 #             'unix_socket': None
20 #          }}
21
22 ORDER = ['operations', 'hit_rate', 'memory', 'keys', 'clients', 'slaves']
23
24 CHARTS = {
25     'operations': {
26         'options': [None, 'Operations', 'operations/s', 'Statistics', 'redis.operations', 'line'],
27         'lines': [
28             ['instantaneous_ops_per_sec', 'operations', 'absolute']
29         ]},
30     'hit_rate': {
31         'options': [None, 'Hit rate', 'percent', 'Statistics', 'redis.hit_rate', 'line'],
32         'lines': [
33             ['hit_rate', 'rate', 'absolute']
34         ]},
35     'memory': {
36         'options': [None, 'Memory utilization', 'kilobytes', 'Memory', 'redis.memory', 'line'],
37         'lines': [
38             ['used_memory', 'total', 'absolute', 1, 1024],
39             ['used_memory_lua', 'lua', 'absolute', 1, 1024]
40         ]},
41     'keys': {
42         'options': [None, 'Database keys', 'keys', 'Keys', 'redis.keys', 'line'],
43         'lines': [
44             # lines are created dynamically in `check()` method
45         ]},
46     'clients': {
47         'options': [None, 'Clients', 'clients', 'Clients', 'redis.clients', 'line'],
48         'lines': [
49             ['connected_clients', 'connected', 'absolute'],
50             ['blocked_clients', 'blocked', 'absolute']
51         ]},
52     'slaves': {
53         'options': [None, 'Slaves', 'slaves', 'Replication', 'redis.slaves', 'line'],
54         'lines': [
55             ['connected_slaves', 'connected', 'absolute']
56         ]}
57 }
58
59
60 class Service(SocketService):
61     def __init__(self, configuration=None, name=None):
62         SocketService.__init__(self, configuration=configuration, name=name)
63         self.request = "INFO\r\n"
64         self.host = "localhost"
65         self.port = 6379
66         self.unix_socket = None
67         self.order = ORDER
68         self.definitions = CHARTS
69         self._keep_alive = True
70         self.chart_name = ""
71
72     def _get_data(self):
73         """
74         Get data from socket
75         :return: dict
76         """
77         try:
78             raw = self._get_raw_data().split("\n")
79         except AttributeError:
80             self.error("no data received")
81             return None
82         data = {}
83         for line in raw:
84             if line.startswith(('instantaneous', 'keyspace', 'used_memory', 'connected', 'blocked')):
85                 try:
86                     t = line.split(':')
87                     data[t[0]] = int(t[1])
88                 except (IndexError, ValueError):
89                     pass
90             elif line.startswith('db'):
91                 tmp = line.split(',')[0].replace('keys=', '')
92                 record = tmp.split(':')
93                 data[record[0]] = int(record[1])
94         try:
95             data['hit_rate'] = int((data['keyspace_hits'] / float(data['keyspace_hits'] + data['keyspace_misses'])) * 100)
96         except:
97             data['hit_rate'] = 0
98
99         if len(data) == 0:
100             self.error("received data doesn't have needed records")
101             return None
102         else:
103             return data
104
105     def _check_raw_data(self, data):
106         """
107         Check if all data has been gathered from socket.
108         Parse first line containing message length and check against received message
109         :param data: str
110         :return: boolean
111         """
112         length = len(data)
113         supposed = data.split('\n')[0][1:]
114         offset = len(supposed) + 4  # 1 dollar sing, 1 new line character + 1 ending sequence '\r\n'
115         supposed = int(supposed)
116         if length - offset >= supposed:
117             return True
118         else:
119             return False
120
121         return False
122
123     def check(self):
124         """
125         Parse configuration, check if redis is available, and dynamically create chart lines data
126         :return: boolean
127         """
128         self._parse_config()
129         if self.name == "":
130             self.name = "local"
131             self.chart_name += "_" + self.name
132         data = self._get_data()
133         if data is None:
134             return False
135
136         for name in data:
137             if name.startswith('db'):
138                 self.definitions['keys']['lines'].append([name, None, 'absolute'])
139
140         return True