redis.chart.py 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268
  1. # -*- coding: utf-8 -*-
  2. # Description: redis netdata python.d module
  3. # Author: Pawel Krupa (paulfantom)
  4. # Author: Ilya Mashchenko (ilyam8)
  5. # SPDX-License-Identifier: GPL-3.0-or-later
  6. import re
  7. from copy import deepcopy
  8. from bases.FrameworkServices.SocketService import SocketService
  9. REDIS_ORDER = [
  10. 'operations',
  11. 'hit_rate',
  12. 'memory',
  13. 'keys_redis',
  14. 'eviction',
  15. 'net',
  16. 'connections',
  17. 'clients',
  18. 'slaves',
  19. 'persistence',
  20. 'bgsave_now',
  21. 'bgsave_health',
  22. 'uptime',
  23. ]
  24. PIKA_ORDER = [
  25. 'operations',
  26. 'hit_rate',
  27. 'memory',
  28. 'keys_pika',
  29. 'connections',
  30. 'clients',
  31. 'slaves',
  32. 'uptime',
  33. ]
  34. CHARTS = {
  35. 'operations': {
  36. 'options': [None, 'Operations', 'operations/s', 'operations', 'redis.operations', 'line'],
  37. 'lines': [
  38. ['total_commands_processed', 'commands', 'incremental'],
  39. ['instantaneous_ops_per_sec', 'operations', 'absolute']
  40. ]
  41. },
  42. 'hit_rate': {
  43. 'options': [None, 'Hit rate', 'percentage', 'hits', 'redis.hit_rate', 'line'],
  44. 'lines': [
  45. ['hit_rate', 'rate', 'absolute']
  46. ]
  47. },
  48. 'memory': {
  49. 'options': [None, 'Memory utilization', 'KiB', 'memory', 'redis.memory', 'area'],
  50. 'lines': [
  51. ['maxmemory', 'max', 'absolute', 1, 1024],
  52. ['used_memory', 'total', 'absolute', 1, 1024],
  53. ['used_memory_lua', 'lua', 'absolute', 1, 1024]
  54. ]
  55. },
  56. 'net': {
  57. 'options': [None, 'Bandwidth', 'kilobits/s', 'network', 'redis.net', 'area'],
  58. 'lines': [
  59. ['total_net_input_bytes', 'in', 'incremental', 8, 1000],
  60. ['total_net_output_bytes', 'out', 'incremental', -8, 1000]
  61. ]
  62. },
  63. 'keys_redis': {
  64. 'options': [None, 'Keys per Database', 'keys', 'keys', 'redis.keys', 'line'],
  65. 'lines': []
  66. },
  67. 'keys_pika': {
  68. 'options': [None, 'Keys', 'keys', 'keys', 'redis.keys', 'line'],
  69. 'lines': [
  70. ['kv_keys', 'kv', 'absolute'],
  71. ['hash_keys', 'hash', 'absolute'],
  72. ['list_keys', 'list', 'absolute'],
  73. ['zset_keys', 'zset', 'absolute'],
  74. ['set_keys', 'set', 'absolute']
  75. ]
  76. },
  77. 'eviction': {
  78. 'options': [None, 'Evicted Keys', 'keys', 'keys', 'redis.eviction', 'line'],
  79. 'lines': [
  80. ['evicted_keys', 'evicted', 'absolute']
  81. ]
  82. },
  83. 'connections': {
  84. 'options': [None, 'Connections', 'connections/s', 'connections', 'redis.connections', 'line'],
  85. 'lines': [
  86. ['total_connections_received', 'received', 'incremental', 1],
  87. ['rejected_connections', 'rejected', 'incremental', -1]
  88. ]
  89. },
  90. 'clients': {
  91. 'options': [None, 'Clients', 'clients', 'connections', 'redis.clients', 'line'],
  92. 'lines': [
  93. ['connected_clients', 'connected', 'absolute', 1],
  94. ['blocked_clients', 'blocked', 'absolute', -1]
  95. ]
  96. },
  97. 'slaves': {
  98. 'options': [None, 'Slaves', 'slaves', 'replication', 'redis.slaves', 'line'],
  99. 'lines': [
  100. ['connected_slaves', 'connected', 'absolute']
  101. ]
  102. },
  103. 'persistence': {
  104. 'options': [None, 'Persistence Changes Since Last Save', 'changes', 'persistence',
  105. 'redis.rdb_changes', 'line'],
  106. 'lines': [
  107. ['rdb_changes_since_last_save', 'changes', 'absolute']
  108. ]
  109. },
  110. 'bgsave_now': {
  111. 'options': [None, 'Duration of the RDB Save Operation', 'seconds', 'persistence',
  112. 'redis.bgsave_now', 'absolute'],
  113. 'lines': [
  114. ['rdb_bgsave_in_progress', 'rdb save', 'absolute']
  115. ]
  116. },
  117. 'bgsave_health': {
  118. 'options': [None, 'Status of the Last RDB Save Operation', 'status', 'persistence',
  119. 'redis.bgsave_health', 'line'],
  120. 'lines': [
  121. ['rdb_last_bgsave_status', 'rdb save', 'absolute']
  122. ]
  123. },
  124. 'uptime': {
  125. 'options': [None, 'Uptime', 'seconds', 'uptime', 'redis.uptime', 'line'],
  126. 'lines': [
  127. ['uptime_in_seconds', 'uptime', 'absolute']
  128. ]
  129. }
  130. }
  131. def copy_chart(name):
  132. return {name: deepcopy(CHARTS[name])}
  133. RE = re.compile(r'\n([a-z_0-9 ]+):(?:keys=)?([^,\r]+)')
  134. class Service(SocketService):
  135. def __init__(self, configuration=None, name=None):
  136. SocketService.__init__(self, configuration=configuration, name=name)
  137. self.order = list()
  138. self.definitions = dict()
  139. self._keep_alive = True
  140. self.host = self.configuration.get('host', 'localhost')
  141. self.port = self.configuration.get('port', 6379)
  142. self.unix_socket = self.configuration.get('socket')
  143. p = self.configuration.get('pass')
  144. self.auth_request = 'AUTH {0} \r\n'.format(p).encode() if p else None
  145. self.request = 'INFO\r\n'.encode()
  146. self.bgsave_time = 0
  147. self.keyspace_dbs = set()
  148. def do_auth(self):
  149. resp = self._get_raw_data(request=self.auth_request)
  150. if not resp:
  151. return False
  152. if resp.strip() != '+OK':
  153. self.error('invalid password')
  154. return False
  155. return True
  156. def get_raw_and_parse(self):
  157. if self.auth_request and not self.do_auth():
  158. return None
  159. resp = self._get_raw_data()
  160. if not resp:
  161. return None
  162. parsed = RE.findall(resp)
  163. if not parsed:
  164. self.error('response is invalid/empty')
  165. return None
  166. return dict((k.replace(' ', '_'), v) for k, v in parsed)
  167. def get_data(self):
  168. """
  169. Get data from socket
  170. :return: dict
  171. """
  172. data = self.get_raw_and_parse()
  173. if not data:
  174. return None
  175. self.calc_hit_rate(data)
  176. self.calc_redis_keys(data)
  177. self.calc_redis_rdb_save_operations(data)
  178. return data
  179. @staticmethod
  180. def calc_hit_rate(data):
  181. try:
  182. hits = int(data['keyspace_hits'])
  183. misses = int(data['keyspace_misses'])
  184. data['hit_rate'] = hits * 100 / (hits + misses)
  185. except (KeyError, ZeroDivisionError):
  186. data['hit_rate'] = 0
  187. def calc_redis_keys(self, data):
  188. if not data.get('redis_version'):
  189. return
  190. # db0:keys=2,expires=0,avg_ttl=0
  191. new_keyspace_dbs = [k for k in data if k.startswith('db') and k not in self.keyspace_dbs]
  192. for db in new_keyspace_dbs:
  193. self.keyspace_dbs.add(db)
  194. self.charts['keys_redis'].add_dimension([db, None, 'absolute'])
  195. for db in self.keyspace_dbs:
  196. if db not in data:
  197. data[db] = 0
  198. def calc_redis_rdb_save_operations(self, data):
  199. if not (data.get('redis_version') and data.get('rdb_bgsave_in_progress')):
  200. return
  201. if data['rdb_bgsave_in_progress'] != '0':
  202. self.bgsave_time += self.update_every
  203. else:
  204. self.bgsave_time = 0
  205. data['rdb_last_bgsave_status'] = 0 if data['rdb_last_bgsave_status'] == 'ok' else 1
  206. data['rdb_bgsave_in_progress'] = self.bgsave_time
  207. def check(self):
  208. """
  209. Parse configuration, check if redis is available, and dynamically create chart lines data
  210. :return: boolean
  211. """
  212. data = self.get_raw_and_parse()
  213. if not data:
  214. return False
  215. self.order = PIKA_ORDER if data.get('pika_version') else REDIS_ORDER
  216. for n in self.order:
  217. self.definitions.update(copy_chart(n))
  218. return True
  219. def _check_raw_data(self, data):
  220. """
  221. Check if all data has been gathered from socket.
  222. Parse first line containing message length and check against received message
  223. :param data: str
  224. :return: boolean
  225. """
  226. length = len(data)
  227. supposed = data.split('\n')[0][1:-1]
  228. offset = len(supposed) + 4 # 1 dollar sing, 1 new line character + 1 ending sequence '\r\n'
  229. if not supposed.isdigit():
  230. return True
  231. supposed = int(supposed)
  232. if length - offset >= supposed:
  233. self.debug('received full response from redis')
  234. return True
  235. self.debug('waiting more data from redis')
  236. return False