forked from elastic/rally
-
Notifications
You must be signed in to change notification settings - Fork 0
/
telemetry.py
2591 lines (2166 loc) · 111 KB
/
telemetry.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Licensed to Elasticsearch B.V. under one or more contributor
# license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright
# ownership. Elasticsearch B.V. licenses this file to you under
# the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
import collections
import fnmatch
import logging
import os
import threading
import tabulate
from esrally import exceptions, metrics, time
from esrally.metrics import MetaInfoScope
from esrally.utils import console, io, opts, process, serverless, sysstats, versions
from esrally.utils.versions import Version
def list_telemetry():
console.println("Available telemetry devices:\n")
devices = [
[device.command, device.human_name, device.help]
for device in [
JitCompiler,
Gc,
FlightRecorder,
Heapdump,
NodeStats,
RecoveryStats,
CcrStats,
SegmentStats,
TransformStats,
SearchableSnapshotsStats,
ShardStats,
DataStreamStats,
IngestPipelineStats,
DiskUsageStats,
GeoIpStats,
]
]
console.println(tabulate.tabulate(devices, ["Command", "Name", "Description"]))
console.println("\nKeep in mind that each telemetry device may incur a runtime overhead which can skew results.")
class Telemetry:
def __init__(self, enabled_devices=None, devices=None, serverless_mode=False, serverless_operator=False):
if devices is None:
devices = []
if enabled_devices is None:
enabled_devices = []
self.enabled_devices = enabled_devices
self.devices = devices
self.serverless_mode = serverless_mode
self.serverless_operator = serverless_operator
def instrument_candidate_java_opts(self):
opts = []
for device in self.devices:
if self._enabled(device):
additional_opts = device.instrument_java_opts()
# properly merge values with the same key
opts.extend(additional_opts)
return opts
def on_pre_node_start(self, node_name):
for device in self.devices:
if self._enabled(device):
device.on_pre_node_start(node_name)
def attach_to_node(self, node):
for device in self.devices:
if self._enabled(device):
device.attach_to_node(node)
def detach_from_node(self, node, running):
for device in self.devices:
if self._enabled(device):
device.detach_from_node(node, running)
def on_benchmark_start(self):
for device in self.devices:
if self._enabled(device):
if self.serverless_mode and not self._available_on_serverless(device):
# Only inform about exclusion if the user explicitly asked for this device
if getattr(device, "command", None) in self.enabled_devices:
console.info(f"Excluding telemetry device [{device.command}] as it is unavailable on serverless.")
continue
device.on_benchmark_start()
def on_benchmark_stop(self):
for device in self.devices:
if self._enabled(device):
if self.serverless_mode and not self._available_on_serverless(device):
# Not informing the user the second time, see on_benchmark_start()
continue
device.on_benchmark_stop()
def store_system_metrics(self, node, metrics_store):
for device in self.devices:
if self._enabled(device):
device.store_system_metrics(node, metrics_store)
def _enabled(self, device):
return device.internal or device.command in self.enabled_devices
def _available_on_serverless(self, device):
if self.serverless_operator:
return device.serverless_status >= serverless.Status.Internal
else:
return device.serverless_status == serverless.Status.Public
########################################################################################
#
# Telemetry devices
#
########################################################################################
class TelemetryDevice:
def __init__(self):
self.logger = logging.getLogger(__name__)
def instrument_java_opts(self):
return {}
def on_pre_node_start(self, node_name):
pass
def attach_to_node(self, node):
pass
def detach_from_node(self, node, running):
pass
def on_benchmark_start(self):
pass
def on_benchmark_stop(self):
pass
def store_system_metrics(self, node, metrics_store):
pass
def __getstate__(self):
state = self.__dict__.copy()
del state["logger"]
return state
def __setstate__(self, state):
self.__dict__.update(state)
self.logger = logging.getLogger(__name__)
class InternalTelemetryDevice(TelemetryDevice):
internal = True
class Sampler:
"""This class contains the actual logic of SamplerThread for unit test purposes."""
def __init__(self, recorder, *, sleep=time.sleep):
self.stop = False
self.recorder = recorder
self.sleep = sleep
def finish(self):
self.stop = True
def run(self):
# noinspection PyBroadException
try:
sleep_left = self.recorder.sample_interval
while True:
if sleep_left <= 0:
self.recorder.record()
sleep_left = self.recorder.sample_interval
if self.stop:
break
# check for self.stop at least every second
sleep_seconds = min(sleep_left, 1)
self.sleep(sleep_seconds)
sleep_left -= sleep_seconds
except BaseException:
logging.getLogger(__name__).exception("Could not determine %s", self.recorder)
class SamplerThread(Sampler, threading.Thread):
def __init__(self, recorder):
threading.Thread.__init__(self)
Sampler.__init__(self, recorder)
def finish(self):
super().finish()
self.join()
class FlightRecorder(TelemetryDevice):
internal = False
command = "jfr"
human_name = "Flight Recorder"
help = "Enables Java Flight Recorder (requires an Oracle JDK or OpenJDK 11+)"
def __init__(self, telemetry_params, log_root, java_major_version):
super().__init__()
self.telemetry_params = telemetry_params
self.log_root = log_root
self.java_major_version = java_major_version
def instrument_java_opts(self):
io.ensure_dir(self.log_root)
log_file = os.path.join(self.log_root, "profile.jfr")
# JFR was integrated into OpenJDK 11 and is not a commercial feature anymore.
if self.java_major_version < 11:
console.println("\n***************************************************************************\n")
console.println("[WARNING] Java flight recorder is a commercial feature of the Oracle JDK.\n")
console.println("You are using Java flight recorder which requires that you comply with\nthe licensing terms stated in:\n")
console.println(console.format.link("http://www.oracle.com/technetwork/java/javase/terms/license/index.html"))
console.println("\nBy using this feature you confirm that you comply with these license terms.\n")
console.println('Otherwise, please abort and rerun Rally without the "jfr" telemetry device.')
console.println("\n***************************************************************************\n")
time.sleep(3)
console.info("%s: Writing flight recording to [%s]" % (self.human_name, log_file), logger=self.logger)
java_opts = self.java_opts(log_file)
self.logger.info("jfr: Adding JVM arguments: [%s].", java_opts)
return java_opts
def java_opts(self, log_file):
recording_template = self.telemetry_params.get("recording-template")
delay = self.telemetry_params.get("jfr-delay")
duration = self.telemetry_params.get("jfr-duration")
java_opts = ["-XX:+UnlockDiagnosticVMOptions", "-XX:+DebugNonSafepoints"]
jfr_cmd = ""
if self.java_major_version < 11:
java_opts.append("-XX:+UnlockCommercialFeatures")
if self.java_major_version < 9:
java_opts.append("-XX:+FlightRecorder")
java_opts.append(f"-XX:FlightRecorderOptions=disk=true,maxage=0s,maxsize=0,dumponexit=true,dumponexitpath={log_file}")
jfr_cmd = "-XX:StartFlightRecording=defaultrecording=true"
else:
jfr_cmd += f"-XX:StartFlightRecording=maxsize=0,maxage=0s,disk=true,dumponexit=true,filename={log_file}"
if delay:
self.logger.info("jfr: Using delay [%s].", delay)
jfr_cmd += f",delay={delay}"
if duration:
self.logger.info("jfr: Using duration [%s].", duration)
jfr_cmd += f",duration={duration}"
if recording_template:
self.logger.info("jfr: Using recording template [%s].", recording_template)
jfr_cmd += f",settings={recording_template}"
else:
self.logger.info("jfr: Using default recording template.")
java_opts.append(jfr_cmd)
return java_opts
class JitCompiler(TelemetryDevice):
internal = False
command = "jit"
human_name = "JIT Compiler Profiler"
help = "Enables JIT compiler logs."
def __init__(self, log_root, java_major_version):
super().__init__()
self.log_root = log_root
self.java_major_version = java_major_version
def instrument_java_opts(self):
io.ensure_dir(self.log_root)
log_file = os.path.join(self.log_root, "jit.log")
console.info("%s: Writing JIT compiler log to [%s]" % (self.human_name, log_file), logger=self.logger)
if self.java_major_version < 9:
return [
"-XX:+UnlockDiagnosticVMOptions",
"-XX:+TraceClassLoading",
"-XX:+LogCompilation",
f"-XX:LogFile={log_file}",
"-XX:+PrintAssembly",
]
else:
return [
"-XX:+UnlockDiagnosticVMOptions",
"-Xlog:class+load=info",
"-XX:+LogCompilation",
f"-XX:LogFile={log_file}",
"-XX:+PrintAssembly",
]
class Gc(TelemetryDevice):
internal = False
command = "gc"
human_name = "GC log"
help = "Enables GC logs."
def __init__(self, telemetry_params, log_root, java_major_version):
super().__init__()
self.telemetry_params = telemetry_params
self.log_root = log_root
self.java_major_version = java_major_version
def instrument_java_opts(self):
io.ensure_dir(self.log_root)
log_file = os.path.join(self.log_root, "gc.log")
console.info("%s: Writing GC log to [%s]" % (self.human_name, log_file), logger=self.logger)
return self.java_opts(log_file)
def java_opts(self, log_file):
if self.java_major_version < 9:
return [
f"-Xloggc:{log_file}",
"-XX:+PrintGCDetails",
"-XX:+PrintGCDateStamps",
"-XX:+PrintGCTimeStamps",
"-XX:+PrintGCApplicationStoppedTime",
"-XX:+PrintGCApplicationConcurrentTime",
"-XX:+PrintTenuringDistribution",
]
else:
log_config = self.telemetry_params.get("gc-log-config", "gc*=info,safepoint=info,age*=trace")
# see https://docs.oracle.com/javase/9/tools/java.htm#JSWOR-GUID-BE93ABDC-999C-4CB5-A88B-1994AAAC74D5
return [f"-Xlog:{log_config}:file={log_file}:utctime,uptimemillis,level,tags:filecount=0"]
class Heapdump(TelemetryDevice):
internal = False
command = "heapdump"
human_name = "Heap Dump"
help = "Captures a heap dump."
def __init__(self, log_root):
super().__init__()
self.log_root = log_root
def detach_from_node(self, node, running):
if running:
io.ensure_dir(self.log_root)
heap_dump_file = os.path.join(self.log_root, f"heap_at_exit_{node.pid}.hprof")
console.info(f"{self.human_name}: Writing heap dump to [{heap_dump_file}]", logger=self.logger)
cmd = f"jmap -dump:format=b,file={heap_dump_file} {node.pid}"
if process.run_subprocess_with_logging(cmd):
self.logger.warning("Could not write heap dump to [%s]", heap_dump_file)
class SegmentStats(TelemetryDevice):
internal = False
serverless_status = serverless.Status.Internal
command = "segment-stats"
human_name = "Segment Stats"
help = "Determines segment stats at the end of the benchmark."
def __init__(self, log_root, client):
super().__init__()
self.log_root = log_root
self.client = client
def on_benchmark_stop(self):
# noinspection PyBroadException
try:
segment_stats = self.client.cat.segments(index="_all", v=True)
stats_file = os.path.join(self.log_root, "segment_stats.log")
console.info(f"{self.human_name}: Writing segment stats to [{stats_file}]", logger=self.logger)
with open(stats_file, "w") as f:
f.write(segment_stats)
except BaseException:
self.logger.exception("Could not retrieve segment stats.")
class CcrStats(TelemetryDevice):
internal = False
serverless_status = serverless.Status.Blocked
command = "ccr-stats"
human_name = "CCR Stats"
help = "Regularly samples Cross Cluster Replication (CCR) related stats"
"""
Gathers CCR stats on a cluster level
"""
def __init__(self, telemetry_params, clients, metrics_store):
"""
:param telemetry_params: The configuration object for telemetry_params.
May optionally specify:
``ccr-stats-indices``: JSON string specifying the indices per cluster to publish statistics from.
Not all clusters need to be specified, but any name used must be be present in target.hosts.
Example:
{"ccr-stats-indices": {"cluster_a": ["follower"],"default": ["leader"]}
``ccr-stats-sample-interval``: positive integer controlling the sampling interval. Default: 1 second.
:param clients: A dict of clients to all clusters.
:param metrics_store: The configured metrics store we write to.
"""
super().__init__()
self.telemetry_params = telemetry_params
self.clients = clients
self.sample_interval = telemetry_params.get("ccr-stats-sample-interval", 1)
if self.sample_interval <= 0:
raise exceptions.SystemSetupError(
f"The telemetry parameter 'ccr-stats-sample-interval' must be greater than zero but was {self.sample_interval}."
)
self.specified_cluster_names = self.clients.keys()
self.indices_per_cluster = self.telemetry_params.get("ccr-stats-indices", False)
if self.indices_per_cluster:
for cluster_name in self.indices_per_cluster.keys():
if cluster_name not in clients:
raise exceptions.SystemSetupError(
"The telemetry parameter 'ccr-stats-indices' must be a JSON Object with keys matching "
"the cluster names [{}] specified in --target-hosts "
"but it had [{}].".format(",".join(sorted(clients.keys())), cluster_name)
)
self.specified_cluster_names = self.indices_per_cluster.keys()
self.metrics_store = metrics_store
self.samplers = []
def on_benchmark_start(self):
recorder = []
for cluster_name in self.specified_cluster_names:
recorder = CcrStatsRecorder(
cluster_name,
self.clients[cluster_name],
self.metrics_store,
self.sample_interval,
self.indices_per_cluster[cluster_name] if self.indices_per_cluster else None,
)
sampler = SamplerThread(recorder)
self.samplers.append(sampler)
sampler.daemon = True
# we don't require starting recorders precisely at the same time
sampler.start()
def on_benchmark_stop(self):
if self.samplers:
for sampler in self.samplers:
sampler.finish()
class CcrStatsRecorder:
"""
Collects and pushes CCR stats for the specified cluster to the metric store.
"""
def __init__(self, cluster_name, client, metrics_store, sample_interval, indices=None):
"""
:param cluster_name: The cluster_name that the client connects to, as specified in target.hosts.
:param client: The Elasticsearch client for this cluster.
:param metrics_store: The configured metrics store we write to.
:param sample_interval: integer controlling the interval, in seconds, between collecting samples.
:param indices: optional list of indices to filter results from.
"""
self.cluster_name = cluster_name
self.client = client
self.metrics_store = metrics_store
self.sample_interval = sample_interval
self.indices = indices
self.logger = logging.getLogger(__name__)
def __str__(self):
return "ccr stats"
def record(self):
"""
Collect CCR stats for indexes (optionally) specified in telemetry parameters and push to metrics store.
"""
# ES returns all stats values in bytes or ms via "human: false"
# pylint: disable=import-outside-toplevel
import elasticsearch
try:
ccr_stats_api_endpoint = "/_ccr/stats"
filter_path = "follow_stats"
stats = self.client.perform_request(
method="GET", path=ccr_stats_api_endpoint, params={"human": "false", "filter_path": filter_path}
)
except elasticsearch.TransportError:
msg = "A transport error occurred while collecting CCR stats from the endpoint [{}?filter_path={}] on cluster [{}]".format(
ccr_stats_api_endpoint, filter_path, self.cluster_name
)
self.logger.exception(msg)
raise exceptions.RallyError(msg)
if filter_path in stats and "indices" in stats[filter_path]:
for indices in stats[filter_path]["indices"]:
try:
if self.indices and indices["index"] not in self.indices:
# Skip metrics for indices not part of user supplied whitelist (ccr-stats-indices) in telemetry params.
continue
self.record_stats_per_index(indices["index"], indices["shards"])
except KeyError:
self.logger.warning(
"The 'indices' key in %s does not contain an 'index' or 'shards' key "
"Maybe the output format of the %s endpoint has changed. Skipping.",
ccr_stats_api_endpoint,
ccr_stats_api_endpoint,
)
def record_stats_per_index(self, name, stats):
"""
:param name: The index name.
:param stats: A dict with returned CCR stats for the index.
"""
for shard_stats in stats:
if "shard_id" in shard_stats:
doc = {"name": "ccr-stats", "shard": shard_stats}
shard_metadata = {"cluster": self.cluster_name, "index": name}
self.metrics_store.put_doc(doc, level=MetaInfoScope.cluster, meta_data=shard_metadata)
class RecoveryStats(TelemetryDevice):
internal = False
serverless_status = serverless.Status.Internal
command = "recovery-stats"
human_name = "Recovery Stats"
help = "Regularly samples shard recovery stats"
"""
Gathers recovery stats on a cluster level
"""
def __init__(self, telemetry_params, clients, metrics_store):
"""
:param telemetry_params: The configuration object for telemetry_params.
May optionally specify:
``recovery-stats-indices``: JSON structure specifying the index pattern per cluster to publish stats from.
Not all clusters need to be specified, but any name used must be be present in target.hosts. Alternatively,
the index pattern can be specified as a string can be specified in case only one cluster is involved.
Example:
{"recovery-stats-indices": {"cluster_a": ["follower"],"default": ["leader"]}
``recovery-stats-sample-interval``: positive integer controlling the sampling interval. Default: 1 second.
:param clients: A dict of clients to all clusters.
:param metrics_store: The configured metrics store we write to.
"""
super().__init__()
self.telemetry_params = telemetry_params
self.clients = clients
self.sample_interval = telemetry_params.get("recovery-stats-sample-interval", 1)
if self.sample_interval <= 0:
raise exceptions.SystemSetupError(
"The telemetry parameter 'recovery-stats-sample-interval' must be greater than zero but was {}.".format(
self.sample_interval
)
)
self.specified_cluster_names = self.clients.keys()
indices_per_cluster = self.telemetry_params.get("recovery-stats-indices", False)
# allow the user to specify either an index pattern as string or as a JSON object
if isinstance(indices_per_cluster, str):
self.indices_per_cluster = {opts.TargetHosts.DEFAULT: indices_per_cluster}
else:
self.indices_per_cluster = indices_per_cluster
if self.indices_per_cluster:
for cluster_name in self.indices_per_cluster.keys():
if cluster_name not in clients:
raise exceptions.SystemSetupError(
"The telemetry parameter 'recovery-stats-indices' must be a JSON Object with keys matching "
"the cluster names [{}] specified in --target-hosts "
"but it had [{}].".format(",".join(sorted(clients.keys())), cluster_name)
)
self.specified_cluster_names = self.indices_per_cluster.keys()
self.metrics_store = metrics_store
self.samplers = []
def on_benchmark_start(self):
for cluster_name in self.specified_cluster_names:
recorder = RecoveryStatsRecorder(
cluster_name,
self.clients[cluster_name],
self.metrics_store,
self.sample_interval,
self.indices_per_cluster[cluster_name] if self.indices_per_cluster else "",
)
sampler = SamplerThread(recorder)
self.samplers.append(sampler)
sampler.daemon = True
# we don't require starting recorders precisely at the same time
sampler.start()
def on_benchmark_stop(self):
if self.samplers:
for sampler in self.samplers:
sampler.finish()
class RecoveryStatsRecorder:
"""
Collects and pushes recovery stats for the specified cluster to the metric store.
"""
def __init__(self, cluster_name, client, metrics_store, sample_interval, indices=None):
"""
:param cluster_name: The cluster_name that the client connects to, as specified in target.hosts.
:param client: The Elasticsearch client for this cluster.
:param metrics_store: The configured metrics store we write to.
:param sample_interval: integer controlling the interval, in seconds, between collecting samples.
:param indices: optional list of indices to filter results from.
"""
self.cluster_name = cluster_name
self.client = client
self.metrics_store = metrics_store
self.sample_interval = sample_interval
self.indices = indices
self.logger = logging.getLogger(__name__)
def __str__(self):
return "recovery stats"
def record(self):
"""
Collect recovery stats for indexes (optionally) specified in telemetry parameters and push to metrics store.
"""
# pylint: disable=import-outside-toplevel
import elasticsearch
try:
stats = self.client.indices.recovery(index=self.indices, active_only=True, detailed=False)
except elasticsearch.TransportError:
msg = f"A transport error occurred while collecting recovery stats on cluster [{self.cluster_name}]"
self.logger.exception(msg)
raise exceptions.RallyError(msg)
for idx, idx_stats in stats.items():
for shard in idx_stats["shards"]:
doc = {"name": "recovery-stats", "shard": shard}
shard_metadata = {"cluster": self.cluster_name, "index": idx, "shard": shard["id"]}
self.metrics_store.put_doc(doc, level=MetaInfoScope.cluster, meta_data=shard_metadata)
class ShardStats(TelemetryDevice):
"""
Collects and pushes shard stats for the specified cluster to the metric store.
"""
internal = False
serverless_status = serverless.Status.Internal
command = "shard-stats"
human_name = "Shard Stats"
help = "Regularly samples nodes stats at shard level"
def __init__(self, telemetry_params, clients, metrics_store):
"""
:param telemetry_params: The configuration object for telemetry_params.
May optionally specify:
``shard-stats-sample-interval``: positive integer controlling the sampling interval. Default: 60 seconds.
:param clients: A dict of clients to all clusters.
:param metrics_store: The configured metrics store we write to.
"""
super().__init__()
self.telemetry_params = telemetry_params
self.clients = clients
self.specified_cluster_names = self.clients.keys()
self.sample_interval = telemetry_params.get("shard-stats-sample-interval", 60)
if self.sample_interval <= 0:
raise exceptions.SystemSetupError(
f"The telemetry parameter 'shard-stats-sample-interval' must be greater than zero but was {self.sample_interval}."
)
self.metrics_store = metrics_store
self.samplers = []
def on_benchmark_start(self):
for cluster_name in self.specified_cluster_names:
recorder = ShardStatsRecorder(cluster_name, self.clients[cluster_name], self.metrics_store, self.sample_interval)
sampler = SamplerThread(recorder)
self.samplers.append(sampler)
sampler.daemon = True
# we don't require starting recorders precisely at the same time
sampler.start()
def on_benchmark_stop(self):
if self.samplers:
for sampler in self.samplers:
sampler.finish()
class ShardStatsRecorder:
"""
Collects and pushes shard stats for the specified cluster to the metric store.
"""
def __init__(self, cluster_name, client, metrics_store, sample_interval):
"""
:param cluster_name: The cluster_name that the client connects to, as specified in target.hosts.
:param client: The Elasticsearch client for this cluster.
:param metrics_store: The configured metrics store we write to.
:param sample_interval: integer controlling the interval, in seconds, between collecting samples.
"""
self.cluster_name = cluster_name
self.client = client
self.metrics_store = metrics_store
self.sample_interval = sample_interval
self.logger = logging.getLogger(__name__)
def __str__(self):
return "shard stats"
def record(self):
"""
Collect node-stats?level=shards and push to metrics store.
"""
# pylint: disable=import-outside-toplevel
import elasticsearch
try:
sample = self.client.nodes.stats(metric="_all", level="shards")
except elasticsearch.TransportError:
msg = f"A transport error occurred while collecting shard stats on cluster [{self.cluster_name}]"
self.logger.exception(msg)
raise exceptions.RallyError(msg)
shard_metadata = {"cluster": self.cluster_name}
for node_stats in sample["nodes"].values():
node_name = node_stats["name"]
collected_node_stats = collections.OrderedDict()
collected_node_stats["name"] = "shard-stats"
shard_stats = node_stats["indices"].get("shards")
for index_name, stats in shard_stats.items():
for curr_shard in stats:
for shard_id, curr_stats in curr_shard.items():
doc = {
"name": "shard-stats",
"shard-id": shard_id,
"index": index_name,
"primary": curr_stats.get("routing", {}).get("primary"),
"docs": curr_stats.get("docs", {}).get("count", -1),
"store": curr_stats.get("store", {}).get("size_in_bytes", -1),
"segments-count": curr_stats.get("segments", {}).get("count", -1),
"node": node_name,
}
self.metrics_store.put_doc(doc, level=MetaInfoScope.cluster, meta_data=shard_metadata)
class NodeStats(TelemetryDevice):
"""
Gathers different node stats.
"""
internal = False
serverless_status = serverless.Status.Internal
command = "node-stats"
human_name = "Node Stats"
help = "Regularly samples node stats"
warning = """You have enabled the node-stats telemetry device with Elasticsearch < 7.2.0. Requests to the
_nodes/stats Elasticsearch endpoint trigger additional refreshes and WILL SKEW results.
"""
def __init__(self, telemetry_params, clients, metrics_store):
super().__init__()
self.telemetry_params = telemetry_params
self.clients = clients
self.specified_cluster_names = self.clients.keys()
self.metrics_store = metrics_store
self.samplers = []
def on_benchmark_start(self):
default_client = self.clients["default"]
es_info = default_client.info()
es_version = es_info["version"].get("number", "7.2.0")
if Version.from_string(es_version) < Version(major=7, minor=2, patch=0):
console.warn(NodeStats.warning, logger=self.logger)
for cluster_name in self.specified_cluster_names:
recorder = NodeStatsRecorder(self.telemetry_params, cluster_name, self.clients[cluster_name], self.metrics_store)
sampler = SamplerThread(recorder)
self.samplers.append(sampler)
sampler.daemon = True
# we don't require starting recorders precisely at the same time
sampler.start()
def on_benchmark_stop(self):
if self.samplers:
for sampler in self.samplers:
sampler.finish()
class NodeStatsRecorder:
def __init__(self, telemetry_params, cluster_name, client, metrics_store):
self.logger = logging.getLogger(__name__)
self.logger.info("node stats recorder")
self.sample_interval = telemetry_params.get("node-stats-sample-interval", 1)
if self.sample_interval <= 0:
raise exceptions.SystemSetupError(
f"The telemetry parameter 'node-stats-sample-interval' must be greater than zero but was {self.sample_interval}."
)
self.include_indices = telemetry_params.get("node-stats-include-indices", False)
self.include_indices_metrics = telemetry_params.get("node-stats-include-indices-metrics", False)
if self.include_indices_metrics:
if isinstance(self.include_indices_metrics, str):
self.include_indices_metrics_list = opts.csv_to_list(self.include_indices_metrics)
else:
# we don't validate the allowable metrics as they may change across ES versions
raise exceptions.SystemSetupError(
"The telemetry parameter 'node-stats-include-indices-metrics' must be a comma-separated string but was {}".format(
type(self.include_indices_metrics)
)
)
else:
self.include_indices_metrics_list = [
"docs",
"store",
"indexing",
"search",
"merges",
"refresh",
"flush",
"query_cache",
"fielddata",
"segments",
"translog",
"request_cache",
]
self.include_thread_pools = telemetry_params.get("node-stats-include-thread-pools", True)
self.include_buffer_pools = telemetry_params.get("node-stats-include-buffer-pools", True)
self.include_breakers = telemetry_params.get("node-stats-include-breakers", True)
self.include_network = telemetry_params.get("node-stats-include-network", True)
self.include_process = telemetry_params.get("node-stats-include-process", True)
self.include_mem_stats = telemetry_params.get("node-stats-include-mem", True)
self.include_cgroup_stats = telemetry_params.get("node-stats-include-cgroup", True)
self.include_gc_stats = telemetry_params.get("node-stats-include-gc", True)
self.include_indexing_pressure = telemetry_params.get("node-stats-include-indexing-pressure", True)
self.include_fs_stats = telemetry_params.get("node-stats-include-fs", True)
self.client = client
self.metrics_store = metrics_store
self.cluster_name = cluster_name
def __str__(self):
return "node stats"
def record(self):
current_sample = self.sample()
for node_stats in current_sample:
node_name = node_stats["name"]
roles = node_stats["roles"]
metrics_store_meta_data = {"cluster": self.cluster_name, "node_name": node_name, "roles": roles}
collected_node_stats = collections.OrderedDict()
collected_node_stats["name"] = "node-stats"
if self.include_indices or self.include_indices_metrics:
collected_node_stats.update(self.indices_stats(node_name, node_stats, include=self.include_indices_metrics_list))
if self.include_thread_pools:
collected_node_stats.update(self.thread_pool_stats(node_name, node_stats))
if self.include_breakers:
collected_node_stats.update(self.circuit_breaker_stats(node_name, node_stats))
if self.include_buffer_pools:
collected_node_stats.update(self.jvm_buffer_pool_stats(node_name, node_stats))
if self.include_mem_stats:
collected_node_stats.update(self.jvm_mem_stats(node_name, node_stats))
collected_node_stats.update(self.os_mem_stats(node_name, node_stats))
if self.include_cgroup_stats:
collected_node_stats.update(self.os_cgroup_stats(node_name, node_stats))
if self.include_gc_stats:
collected_node_stats.update(self.jvm_gc_stats(node_name, node_stats))
if self.include_network:
collected_node_stats.update(self.network_stats(node_name, node_stats))
if self.include_process:
collected_node_stats.update(self.process_stats(node_name, node_stats))
if self.include_indexing_pressure:
collected_node_stats.update(self.indexing_pressure(node_name, node_stats))
if self.include_fs_stats:
collected_node_stats.update(self.fs_stats(node_name, node_stats))
self.metrics_store.put_doc(
dict(collected_node_stats), level=MetaInfoScope.node, node_name=node_name, meta_data=metrics_store_meta_data
)
def indices_stats(self, node_name, node_stats, include):
idx_stats = node_stats["indices"]
ordered_results = collections.OrderedDict()
for section in include:
if section in idx_stats:
ordered_results.update(flatten_stats_fields(prefix="indices_" + section, stats=idx_stats[section]))
return ordered_results
def thread_pool_stats(self, node_name, node_stats):
return flatten_stats_fields(prefix="thread_pool", stats=node_stats["thread_pool"])
def circuit_breaker_stats(self, node_name, node_stats):
return flatten_stats_fields(prefix="breakers", stats=node_stats["breakers"])
def jvm_buffer_pool_stats(self, node_name, node_stats):
return flatten_stats_fields(prefix="jvm_buffer_pools", stats=node_stats["jvm"]["buffer_pools"])
def jvm_mem_stats(self, node_name, node_stats):
return flatten_stats_fields(prefix="jvm_mem", stats=node_stats["jvm"]["mem"])
def os_mem_stats(self, node_name, node_stats):
return flatten_stats_fields(prefix="os_mem", stats=node_stats["os"]["mem"])
def os_cgroup_stats(self, node_name, node_stats):
cgroup_stats = {}
try:
cgroup_stats = flatten_stats_fields(prefix="os_cgroup", stats=node_stats["os"]["cgroup"])
except KeyError:
self.logger.debug("Node cgroup stats requested with none present.")
return cgroup_stats
def jvm_gc_stats(self, node_name, node_stats):
return flatten_stats_fields(prefix="jvm_gc", stats=node_stats["jvm"]["gc"])
def network_stats(self, node_name, node_stats):
return flatten_stats_fields(prefix="transport", stats=node_stats.get("transport"))
def process_stats(self, node_name, node_stats):
return flatten_stats_fields(prefix="process_cpu", stats=node_stats["process"]["cpu"])
def indexing_pressure(self, node_name, node_stats):
return flatten_stats_fields(prefix="indexing_pressure", stats=node_stats["indexing_pressure"])
def fs_stats(self, node_name, node_stats):
return flatten_stats_fields(prefix="fs", stats=node_stats.get("fs"))
def sample(self):
# pylint: disable=import-outside-toplevel
import elasticsearch
try:
stats = self.client.nodes.stats(metric="_all")
except elasticsearch.TransportError:
logging.getLogger(__name__).exception("Could not retrieve node stats.")
return {}
return stats["nodes"].values()
class TransformStats(TelemetryDevice):
internal = False
serverless_status = serverless.Status.Public
command = "transform-stats"
human_name = "Transform Stats"
help = "Regularly samples transform stats"
"""
Gathers Transform stats
"""
def __init__(self, telemetry_params, clients, metrics_store):
"""
:param telemetry_params: The configuration object for telemetry_params.
:param clients: A dict of clients to all clusters.
:param metrics_store: The configured metrics store we write to.
"""
super().__init__()
self.telemetry_params = telemetry_params
self.clients = clients
self.sample_interval = telemetry_params.get("transform-stats-sample-interval", 1)
if self.sample_interval <= 0:
raise exceptions.SystemSetupError(
f"The telemetry parameter 'transform-stats-sample-interval' must be greater than zero but was [{self.sample_interval}]."
)
self.specified_cluster_names = self.clients.keys()
self.transforms_per_cluster = self.telemetry_params.get("transform-stats-transforms", False)
if self.transforms_per_cluster:
for cluster_name in self.transforms_per_cluster.keys():
if cluster_name not in clients:
raise exceptions.SystemSetupError(
f"The telemetry parameter 'transform-stats-transforms' must be a JSON Object with keys "
f"matching the cluster names [{','.join(sorted(clients.keys()))}] specified in --target-hosts "
f"but it had [{cluster_name}]."
)
self.specified_cluster_names = self.transforms_per_cluster.keys()