blob: 8954674192030b906ca5e6cf55803a54782a8ba7 [file] [log] [blame]
Neels Hofmeyrdae3d3c2017-03-28 12:16:58 +02001# osmo_gsm_tester: process management
2#
3# Copyright (C) 2016-2017 by sysmocom - s.f.m.c. GmbH
4#
5# Author: Neels Hofmeyr <neels@hofmeyr.de>
6#
7# This program is free software: you can redistribute it and/or modify
Harald Welte27205342017-06-03 09:51:45 +02008# it under the terms of the GNU General Public License as
Neels Hofmeyrdae3d3c2017-03-28 12:16:58 +02009# published by the Free Software Foundation, either version 3 of the
10# License, or (at your option) any later version.
11#
12# This program is distributed in the hope that it will be useful,
13# but WITHOUT ANY WARRANTY; without even the implied warranty of
14# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
Harald Welte27205342017-06-03 09:51:45 +020015# GNU General Public License for more details.
Neels Hofmeyrdae3d3c2017-03-28 12:16:58 +020016#
Harald Welte27205342017-06-03 09:51:45 +020017# You should have received a copy of the GNU General Public License
Neels Hofmeyrdae3d3c2017-03-28 12:16:58 +020018# along with this program. If not, see <http://www.gnu.org/licenses/>.
19
Neels Hofmeyr3531a192017-03-28 14:30:28 +020020import os
21import time
22import subprocess
23import signal
Holger Hans Peter Freyther20b52c12019-02-27 02:31:50 +000024from abc import ABCMeta, abstractmethod
Pau Espin Pedrol0d8deec2017-06-23 11:43:38 +020025from datetime import datetime
Neels Hofmeyr3531a192017-03-28 14:30:28 +020026
Pau Espin Pedrol9a4631c2018-03-28 19:17:34 +020027from . import log
28from .event_loop import MainLoop
Neels Hofmeyr3531a192017-03-28 14:30:28 +020029from .util import Dir
30
Holger Hans Peter Freyther20b52c12019-02-27 02:31:50 +000031class TerminationStrategy(log.Origin, metaclass=ABCMeta):
32 """A baseclass for terminating a collection of processes."""
33
34 def __init__(self):
35 self._processes = []
36
37 def add_process(self, process):
38 """Remembers a process that needs to be terminated."""
39 self._processes.append(process)
40
41 @abstractmethod
42 def terminate_all(self):
43 "Terminates all scheduled processes and waits for the termination."""
44 pass
45
46
47class ParallelTerminationStrategy(TerminationStrategy):
48 """Processes will be terminated in parallel."""
49
Holger Hans Peter Freyther54b4fa92019-02-27 13:00:33 +000050 def _prune_dead_processes(self, poll_first):
51 """Removes all dead processes from the list."""
52 # Remove all processes that terminated!
53 self._processes = list(filter(lambda proc: proc.is_running(poll_first), self._processes))
54
55 def _build_process_map(self):
56 """Builds a mapping from pid to process."""
57 self._process_map = {}
Holger Hans Peter Freyther20b52c12019-02-27 02:31:50 +000058 for process in self._processes:
Holger Hans Peter Freyther54b4fa92019-02-27 13:00:33 +000059 pid = process.pid()
60 if pid is None:
61 continue
62 self._process_map[pid] = process
63
64 def _poll_once(self):
65 """Polls for to be collected children once."""
66 pid, result = os.waitpid(0, os.WNOHANG)
67 # Did some other process die?
68 if pid == 0:
69 return False
70 proc = self._process_map.get(pid)
71 if proc is None:
72 self.dbg("Unknown process with pid(%d) died." % pid)
73 return False
74 # Update the process state and forget about it
75 self.log("PID %d died..." % pid)
76 proc.result = result
77 proc.cleanup()
78 self._processes.remove(proc)
79 del self._process_map[pid]
80 return True
81
82 def _poll_for_termination(self, time_to_wait_for_term=5):
83 """Waits for the termination of processes until timeout|all ended."""
84
85 wait_step = 0.001
86 waited_time = 0
87 while len(self._processes) > 0:
88 # Collect processes until there are none to be collected.
89 while True:
90 try:
91 if not self._poll_once():
92 break
93 except ChildProcessError:
94 break
95
96 # All processes died and we can return before sleeping
97 if len(self._processes) == 0:
98 break
99 waited_time += wait_step
100 # make wait_step approach 1.0
101 wait_step = (1. + 5. * wait_step) / 6.
102 if waited_time >= time_to_wait_for_term:
103 break
104 time.sleep(wait_step)
105
106 def terminate_all(self):
Pau Espin Pedrol04096552019-04-04 16:43:12 +0200107 num_processes = len(self._processes)
108 self.dbg("Scheduled to terminate %d processes." % num_processes)
109 if num_processes == 0:
110 return
Holger Hans Peter Freyther54b4fa92019-02-27 13:00:33 +0000111 self._prune_dead_processes(True)
112 self._build_process_map()
113
114 # Iterate through all signals.
115 for sig in [signal.SIGTERM, signal.SIGINT, signal.SIGKILL]:
116 self.dbg("Starting to kill with %s" % sig.name)
117 for process in self._processes:
118 process.kill(sig)
119 if sig == signal.SIGKILL:
120 continue
121 self._poll_for_termination()
Pau Espin Pedrol04096552019-04-04 16:43:12 +0200122 if len(self._processes) == 0:
123 return
Holger Hans Peter Freyther20b52c12019-02-27 02:31:50 +0000124
125
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200126class Process(log.Origin):
127
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200128 def __init__(self, name, run_dir, popen_args, **popen_kwargs):
Neels Hofmeyr1a7a3f02017-06-10 01:18:27 +0200129 super().__init__(log.C_RUN, name)
Pau Espin Pedrol58603672018-08-09 13:45:55 +0200130 self.process_obj = None
131 self.result = None
132 self.killed = None
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200133 self.name_str = name
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200134 self.run_dir = run_dir
135 self.popen_args = popen_args
136 self.popen_kwargs = popen_kwargs
137 self.outputs = {}
138 if not isinstance(self.run_dir, Dir):
139 self.run_dir = Dir(os.path.abspath(str(self.run_dir)))
140
141 def set_env(self, key, value):
142 env = self.popen_kwargs.get('env') or {}
143 env[key] = value
144 self.popen_kwargs['env'] = env
145
146 def make_output_log(self, name):
147 '''
148 create a non-existing log output file in run_dir to pipe stdout and
149 stderr from this process to.
150 '''
151 path = self.run_dir.new_child(name)
152 f = open(path, 'w')
153 self.dbg(path)
Pau Espin Pedrol0d8deec2017-06-23 11:43:38 +0200154 f.write('(launched: %s)\n' % datetime.now().strftime(log.LONG_DATEFMT))
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200155 f.flush()
156 self.outputs[name] = (path, f)
157 return f
158
159 def launch(self):
Pau Espin Pedrol3a479c22019-04-05 19:47:40 +0200160 preexec_fn = None
Neels Hofmeyr1a7a3f02017-06-10 01:18:27 +0200161 log.dbg('cd %r; %s %s' % (
162 os.path.abspath(str(self.run_dir)),
163 ' '.join(['%s=%r'%(k,v) for k,v in self.popen_kwargs.get('env', {}).items()]),
164 ' '.join(self.popen_args)))
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200165
Pau Espin Pedrol3a479c22019-04-05 19:47:40 +0200166 if self.popen_args[0] == "sudo":
167 # sudo drops forwarding of signals sent by processes of the same
168 # process group, which means by default will drop signals from
169 # parent and children processes. By moving it to another group, we
170 # will later be able to kill it.
171 # Note: sudo documentation is wrong, since it states it only drops
172 # signals from children.
173 preexec_fn = os.setpgrp
174
Neels Hofmeyr1a7a3f02017-06-10 01:18:27 +0200175 self.process_obj = subprocess.Popen(
176 self.popen_args,
177 stdout=self.make_output_log('stdout'),
178 stderr=self.make_output_log('stderr'),
179 stdin=subprocess.PIPE,
Pau Espin Pedrol3a479c22019-04-05 19:47:40 +0200180 preexec_fn=preexec_fn,
Neels Hofmeyr1a7a3f02017-06-10 01:18:27 +0200181 shell=False,
182 cwd=self.run_dir.path,
183 **self.popen_kwargs)
184 self.set_name(self.name_str, pid=self.process_obj.pid)
185 self.log('Launched')
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200186
Pau Espin Pedrol78087be2018-11-12 18:20:52 +0100187 def launch_sync(self, raise_nonsuccess=True):
Pau Espin Pedrol79df7392018-11-12 18:15:30 +0100188 '''
189 calls launch() method and block waiting for it to finish, serving the
190 mainloop meanwhile.
191 '''
192 try:
193 self.launch()
194 self.wait()
195 except Exception as e:
196 self.terminate()
197 raise e
Pau Espin Pedrol78087be2018-11-12 18:20:52 +0100198 if raise_nonsuccess and self.result != 0:
Pau Espin Pedrol7e30d842020-06-04 16:23:46 +0200199 raise self.RunError('launch_sync()')
Pau Espin Pedrol78087be2018-11-12 18:20:52 +0100200 return self.result
Pau Espin Pedrol79df7392018-11-12 18:15:30 +0100201
Pau Espin Pedrolb1526b92018-05-22 20:32:30 +0200202 def respawn(self):
203 self.dbg('respawn')
204 assert not self.is_running()
205 self.result = None
206 self.killed = None
Pau Espin Pedrol922ce5a2019-09-10 13:44:20 +0200207 return self.launch()
Pau Espin Pedrolb1526b92018-05-22 20:32:30 +0200208
Pau Espin Pedroldd7bb2c2019-09-10 13:44:39 +0200209 def respawn_sync(self, raise_nonsuccess=True):
210 self.dbg('respawn_sync')
211 assert not self.is_running()
212 self.result = None
213 self.killed = None
214 return self.launch_sync(raise_nonsuccess)
215
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200216 def _poll_termination(self, time_to_wait_for_term=5):
217 wait_step = 0.001
218 waited_time = 0
219 while True:
220 # poll returns None if proc is still running
221 self.result = self.process_obj.poll()
222 if self.result is not None:
223 return True
224 waited_time += wait_step
225 # make wait_step approach 1.0
226 wait_step = (1. + 5. * wait_step) / 6.
227 if waited_time >= time_to_wait_for_term:
228 break
229 time.sleep(wait_step)
230 return False
231
Pau Espin Pedrolfd4c1442018-10-25 17:37:23 +0200232 def send_signal(self, sig):
233 os.kill(self.process_obj.pid, sig)
234
Holger Hans Peter Freyther54b4fa92019-02-27 13:00:33 +0000235 def pid(self):
236 if self.process_obj is None:
237 return None
238 return self.process_obj.pid
239
Holger Hans Peter Freyther0d714c92019-02-27 09:50:52 +0000240 def kill(self, sig):
241 """Kills the process with the given signal and remembers it."""
242 self.log('Terminating (%s)' % sig.name)
243 self.send_signal(sig)
244 self.killed = sig
245
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200246 def terminate(self):
247 if self.process_obj is None:
248 return
249 if self.result is not None:
250 return
251
252 while True:
253 # first try SIGINT to allow stdout+stderr flushing
Holger Hans Peter Freyther0d714c92019-02-27 09:50:52 +0000254 self.kill(signal.SIGINT)
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200255 if self._poll_termination():
256 break
257
258 # SIGTERM maybe?
Holger Hans Peter Freyther0d714c92019-02-27 09:50:52 +0000259 self.kill(signal.SIGTERM)
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200260 if self._poll_termination():
261 break
262
263 # out of patience
Holger Hans Peter Freyther0d714c92019-02-27 09:50:52 +0000264 self.kill(signal.SIGKILL)
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200265 break;
266
267 self.process_obj.wait()
268 self.cleanup()
269
270 def cleanup(self):
Pau Espin Pedrol06ada452018-05-22 19:20:41 +0200271 self.dbg('Cleanup')
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200272 self.close_output_logs()
273 if self.result == 0:
274 self.log('Terminated: ok', rc=self.result)
275 elif self.killed:
276 self.log('Terminated', rc=self.result)
277 else:
278 self.err('Terminated: ERROR', rc=self.result)
Pau Espin Pedrol9dbdb622020-05-25 16:45:34 +0200279 self.log_stdout_tail()
Neels Hofmeyr85eb3242017-04-09 22:01:16 +0200280 self.log_stderr_tail()
281
282 def log_stdout_tail(self):
283 m = self.get_stdout_tail(prefix='| ')
284 if not m:
285 return
286 self.log('stdout:\n', m, '\n')
287
288 def log_stderr_tail(self):
289 m = self.get_stderr_tail(prefix='| ')
290 if not m:
291 return
292 self.log('stderr:\n', m, '\n')
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200293
294 def close_output_logs(self):
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200295 for k, v in self.outputs.items():
296 path, f = v
297 if f:
298 f.flush()
299 f.close()
300 self.outputs[k] = (path, None)
301
302 def poll(self):
303 if self.process_obj is None:
304 return
305 if self.result is not None:
306 return
307 self.result = self.process_obj.poll()
308 if self.result is not None:
309 self.cleanup()
310
Neels Hofmeyr5356d0a2017-04-10 03:45:30 +0200311 def is_running(self, poll_first=True):
312 if poll_first:
313 self.poll()
Neels Hofmeyr85eb3242017-04-09 22:01:16 +0200314 return self.process_obj is not None and self.result is None
315
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200316 def get_output(self, which):
317 v = self.outputs.get(which)
318 if not v:
319 return None
320 path, f = v
321 with open(path, 'r') as f2:
322 return f2.read()
323
324 def get_output_tail(self, which, tail=10, prefix=''):
Neels Hofmeyr5356d0a2017-04-10 03:45:30 +0200325 out = self.get_output(which)
326 if not out:
327 return None
328 out = out.splitlines()
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200329 tail = min(len(out), tail)
Neels Hofmeyr5356d0a2017-04-10 03:45:30 +0200330 return prefix + ('\n' + prefix).join(out[-tail:])
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200331
332 def get_stdout(self):
333 return self.get_output('stdout')
334
335 def get_stderr(self):
336 return self.get_output('stderr')
337
338 def get_stdout_tail(self, tail=10, prefix=''):
339 return self.get_output_tail('stdout', tail, prefix)
340
341 def get_stderr_tail(self, tail=10, prefix=''):
342 return self.get_output_tail('stderr', tail, prefix)
343
Neels Hofmeyr5356d0a2017-04-10 03:45:30 +0200344 def terminated(self, poll_first=True):
345 if poll_first:
346 self.poll()
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200347 return self.result is not None
348
Neels Hofmeyr5356d0a2017-04-10 03:45:30 +0200349 def wait(self, timeout=300):
Pau Espin Pedrol664e3832020-06-10 19:30:33 +0200350 MainLoop.wait(self.terminated, timeout=timeout)
Neels Hofmeyrdae3d3c2017-03-28 12:16:58 +0200351
Andre Puschmann66272f82020-03-21 21:01:31 +0100352 def stdin_write(self, cmd):
353 '''
354 Send a cmd to the stdin of a process (convert to byte before)
355 '''
356 if self.process_obj.stdin is not None:
357 self.process_obj.stdin.write(cmd.encode("utf-8"))
358 self.process_obj.stdin.flush()
Neels Hofmeyrdae3d3c2017-03-28 12:16:58 +0200359
Pau Espin Pedrol7e30d842020-06-04 16:23:46 +0200360 def RunError(self, msg_prefix):
361 'Get a log.Error filled in with Result information. Use when program is terminated and result !=0'
362 msg = '%s: local process exited with status %d' % (msg_prefix, self.result)
363 return log.Error(msg)
364
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200365class RemoteProcess(Process):
366
Pau Espin Pedrolf6d45ad2020-02-11 14:39:15 +0100367 def __init__(self, name, run_dir, remote_user, remote_host, remote_cwd, popen_args, remote_env={}, **popen_kwargs):
Neels Hofmeyr5356d0a2017-04-10 03:45:30 +0200368 super().__init__(name, run_dir, popen_args, **popen_kwargs)
Pau Espin Pedrol3895fec2017-04-28 16:13:03 +0200369 self.remote_user = remote_user
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200370 self.remote_host = remote_host
371 self.remote_cwd = remote_cwd
Pau Espin Pedrolf6d45ad2020-02-11 14:39:15 +0100372 self.remote_env = remote_env
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200373
374 # hacky: instead of just prepending ssh, i.e. piping stdout and stderr
375 # over the ssh link, we should probably run on the remote side,
376 # monitoring the process remotely.
Neels Hofmeyr5356d0a2017-04-10 03:45:30 +0200377 if self.remote_cwd:
Pau Espin Pedrolf6d45ad2020-02-11 14:39:15 +0100378 cd = 'cd "%s";' % self.remote_cwd
Neels Hofmeyr5356d0a2017-04-10 03:45:30 +0200379 else:
380 cd = ''
Pau Espin Pedrol302c7562018-10-02 13:08:02 +0200381 # We need double -t to force tty and be able to forward signals to
382 # processes (SIGHUP) when we close ssh on the local side. As a result,
383 # stderr seems to be merged into stdout in ssh client.
384 self.popen_args = ['ssh', '-t', '-t', self.remote_user+'@'+self.remote_host,
Pau Espin Pedrolf6d45ad2020-02-11 14:39:15 +0100385 '%s %s %s' % (cd,
386 ' '.join(['%s=%r'%(k,v) for k,v in self.remote_env.items()]),
387 ' '.join(self.popen_args))]
388 self.dbg(self.popen_args, dir=self.run_dir, conf=self.popen_kwargs, remote_env=self.remote_env)
Neels Hofmeyrdae3d3c2017-03-28 12:16:58 +0200389
Pau Espin Pedrol7e30d842020-06-04 16:23:46 +0200390 def RunError(self, msg_prefix):
391 'Overwrite Process method with ssh extra information'
392 # man ssh states it returns 255 if an ssh error occurred:
393 msg = msg_prefix + ': '
394 if self.result == 255:
395 tail = ' (' + (self.get_stderr_tail(tail=1, prefix='') or '').rstrip() + ')'
396 msg += 'local ssh process exited with status %d%s' % (self.result, tail if 'ssh' in tail else '')
397 else:
398 msg += 'remote process exited with status %d' % (self.result)
399 return log.Error(msg)
400
Pau Espin Pedrolfd4c1442018-10-25 17:37:23 +0200401class NetNSProcess(Process):
402 NETNS_EXEC_BIN = 'osmo-gsm-tester_netns_exec.sh'
403 def __init__(self, name, run_dir, netns, popen_args, **popen_kwargs):
404 super().__init__(name, run_dir, popen_args, **popen_kwargs)
405 self.netns = netns
406
407 self.popen_args = ['sudo', self.NETNS_EXEC_BIN, self.netns] + list(popen_args)
408 self.dbg(self.popen_args, dir=self.run_dir, conf=self.popen_kwargs)
409
410 # HACK: Since we run under sudo, only way to kill root-owned process is to kill as root...
411 # This function is overwritten from Process.
412 def send_signal(self, sig):
Pau Espin Pedrole159cd22019-04-03 17:53:54 +0200413 if sig == signal.SIGKILL:
414 # if we kill sudo, its children (bash running NETNS_EXEC_BIN +
415 # tcpdump under it) are kept alive. Let's instead tell the script to
416 # kill tcpdump:
417 sig = signal.SIGUSR1
Pau Espin Pedrolfd4c1442018-10-25 17:37:23 +0200418 kill_cmd = ('kill', '-%d' % int(sig), str(self.process_obj.pid))
Pau Espin Pedrol17a4ed92019-04-03 17:10:31 +0200419 run_local_netns_sync(self.run_dir, self.name()+"-kill"+str(sig), self.netns, kill_cmd)
Pau Espin Pedrolfd4c1442018-10-25 17:37:23 +0200420
Pau Espin Pedrol14022d32020-02-11 14:20:00 +0100421class RemoteNetNSProcess(RemoteProcess):
422 NETNS_EXEC_BIN = 'osmo-gsm-tester_netns_exec.sh'
423 def __init__(self, name, run_dir, remote_user, remote_host, remote_cwd, netns, popen_args, **popen_kwargs):
Pau Espin Pedrol4983eb52020-02-11 19:16:06 +0100424 self.netns = netns
Pau Espin Pedrol14022d32020-02-11 14:20:00 +0100425 args = ['sudo', self.NETNS_EXEC_BIN, self.netns] + list(popen_args)
426 super().__init__(name, run_dir, remote_user, remote_host, remote_cwd, args, **popen_kwargs)
Pau Espin Pedrolfd4c1442018-10-25 17:37:23 +0200427
Pau Espin Pedrole4358a92018-10-01 11:27:55 +0200428def run_local_sync(run_dir, name, popen_args):
429 run_dir =run_dir.new_dir(name)
430 proc = Process(name, run_dir, popen_args)
Pau Espin Pedrol79df7392018-11-12 18:15:30 +0100431 proc.launch_sync()
Pau Espin Pedrol12c5ea42019-11-26 14:25:33 +0100432 return proc
Pau Espin Pedrole4358a92018-10-01 11:27:55 +0200433
Pau Espin Pedrolfd4c1442018-10-25 17:37:23 +0200434def run_local_netns_sync(run_dir, name, netns, popen_args):
435 run_dir =run_dir.new_dir(name)
436 proc = NetNSProcess(name, run_dir, netns, popen_args)
Pau Espin Pedrol79df7392018-11-12 18:15:30 +0100437 proc.launch_sync()
Pau Espin Pedrol12c5ea42019-11-26 14:25:33 +0100438 return proc
Neels Hofmeyrdae3d3c2017-03-28 12:16:58 +0200439# vim: expandtab tabstop=4 shiftwidth=4