3 """A simple utility to unpickle some code, run it, and pickle the
13 from typing import Optional
15 import cloudpickle # type: ignore
16 import psutil # type: ignore
21 from stopwatch import Timer
22 from thread_utils import background_thread
25 logger = logging.getLogger(__file__)
27 cfg = config.add_commandline_args(
28 f"Remote Worker ({__file__})",
29 "Helper to run pickled code remotely and return results",
36 help='The location of the bundle of code to execute.',
43 help='The location where we should write the computation results.',
47 action=argparse_utils.ActionNoYes,
49 help='Should we watch for the cancellation of our parent ssh process?',
54 def watch_for_cancel(terminate_event: threading.Event) -> None:
55 logger.debug('Starting up background thread...')
56 p = psutil.Process(os.getpid())
59 ancestors = p.parents()
60 for ancestor in ancestors:
61 name = ancestor.name()
63 logger.debug(f'Ancestor process {name} (pid={pid})')
64 if 'ssh' in name.lower():
69 'Did not see sshd in our ancestors list?! Committing suicide.'
72 os.kill(os.getpid(), signal.SIGTERM)
74 os.kill(os.getpid(), signal.SIGKILL)
76 if terminate_event.is_set():
82 thread: Optional[threading.Thread],
83 stop_thread: Optional[threading.Event],
86 if stop_thread is not None:
88 assert thread is not None
95 in_file = config.config['code_file']
96 out_file = config.config['result_file']
100 if config.config['watch_for_cancel']:
101 (thread, stop_thread) = watch_for_cancel()
103 logger.debug(f'Reading {in_file}.')
105 with open(in_file, 'rb') as rb:
106 serialized = rb.read()
107 except Exception as e:
109 logger.critical(f'Problem reading {in_file}. Aborting.')
110 cleanup_and_exit(thread, stop_thread, 1)
112 logger.debug(f'Deserializing {in_file}.')
114 fun, args, kwargs = cloudpickle.loads(serialized)
115 except Exception as e:
117 logger.critical(f'Problem deserializing {in_file}. Aborting.')
118 cleanup_and_exit(thread, stop_thread, 2)
120 logger.debug('Invoking user code...')
122 ret = fun(*args, **kwargs)
123 logger.debug(f'User code took {t():.1f}s')
125 logger.debug('Serializing results')
127 serialized = cloudpickle.dumps(ret)
128 except Exception as e:
130 logger.critical(f'Could not serialize result ({type(ret)}). Aborting.')
131 cleanup_and_exit(thread, stop_thread, 3)
133 logger.debug(f'Writing {out_file}.')
135 with open(out_file, 'wb') as wb:
137 except Exception as e:
139 logger.critical(f'Error writing {out_file}. Aborting.')
140 cleanup_and_exit(thread, stop_thread, 4)
141 cleanup_and_exit(thread, stop_thread, 0)
144 if __name__ == '__main__':