]> arthur.barton.de Git - netdata.git/blob - python.d/redis.chart.py
better debugging and logging for SocketService modules; redis enhancements
[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', 'connections', 'clients', 'slaves', 'persistence']
23
24 CHARTS = {
25     'operations': {
26         'options': [None, 'Operations', 'operations/s', 'operations', 'redis.operations', 'line'],
27         'lines': [
28             ['total_commands_processed', 'commands', 'incremental'],
29             ['instantaneous_ops_per_sec', 'operations', 'absolute']
30         ]},
31     'hit_rate': {
32         'options': [None, 'Hit rate', 'percent', 'hits', 'redis.hit_rate', 'line'],
33         'lines': [
34             ['hit_rate', 'rate', 'absolute']
35         ]},
36     'memory': {
37         'options': [None, 'Memory utilization', 'kilobytes', 'memory', 'redis.memory', 'line'],
38         'lines': [
39             ['used_memory', 'total', 'absolute', 1, 1024],
40             ['used_memory_lua', 'lua', 'absolute', 1, 1024]
41         ]},
42     'keys': {
43         'options': [None, 'Database keys', 'keys', 'keys', 'redis.keys', 'line'],
44         'lines': [
45             # lines are created dynamically in `check()` method
46         ]},
47     'connections': {
48         'options': [None, 'Connections', 'connections/s', 'connections', 'redis.connections', 'line'],
49         'lines': [
50             ['total_connections_received', 'received', 'incremental'],
51             ['rejected_connections', 'rejected', 'incremental']
52         ]},
53     'clients': {
54         'options': [None, 'Clients', 'clients', 'connections', 'redis.clients', 'line'],
55         'lines': [
56             ['connected_clients', 'connected', 'absolute'],
57             ['blocked_clients', 'blocked', 'absolute']
58         ]},
59     'slaves': {
60         'options': [None, 'Slaves', 'slaves', 'replication', 'redis.slaves', 'line'],
61         'lines': [
62             ['connected_slaves', 'connected', 'absolute']
63         ]},
64     'persistence': {
65         'options': [None, 'Changes since last save', 'changes', 'persistence', 'redis.rdb_changes', 'line'],
66         'lines': [
67             ['rdb_changes_since_last_save', 'changes', 'absolute']
68         ]}
69 }
70
71
72 class Service(SocketService):
73     def __init__(self, configuration=None, name=None):
74         SocketService.__init__(self, configuration=configuration, name=name)
75         self.request = "INFO\r\n"
76         self.host = "localhost"
77         self.port = 6379
78         self.unix_socket = None
79         self.order = ORDER
80         self.definitions = CHARTS
81         self._keep_alive = True
82         self.chart_name = ""
83
84     def _get_data(self):
85         """
86         Get data from socket
87         :return: dict
88         """
89         response = self._get_raw_data()
90         if response is None:
91             # error has already been logged
92             return None
93
94         try:
95             parsed = response.split("\n")
96         except AttributeError:
97             self.error("response is invalid/empty")
98             return None
99
100         data = {}
101         for line in parsed:
102             if len(line) < 5 or line[0] == '$' or line[0] == '#':
103                 continue
104
105             if line.startswith('db'):
106                 tmp = line.split(',')[0].replace('keys=', '')
107                 record = tmp.split(':')
108                 data[record[0]] = record[1]
109                 continue
110
111             try:
112                 t = line.split(':')
113                 data[t[0]] = t[1]
114             except (IndexError, ValueError):
115                 self.debug("invalid line received: " + str(line))
116                 pass
117
118         if len(data) == 0:
119             self.error("received data doesn't have any records")
120             return None
121
122         try:
123             data['hit_rate'] = (int(data['keyspace_hits']) * 100) / (int(data['keyspace_hits']) + int(data['keyspace_misses']))
124         except:
125             data['hit_rate'] = 0
126
127         return data
128
129     def _check_raw_data(self, data):
130         """
131         Check if all data has been gathered from socket.
132         Parse first line containing message length and check against received message
133         :param data: str
134         :return: boolean
135         """
136         length = len(data)
137         supposed = data.split('\n')[0][1:]
138         offset = len(supposed) + 4  # 1 dollar sing, 1 new line character + 1 ending sequence '\r\n'
139         supposed = int(supposed)
140
141         if length - offset >= supposed:
142             self.debug("received full response from redis")
143             return True
144
145         self.debug("waiting more data from redis")
146         return False
147
148     def check(self):
149         """
150         Parse configuration, check if redis is available, and dynamically create chart lines data
151         :return: boolean
152         """
153         self._parse_config()
154         if self.name == "":
155             self.name = "local"
156             self.chart_name += "_" + self.name
157         data = self._get_data()
158         if data is None:
159             return False
160
161         for name in data:
162             if name.startswith('db'):
163                 self.definitions['keys']['lines'].append([name, None, 'absolute'])
164
165         return True