3 from __future__ import annotations
5 from abc import ABC, abstractmethod
6 import concurrent.futures as fut
7 from collections import defaultdict
8 from dataclasses import dataclass
17 from typing import Any, Callable, Dict, List, Optional, Set
19 import cloudpickle # type: ignore
21 from ansi import bg, fg, underline, reset
24 from exec_utils import run_silently, cmd_in_background
25 from decorator_utils import singleton
28 logger = logging.getLogger(__name__)
30 parser = config.add_commandline_args(
31 f"Executors ({__file__})",
32 "Args related to processing executors."
35 '--executors_threadpool_size',
38 help='Number of threads in the default threadpool, leave unset for default',
42 '--executors_processpool_size',
45 help='Number of processes in the default processpool, leave unset for default',
49 '--executors_schedule_remote_backups',
51 action=argparse_utils.ActionNoYes,
52 help='Should we schedule duplicative backup work if a remote bundle is slow',
55 '--executors_max_bundle_failures',
59 help='Maximum number of failures before giving up on a bundle',
62 RSYNC = 'rsync -q --no-motd -W --ignore-existing --timeout=60 --size-only -z'
63 SSH = 'ssh -oForwardX11=no'
64 HIST = histogram.SimpleHistogram(
65 histogram.SimpleHistogram.n_evenly_spaced_buckets(
71 def run_local_bundle(fun, *args, **kwargs):
72 logger.debug(f"Running local bundle at {fun.__name__}")
74 result = fun(*args, **kwargs)
76 duration = end - start
77 logger.debug(f"{fun.__name__} finished; used {duration:.1f}s")
78 HIST.add_item(duration)
82 def run_cloud_pickle(pickle):
83 fun, args, kwargs = cloudpickle.loads(pickle)
84 logger.debug(f"Running pickled bundle at {fun.__name__}")
86 result = fun(*args, **kwargs)
88 duration = end - start
89 logger.debug(f"{fun.__name__} finished; used {duration:.1f}s")
93 def make_cloud_pickle(fun, *args, **kwargs):
94 logger.info(f"Making cloudpickled bundle at {fun.__name__}")
95 return cloudpickle.dumps((fun, args, kwargs))
98 class BaseExecutor(ABC):
106 **kwargs) -> fut.Future:
111 wait: bool = True) -> None:
115 class ThreadExecutor(BaseExecutor):
117 max_workers: Optional[int] = None):
120 if max_workers is not None:
121 workers = max_workers
122 elif 'executors_threadpool_size' in config.config:
123 workers = config.config['executors_threadpool_size']
124 logger.debug(f'Creating threadpool executor with {workers} workers')
125 self._thread_pool_executor = fut.ThreadPoolExecutor(
127 thread_name_prefix="thread_executor_helper"
134 **kwargs) -> fut.Future:
137 f'Submitted work to threadpool; there are now {self.job_count} items.'
140 newargs.append(function)
143 return self._thread_pool_executor.submit(
149 wait = True) -> None:
150 logger.debug("Shutting down threadpool executor.")
152 self._thread_pool_executor.shutdown(wait)
155 class ProcessExecutor(BaseExecutor):
160 if max_workers is not None:
161 workers = max_workers
162 elif 'executors_processpool_size' in config.config:
163 workers = config.config['executors_processpool_size']
164 logger.debug(f'Creating processpool executor with {workers} workers.')
165 self._process_executor = fut.ProcessPoolExecutor(
173 **kwargs) -> fut.Future:
174 # Bundle it up before submitting because pickle sucks.
175 pickle = make_cloud_pickle(function, *args, **kwargs)
178 f'Submitting work to processpool executor; there are now {self.job_count} items.'
180 return self._process_executor.submit(run_cloud_pickle, pickle)
182 def shutdown(self, wait=True) -> None:
183 logger.debug('Shutting down processpool executor')
185 self._process_executor.shutdown(wait)
189 class RemoteWorkerRecord:
196 return hash((self.username, self.machine))
199 return f'{self.username}@{self.machine}'
206 worker: Optional[RemoteWorkerRecord]
207 username: Optional[str]
208 machine: Optional[str]
217 src_bundle: BundleDetails
218 is_cancelled: threading.Event
220 backup_bundles: Optional[List[BundleDetails]]
224 class RemoteExecutorStatus:
225 def __init__(self, total_worker_count: int) -> None:
226 self.worker_count = total_worker_count
227 self.known_workers: Set[RemoteWorkerRecord] = set()
228 self.start_per_bundle: Dict[str, float] = defaultdict(float)
229 self.end_per_bundle: Dict[str, float] = defaultdict(float)
230 self.finished_bundle_timings_per_worker: Dict[
234 self.in_flight_bundles_by_worker: Dict[
238 self.bundle_details_by_uuid: Dict[str, BundleDetails] = {}
239 self.finished_bundle_timings: List[float] = []
240 self.last_periodic_dump: Optional[float] = None
241 self.total_bundles_submitted = 0
243 # Protects reads and modification using self. Also used
244 # as a memory fence for modifications to bundle.
245 self.lock = threading.Lock()
247 def record_acquire_worker(
249 worker: RemoteWorkerRecord,
253 self.record_acquire_worker_already_locked(
258 def record_acquire_worker_already_locked(
260 worker: RemoteWorkerRecord,
263 assert self.lock.locked()
264 self.known_workers.add(worker)
265 self.start_per_bundle[uuid] = time.time()
266 x = self.in_flight_bundles_by_worker.get(worker, set())
268 self.in_flight_bundles_by_worker[worker] = x
270 def record_bundle_details(
272 details: BundleDetails) -> None:
274 self.record_bundle_details_already_locked(details)
276 def record_bundle_details_already_locked(
278 details: BundleDetails) -> None:
279 assert self.lock.locked()
280 self.bundle_details_by_uuid[details.uuid] = details
282 def record_release_worker_already_locked(
284 worker: RemoteWorkerRecord,
288 assert self.lock.locked()
290 self.end_per_bundle[uuid] = ts
291 self.in_flight_bundles_by_worker[worker].remove(uuid)
292 if not was_cancelled:
293 bundle_latency = ts - self.start_per_bundle[uuid]
294 x = self.finished_bundle_timings_per_worker.get(worker, list())
295 x.append(bundle_latency)
296 self.finished_bundle_timings_per_worker[worker] = x
297 self.finished_bundle_timings.append(bundle_latency)
299 def total_in_flight(self) -> int:
300 assert self.lock.locked()
302 for worker in self.known_workers:
303 total_in_flight += len(self.in_flight_bundles_by_worker[worker])
304 return total_in_flight
306 def total_idle(self) -> int:
307 assert self.lock.locked()
308 return self.worker_count - self.total_in_flight()
311 assert self.lock.locked()
313 total_finished = len(self.finished_bundle_timings)
314 total_in_flight = self.total_in_flight()
315 ret = f'\n\n{underline()}Remote Executor Pool Status{reset()}: '
317 if len(self.finished_bundle_timings) > 1:
318 qall = numpy.quantile(self.finished_bundle_timings, [0.5, 0.95])
320 f'⏱=∀p50:{qall[0]:.1f}s, ∀p95:{qall[1]:.1f}s, '
321 f'✅={total_finished}/{self.total_bundles_submitted}, '
322 f'💻n={total_in_flight}/{self.worker_count}\n'
326 f' ✅={total_finished}/{self.total_bundles_submitted}, '
327 f'💻n={total_in_flight}/{self.worker_count}\n'
330 for worker in self.known_workers:
331 ret += f' {fg("lightning yellow")}{worker.machine}{reset()}: '
332 timings = self.finished_bundle_timings_per_worker.get(worker, [])
336 qworker = numpy.quantile(timings, [0.5, 0.95])
337 ret += f' 💻p50: {qworker[0]:.1f}s, 💻p95: {qworker[1]:.1f}s\n'
341 ret += f' ...finished {count} total bundle(s) so far\n'
342 in_flight = len(self.in_flight_bundles_by_worker[worker])
344 ret += f' ...{in_flight} bundles currently in flight:\n'
345 for bundle_uuid in self.in_flight_bundles_by_worker[worker]:
346 details = self.bundle_details_by_uuid.get(
350 pid = str(details.pid) if details is not None else "TBD"
351 sec = ts - self.start_per_bundle[bundle_uuid]
352 ret += f' (pid={pid}): {bundle_uuid} for {sec:.1f}s so far '
353 if qworker is not None:
355 ret += f'{bg("red")}>💻p95{reset()} '
356 elif sec > qworker[0]:
357 ret += f'{fg("red")}>💻p50{reset()} '
359 if sec > qall[1] * 1.5:
360 ret += f'{bg("red")}!!!{reset()}'
361 if details is not None:
362 logger.debug(f'Flagging {details.uuid} for another backup')
363 details.super_slow = True
365 ret += f'{bg("red")}>∀p95{reset()} '
366 if details is not None:
367 logger.debug(f'Flagging {details.uuid} for a backup')
368 details.too_slow = True
370 ret += f'{fg("red")}>∀p50{reset()}'
374 def periodic_dump(self, total_bundles_submitted: int) -> None:
375 assert self.lock.locked()
376 self.total_bundles_submitted = total_bundles_submitted
379 self.last_periodic_dump is None
380 or ts - self.last_periodic_dump > 5.0
383 self.last_periodic_dump = ts
386 class RemoteWorkerSelectionPolicy(ABC):
387 def register_worker_pool(self, workers):
389 self.workers = workers
392 def is_worker_available(self) -> bool:
398 machine_to_avoid = None
399 ) -> Optional[RemoteWorkerRecord]:
403 class WeightedRandomRemoteWorkerSelectionPolicy(RemoteWorkerSelectionPolicy):
404 def is_worker_available(self) -> bool:
405 for worker in self.workers:
412 machine_to_avoid = None
413 ) -> Optional[RemoteWorkerRecord]:
415 for worker in self.workers:
416 for x in range(0, worker.count):
417 for y in range(0, worker.weight):
418 grabbag.append(worker)
420 for _ in range(0, 5):
421 random.shuffle(grabbag)
423 if worker.machine != machine_to_avoid or _ > 2:
426 logger.debug(f'Selected worker {worker}')
428 logger.warning("Couldn't find a worker; go fish.")
432 class RoundRobinRemoteWorkerSelectionPolicy(RemoteWorkerSelectionPolicy):
433 def __init__(self) -> None:
436 def is_worker_available(self) -> bool:
437 for worker in self.workers:
444 machine_to_avoid: str = None
445 ) -> Optional[RemoteWorkerRecord]:
448 worker = self.workers[x]
452 if x >= len(self.workers):
455 logger.debug(f'Selected worker {worker}')
458 if x >= len(self.workers):
461 logger.warning("Couldn't find a worker; go fish.")
465 class RemoteExecutor(BaseExecutor):
467 workers: List[RemoteWorkerRecord],
468 policy: RemoteWorkerSelectionPolicy) -> None:
470 self.workers = workers
471 self.worker_count = 0
472 for worker in self.workers:
473 self.worker_count += worker.count
474 if self.worker_count <= 0:
475 msg = f"We need somewhere to schedule work; count was {self.worker_count}"
479 self.policy.register_worker_pool(self.workers)
480 self.cv = threading.Condition()
481 self._helper_executor = fut.ThreadPoolExecutor(
482 thread_name_prefix="remote_executor_helper",
483 max_workers=self.worker_count,
485 self.status = RemoteExecutorStatus(self.worker_count)
486 self.total_bundles_submitted = 0
488 f'Creating remote processpool with {self.worker_count} remote endpoints.'
491 def is_worker_available(self) -> bool:
492 return self.policy.is_worker_available()
496 machine_to_avoid: str = None
497 ) -> Optional[RemoteWorkerRecord]:
498 return self.policy.acquire_worker(machine_to_avoid)
500 def find_available_worker_or_block(
502 machine_to_avoid: str = None
503 ) -> RemoteWorkerRecord:
505 while not self.is_worker_available():
507 worker = self.acquire_worker(machine_to_avoid)
508 if worker is not None:
510 msg = "We should never reach this point in the code"
514 def release_worker(self, worker: RemoteWorkerRecord) -> None:
515 logger.debug(f'Released worker {worker}')
520 def heartbeat(self) -> None:
521 with self.status.lock:
522 # Regular progress report
523 self.status.periodic_dump(self.total_bundles_submitted)
525 # Look for bundles to reschedule
526 if len(self.status.finished_bundle_timings) > 7:
527 for worker, bundle_uuids in self.status.in_flight_bundles_by_worker.items():
528 for uuid in bundle_uuids:
529 bundle = self.status.bundle_details_by_uuid.get(uuid, None)
531 bundle is not None and
533 bundle.src_bundle is None and
534 config.config['executors_schedule_remote_backups']
536 self.consider_backup_for_bundle(bundle)
538 def consider_backup_for_bundle(self, bundle: BundleDetails) -> None:
539 assert self.status.lock.locked()
542 and len(bundle.backup_bundles) == 0 # one backup per
544 msg = f"*** Rescheduling {bundle.pid}/{bundle.uuid} ***"
546 self.schedule_backup_for_bundle(bundle)
550 and len(bundle.backup_bundles) < 2 # two backups in dire situations
551 and self.status.total_idle() > 4
553 msg = f"*** Rescheduling {bundle.pid}/{bundle.uuid} ***"
555 self.schedule_backup_for_bundle(bundle)
558 def check_if_cancelled(self, bundle: BundleDetails) -> bool:
559 with self.status.lock:
560 if bundle.is_cancelled.wait(timeout=0.0):
561 logger.debug(f'Bundle {bundle.uuid} is cancelled, bail out.')
562 bundle.was_cancelled = True
566 def launch(self, bundle: BundleDetails) -> Any:
567 """Find a worker for bundle or block until one is available."""
569 hostname = bundle.hostname
572 # Try not to schedule a backup on the same host as the original.
573 if bundle.src_bundle is not None:
574 avoid_machine = bundle.src_bundle.machine
576 while worker is None:
577 worker = self.find_available_worker_or_block(avoid_machine)
578 bundle.worker = worker
579 machine = bundle.machine = worker.machine
580 username = bundle.username = worker.username
581 self.status.record_acquire_worker(worker, uuid)
582 logger.debug(f'Running bundle {uuid} on {worker}...')
584 # Before we do any work, make sure the bundle is still viable.
585 if self.check_if_cancelled(bundle):
587 return self.post_launch_work(bundle)
588 except Exception as e:
590 logger.info(f"Bundle {uuid} seems to have failed?!")
591 if bundle.failure_count < config.config['executors_max_bundle_failures']:
592 return self.launch(bundle)
594 logger.info(f"Bundle {uuid} is poison, giving up on it.")
597 # Send input to machine if it's not local.
598 if hostname not in machine:
599 cmd = f'{RSYNC} {bundle.code_file} {username}@{machine}:{bundle.code_file}'
600 logger.info(f"Copying work to {worker} via {cmd}")
604 cmd = (f'{SSH} {bundle.username}@{bundle.machine} '
605 f'"source remote-execution/bin/activate &&'
606 f' /home/scott/lib/python_modules/remote_worker.py'
607 f' --code_file {bundle.code_file} --result_file {bundle.result_file}"')
608 p = cmd_in_background(cmd, silent=True)
609 bundle.pid = pid = p.pid
610 logger.info(f"Running {cmd} in the background as process {pid}")
615 except subprocess.TimeoutExpired:
618 # Both source and backup bundles can be cancelled by
619 # the other depending on which finishes first.
620 if self.check_if_cancelled(bundle):
625 f"{pid}/{bundle.uuid} has finished its work normally."
630 return self.post_launch_work(bundle)
631 except Exception as e:
633 logger.info(f"Bundle {uuid} seems to have failed?!")
634 if bundle.failure_count < config.config['executors_max_bundle_failures']:
635 return self.launch(bundle)
636 logger.info(f"Bundle {uuid} is poison, giving up on it.")
639 def post_launch_work(self, bundle: BundleDetails) -> Any:
640 with self.status.lock:
641 is_original = bundle.src_bundle is None
642 was_cancelled = bundle.was_cancelled
643 username = bundle.username
644 machine = bundle.machine
645 result_file = bundle.result_file
646 code_file = bundle.code_file
648 # Whether original or backup, if we finished first we must
649 # fetch the results if the computation happened on a
651 if not was_cancelled:
652 assert bundle.machine is not None
653 if bundle.hostname not in bundle.machine:
654 cmd = f'{RSYNC} {username}@{machine}:{result_file} {result_file} 2>/dev/null'
656 f"Fetching results from {username}@{machine} via {cmd}"
660 except subprocess.CalledProcessError:
662 run_silently(f'{SSH} {username}@{machine}'
663 f' "/bin/rm -f {code_file} {result_file}"')
664 bundle.end_ts = time.time()
665 assert bundle.worker is not None
666 self.status.record_release_worker_already_locked(
671 if not was_cancelled:
672 dur = bundle.end_ts - bundle.start_ts
675 # Original or not, the results should be back on the local
677 if not os.path.exists(result_file):
678 msg = f'{result_file} unexpectedly missing, wtf?!'
680 bundle.failure_count += 1
681 self.release_worker(bundle.worker)
684 # Only the original worker should unpickle the file contents
685 # though since it's the only one whose result matters.
687 logger.debug(f"Unpickling {result_file}.")
689 with open(f'{result_file}', 'rb') as rb:
690 serialized = rb.read()
691 result = cloudpickle.loads(serialized)
692 except Exception as e:
693 msg = f'Failed to load {result_file}'
695 bundle.failure_count += 1
696 self.release_worker(bundle.worker)
698 os.remove(f'{result_file}')
699 os.remove(f'{code_file}')
701 # Notify any backups that the original is done so they
702 # should stop ASAP. Do this whether or not we
703 # finished first since there could be more than one
705 if bundle.backup_bundles is not None:
706 for backup in bundle.backup_bundles:
708 f'Notifying backup {backup.uuid} that it is cancelled'
710 backup.is_cancelled.set()
714 # Backup results don't matter, they just need to leave the
715 # result file in the right place for their original to
719 # Tell the original to stop if we finished first.
720 if not was_cancelled:
722 f'Notifying original {bundle.src_bundle.uuid} that it is cancelled'
724 bundle.src_bundle.is_cancelled.set()
726 assert bundle.worker is not None
727 self.release_worker(bundle.worker)
730 def create_original_bundle(self, pickle):
731 from string_utils import generate_uuid
732 uuid = generate_uuid(as_hex=True)
733 code_file = f'/tmp/{uuid}.code.bin'
734 result_file = f'/tmp/{uuid}.result.bin'
736 logger.debug(f'Writing pickled code to {code_file}')
737 with open(f'{code_file}', 'wb') as wb:
740 bundle = BundleDetails(
741 pickled_code = pickle,
746 hostname = platform.node(),
747 code_file = code_file,
748 result_file = result_file,
750 start_ts = time.time(),
755 is_cancelled = threading.Event(),
756 was_cancelled = False,
760 self.status.record_bundle_details(bundle)
761 logger.debug(f'Created original bundle {uuid}')
764 def create_backup_bundle(self, src_bundle: BundleDetails):
765 assert src_bundle.backup_bundles is not None
766 n = len(src_bundle.backup_bundles)
767 uuid = src_bundle.uuid + f'_backup#{n}'
769 backup_bundle = BundleDetails(
770 pickled_code = src_bundle.pickled_code,
775 hostname = src_bundle.hostname,
776 code_file = src_bundle.code_file,
777 result_file = src_bundle.result_file,
779 start_ts = time.time(),
783 src_bundle = src_bundle,
784 is_cancelled = threading.Event(),
785 was_cancelled = False,
786 backup_bundles = None, # backup backups not allowed
789 src_bundle.backup_bundles.append(backup_bundle)
790 self.status.record_bundle_details_already_locked(backup_bundle)
791 logger.debug(f'Created backup bundle {uuid}')
794 def schedule_backup_for_bundle(self,
795 src_bundle: BundleDetails):
796 assert self.status.lock.locked()
797 backup_bundle = self.create_backup_bundle(src_bundle)
799 f'Scheduling backup bundle {backup_bundle.uuid} for execution'
801 self._helper_executor.submit(self.launch, backup_bundle)
803 # Results from backups don't matter; if they finish first
804 # they will move the result_file to this machine and let
805 # the original pick them up and unpickle them.
810 **kwargs) -> fut.Future:
811 pickle = make_cloud_pickle(function, *args, **kwargs)
812 bundle = self.create_original_bundle(pickle)
813 self.total_bundles_submitted += 1
815 f'Submitted work to remote executor; {self.total_bundles_submitted} items now submitted'
817 return self._helper_executor.submit(self.launch, bundle)
819 def shutdown(self, wait=True) -> None:
820 self._helper_executor.shutdown(wait)
825 class DefaultExecutors(object):
827 self.thread_executor: Optional[ThreadExecutor] = None
828 self.process_executor: Optional[ProcessExecutor] = None
829 self.remote_executor: Optional[RemoteExecutor] = None
831 def ping(self, host) -> bool:
832 command = ['ping', '-c', '1', host]
833 return subprocess.call(
835 stdout=subprocess.DEVNULL,
836 stderr=subprocess.DEVNULL,
839 def thread_pool(self) -> ThreadExecutor:
840 if self.thread_executor is None:
841 self.thread_executor = ThreadExecutor()
842 return self.thread_executor
844 def process_pool(self) -> ProcessExecutor:
845 if self.process_executor is None:
846 self.process_executor = ProcessExecutor()
847 return self.process_executor
849 def remote_pool(self) -> RemoteExecutor:
850 if self.remote_executor is None:
851 pool: List[RemoteWorkerRecord] = []
852 if self.ping('cheetah.house'):
856 machine = 'cheetah.house',
861 if self.ping('video.house'):
865 machine = 'video.house',
870 if self.ping('wannabe.house'):
874 machine = 'wannabe.house',
879 if self.ping('meerkat.cabin'):
883 machine = 'meerkat.cabin',
888 if self.ping('backup.house'):
892 machine = 'backup.house',
897 if self.ping('puma.cabin'):
901 machine = 'puma.cabin',
906 policy = WeightedRandomRemoteWorkerSelectionPolicy()
907 policy.register_worker_pool(pool)
908 self.remote_executor = RemoteExecutor(pool, policy)
909 return self.remote_executor