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