-
Notifications
You must be signed in to change notification settings - Fork 313
/
driver.py
2487 lines (2147 loc) · 106 KB
/
driver.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 asyncio
import collections
import concurrent.futures
import datetime
import itertools
import logging
import math
import multiprocessing
import queue
import threading
import time
from dataclasses import dataclass
from enum import Enum
from io import BytesIO
from typing import Callable
import thespian.actors
from esrally import (
PROGRAM_NAME,
actor,
client,
config,
exceptions,
metrics,
paths,
telemetry,
track,
)
from esrally.client import delete_api_keys
from esrally.driver import runner, scheduler
from esrally.track import TrackProcessorRegistry, load_track, load_track_plugins
from esrally.utils import console, convert, net
##################################
#
# Messages sent between drivers
#
##################################
class PrepareBenchmark:
"""
Initiates preparation steps for a benchmark. The benchmark should only be started after StartBenchmark is sent.
"""
def __init__(self, config, track):
"""
:param config: Rally internal configuration object.
:param track: The track to use.
"""
self.config = config
self.track = track
class StartBenchmark:
pass
class Bootstrap:
"""
Prompts loading of track code on new actors
"""
def __init__(self, cfg):
self.config = cfg
class PrepareTrack:
"""
Initiates preparation of a track.
"""
def __init__(self, track):
"""
:param track: The track to use.
"""
self.track = track
class TrackPrepared:
pass
class StartTaskLoop:
def __init__(self, track_name, cfg):
self.track_name = track_name
self.cfg = cfg
class DoTask:
def __init__(self, task, cfg):
self.task = task
self.cfg = cfg
@dataclass(frozen=True)
class WorkerTask:
"""
Unit of work that should be completed by the low-level TaskExecutionActor
"""
func: Callable
params: dict
class ReadyForWork:
pass
class WorkerIdle:
pass
class PreparationComplete:
def __init__(self, distribution_flavor, distribution_version, revision):
self.distribution_flavor = distribution_flavor
self.distribution_version = distribution_version
self.revision = revision
class StartWorker:
"""
Starts a worker.
"""
def __init__(self, worker_id, config, track, client_allocations, client_contexts):
"""
:param worker_id: Unique (numeric) id of the worker.
:param config: Rally internal configuration object.
:param track: The track to use.
:param client_allocations: A structure describing which clients need to run which tasks.
:param client_contexts: A dict ``ClientContext`` objects keyed by client ID
"""
self.worker_id = worker_id
self.config = config
self.track = track
self.client_allocations = client_allocations
self.client_contexts = client_contexts
class Drive:
"""
Tells a load generator to drive (either after a join point or initially).
"""
def __init__(self, client_start_timestamp):
self.client_start_timestamp = client_start_timestamp
class CompleteCurrentTask:
"""
Tells a load generator to prematurely complete its current task. This is used to model task dependencies for parallel tasks (i.e. if a
specific task that is marked accordingly in the track finishes, it will also signal termination of all other tasks in the same parallel
element).
"""
class UpdateSamples:
"""
Used to send samples from a load generator node to the master.
"""
def __init__(self, client_id, samples):
self.client_id = client_id
self.samples = samples
class JoinPointReached:
"""
Tells the master that a load generator has reached a join point. Used for coordination across multiple load generators.
"""
def __init__(self, worker_id, task):
self.worker_id = worker_id
# Using perf_counter here is fine even in the distributed case. Although we "leak" this value to other
# machines, we will only ever interpret this value on the same machine (see `Drive` and the implementation
# in `Driver#joinpoint_reached()`).
self.worker_timestamp = time.perf_counter()
self.task = task
class BenchmarkComplete:
"""
Indicates that the benchmark is complete.
"""
def __init__(self, metrics):
self.metrics = metrics
class TaskFinished:
def __init__(self, metrics, next_task_scheduled_in):
self.metrics = metrics
self.next_task_scheduled_in = next_task_scheduled_in
class DriverActor(actor.RallyActor):
RESET_RELATIVE_TIME_MARKER = "reset_relative_time"
WAKEUP_INTERVAL_SECONDS = 1
# post-process request metrics every N seconds and send it to the metrics store
POST_PROCESS_INTERVAL_SECONDS = 30
"""
Coordinates all workers. This is actually only a thin actor wrapper layer around ``Driver`` which does the actual work.
"""
def __init__(self):
super().__init__()
self.start_sender = None
self.coordinator = None
self.status = "init"
self.post_process_timer = 0
self.cluster_details = {}
def receiveMsg_PoisonMessage(self, poisonmsg, sender):
self.logger.error("Main driver received a fatal indication from a load generator (%s). Shutting down.", poisonmsg.details)
self.coordinator.close()
self.send(self.start_sender, actor.BenchmarkFailure("Fatal track or load generator indication", poisonmsg.details))
def receiveMsg_BenchmarkFailure(self, msg, sender):
self.logger.error("Main driver received a fatal exception from a load generator. Shutting down.")
self.coordinator.close()
self.send(self.start_sender, msg)
def receiveMsg_BenchmarkCancelled(self, msg, sender):
self.logger.info("Main driver received a notification that the benchmark has been cancelled.")
self.coordinator.close()
self.send(self.start_sender, msg)
def receiveMsg_ActorExitRequest(self, msg, sender):
self.logger.info("Main driver received ActorExitRequest and will terminate all load generators.")
self.status = "exiting"
def receiveMsg_ChildActorExited(self, msg, sender):
# is it a worker?
if msg.childAddress in self.coordinator.workers:
worker_index = self.coordinator.workers.index(msg.childAddress)
if self.status == "exiting":
self.logger.debug("Worker [%d] has exited.", worker_index)
else:
self.logger.error("Worker [%d] has exited prematurely. Aborting benchmark.", worker_index)
self.send(self.start_sender, actor.BenchmarkFailure(f"Worker [{worker_index}] has exited prematurely."))
else:
self.logger.debug("A track preparator has exited.")
def receiveUnrecognizedMessage(self, msg, sender):
self.logger.debug("Main driver received unknown message [%s] (ignoring).", str(msg))
@actor.no_retry("driver") # pylint: disable=no-value-for-parameter
def receiveMsg_PrepareBenchmark(self, msg, sender):
self.start_sender = sender
self.coordinator = Driver(self, msg.config)
self.coordinator.prepare_benchmark(msg.track)
@actor.no_retry("driver") # pylint: disable=no-value-for-parameter
def receiveMsg_StartBenchmark(self, msg, sender):
self.start_sender = sender
self.coordinator.start_benchmark()
self.wakeupAfter(datetime.timedelta(seconds=DriverActor.WAKEUP_INTERVAL_SECONDS))
@actor.no_retry("driver") # pylint: disable=no-value-for-parameter
def receiveMsg_TrackPrepared(self, msg, sender):
self.transition_when_all_children_responded(
sender, msg, expected_status=None, new_status=None, transition=self._after_track_prepared
)
@actor.no_retry("driver") # pylint: disable=no-value-for-parameter
def receiveMsg_JoinPointReached(self, msg, sender):
self.coordinator.joinpoint_reached(msg.worker_id, msg.worker_timestamp, msg.task)
@actor.no_retry("driver") # pylint: disable=no-value-for-parameter
def receiveMsg_UpdateSamples(self, msg, sender):
self.coordinator.update_samples(msg.samples)
@actor.no_retry("driver") # pylint: disable=no-value-for-parameter
def receiveMsg_WakeupMessage(self, msg, sender):
if msg.payload == DriverActor.RESET_RELATIVE_TIME_MARKER:
self.coordinator.reset_relative_time()
elif not self.coordinator.finished():
self.post_process_timer += DriverActor.WAKEUP_INTERVAL_SECONDS
if self.post_process_timer >= DriverActor.POST_PROCESS_INTERVAL_SECONDS:
self.post_process_timer = 0
self.coordinator.post_process_samples()
self.coordinator.update_progress_message()
self.wakeupAfter(datetime.timedelta(seconds=DriverActor.WAKEUP_INTERVAL_SECONDS))
def create_client(self, host, cfg):
worker = self.createActor(Worker, targetActorRequirements=self._requirements(host))
self.send(worker, Bootstrap(cfg))
return worker
def start_worker(self, driver, worker_id, cfg, track, allocations, client_contexts=None):
self.send(driver, StartWorker(worker_id, cfg, track, allocations, client_contexts))
def drive_at(self, driver, client_start_timestamp):
self.send(driver, Drive(client_start_timestamp))
def complete_current_task(self, driver):
self.send(driver, CompleteCurrentTask())
def on_task_finished(self, metrics, next_task_scheduled_in):
if next_task_scheduled_in > 0:
self.wakeupAfter(datetime.timedelta(seconds=next_task_scheduled_in), payload=DriverActor.RESET_RELATIVE_TIME_MARKER)
else:
self.coordinator.reset_relative_time()
self.send(self.start_sender, TaskFinished(metrics, next_task_scheduled_in))
def _requirements(self, host):
if host == "localhost":
return {"coordinator": True}
else:
return {"ip": host}
def prepare_track(self, hosts, cfg, track):
self.track = track
self.logger.info("Starting prepare track process on hosts [%s]", hosts)
self.children = [self._create_track_preparator(h) for h in hosts]
msg = Bootstrap(cfg)
for child in self.children:
self.send(child, msg)
@actor.no_retry("driver") # pylint: disable=no-value-for-parameter
def receiveMsg_ReadyForWork(self, msg, sender):
msg = PrepareTrack(self.track)
self.send(sender, msg)
def _create_track_preparator(self, host):
return self.createActor(TrackPreparationActor, targetActorRequirements=self._requirements(host))
def _after_track_prepared(self):
cluster_version = self.cluster_details["version"] if self.cluster_details else {}
for child in self.children:
self.send(child, thespian.actors.ActorExitRequest())
self.children = []
self.send(
self.start_sender,
PreparationComplete(
# manually compiled versions don't expose build_flavor but Rally expects a value in telemetry devices
# we should default to trial/basic, but let's default to oss for now to avoid breaking the charts
cluster_version.get("build_flavor", "oss"),
cluster_version.get("number"),
cluster_version.get("build_hash"),
),
)
def on_benchmark_complete(self, metrics):
self.send(self.start_sender, BenchmarkComplete(metrics))
def load_local_config(coordinator_config):
cfg = config.auto_load_local_config(
coordinator_config,
additional_sections=[
# only copy the relevant bits
"track",
"driver",
"client",
# due to distribution version...
"mechanic",
"telemetry",
],
)
# set root path (normally done by the main entry point)
cfg.add(config.Scope.application, "node", "rally.root", paths.rally_root())
return cfg
class TaskExecutionActor(actor.RallyActor):
"""
This class should be used for long-running tasks, as it ensures they do not block the actor's messaging system
"""
def __init__(self):
super().__init__()
self.pool = concurrent.futures.ThreadPoolExecutor(max_workers=1)
self.executor_future = None
self.wakeup_interval = 5
self.parent = None
self.logger = logging.getLogger(__name__)
self.track_name = None
self.cfg = None
@actor.no_retry("task executor") # pylint: disable=no-value-for-parameter
def receiveMsg_StartTaskLoop(self, msg, sender):
self.parent = sender
self.track_name = msg.track_name
self.cfg = load_local_config(msg.cfg)
if self.cfg.opts("track", "test.mode.enabled"):
self.wakeup_interval = 0.5
track.load_track_plugins(self.cfg, self.track_name)
self.send(self.parent, ReadyForWork())
@actor.no_retry("task executor") # pylint: disable=no-value-for-parameter
def receiveMsg_DoTask(self, msg, sender):
# actor can arbitrarily execute code based on these messages. if anyone besides our parent sends a task, ignore
if sender != self.parent:
msg = f"TaskExecutionActor expected message from [{self.parent}] but the received the following from [{sender}]: {vars(msg)}"
raise exceptions.RallyError(msg)
task = msg.task
if self.executor_future is not None:
msg = f"TaskExecutionActor received DoTask message [{vars(msg)}], but was already busy"
raise exceptions.RallyError(msg)
if task is None:
self.send(self.parent, WorkerIdle())
else:
# this is a potentially long-running operation so we offload it a background thread so we don't block
# the actor (e.g. logging works properly as log messages are forwarded timely).
self.executor_future = self.pool.submit(task.func, **task.params)
self.wakeupAfter(datetime.timedelta(seconds=self.wakeup_interval))
@actor.no_retry("task executor") # pylint: disable=no-value-for-parameter
def receiveMsg_WakeupMessage(self, msg, sender):
if self.executor_future is not None and self.executor_future.done():
e = self.executor_future.exception(timeout=0)
if e:
self.logger.exception("Worker failed. Notifying parent...", exc_info=e)
# the exception might be user-defined and not be on the load path of the original sender. Hence, it
# cannot be deserialized on the receiver so we convert it here to a plain string.
self.send(self.parent, actor.BenchmarkFailure("Error in task executor", str(e)))
else:
self.executor_future = None
self.send(self.parent, ReadyForWork())
else:
self.wakeupAfter(datetime.timedelta(seconds=self.wakeup_interval))
def receiveMsg_BenchmarkFailure(self, msg, sender):
# sent by our no_retry infrastructure; forward to master
self.send(self.parent, msg)
class TrackPreparationActor(actor.RallyActor):
class Status(Enum):
INITIALIZING = "initializing"
PROCESSOR_RUNNING = "processor running"
PROCESSOR_COMPLETE = "processor complete"
def __init__(self):
super().__init__()
self.processors = queue.Queue()
self.original_sender = None
self.logger.info("Track Preparator started")
self.status = self.Status.INITIALIZING
self.children = []
self.tasks = []
self.cfg = None
self.data_root_dir = None
self.track = None
def receiveMsg_PoisonMessage(self, poisonmsg, sender):
self.logger.error("Track Preparator received a fatal indication from a load generator (%s). Shutting down.", poisonmsg.details)
self.send(self.original_sender, actor.BenchmarkFailure("Fatal track preparation indication", poisonmsg.details))
@actor.no_retry("track preparator") # pylint: disable=no-value-for-parameter
def receiveMsg_Bootstrap(self, msg, sender):
# load node-specific config to have correct paths available
self.cfg = load_local_config(msg.config)
# this instance of load_track occurs once per host, so install dependencies if necessary
load_track(self.cfg, install_dependencies=False)
self.send(sender, ReadyForWork())
@actor.no_retry("track preparator") # pylint: disable=no-value-for-parameter
def receiveMsg_ActorExitRequest(self, msg, sender):
self.logger.debug("ActorExitRequest received. Forwarding to children")
for child in self.children:
self.send(child, msg)
@actor.no_retry("track preparator") # pylint: disable=no-value-for-parameter
def receiveMsg_BenchmarkFailure(self, msg, sender):
# sent by our generic worker; forward to parent
self.send(self.original_sender, msg)
@actor.no_retry("track preparator") # pylint: disable=no-value-for-parameter
def receiveMsg_PrepareTrack(self, msg, sender):
self.original_sender = sender
self.data_root_dir = self.cfg.opts("benchmarks", "local.dataset.cache")
tpr = TrackProcessorRegistry(self.cfg)
self.track = msg.track
self.logger.info("Preparing track [%s]", self.track.name)
self.logger.info("Reloading track [%s] to ensure plugins are up-to-date.", self.track.name)
# the track might have been loaded on a different machine (the coordinator machine) so we force a track
# update to ensure we use the latest version of plugins.
load_track(self.cfg)
load_track_plugins(self.cfg, self.track.name, register_track_processor=tpr.register_track_processor, force_update=True)
# we expect on_prepare_track can take a long time. seed a queue of tasks and delegate to child workers
self.children = [self._create_task_executor() for _ in range(num_cores(self.cfg))]
for processor in tpr.processors:
self.processors.put(processor)
self._seed_tasks(self.processors.get())
self.send_to_children_and_transition(
self, StartTaskLoop(self.track.name, self.cfg), self.Status.INITIALIZING, self.Status.PROCESSOR_RUNNING
)
def resume(self):
if not self.processors.empty():
self._seed_tasks(self.processors.get())
self.send_to_children_and_transition(
self, StartTaskLoop(self.track.name, self.cfg), self.Status.PROCESSOR_COMPLETE, self.Status.PROCESSOR_RUNNING
)
else:
self.send(self.original_sender, TrackPrepared())
def _seed_tasks(self, processor):
self.tasks = list(WorkerTask(func, params) for func, params in processor.on_prepare_track(self.track, self.data_root_dir))
def _create_task_executor(self):
return self.createActor(TaskExecutionActor)
@actor.no_retry("track preparator") # pylint: disable=no-value-for-parameter
def receiveMsg_ReadyForWork(self, msg, sender):
if self.tasks:
next_task = self.tasks.pop()
else:
next_task = None
new_msg = DoTask(next_task, self.cfg)
self.logger.debug("Track Preparator sending %s to %s", vars(new_msg), sender)
self.send(sender, new_msg)
@actor.no_retry("track preparator") # pylint: disable=no-value-for-parameter
def receiveMsg_WorkerIdle(self, msg, sender):
self.transition_when_all_children_responded(sender, msg, self.Status.PROCESSOR_RUNNING, self.Status.PROCESSOR_COMPLETE, self.resume)
def num_cores(cfg):
return int(cfg.opts("system", "available.cores", mandatory=False, default_value=multiprocessing.cpu_count()))
ApiKey = collections.namedtuple("ApiKey", ["id", "secret"])
@dataclass
class ClientContext:
client_id: int
parent_worker_id: int
api_key: ApiKey = None
class Driver:
def __init__(self, target, config, es_client_factory_class=client.EsClientFactory):
"""
Coordinates all workers. It is technology-agnostic, i.e. it does not know anything about actors. To allow us to hook in an actor,
we provide a ``target`` parameter which will be called whenever some event has occurred. The ``target`` can use this to send
appropriate messages.
:param target: A target that will be notified of important events.
:param config: The current config object.
"""
self.logger = logging.getLogger(__name__)
self.target = target
self.config = config
self.es_client_factory = es_client_factory_class
self.default_sync_es_client = None
self.track = None
self.challenge = None
self.metrics_store = None
self.load_driver_hosts = []
self.workers = []
# which client ids are assigned to which workers?
self.clients_per_worker = {}
self.client_contexts = {}
self.generated_api_key_ids = []
self.progress_reporter = console.progress()
self.progress_counter = 0
self.quiet = False
self.allocations = None
self.raw_samples = []
self.most_recent_sample_per_client = {}
self.sample_post_processor = None
self.number_of_steps = 0
self.currently_completed = 0
self.workers_completed_current_step = {}
self.current_step = -1
self.tasks_per_join_point = None
self.complete_current_task_sent = False
self.telemetry = None
def create_es_clients(self):
all_hosts = self.config.opts("client", "hosts").all_hosts
distribution_version = self.config.opts("mechanic", "distribution.version", mandatory=False)
es = {}
for cluster_name, cluster_hosts in all_hosts.items():
all_client_options = self.config.opts("client", "options").all_client_options
cluster_client_options = dict(all_client_options[cluster_name])
# Use retries to avoid aborts on long living connections for telemetry devices
cluster_client_options["retry_on_timeout"] = True
es[cluster_name] = self.es_client_factory(
cluster_hosts, cluster_client_options, distribution_version=distribution_version
).create()
return es
def prepare_telemetry(self, es, enable, index_names, data_stream_names):
enabled_devices = self.config.opts("telemetry", "devices")
telemetry_params = self.config.opts("telemetry", "params")
log_root = paths.race_root(self.config)
es_default = es["default"]
if enable:
devices = [
telemetry.NodeStats(telemetry_params, es, self.metrics_store),
telemetry.ExternalEnvironmentInfo(es_default, self.metrics_store),
telemetry.ClusterEnvironmentInfo(es_default, self.metrics_store),
telemetry.JvmStatsSummary(es_default, self.metrics_store),
telemetry.IndexStats(es_default, self.metrics_store),
telemetry.MlBucketProcessingTime(es_default, self.metrics_store),
telemetry.MasterNodeStats(telemetry_params, es_default, self.metrics_store),
telemetry.SegmentStats(log_root, es_default),
telemetry.CcrStats(telemetry_params, es, self.metrics_store),
telemetry.RecoveryStats(telemetry_params, es, self.metrics_store),
telemetry.ShardStats(telemetry_params, es, self.metrics_store),
telemetry.TransformStats(telemetry_params, es, self.metrics_store),
telemetry.SearchableSnapshotsStats(telemetry_params, es, self.metrics_store),
telemetry.DataStreamStats(telemetry_params, es, self.metrics_store),
telemetry.IngestPipelineStats(es, self.metrics_store),
telemetry.DiskUsageStats(telemetry_params, es_default, self.metrics_store, index_names, data_stream_names),
]
else:
devices = []
self.telemetry = telemetry.Telemetry(enabled_devices, devices=devices)
def wait_for_rest_api(self, es):
es_default = es["default"]
self.logger.info("Checking if REST API is available.")
if client.wait_for_rest_layer(es_default, max_attempts=40):
self.logger.info("REST API is available.")
else:
self.logger.error("REST API layer is not yet available. Stopping benchmark.")
raise exceptions.SystemSetupError("Elasticsearch REST API layer is not available.")
def retrieve_cluster_info(self, es):
try:
return es["default"].info()
except BaseException:
self.logger.exception("Could not retrieve cluster info on benchmark start")
return None
def create_api_key(self, es, client_id):
self.logger.debug("Creating ES API key for client [%s].", client_id)
try:
api_key = client.create_api_key(es, client_id)
self.logger.debug("ES API key created for client [%s].", client_id)
# Store the API key ID for deletion upon benchmark completion
self.generated_api_key_ids.append(api_key["id"])
return api_key
except Exception as e:
self.logger.error("Unable to create API keys. Stopping benchmark.")
raise exceptions.SystemSetupError(e.message)
def prepare_benchmark(self, t):
self.track = t
self.challenge = select_challenge(self.config, self.track)
self.quiet = self.config.opts("system", "quiet.mode", mandatory=False, default_value=False)
downsample_factor = int(self.config.opts("reporting", "metrics.request.downsample.factor", mandatory=False, default_value=1))
self.metrics_store = metrics.metrics_store(cfg=self.config, track=self.track.name, challenge=self.challenge.name, read_only=False)
self.sample_post_processor = SamplePostprocessor(
self.metrics_store, downsample_factor, self.track.meta_data, self.challenge.meta_data
)
es_clients = self.create_es_clients()
self.default_sync_es_client = es_clients["default"]
skip_rest_api_check = self.config.opts("mechanic", "skip.rest.api.check")
uses_static_responses = self.config.opts("client", "options").uses_static_responses
if skip_rest_api_check:
self.logger.info("Skipping REST API check as requested explicitly.")
elif uses_static_responses:
self.logger.info("Skipping REST API check as static responses are used.")
else:
self.wait_for_rest_api(es_clients)
self.target.cluster_details = self.retrieve_cluster_info(es_clients)
# Avoid issuing any requests to the target cluster when static responses are enabled. The results
# are not useful and attempts to connect to a non-existing cluster just lead to exception traces in logs.
self.prepare_telemetry(
es_clients,
enable=not uses_static_responses,
index_names=self.track.index_names(),
data_stream_names=self.track.data_stream_names(),
)
for host in self.config.opts("driver", "load_driver_hosts"):
host_config = {
# for simplicity we assume that all benchmark machines have the same specs
"cores": num_cores(self.config)
}
if host != "localhost":
host_config["host"] = net.resolve(host)
else:
host_config["host"] = host
self.load_driver_hosts.append(host_config)
self.target.prepare_track([h["host"] for h in self.load_driver_hosts], self.config, self.track)
def start_benchmark(self):
self.logger.info("Benchmark is about to start.")
# ensure relative time starts when the benchmark starts.
self.reset_relative_time()
self.logger.info("Attaching cluster-level telemetry devices.")
self.telemetry.on_benchmark_start()
self.logger.info("Cluster-level telemetry devices are now attached.")
allocator = Allocator(self.challenge.schedule)
self.allocations = allocator.allocations
self.number_of_steps = len(allocator.join_points) - 1
self.tasks_per_join_point = allocator.tasks_per_joinpoint
self.logger.info("Benchmark consists of [%d] steps executed by [%d] clients.", self.number_of_steps, len(self.allocations))
# avoid flooding the log if there are too many clients
if allocator.clients < 128:
self.logger.debug("Allocation matrix:\n%s", "\n".join([str(a) for a in self.allocations]))
create_api_keys = self.config.opts("client", "options").all_client_options["default"].get("create_api_key_per_client", None)
worker_assignments = calculate_worker_assignments(self.load_driver_hosts, allocator.clients)
worker_id = 0
for assignment in worker_assignments:
host = assignment["host"]
for clients in assignment["workers"]:
# don't assign workers without any clients
if len(clients) > 0:
self.logger.debug("Allocating worker [%d] on [%s] with [%d] clients.", worker_id, host, len(clients))
worker = self.target.create_client(host, self.config)
client_allocations = ClientAllocations()
worker_client_contexts = {}
for client_id in clients:
client_allocations.add(client_id, self.allocations[client_id])
self.clients_per_worker[client_id] = worker_id
client_context = ClientContext(client_id=client_id, parent_worker_id=worker_id)
if create_api_keys:
resp = self.create_api_key(self.default_sync_es_client, client_id)
client_context.api_key = ApiKey(id=resp["id"], secret=resp["api_key"])
worker_client_contexts[client_id] = client_context
self.client_contexts[worker_id] = worker_client_contexts
self.target.start_worker(
worker, worker_id, self.config, self.track, client_allocations, client_contexts=worker_client_contexts
)
self.workers.append(worker)
worker_id += 1
self.update_progress_message()
def joinpoint_reached(self, worker_id, worker_local_timestamp, task_allocations):
self.currently_completed += 1
self.workers_completed_current_step[worker_id] = (worker_local_timestamp, time.perf_counter())
self.logger.debug(
"[%d/%d] workers reached join point [%d/%d].",
self.currently_completed,
len(self.workers),
self.current_step + 1,
self.number_of_steps,
)
if self.currently_completed == len(self.workers):
self.logger.info("All workers completed their tasks until join point [%d/%d].", self.current_step + 1, self.number_of_steps)
# we can go on to the next step
self.currently_completed = 0
self.complete_current_task_sent = False
# make a copy and reset early to avoid any race conditions from clients that reach a join point already while we are sending...
workers_curr_step = self.workers_completed_current_step
self.workers_completed_current_step = {}
self.update_progress_message(task_finished=True)
# clear per step
self.most_recent_sample_per_client = {}
self.current_step += 1
self.logger.debug("Postprocessing samples...")
self.post_process_samples()
if self.finished():
self.telemetry.on_benchmark_stop()
self.logger.info("All steps completed.")
# Some metrics store implementations return None because no external representation is required.
# pylint: disable=assignment-from-none
m = self.metrics_store.to_externalizable(clear=True)
self.logger.debug("Closing metrics store...")
self.metrics_store.close()
# immediately clear as we don't need it anymore and it can consume a significant amount of memory
self.metrics_store = None
if self.generated_api_key_ids:
self.logger.debug("Deleting auto-generated client API keys...")
try:
delete_api_keys(self.default_sync_es_client, self.generated_api_key_ids)
except exceptions.RallyError:
console.warn(
"Unable to delete auto-generated API keys. You may need to manually delete them. "
"Please check the logs for details."
)
self.logger.debug("Sending benchmark results...")
self.target.on_benchmark_complete(m)
else:
self.move_to_next_task(workers_curr_step)
else:
self.may_complete_current_task(task_allocations)
def move_to_next_task(self, workers_curr_step):
if self.config.opts("track", "test.mode.enabled"):
# don't wait if test mode is enabled and start the next task immediately.
waiting_period = 0
else:
# start the next task in one second (relative to master's timestamp)
#
# Assumption: We don't have a lot of clock skew between reaching the join point and sending the next task
# (it doesn't matter too much if we're a few ms off).
waiting_period = 1.0
# Some metrics store implementations return None because no external representation is required.
# pylint: disable=assignment-from-none
m = self.metrics_store.to_externalizable(clear=True)
self.target.on_task_finished(m, waiting_period)
# Using a perf_counter here is fine also in the distributed case as we subtract it from `master_received_msg_at` making it
# a relative instead of an absolute value.
start_next_task = time.perf_counter() + waiting_period
for worker_id, worker in enumerate(self.workers):
worker_ended_task_at, master_received_msg_at = workers_curr_step[worker_id]
worker_start_timestamp = worker_ended_task_at + (start_next_task - master_received_msg_at)
self.logger.debug(
"Scheduling next task for worker id [%d] at their timestamp [%f] (master timestamp [%f])",
worker_id,
worker_start_timestamp,
start_next_task,
)
self.target.drive_at(worker, worker_start_timestamp)
def may_complete_current_task(self, task_allocations):
any_joinpoints_completing_parent = [a for a in task_allocations if a.task.any_task_completes_parent]
joinpoints_completing_parent = [a for a in task_allocations if a.task.preceding_task_completes_parent]
# If 'completed-by' is set to 'any', then we *do* want to check for completion by
# any client and *not* wait until the remaining runner has completed. This way the 'parallel' task will exit
# on the completion of _any_ client for any task, i.e. given a contrived track with two tasks to execute inside
# a parallel block:
# * parallel:
# * bulk-1, with clients 8
# * bulk-2, with clients: 8
#
# 1. Both 'bulk-1' and 'bulk-2' execute in parallel
# 2. 'bulk-1' client[0]'s runner is first to complete and reach the next joinpoint successfully
# 3. 'bulk-1' will now cause the parent task to complete and _not_ wait for all 8 clients' runner to complete,
# or for 'bulk-2' at all
#
# The reasoning for the distinction between 'any_joinpoints_completing_parent' & 'joinpoints_completing_parent'
# is to simplify logic, otherwise we'd need to implement some form of state machine involving actor-to-actor
# communication.
if len(any_joinpoints_completing_parent) > 0 and not self.complete_current_task_sent:
self.logger.info(
"Any task before join point [%s] is able to complete the parent structure. Telling all clients to exit immediately.",
any_joinpoints_completing_parent[0].task,
)
self.complete_current_task_sent = True
for worker in self.workers:
self.target.complete_current_task(worker)
# If we have a specific 'completed-by' task specified, then we want to make sure that all clients for that task
# are able to complete their runners as expected before completing the parent
elif len(joinpoints_completing_parent) > 0 and not self.complete_current_task_sent:
# while this list could contain multiple items, it should always be the same task (but multiple
# different clients) so any item is sufficient.
current_join_point = joinpoints_completing_parent[0].task
self.logger.info(
"Tasks before join point [%s] are able to complete the parent structure. Checking "
"if all [%d] clients have finished yet.",
current_join_point,
len(current_join_point.clients_executing_completing_task),
)
pending_client_ids = []
for client_id in current_join_point.clients_executing_completing_task:
# We assume that all clients have finished if their corresponding worker has finished
worker_id = self.clients_per_worker[client_id]
if worker_id not in self.workers_completed_current_step:
pending_client_ids.append(client_id)
# are all clients executing said task already done? if so we need to notify the remaining clients
if len(pending_client_ids) == 0:
# As we are waiting for other clients to finish, we would send this message over and over again.
# Hence we need to memorize whether we have already sent it for the current step.
self.complete_current_task_sent = True
self.logger.info("All affected clients have finished. Notifying all clients to complete their current tasks.")
for worker in self.workers:
self.target.complete_current_task(worker)
else:
if len(pending_client_ids) > 32:
self.logger.info("[%d] clients did not yet finish.", len(pending_client_ids))
else:
self.logger.info("Client id(s) [%s] did not yet finish.", ",".join(map(str, pending_client_ids)))
def reset_relative_time(self):
self.logger.debug("Resetting relative time of request metrics store.")
self.metrics_store.reset_relative_time()
def finished(self):
return self.current_step == self.number_of_steps
def close(self):
self.progress_reporter.finish()
if self.metrics_store and self.metrics_store.opened:
self.metrics_store.close()
def update_samples(self, samples):
if len(samples) > 0:
self.raw_samples += samples
# We need to check all samples, they will be from different clients
for s in samples:
self.most_recent_sample_per_client[s.client_id] = s
def update_progress_message(self, task_finished=False):
if not self.quiet and self.current_step >= 0:
tasks = ",".join([t.name for t in self.tasks_per_join_point[self.current_step]])
if task_finished:
total_progress = 1.0
else:
# we only count clients which actually contribute to progress. If clients are executing tasks eternally in a parallel
# structure, we should not count them. The reason is that progress depends entirely on the client(s) that execute the
# task that is completing the parallel structure.
progress_per_client = [
s.percent_completed for s in self.most_recent_sample_per_client.values() if s.percent_completed is not None
]
num_clients = max(len(progress_per_client), 1)
total_progress = sum(progress_per_client) / num_clients
self.progress_reporter.print("Running %s" % tasks, "[%3d%% done]" % (round(total_progress * 100)))
if task_finished:
self.progress_reporter.finish()
def post_process_samples(self):
# we do *not* do this here to avoid concurrent updates (actors are single-threaded) but rather to make it clear that we use
# only a snapshot and that new data will go to a new sample set.
raw_samples = self.raw_samples
self.raw_samples = []
self.sample_post_processor(raw_samples)
class SamplePostprocessor:
def __init__(self, metrics_store, downsample_factor, track_meta_data, challenge_meta_data):
self.logger = logging.getLogger(__name__)
self.metrics_store = metrics_store
self.track_meta_data = track_meta_data
self.challenge_meta_data = challenge_meta_data
self.throughput_calculator = ThroughputCalculator()
self.downsample_factor = downsample_factor
def __call__(self, raw_samples):
if len(raw_samples) == 0:
return
total_start = time.perf_counter()
start = total_start
final_sample_count = 0
for idx, sample in enumerate(raw_samples):
if idx % self.downsample_factor == 0:
final_sample_count += 1
meta_data = self.merge(
self.track_meta_data,
self.challenge_meta_data,
sample.operation_meta_data,
sample.task.meta_data,
sample.request_meta_data,
)
self.metrics_store.put_value_cluster_level(
name="latency",
value=convert.seconds_to_ms(sample.latency),
unit="ms",
task=sample.task.name,
operation=sample.operation_name,
operation_type=sample.operation_type,
sample_type=sample.sample_type,
absolute_time=sample.absolute_time,
relative_time=sample.relative_time,
meta_data=meta_data,
)
self.metrics_store.put_value_cluster_level(
name="service_time",
value=convert.seconds_to_ms(sample.service_time),
unit="ms",