-
Notifications
You must be signed in to change notification settings - Fork 4
/
simulator.py
2040 lines (1866 loc) · 86.4 KB
/
simulator.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
import heapq
import logging
import os
import sys
from enum import Enum
from functools import total_ordering
from operator import attrgetter, itemgetter
from typing import Mapping, Optional, Sequence
import absl # noqa: F401
from data import BaseWorkloadLoader
from schedulers import BaseScheduler
from utils import EventTime, setup_csv_logging, setup_logging
from workers import WorkerPools
from workload import (
Placement,
Placements,
Resource,
Task,
TaskGraph,
TaskState,
Workload,
)
@total_ordering
class EventType(Enum):
"""Represents the different Events that a simulator has to simulate."""
SIMULATOR_START = 0 # Signify the start of the simulator loop.
TASK_CANCEL = 1 # Ask the simulator to cancel the task.
EVICT_PROFILE = 2 # Ask the simulator to evict the profile from the WorkerPool.
TASK_FINISHED = 3 # Notify the simulator of the end of a task.
TASK_GRAPH_RELEASE = 4 # Notify the simulator of the release of a task graph.
TASK_RELEASE = 5 # Ask the simulator to release the task.
UPDATE_WORKLOAD = 6 # Ask the simulator to update the workload.
TASK_PREEMPT = 7 # Ask the simulator to preempt a task.
TASK_MIGRATION = 8 # Ask the simulator to migrate a task.
LOAD_PROFILE = 9 # Ask the simulator to load a profile into the WorkerPool.
TASK_PLACEMENT = 10 # Ask the simulator to place a task.
SCHEDULER_START = 11 # Requires the simulator to invoke the scheduler.
SCHEDULER_FINISHED = 12 # Signifies the end of the scheduler loop.
SIMULATOR_END = 13 # Signify the end of the simulator loop.
LOG_UTILIZATION = 14 # Ask the simulator to log worker pool utilization.
def __lt__(self, other) -> bool:
# This method is used to order events in the event queue. We prioritize
# events that first free resources.
return self.value < other.value
def __eq__(self, other) -> bool:
return self.value == other.value
class Event(object):
"""Represents an `Event` that is managed by the `EventQueue` and informs
what action the simulator needs to do at the given simulator time.
Args:
event_type (`EventType`): The type of the event.
time (`EventTime`): The simulator time at which the event occurred.
task (`Optional[Task]`): The task associated with this event if it is
of type `TASK_RELEASE` or `TASK_FINISHED`.
task_graph (`Optional[str]`): The name of the TaskGraph associated with
this event.
Raises:
`ValueError` if the event is of type `TASK_RELEASE` or `TASK_FINISHED`
and no associated task is provided, or if the time is not of type `EventTime`.
"""
def __init__(
self,
event_type: EventType,
time: EventTime,
task: Optional[Task] = None,
task_graph: Optional[str] = None,
placement: Optional[Placement] = None,
):
if event_type in [
EventType.TASK_CANCEL,
EventType.TASK_RELEASE,
EventType.TASK_PLACEMENT,
EventType.TASK_PREEMPT,
EventType.TASK_MIGRATION,
EventType.TASK_FINISHED,
]:
if task is None:
raise ValueError(f"No task provided with {event_type}.")
if event_type in [EventType.TASK_PLACEMENT, EventType.TASK_MIGRATION]:
if placement is None:
raise ValueError(f"No placement provided with {event_type}.")
elif type(placement) != Placement:
raise ValueError(f"Invalid type for placement: {type(placement)}.")
if event_type == EventType.TASK_GRAPH_RELEASE and task_graph is None:
raise ValueError(f"No task graph provided with {event_type}.")
if type(time) != EventTime:
raise ValueError(f"Invalid type for time: {type(time)}")
self._event_type = event_type
self._time = time
self._task = task
self._task_graph = (
task.task_graph if task is not None and task_graph is None else task_graph
)
self._placement = placement
def __lt__(self, other: "Event") -> bool:
if self.time == other.time:
if (
self.event_type == other.event_type
and self.task is not None
and other.task is not None
):
return self.task.unique_name < other.task.unique_name
return self.event_type < other.event_type
return self.time < other.time
def __str__(self):
if self.task is None:
return f"Event(time={self.time}, type={self.event_type})"
else:
return f"Event(time={self.time}, type={self.event_type}, task={self.task})"
def __repr__(self):
return str(self)
@property
def time(self) -> EventTime:
return self._time
@property
def event_type(self) -> EventType:
return self._event_type
@property
def task(self) -> Optional[Task]:
return self._task
@property
def task_graph(self) -> Optional[str]:
return self._task_graph
@property
def placement(self) -> Optional[Placement]:
return self._placement
class EventQueue(object):
"""An `EventQueue` provides an abstraction that is used by the simulator
to add the events into, and retrieve events from according to their
release time.
"""
def __init__(self):
self._event_queue = []
def add_event(self, event: Event):
"""Add the given event to the queue.
Args:
event (`Event`): The event to be added to the queue.
"""
heapq.heappush(self._event_queue, event)
def remove_event(self, event: Event):
"""Removes the event from the queue.
Args:
event (`Event`): The event to be removed from the queue.
Raises:
`ValueError` if the event was not found.
"""
self._event_queue.remove(event)
self.reheapify()
def next(self) -> Event:
"""Retrieve the next event from the queue.
Returns:
The next event in the queue ordered according to the release time.
"""
return heapq.heappop(self._event_queue)
def peek(self) -> Optional[Event]:
"""Peek at the next event in the queue without popping it.
Returns:
The next event in the queue ordered according to the release time.
"""
if len(self._event_queue) == 0:
return None
return self._event_queue[0]
def get_next_event_of_type(self, event_type: EventType) -> Optional[Event]:
"""Retrieve the next event of the given type from the queue.
Note that this method iterates over the entire queue, and can be slow.
Args:
event_type (`EventType`): The type of the event to retrieve.
Returns:
The next event of the given type in the queue ordered according to the
release time.
"""
filtered_values = list(
filter(lambda event: event.event_type == event_type, self._event_queue)
)
return min(filtered_values) if len(filtered_values) > 0 else None
def reheapify(self):
"""Reheapify the current queue.
This method should be used if any in-place changes have been made to
the events already inserted into the queue.
"""
heapq.heapify(self._event_queue)
def __len__(self) -> int:
return len(self._event_queue)
class Simulator(object):
"""A `Simulator` simulates the execution of the different tasks in the
system.
It starts with a list of tasks generated by the sources at a fixed
frequency, schedules them using the given instance of the Scheduler,
ensures their execution on the given set of WorkerPools.
Args:
worker_pools (`WorkerPools`): A `WorkerPools` instance describing
the worker pools available for the simulator to execute the tasks on.
scheduler (`Type[BaseScheduler]`): A scheduler that implements the
`BaseScheduler` interface, and is used by the simulator to schedule
the set of available tasks at a regular interval.
loop_timeout (`EventTime`) [default=sys.maxsize]: The simulator time (in us)
upto which to run the loop. The default runs until we have exhausted all
the events in the system.
scheduler_frequency (`EventTime`) [default=-1]: The time (in us) between two
subsequent scheduler invocations. The default invokes a new run of
the scheduler just after the previous one has completed.
_flags (`absl.flags`): The flags used to initialize the app, if any.
"""
def __init__(
self,
worker_pools: WorkerPools,
scheduler: BaseScheduler,
workload_loader: BaseWorkloadLoader,
loop_timeout: EventTime = EventTime(time=sys.maxsize, unit=EventTime.Unit.US),
scheduler_frequency: EventTime = EventTime(time=-1, unit=EventTime.Unit.US),
_flags: Optional["absl.flags"] = None,
):
if not isinstance(scheduler, BaseScheduler):
raise ValueError("Scheduler must implement the BaseScheduler interface.")
if not isinstance(workload_loader, BaseWorkloadLoader):
raise ValueError(
"WorkloadLoader must implement the BaseWorkloadLoader interface."
)
if type(loop_timeout) != EventTime:
raise ValueError(f"Unexpected type of loop_timeout: {type(loop_timeout)}")
if type(scheduler_frequency) != EventTime:
raise ValueError(
f"Unexpected type of scheduler_frequency: {type(scheduler_frequency)}"
)
# Set up the logger.
# Amended from https://tinyurl.com/da5jfm58
def event_representation_filter(record):
if record.args:
args = []
for arg in record.args:
if isinstance(arg, Event):
arg = repr(arg)
else:
arg = str(arg)
args.append(arg)
record.args = tuple(args)
return True
if _flags:
self._logger = setup_logging(
name=self.__class__.__name__,
log_dir=_flags.log_dir,
log_file=_flags.log_file_name,
log_level=_flags.log_level,
)
self._csv_logger = setup_csv_logging(
name=self.__class__.__name__,
log_dir=_flags.log_dir,
log_file=_flags.csv_file_name,
)
self._log_dir = _flags.log_dir
else:
self._logger = setup_logging(name=self.__class__.__name__)
self._csv_logger = setup_csv_logging(
name=self.__class__.__name__, log_file=None
)
self._log_dir = os.getcwd()
if not self._logger.isEnabledFor(logging.DEBUG):
self._logger.addFilter(event_representation_filter)
# Simulator variables.
self._scheduler = scheduler
self._simulator_time = EventTime.zero()
self._scheduler_frequency = scheduler_frequency
self._loop_timeout = loop_timeout
self._task_id_added_to_event_queue = set()
# Workload variables.
self._workload_loader = workload_loader
self._workload: Workload = Workload.empty(_flags)
self._worker_pools = worker_pools
self._logger.info("The Worker Pools are: ")
for worker_pool in self._worker_pools.worker_pools:
self._logger.info(f"{worker_pool}")
resources_str = ",".join(
[
",".join((resource.name, resource.id, str(quantity)))
for resource, quantity in worker_pool.resources.resources
]
)
self._csv_logger.debug(
f"0,WORKER_POOL,{worker_pool.name},{worker_pool.id},{resources_str}"
)
for worker in worker_pool.workers:
self._logger.info(f"\t{worker}")
self.__log_utilization(self._simulator_time)
# Internal data.
self._last_scheduler_start_time = self._simulator_time
self._next_scheduler_event = None
self._last_scheduler_placements: Optional[Placements] = None
# A Cache from the TaskID to a future Placement event in the EventQueue.
# The Simulator uses this bookkeeping to revoke / invalidate decisions made
# by the past scheduler invocations.
self._future_placement_events: Mapping[str, Placement] = {}
# Flag values.
self._scheduler_delay = EventTime(
_flags.scheduler_delay if _flags else 0, EventTime.Unit.US
)
self._runtime_variance = _flags.runtime_variance if _flags else 0
self._drop_skipped_tasks = _flags.drop_skipped_tasks if _flags else False
self._verify_schedule = _flags.verify_schedule if _flags else False
self._run_scheduler_at_worker_free = (
_flags.scheduler_run_at_worker_free if _flags else False
)
self._workload_update_interval = (
EventTime(_flags.workload_update_interval, EventTime.Unit.US)
if _flags
else EventTime.invalid()
)
self._log_task_graphs = _flags.log_graphs if _flags else False
# Statistics about the Task.
self._finished_tasks = 0
self._cancelled_tasks = 0
self._missed_task_deadlines = 0
# Statistics about the TaskGraph.
self._finished_task_graphs = 0
self._missed_task_graph_deadlines = 0
# Initialize the event queue.
# To make the system continue working the loop, we add three events:
# - SIMULATOR_START: A notional event start the simulator and log into the CSV.
# - UPDATE_WORKLOAD: An event to reach out to the WorkloadLoader and get the
# next batch of TaskGraphs.
# - SCHEDULER_START: An event to invoke the scheduler.
self._event_queue = EventQueue()
# First, create the SIMULATOR_START event to signify the start of the Simulator.
sim_start_event = Event(
event_type=EventType.SIMULATOR_START, time=self._simulator_time
)
self._event_queue.add_event(sim_start_event)
self._logger.info(
"[%s] Added %s to the event queue.",
self._simulator_time.time,
sim_start_event,
)
# Second, create the UPDATE_WORKLOAD event to retrieve the latest Workload.
upate_workload_event = Event(
event_type=EventType.UPDATE_WORKLOAD, time=self._simulator_time
)
self._event_queue.add_event(upate_workload_event)
self._logger.info(
"[%s] Added %s to the event queue.",
self._simulator_time.time,
upate_workload_event,
)
# Third, create the SCHEDULER_START event to invoke the scheduler.
sched_start_event = Event(
event_type=EventType.SCHEDULER_START, time=self._simulator_time
)
self._event_queue.add_event(sched_start_event)
self._logger.info(
"[%s] Added %s to the event queue.",
self._simulator_time.time,
sched_start_event,
)
def dry_run(self) -> None:
"""Displays the order in which the TaskGraphs will be released."""
start_time = EventTime.zero()
while True:
# Get the next Workload from the WorkloadLoader.
next_workload = self._workload_loader.get_next_workload(start_time)
if next_workload is None:
self._logger.info(
f"The WorkloadLoader '{type(self._workload_loader).__name__}' "
f"released no more Workloads."
)
break
# A new Workload has been released, we log the release times of the
# TaskGraphs from this instance of the Workload.
self._workload = next_workload
task_graphs = list(
sorted(
self._workload.task_graphs.values(),
key=lambda task_graph: task_graph.release_time,
)
)
self._logger.info(
f"The WorkloadLoader '{type(self._workload_loader).__name__}' released "
f"a Workload with {len(task_graphs)} TaskGraphs."
)
start_time = task_graphs[-1].release_time
for task_graph in task_graphs:
self._logger.info(
"[%s] The TaskGraph %s will be released with deadline "
"%s and critical path runtime %s.",
task_graph.release_time.to(EventTime.Unit.US).time,
task_graph.name,
task_graph.deadline,
task_graph.critical_path_runtime,
)
self._csv_logger.info(
"%s,TASK_GRAPH_RELEASE,%s,%s,%s,%s",
task_graph.release_time.to(EventTime.Unit.US).time,
task_graph.name,
task_graph.deadline.to(EventTime.Unit.US).time,
len(task_graph.get_nodes()),
task_graph.critical_path_runtime.to(EventTime.Unit.US).time,
)
if self._log_task_graphs:
# Log a DOT representation of the TaskGraph, if requested.
task_graph.to_dot(
os.path.join(self._log_dir, f"{task_graph.name}.dot")
)
def simulate(self) -> None:
"""Run the simulator loop.
This loop requires the `Workload` to be populated with the `TaskGraph`s whose
execution is to be simulated using the Scheduler.
"""
# Run the simulator loop.
while True:
time_until_next_event = self._event_queue.peek().time - self._simulator_time
# If there are any running tasks, step through the execution of the
# Simulator until the closest remaining time.
running_tasks = self._worker_pools.get_placed_tasks()
if len(running_tasks) > 0:
# There are running tasks, figure out the minimum remaining
# time across all the tasks.
min_task_remaining_time = min(
map(attrgetter("remaining_time"), running_tasks)
)
self._logger.debug(
"[%s] The minimum task remaining time was %s, "
"and the time until next event was %s.",
self._simulator_time.to(EventTime.Unit.US).time,
min_task_remaining_time,
time_until_next_event,
)
# If the minimum remaining time comes before the time until
# the next event in the queue, step all workers until the
# completion of that task, otherwise, handle the next event.
if min_task_remaining_time < time_until_next_event:
self.__step(step_size=min_task_remaining_time)
else:
# NOTE: We step here so that all the Tasks that are going
# to finish as a result of this step have their TASK_FINISHED
# events processed first before any future placement occurs
# that is decided prior.
self.__step(step_size=time_until_next_event)
if self.__handle_event(self._event_queue.next()):
break
else:
# Step until the next event is supposed to be executed.
self.__step(step_size=time_until_next_event)
if self.__handle_event(self._event_queue.next()):
break
def __handle_scheduler_start(self, event: Event) -> None:
"""Handle the SCHEDULER_START event. The method invokes the scheduler, and adds
a SCHEDULER_FINISHED event to the event queue.
Args:
event (`Event`): The event to handle.
"""
# Log the required CSV information.
currently_placed_tasks = self._worker_pools.get_placed_tasks()
schedulable_tasks = self._workload.get_schedulable_tasks(
event.time,
self._scheduler.lookahead,
self._scheduler.preemptive,
self._scheduler.retract_schedules,
self._worker_pools,
self._scheduler.policy,
self._scheduler.branch_prediction_accuracy,
self._scheduler.release_taskgraphs,
)
self._csv_logger.debug(
f"{event.time.time},SCHEDULER_START,{len(schedulable_tasks)},"
f"{len(currently_placed_tasks)}"
)
self.__log_utilization(event.time)
# Execute the scheduler, and insert an event notifying the
# end of the scheduler into the loop.
self._last_scheduler_start_time = event.time
self._next_scheduler_event = None
self._logger.info(
"[%s] Running the scheduler with %s schedulable tasks and "
"%s tasks already placed across %s worker pools.",
event.time.time,
len(schedulable_tasks),
len(currently_placed_tasks),
len(self._worker_pools),
)
sched_finished_event = self.__run_scheduler(event)
self._event_queue.add_event(sched_finished_event)
self._logger.info(
"[%s] Added %s to the event queue.",
event.time.time,
sched_finished_event,
)
def __handle_profile_eviction(self, event: Event) -> None:
"""Handles the eviction of `WorkProfile`s from the given `WorkerPool`.
Args:
event (`Event`): The event that contains the `placement` information with
the type `Placement.PlacementType.EVICT_WORK_PROFILE`.
"""
if event.placement.placement_type != Placement.PlacementType.EVICT_WORK_PROFILE:
raise ValueError(
f"The placement type of the event {event.placement.placement_type} is "
f"not {Placement.PlacementType.EVICT_WORK_PROFILE}."
)
self._logger.info(
"[%s] The Simulator is requesting the eviction of %s "
"from the WorkerPool %s and the Worker %s.",
event.time.to(EventTime.Unit.US).time,
event.placement.work_profile,
event.placement.worker_pool_id,
event.placement.worker_id,
)
worker_pool = self._worker_pools.get_worker_pool(event.placement.worker_pool_id)
if worker_pool is None:
raise ValueError(
f"The WorkerPool {event.placement.worker_pool_id} does not exist."
)
else:
worker_pool.evict_profile(
event.placement.work_profile,
event.placement.worker_id,
)
def __handle_profile_loading(self, event: Event) -> None:
"""Handles the loading of a `WorkProfile` into the given `WorkerPool`.
Args:
event (`Event`): The event that contains the `placement` information with
the type `Placement.PlacementType.LOAD_WORK_PROFILE`.
"""
if event.placement.placement_type != Placement.PlacementType.LOAD_WORK_PROFILE:
raise ValueError(
f"The placement type of the event {event.placement.placement_type} is "
f"not {Placement.PlacementType.LOAD_WORK_PROFILE}."
)
self._logger.info(
"[%s] The Simulator is requesting the loading of %s "
"into the WorkerPool %s and the Worker %s.",
event.time.to(EventTime.Unit.US).time,
event.placement.work_profile,
event.placement.worker_pool_id,
event.placement.worker_id,
)
worker_pool = self._worker_pools.get_worker_pool(event.placement.worker_pool_id)
if worker_pool is None:
raise ValueError(
f"The WorkerPool {event.placement.worker_pool_id} does not exist."
)
else:
worker_pool.load_profile(
event.placement.work_profile,
event.placement.loading_strategy,
event.placement.worker_id,
)
def __create_events_from_task_placement_skip(
self,
time: EventTime,
placement: Placement,
drop_skipped_tasks: bool = False,
) -> Sequence[Event]:
"""Handles the non-placement of Tasks by the Scheduler.
If the simulator was required to drop tasks that were not placed, it returns
a sequence of `TASK_CANCEL` Events for`Task`s that were cancelled as a result
of the non-placement of this task, and delays the execution of the Task to the
next available timestamp otherwise.
Args:
time (`EventTime`): The time at which the skipping is being requested.
placement (`Placement`): The Placement object returned by a Scheduler.
drop_skipped_tasks (`bool`): If `True`, the cancellation of the `Task` and
its dependents will be requested.
Returns:
A (possibly empty) sequence of cancellation events for `Task`s.
"""
assert (
not placement.is_placed()
), f"Skipping requested for a placed Task {placement.task.unique_name}."
self._logger.debug(
"[%s] Creating events from the skipping of %s, "
"with drop_skipped_tasks set to %s.",
time.to(EventTime.Unit.US).time,
placement.task.unique_name,
drop_skipped_tasks,
)
task_events = []
if drop_skipped_tasks:
# The configuration requires us to drop tasks that were skipped, we request
# the Simulator to cancel this Task along with all of its dependents that
# cannot be executed as a result.
task_graph = self._workload.get_task_graph(placement.task.task_graph)
if task_graph is None:
raise ValueError(f"No TaskGraph found for {placement.task.task_graph}")
for cancelled_task in task_graph.cancel(placement.task, time):
task_events.append(
Event(
event_type=EventType.TASK_CANCEL,
time=cancelled_task.cancellation_time,
task=cancelled_task,
)
)
if task_graph.is_cancelled():
released_tasks_from_new_task_graph = (
self._workload.notify_task_graph_completion(
task_graph,
time,
)
)
self._logger.info(
"[%s] Notified the Workload of the cancellation of %s, "
"and received %s new Tasks from new TaskGraphs.",
time.to(EventTime.Unit.US).time,
task_graph.name,
len(released_tasks_from_new_task_graph),
)
for released_task in released_tasks_from_new_task_graph:
task_events.append(
Event(
event_type=EventType.TASK_RELEASE,
time=released_task.release_time,
task=released_task,
)
)
else:
self._csv_logger.debug(
f"{time.to(EventTime.Unit.US).time},TASK_SKIP,{placement.task.name},"
f"{placement.task.task_graph},{placement.task.timestamp},"
f"{placement.task.id}"
)
if placement.task.id in self._future_placement_events:
future_placement_event = self._future_placement_events[
placement.task.id
]
self._logger.warning(
"[%s] Failed to place %s, skipping it for future reconsideration "
"and invalidating the previously scheduled Placement event for %s.",
time.to(EventTime.Unit.US).time,
placement.task,
future_placement_event.time,
)
self._event_queue.remove_event(future_placement_event)
del self._future_placement_events[placement.task.id]
# Unschedule the Task.
placement.task.unschedule(time)
else:
self._logger.warning(
"[%s] Failed to place %s, skipping it for future reconsideration.",
time.to(EventTime.Unit.US).time,
placement.task,
)
return task_events
def __create_events_from_task_placement(
self, event_time: EventTime, placement: Placement
) -> Sequence[Event]:
"""Handle the placement of a Task by the Scheduler.
Note that the `Placement` must be of type `Placement.PlacementType.PLACE_TASK`.
Args:
event_time (`EventTime`): The time at which the placement was received.
placement (`Placement`): The Placement object returned by a Scheduler.
Returns:
A sequence of events that need to be added to the event queue as a result
of this Placement.
"""
if placement.placement_type != Placement.PlacementType.PLACE_TASK:
raise ValueError(
f"Invalid placement type {placement.placement_type} for "
f"{placement.task.unique_name}."
)
simulator_events = []
if placement.task.state < TaskState.SCHEDULED:
if placement.is_placed():
# The Task has not been scheduled before, we populate the
# required fields and cache the placement event in case
# changes need to be made before the task is actually executed.
self._logger.debug(
"[%s] Scheduling the Task %s for the first time to be "
"executed on WorkerPool %s at %s.",
event_time.to(EventTime.Unit.US).time,
placement.task,
placement.worker_pool_id,
placement.placement_time,
)
placement.task.schedule(event_time, placement)
simulator_event = Event(
event_type=EventType.TASK_PLACEMENT,
time=placement.placement_time,
task=placement.task,
placement=placement,
)
self._future_placement_events[placement.task.id] = simulator_event
simulator_events.append(simulator_event)
else:
simulator_events.extend(
self.__create_events_from_task_placement_skip(
event_time, placement, self._drop_skipped_tasks
)
)
elif placement.task.state == TaskState.SCHEDULED:
if placement.is_placed():
# The Task was SCHEDULED previously, we update any changes to
# both the Task and any future placement events in the queue.
if placement.task.id not in self._future_placement_events:
self._logger.debug(
"[%s] The Task %s in %s state did not have any "
"corresponding cached Placement events in the future."
"Rescheduling the Task to be executed on the "
"WorkerPool %s at %s.",
event_time.to(EventTime.Unit.US).time,
placement.task,
placement.task.state,
placement.worker_pool_id,
placement.placement_time,
)
placement.task.schedule(event_time, placement)
simulator_event = Event(
event_type=EventType.TASK_PLACEMENT,
time=placement.placement_time,
task=placement.task,
placement=placement,
)
self._future_placement_events[placement.task.id] = simulator_event
simulator_events.append(simulator_event)
else:
cached_placement_event = self._future_placement_events[
placement.task.id
]
self._logger.debug(
"[%s] Updating a prior placement of Task %s from "
"WorkerPool %s and time %s to WorkerPool %s and time %s.",
event_time.to(EventTime.Unit.US).time,
placement.task,
cached_placement_event.placement.worker_pool_id,
cached_placement_event.time,
placement.worker_pool_id,
placement.placement_time,
)
placement.task.schedule(event_time, placement)
cached_placement_event._time = placement.placement_time
cached_placement_event._placement = placement
# Reheapify since we changed the time of some already cached events.
self._event_queue.reheapify()
else:
simulator_events.extend(
self.__create_events_from_task_placement_skip(
event_time, placement, self._drop_skipped_tasks
)
)
elif placement.task.state == TaskState.RUNNING:
if placement.is_placed():
if (
placement.worker_pool_id != placement.task.worker_pool_id
or placement.placement_time > event_time
):
self._logger.debug(
"[%s] The Task %s in state %s was migrated from "
"WorkerPool %s to WorkerPool %s to be started at %s.",
event_time.to(EventTime.Unit.US).time,
placement.task,
placement.task.state,
placement.task.worker_pool_id,
placement.worker_pool_id,
placement.placement_time,
)
simulator_events.append(
Event(
event_type=EventType.TASK_PREEMPT,
time=event_time,
task=placement.task,
)
)
simulator_events.append(
Event(
event_type=EventType.TASK_MIGRATION,
time=placement.placement_time,
task=placement.task,
placement=placement,
)
)
else:
self._logger.debug(
"[%s] The Task %s in state %s was preempted.",
event_time.to(EventTime.Unit.US).time,
placement.task,
placement.task.state,
)
simulator_events.append(
Event(
event_type=EventType.TASK_PREEMPT,
time=event_time,
task=placement.task,
)
)
elif placement.task.state == TaskState.PREEMPTED:
raise NotImplementedError(
"Rescheduling of PREEMPTED tasks hasn't been implemented yet."
)
else:
if not placement.is_placed():
self._logger.debug(
"[%s] The Task %s was cancelled by an upstream task, "
"skipping its re-cancellation.",
event_time.to(EventTime.Unit.US).time,
placement.task,
)
else:
# Task was either completed or cancelled before the Scheduler finished,
# we skip the application of this Placement decision.
self._logger.warning(
"[%s] Skipping the application of Placement of Task %s at "
"time %s because the Task was in %s state.",
event_time.to(EventTime.Unit.US).time,
placement.task,
placement.placement_time,
placement.task.state,
)
return simulator_events
def __handle_scheduler_finish(self, event: Event) -> None:
"""Handle the SCHEDULER_FINISHED event. The method places the profiles and tasks
on the appropriate workers, and computes the next scheduler start time.
Args:
event (`Event`): The event to handle.
"""
# Place the tasks on the assigned worker pool, and reset the
# available events to the tasks that could not be placed.
self._logger.info(
"[%s] Finished executing the scheduler initiated at %s. Placing tasks.",
event.time.time,
self._last_scheduler_start_time,
)
# Log the required CSV information.
def count_placed_tasks(placements: Placements):
return len(
list(
filter(
lambda p: p.placement_type == Placement.PlacementType.PLACE_TASK
and p.is_placed(),
placements,
)
)
)
num_placed = count_placed_tasks(self._last_scheduler_placements)
num_unplaced = count_placed_tasks(self._last_scheduler_placements) - num_placed
scheduler_runtime = event.time - self._last_scheduler_start_time
self._csv_logger.debug(
f"{event.time.time},SCHEDULER_FINISHED,"
f"{scheduler_runtime.to(EventTime.Unit.US).time},"
f"{num_placed},{num_unplaced},"
f"{self._last_scheduler_placements.true_runtime.to(EventTime.Unit.US).time}"
)
if self._verify_schedule:
self._scheduler.verify_schedule(
event.time,
self._workload,
self._worker_pools,
self._last_scheduler_placements,
)
simulator_events = []
for placement in self._last_scheduler_placements:
if placement.placement_type == Placement.PlacementType.CANCEL_TASK:
# Request the cancellation of this `Task` and all its dependent `Task`s
# that cannot complete their execution without this `Task`.
simulator_events.extend(
self.__create_events_from_task_placement_skip(
time=event.time, placement=placement, drop_skipped_tasks=True
)
)
elif placement.placement_type == Placement.PlacementType.PLACE_TASK:
# Ensure that the Placement always occurs in the present or future.
if placement.is_placed() and placement.placement_time < event.time:
self._logger.error(
"[%s] A Placement for the Task %s occurred in the past at %s.",
event.time.to(EventTime.Unit.US).time,
placement.task,
placement.placement_time,
)
raise ValueError(
f"A Placement for the Task {placement.task.unique_name} "
f"occurred in the past at {placement.placement_time}."
)
if placement.is_placed():
# If there was a Placement, log the Task scheduling event.
self._csv_logger.debug(
f"{event.time.time},TASK_SCHEDULED,{placement.task.name},"
f"{placement.task.task_graph},{placement.task.timestamp},"
f"{placement.task.id},{placement.task.deadline.time},"
f"{placement.placement_time.time},{placement.worker_pool_id},"
f"{placement.execution_strategy.runtime.time}"
)
simulator_events.extend(
self.__create_events_from_task_placement(event.time, placement)
)
elif placement.placement_type == Placement.PlacementType.EVICT_WORK_PROFILE:
# Ensure that the Placement always occurs in the present or future.
if placement.placement_time < event.time:
self._logger.error(
"[%s] A Placement for the WorkProfile %s occurred in "
"the past at %s.",
event.time.to(EventTime.Unit.US).time,
placement.work_profile,
placement.placement_time,
)
raise ValueError(
f"A Placement for the WorkProfile {placement.work_profile} "
f"occurred in the past at {placement.placement_time}."
)
eviction_event = Event(
event_type=EventType.EVICT_PROFILE,
time=placement.placement_time,
placement=placement,
)
simulator_events.append(eviction_event)
elif placement.placement_type == Placement.PlacementType.LOAD_WORK_PROFILE:
# Ensure that the Placement always occurs in the present or future.
if placement.placement_time < event.time:
self._logger.error(