]> arthur.barton.de Git - netdata.git/blob - python.d/redis.chart.py
non-blocking `SocketService` draft 2
[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.statistics', 'line'],
27         'lines': [
28             ['instantaneous_ops_per_sec', 'operations', 'absolute']
29         ]},
30     'hit_rate': {
31         'options': [None, 'Hit rate', 'percent', 'Statistics', 'redis.statistics', '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.replication', '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
71     def _get_data(self):
72         """
73         Get data from socket
74         :return: dict
75         """
76         try:
77             raw = self._get_raw_data().split("\n")
78         except AttributeError:
79             self.error("no data received")
80             return None
81         data = {}
82         for line in raw:
83             if line.startswith(('instantaneous', 'keyspace', 'used_memory', 'connected', 'blocked')):
84                 try:
85                     t = line.split(':')
86                     data[t[0]] = int(t[1])
87                 except (IndexError, ValueError):
88                     pass
89             elif line.startswith('db'):
90                 tmp = line.split(',')[0].replace('keys=', '')
91                 record = tmp.split(':')
92                 data[record[0]] = int(record[1])
93         try:
94             data['hit_rate'] = int((data['keyspace_hits'] / float(data['keyspace_hits'] + data['keyspace_misses'])) * 100)
95         except:
96             data['hit_rate'] = 0
97
98         if len(data) == 0:
99             self.error("received data doesn't have needed records")
100             return None
101         else:
102             return data
103
104     def _check_raw_data(self, data):
105         """
106         Check if all data has been gathered from socket.
107         Parse first line containing message length and check against received message
108         :param data: str
109         :return: boolean
110         """
111         length = len(data)
112         supposed = data.split('\n')[0][1:]
113         offset = len(supposed) + 4  # 1 dollar sing, 1 new line character + 1 ending sequence '\r\n'
114         supposed = int(supposed)
115         if length - offset >= supposed:
116             return True
117         else:
118             return False
119
120         return False
121
122     def check(self):
123         """
124         Parse configuration, check if redis is available, and dynamically create chart lines data
125         :return: boolean
126         """
127         self._parse_config()
128         if self.name == "":
129             self.name = "local"
130             self.chart_name += "_" + self.name
131         data = self._get_data()
132         if data is None:
133             return False
134
135         for name in data:
136             if name.startswith('db'):
137                 self.definitions['keys']['lines'].append([name.decode(), None, 'absolute'])
138
139         return True