elasticsearch plugin: initial version added
Ilya committed
Jan 19, 2017 at 15:29 UTC
7ba276c7c913e37740c242cc487dacfd23fb7fe0
1 file changed
+365
python.d/elasticsearch.chart.py
new
+365
@@ -0,0 +1,365 @@
1
+# -*- coding: utf-8 -*-
2
+# Description: elastic search node stats netdata python.d module
3
+# Author: l2isbad
4
+
5
+from base import UrlService
6
+from requests import get
7
+from socket import gethostbyname
8
+try:
9
+ from queue import Queue
10
+except ImportError:
11
+ from Queue import Queue
12
+from threading import Thread
13
+
14
+# default module values (can be overridden per job in `config`)
15
+# update_every = 2
16
+update_every = 5
17
+priority = 60000
18
+retries = 60
19
+
20
+# charts order (can be overridden if you want less charts, or different order)
21
+ORDER = ['search_perf_total', 'search_perf_time', 'search_latency', 'index_perf_total', 'index_perf_time',
22
+ 'index_latency', 'jvm_mem_heap', 'jvm_gc_count', 'jvm_gc_time', 'thread_pool_qr', 'fdata_cache',
23
+ 'fdata_ev_tr', 'cluster_health_nodes', 'cluster_health_shards', 'cluster_stats_nodes',
24
+ 'cluster_stats_query_cache', 'cluster_stats_docs', 'cluster_stats_store', 'cluster_stats_indices_shards']
25
+
26
+CHARTS = {
27
+ 'search_perf_total': {
28
+ 'options': [None, 'Number of queries, fetches', 'queries', 'Search performance', 'es.search_query', 'stacked'],
29
+ 'lines': [
30
+ ['query_total', 'search_total', 'incremental'],
31
+ ["fetch_total", 'fetch_total', 'incremental'],
32
+ ["query_current", 'search_current', 'absolute'],
33
+ ["fetch_current", 'fetch_current', 'absolute']
34
+ ]},
35
+ 'search_perf_time': {
36
+ 'options': [None, 'Time spent on queries, fetches', 'seconds', 'Search performance', 'es.search_time', 'stacked'],
37
+ 'lines': [
38
+ ["query_time_in_millis", 'query', 'incremental', 1, 1000],
39
+ ["fetch_time_in_millis", 'fetch', 'incremental', 1, 1000]
40
+ ]},
41
+ 'search_latency': {
42
+ 'options': [None, 'Query and fetch latency', 'ms', 'Search performance', 'es.search_latency', 'stacked'],
43
+ 'lines': [
44
+ ["query_latency", 'query', 'absolute', 1, 1000],
45
+ ["fetch_latency", 'fetch', 'absolute', 1, 1000]
46
+ ]},
47
+ 'index_perf_total': {
48
+ 'options': [None, 'Number of documents indexed, index refreshes, flushes', 'documents/indexes',
49
+ 'Indexing performance', 'es.index_doc', 'stacked'],
50
+ 'lines': [
51
+ ['indexing_index_total', 'indexed', 'incremental'],
52
+ ["refresh_total", 'refreshes', 'incremental'],
53
+ ["flush_total", 'flushes', 'incremental'],
54
+ ["indexing_index_current", 'indexed_current', 'absolute'],
55
+ ]},
56
+ 'index_perf_time': {
57
+ 'options': [None, 'Time spent on indexing, refreshing, flushing', 'seconds', 'Indexing performance',
58
+ 'es.search_time', 'stacked'],
59
+ 'lines': [
60
+ ['indexing_index_time_in_millis', 'indexing', 'incremental', 1, 1000],
61
+ ['refresh_total_time_in_millis', 'refreshing', 'incremental', 1, 1000],
62
+ ['flush_total_time_in_millis', 'flushing', 'incremental', 1, 1000]
63
+ ]},
64
+ 'index_latency': {
65
+ 'options': [None, 'Indexing and flushing latency', 'ms', 'Indexing performance',
66
+ 'es.index_latency', 'stacked'],
67
+ 'lines': [
68
+ ['indexing_latency', 'indexing', 'absolute', 1, 1000],
69
+ ['flushing_latency', 'flushing', 'absolute', 1, 1000]
70
+ ]},
71
+ 'jvm_mem_heap': {
72
+ 'options': [None, 'JVM heap currently in use/committed', 'percent/MB', 'Memory usage and gc',
73
+ 'es.jvm_heap', 'area'],
74
+ 'lines': [
75
+ ["jvm_heap_percent", 'inuse', 'absolute'],
76
+ ["jvm_heap_commit", 'commit', 'absolute', -1, 1048576]
77
+ ]},
78
+ 'jvm_gc_count': {
79
+ 'options': [None, 'Count of garbage collections', 'counts', 'Memory usage and gc', 'es.gc_count', 'stacked'],
80
+ 'lines': [
81
+ ["young_collection_count", 'young', 'incremental'],
82
+ ["old_collection_count", 'old', 'incremental']
83
+ ]},
84
+ 'jvm_gc_time': {
85
+ 'options': [None, 'Time spent on garbage collections', 'ms', 'Memory usage and gc', 'es.gc_time', 'stacked'],
86
+ 'lines': [
87
+ ["young_collection_time_in_millis", 'young', 'incremental'],
88
+ ["old_collection_time_in_millis", 'old', 'incremental']
89
+ ]},
90
+ 'thread_pool_qr': {
91
+ 'options': [None, 'Number of queued/rejected threads in thread pool', 'threads', 'Queues and rejections',
92
+ 'es.qr', 'stacked'],
93
+ 'lines': [
94
+ ["bulk_queue", 'bulk_queue', 'absolute'],
95
+ ["index_queue", 'index_queue', 'absolute'],
96
+ ["search_queue", 'search_queue', 'absolute'],
97
+ ["merge_queue", 'merge_queue', 'absolute'],
98
+ ["bulk_rejected", 'bulk_rej', 'absolute'],
99
+ ["index_rejected", 'index_rej', 'absolute'],
100
+ ["search_rejected", 'search_rej', 'absolute'],
101
+ ["merge_rejected", 'merge_rej', 'absolute']
102
+ ]},
103
+ 'fdata_cache': {
104
+ 'options': [None, 'Fielddata cache size', 'MB', 'Fielddata cache', 'es.fdata_cache', 'line'],
105
+ 'lines': [
106
+ ["index_fdata_mem", 'mem_size', 'absolute', 1, 1048576]
107
+ ]},
108
+ 'fdata_ev_tr': {
109
+ 'options': [None, 'Fielddata evictions and circuit breaker tripped count', 'number of events',
110
+ 'Fielddata cache', 'es.fdata_ev_tr', 'line'],
111
+ 'lines': [
112
+ ["index_fdata_evic", 'evictions', 'incremental'],
113
+ ["breakers_fdata_trip", 'tripped', 'incremental']
114
+ ]},
115
+ 'cluster_health_nodes': {
116
+ 'options': [None, 'Nodes and tasks statistics', 'units', 'Cluster health API',
117
+ 'es.cluster_health', 'stacked'],
118
+ 'lines': [
119
+ ["health_number_of_nodes", 'nodes', 'absolute'],
120
+ ["health_number_of_data_nodes", 'data_nodes', 'absolute'],
121
+ ["health_number_of_pending_tasks", 'pending_tasks', 'absolute'],
122
+ ["health_number_of_in_flight_fetch", 'inflight_fetch', 'absolute']
123
+ ]},
124
+ 'cluster_health_shards': {
125
+ 'options': [None, 'Shards statistics', 'shards', 'Cluster health API',
126
+ 'es.cluster_health_sharts', 'stacked'],
127
+ 'lines': [
128
+ ["health_active_shards", 'active_shards', 'absolute'],
129
+ ["health_relocating_shards", 'relocating_shards', 'absolute'],
130
+ ["health_unassigned_shards", 'unassigned', 'absolute'],
131
+ ["health_delayed_unassigned_shards", 'delayed_unassigned', 'absolute'],
132
+ ["health_initializing_shards", 'initializing', 'absolute'],
133
+ ["health_active_shards_percent_as_number", 'active_percent', 'absolute']
134
+ ]},
135
+ 'cluster_stats_nodes': {
136
+ 'options': [None, 'Nodes statistics', 'nodes', 'Cluster stats API',
137
+ 'es.cluster_stats_nodes', 'stacked'],
138
+ 'lines': [
139
+ ['count_data_only', 'data_only', 'absolute'],
140
+ ['count_master_data', 'master_data', 'absolute'],
141
+ ['count_total', 'total', 'absolute'],
142
+ ['count_master_only', 'master_only', 'absolute'],
143
+ ['count_client', 'client', 'absolute']
144
+ ]},
145
+ 'cluster_stats_query_cache': {
146
+ 'options': [None, 'Query cache statistics', 'queries', 'Cluster stats API',
147
+ 'es.cluster_stats_query_cache', 'stacked'],
148
+ 'lines': [
149
+ ['query_cache_hit_count', 'hit', 'incremental'],
150
+ ['query_cache_miss_count', 'miss', 'incremental']
151
+ ]},
152
+ 'cluster_stats_docs': {
153
+ 'options': [None, 'Docs statistics', 'count', 'Cluster stats API',
154
+ 'es.cluster_stats_docs', 'line'],
155
+ 'lines': [
156
+ ['docs_count', 'docs', 'absolute']
157
+ ]},
158
+ 'cluster_stats_store': {
159
+ 'options': [None, 'Store statistics', 'MB', 'Cluster stats API',
160
+ 'es.cluster_stats_store', 'line'],
161
+ 'lines': [
162
+ ['store_size_in_bytes', 'size', 'absolute', 1, 1048567]
163
+ ]},
164
+ 'cluster_stats_indices_shards': {
165
+ 'options': [None, 'Inidecs and shards statistics', 'count', 'Cluster stats API',
166
+ 'es.cluster_stats_ind_sha', 'stacked'],
167
+ 'lines': [
168
+ ['indices_count', 'indices', 'absolute'],
169
+ ['shards_total', 'shards', 'absolute']
170
+ ]}
171
+}
172
+
173
+
174
+class Service(UrlService):
175
+ def __init__(self, configuration=None, name=None):
176
+ UrlService.__init__(self, configuration=configuration, name=name)
177
+ self.order = ORDER
178
+ self.definitions = CHARTS
179
+ self.host = self.configuration.get('host')
180
+ self.port = self.configuration.get('port')
181
+ self.user = self.configuration.get('user')
182
+ self.password = self.configuration.get('pass')
183
+ self.latency = dict()
184
+
185
+ def check(self):
186
+ # We can't start if <host> AND <port> not specified
187
+ if not all([self.host, self.port]):
188
+ return False
189
+
190
+ # It as a bad idea to use hostname.
191
+ # Hostname -> ipaddress
192
+ try:
193
+ self.host = gethostbyname(self.host)
194
+ except Exception as e:
195
+ self.error(str(e))
196
+ return False
197
+
198
+ # HTTP Auth? NOT TESTED
199
+ self.auth = self.user and self.password
200
+
201
+ # Create URL for every Elasticsearch API
202
+ url_node_stats = 'http://%s:%s/_nodes/_local/stats' % (self.host, self.port)
203
+ url_cluster_health = 'http://%s:%s/_cluster/health' % (self.host, self.port)
204
+ url_cluster_stats = 'http://%s:%s/_cluster/stats' % (self.host, self.port)
205
+
206
+ # Create list of enabled API calls
207
+ user_choice = [bool(self.configuration.get('node_stats', True)),
208
+ bool(self.configuration.get('cluster_health', True)),
209
+ bool(self.configuration.get('cluster_stats', True))]
210
+
211
+ avail_methods = [(self._get_node_stats, url_node_stats),
212
+ (self._get_cluster_health, url_cluster_health),
213
+ (self._get_cluster_stats, url_cluster_stats)]
214
+
215
+ # Remove disabled API calls from 'avail methods'
216
+ self.methods = [choice[0] for choice in list(zip(avail_methods, user_choice)) if choice[1]]
217
+
218
+ # Run _get_data for ALL active API calls.
219
+ api_result = {}
220
+ for method in self.methods:
221
+ api_result[method[1]] = (bool(self._get_raw_data(method[1])))
222
+
223
+ # We can start ONLY if all active API calls returned NOT None
224
+ if not all(api_result.values()):
225
+ self.error('Plugin could not get data from all APIs')
226
+ self.error('%s' % api_result)
227
+ return False
228
+ else:
229
+ self.info('%s' % api_result)
230
+ self.info('Plugin was started successfully')
231
+
232
+ return True
233
+
234
+ def _get_raw_data(self, url):
235
+ try:
236
+ if not self.auth:
237
+ raw_data = get(url)
238
+ else:
239
+ raw_data = get(url, auth=(self.user, self.password))
240
+ except Exception:
241
+ return None
242
+
243
+ return raw_data
244
+
245
+ def _get_data(self):
246
+ threads = list()
247
+ queue = Queue()
248
+ result = dict()
249
+
250
+ for method in self.methods:
251
+ th = Thread(target=method[0], args=(queue, method[1]))
252
+ th.start()
253
+ threads.append(th)
254
+
255
+ for thread in threads:
256
+ thread.join()
257
+ result.update(queue.get())
258
+
259
+ if result:
260
+ return result
261
+ else:
262
+ return None
263
+
264
+ def _get_cluster_health(self, queue, url):
265
+ """
266
+ Format data received from http request
267
+ :return: dict
268
+ """
269
+
270
+ data = self._get_raw_data(url)
271
+
272
+ if not data:
273
+ queue.put({})
274
+ else:
275
+ data = data.json()
276
+
277
+ to_netdata = dict()
278
+ to_netdata.update(update_key('health', data))
279
+
280
+ queue.put(to_netdata)
281
+
282
+ def _get_cluster_stats(self, queue, url):
283
+ """
284
+ Format data received from http request
285
+ :return: dict
286
+ """
287
+
288
+ data = self._get_raw_data(url)
289
+
290
+ if not data:
291
+ queue.put({})
292
+ else:
293
+ data = data.json()
294
+
295
+ to_netdata = dict()
296
+ to_netdata.update(update_key('count', data['nodes']['count']))
297
+ to_netdata.update(update_key('query_cache', data['indices']['query_cache']))
298
+ to_netdata.update(update_key('docs', data['indices']['docs']))
299
+ to_netdata.update(update_key('store', data['indices']['store']))
300
+ to_netdata['indices_count'] = data['indices']['count']
301
+ to_netdata['shards_total'] = data['indices']['shards']['total']
302
+
303
+ queue.put(to_netdata)
304
+
305
+ def _get_node_stats(self, queue, url):
306
+ """
307
+ Format data received from http request
308
+ :return: dict
309
+ """
310
+
311
+ data = self._get_raw_data(url)
312
+
313
+ if not data:
314
+ queue.put({})
315
+ else:
316
+ data = data.json()
317
+ node = list(data['nodes'].keys())[0]
318
+ to_netdata = dict()
319
+ # Search performance metrics
320
+ to_netdata.update(data['nodes'][node]['indices']['search'])
321
+ to_netdata['query_latency'] = self.find_avg(to_netdata['query_total'],
322
+ to_netdata['query_time_in_millis'], 'query_latency')
323
+ to_netdata['fetch_latency'] = self.find_avg(to_netdata['fetch_total'],
324
+ to_netdata['fetch_time_in_millis'], 'fetch_latency')
325
+
326
+ # Indexing performance metrics
327
+ for key in ['indexing', 'refresh', 'flush']:
328
+ to_netdata.update(update_key(key, data['nodes'][node]['indices'].get(key, {})))
329
+ to_netdata['indexing_latency'] = self.find_avg(to_netdata['indexing_index_total'],
330
+ to_netdata['indexing_index_time_in_millis'], 'index_latency')
331
+ to_netdata['flushing_latency'] = self.find_avg(to_netdata['flush_total'],
332
+ to_netdata['flush_total_time_in_millis'], 'flush_latency')
333
+ # Memory usage and garbage collection
334
+ to_netdata.update(update_key('young', data['nodes'][node]['jvm']['gc']['collectors']['young']))
335
+ to_netdata.update(update_key('old', data['nodes'][node]['jvm']['gc']['collectors']['old']))
336
+ to_netdata['jvm_heap_percent'] = data['nodes'][node]['jvm']['mem']['heap_used_percent']
337
+ to_netdata['jvm_heap_commit'] = data['nodes'][node]['jvm']['mem']['heap_committed_in_bytes']
338
+
339
+ # Thread pool queues and rejections
340
+ for key in ['bulk', 'index', 'search', 'merge']:
341
+ to_netdata.update(update_key(key, data['nodes'][node]['thread_pool'].get(key, {})))
342
+
343
+ # Fielddata cache
344
+ to_netdata['index_fdata_mem'] = data['nodes'][node]['indices']['fielddata']['memory_size_in_bytes']
345
+ to_netdata['index_fdata_evic'] = data['nodes'][node]['indices']['fielddata']['evictions']
346
+ to_netdata['breakers_fdata_trip'] = data['nodes'][node]['breakers']['fielddata']['tripped']
347
+
348
+ queue.put(to_netdata)
349
+
350
+ def find_avg(self, value1, value2, key):
351
+ if key not in self.latency.keys():
352
+ self.latency.update({key: [value1, value2]})
353
+ return 0
354
+ else:
355
+ if not self.latency[key][0] == value1:
356
+ latency = round(float(value2 - self.latency[key][1]) / float(value1 - self.latency[key][0]) * 1000)
357
+ self.latency.update({key: [value1, value2]})
358
+ return latency
359
+ else:
360
+ self.latency.update({key: [value1, value2]})
361
+ return 0
362
+
363
+
364
+def update_key(string, dictionary):
365
+ return {'_'.join([string, k]): v for k, v in dictionary.items()}