Start using warnings from stdlib.
[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 platform
10 import signal
11 import threading
12 import sys
13 import time
14
15 import cloudpickle  # type: ignore
16 import psutil  # type: ignore
17
18 import argparse_utils
19 import bootstrap
20 import config
21 from thread_utils import background_thread
22
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=False,
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(f'Ancestor process {name} (pid={pid})')
63             if 'ssh' in name.lower():
64                 saw_sshd = True
65                 break
66         if not saw_sshd:
67             logger.error('Did not see sshd in our ancestors list?!  Committing suicide.')
68             os.system('pstree')
69             os.kill(os.getpid(), signal.SIGTERM)
70             time.sleep(5.0)
71             os.kill(os.getpid(), signal.SIGKILL)
72             sys.exit(-1)
73         if terminate_event.is_set():
74             return
75         time.sleep(1.0)
76
77
78 @bootstrap.initialize
79 def main() -> None:
80     in_file = config.config['code_file']
81     out_file = config.config['result_file']
82
83     stop_thread = None
84     if config.config['watch_for_cancel']:
85         (thread, stop_thread) = watch_for_cancel()
86
87     logger.debug(f'Reading {in_file}.')
88     try:
89         with open(in_file, 'rb') as rb:
90             serialized = rb.read()
91     except Exception as e:
92         logger.exception(e)
93         logger.critical(f'Problem reading {in_file}.  Aborting.')
94         stop_thread.set()
95         sys.exit(-1)
96
97     logger.debug(f'Deserializing {in_file}.')
98     try:
99         fun, args, kwargs = cloudpickle.loads(serialized)
100     except Exception as e:
101         logger.exception(e)
102         logger.critical(f'Problem deserializing {in_file}.  Aborting.')
103         stop_thread.set()
104         sys.exit(-1)
105
106     logger.debug('Invoking user code...')
107     start = time.time()
108     ret = fun(*args, **kwargs)
109     end = time.time()
110     logger.debug(f'User code took {end - start:.1f}s')
111
112     logger.debug('Serializing results')
113     try:
114         serialized = cloudpickle.dumps(ret)
115     except Exception as e:
116         logger.exception(e)
117         logger.critical(f'Could not serialize result ({type(ret)}).  Aborting.')
118         stop_thread.set()
119         sys.exit(-1)
120
121     logger.debug(f'Writing {out_file}.')
122     try:
123         with open(out_file, 'wb') as wb:
124             wb.write(serialized)
125     except Exception as e:
126         logger.exception(e)
127         logger.critical(f'Error writing {out_file}.  Aborting.')
128         stop_thread.set()
129         sys.exit(-1)
130
131     if stop_thread is not None:
132         stop_thread.set()
133         thread.join()
134
135
136 if __name__ == '__main__':
137     main()