Towards a more type-clean mypy check.
[pyutils.git] / src / pyutils / remote_worker.py
1 #!/usr/bin/env python3
2
3 # © Copyright 2021-2022, Scott Gasch
4
5 """A simple utility to unpickle some code, run it, and pickle the
6 results.  Please don't unpickle (or run!) code you do not know.
7 """
8
9 import logging
10 import os
11 import signal
12 import sys
13 import threading
14 import time
15 from typing import Optional
16
17 import cloudpickle  # type: ignore
18 import psutil  # type: ignore
19
20 from pyutils import argparse_utils, bootstrap, config
21 from pyutils.parallelize.thread_utils import background_thread
22 from pyutils.stopwatch import Timer
23
24 logger = logging.getLogger(__file__)
25
26 cfg = config.add_commandline_args(
27     f"Remote Worker ({__file__})",
28     "Helper to run pickled code remotely and return results",
29 )
30 cfg.add_argument(
31     '--code_file',
32     type=str,
33     required=True,
34     metavar='FILENAME',
35     help='The location of the bundle of code to execute.',
36 )
37 cfg.add_argument(
38     '--result_file',
39     type=str,
40     required=True,
41     metavar='FILENAME',
42     help='The location where we should write the computation results.',
43 )
44 cfg.add_argument(
45     '--watch_for_cancel',
46     action=argparse_utils.ActionNoYes,
47     default=True,
48     help='Should we watch for the cancellation of our parent ssh process?',
49 )
50
51
52 @background_thread
53 def watch_for_cancel(terminate_event: threading.Event) -> None:
54     logger.debug('Starting up background thread...')
55     p = psutil.Process(os.getpid())
56     while True:
57         saw_sshd = False
58         ancestors = p.parents()
59         for ancestor in ancestors:
60             name = ancestor.name()
61             pid = ancestor.pid
62             logger.debug('Ancestor process %s (pid=%d)', name, pid)
63             if 'ssh' in name.lower():
64                 saw_sshd = True
65                 break
66         if not saw_sshd:
67             logger.error(
68                 'Did not see sshd in our ancestors list?!  Committing suicide.'
69             )
70             os.system('pstree')
71             os.kill(os.getpid(), signal.SIGTERM)
72             time.sleep(5.0)
73             os.kill(os.getpid(), signal.SIGKILL)
74             sys.exit(-1)
75         if terminate_event.is_set():
76             return
77         time.sleep(1.0)
78
79
80 def cleanup_and_exit(
81     thread: Optional[threading.Thread],
82     stop_thread: Optional[threading.Event],
83     exit_code: int,
84 ) -> None:
85     if stop_thread is not None:
86         stop_thread.set()
87         assert thread is not None
88         thread.join()
89     sys.exit(exit_code)
90
91
92 @bootstrap.initialize
93 def main() -> None:
94     in_file = config.config['code_file']
95     assert in_file and type(in_file) == str
96     out_file = config.config['result_file']
97     assert out_file and type(out_file) == str
98
99     thread = None
100     stop_thread = None
101     if config.config['watch_for_cancel']:
102         (thread, stop_thread) = watch_for_cancel()
103
104     logger.debug('Reading %s.', in_file)
105     try:
106         with open(in_file, 'rb') as rb:
107             serialized = rb.read()
108     except Exception as e:
109         logger.exception(e)
110         logger.critical('Problem reading %s. Aborting.', in_file)
111         cleanup_and_exit(thread, stop_thread, 1)
112
113     logger.debug('Deserializing %s', in_file)
114     try:
115         fun, args, kwargs = cloudpickle.loads(serialized)
116     except Exception as e:
117         logger.exception(e)
118         logger.critical('Problem deserializing %s. Aborting.', in_file)
119         cleanup_and_exit(thread, stop_thread, 2)
120
121     logger.debug('Invoking user code...')
122     with Timer() as t:
123         ret = fun(*args, **kwargs)
124     logger.debug('User code took %.1fs', t())
125
126     logger.debug('Serializing results')
127     try:
128         serialized = cloudpickle.dumps(ret)
129     except Exception as e:
130         logger.exception(e)
131         logger.critical('Could not serialize result (%s). Aborting.', type(ret))
132         cleanup_and_exit(thread, stop_thread, 3)
133
134     logger.debug('Writing %s', out_file)
135     try:
136         with open(out_file, 'wb') as wb:
137             wb.write(serialized)
138     except Exception as e:
139         logger.exception(e)
140         logger.critical('Error writing %s. Aborting.', out_file)
141         cleanup_and_exit(thread, stop_thread, 4)
142     cleanup_and_exit(thread, stop_thread, 0)
143
144
145 if __name__ == '__main__':
146     main()