blob: 5d02ab578ebced71827af7ec919388302a49a46a [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 Pedrol79df7392018-11-12 18:15:30 +0100199 log.ctx(self)
Pau Espin Pedrol78087be2018-11-12 18:20:52 +0100200 raise log.Error('Exited in error %d' % self.result)
201 return self.result
Pau Espin Pedrol79df7392018-11-12 18:15:30 +0100202
Pau Espin Pedrolb1526b92018-05-22 20:32:30 +0200203 def respawn(self):
204 self.dbg('respawn')
205 assert not self.is_running()
206 self.result = None
207 self.killed = None
Pau Espin Pedrol922ce5a2019-09-10 13:44:20 +0200208 return self.launch()
Pau Espin Pedrolb1526b92018-05-22 20:32:30 +0200209
Pau Espin Pedroldd7bb2c2019-09-10 13:44:39 +0200210 def respawn_sync(self, raise_nonsuccess=True):
211 self.dbg('respawn_sync')
212 assert not self.is_running()
213 self.result = None
214 self.killed = None
215 return self.launch_sync(raise_nonsuccess)
216
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200217 def _poll_termination(self, time_to_wait_for_term=5):
218 wait_step = 0.001
219 waited_time = 0
220 while True:
221 # poll returns None if proc is still running
222 self.result = self.process_obj.poll()
223 if self.result is not None:
224 return True
225 waited_time += wait_step
226 # make wait_step approach 1.0
227 wait_step = (1. + 5. * wait_step) / 6.
228 if waited_time >= time_to_wait_for_term:
229 break
230 time.sleep(wait_step)
231 return False
232
Pau Espin Pedrolfd4c1442018-10-25 17:37:23 +0200233 def send_signal(self, sig):
234 os.kill(self.process_obj.pid, sig)
235
Holger Hans Peter Freyther54b4fa92019-02-27 13:00:33 +0000236 def pid(self):
237 if self.process_obj is None:
238 return None
239 return self.process_obj.pid
240
Holger Hans Peter Freyther0d714c92019-02-27 09:50:52 +0000241 def kill(self, sig):
242 """Kills the process with the given signal and remembers it."""
243 self.log('Terminating (%s)' % sig.name)
244 self.send_signal(sig)
245 self.killed = sig
246
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200247 def terminate(self):
248 if self.process_obj is None:
249 return
250 if self.result is not None:
251 return
252
253 while True:
254 # first try SIGINT to allow stdout+stderr flushing
Holger Hans Peter Freyther0d714c92019-02-27 09:50:52 +0000255 self.kill(signal.SIGINT)
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200256 if self._poll_termination():
257 break
258
259 # SIGTERM maybe?
Holger Hans Peter Freyther0d714c92019-02-27 09:50:52 +0000260 self.kill(signal.SIGTERM)
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200261 if self._poll_termination():
262 break
263
264 # out of patience
Holger Hans Peter Freyther0d714c92019-02-27 09:50:52 +0000265 self.kill(signal.SIGKILL)
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200266 break;
267
268 self.process_obj.wait()
269 self.cleanup()
270
271 def cleanup(self):
Pau Espin Pedrol06ada452018-05-22 19:20:41 +0200272 self.dbg('Cleanup')
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200273 self.close_output_logs()
274 if self.result == 0:
275 self.log('Terminated: ok', rc=self.result)
276 elif self.killed:
277 self.log('Terminated', rc=self.result)
278 else:
279 self.err('Terminated: ERROR', rc=self.result)
Neels Hofmeyr85eb3242017-04-09 22:01:16 +0200280 #self.log_stdout_tail()
281 self.log_stderr_tail()
282
283 def log_stdout_tail(self):
284 m = self.get_stdout_tail(prefix='| ')
285 if not m:
286 return
287 self.log('stdout:\n', m, '\n')
288
289 def log_stderr_tail(self):
290 m = self.get_stderr_tail(prefix='| ')
291 if not m:
292 return
293 self.log('stderr:\n', m, '\n')
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200294
295 def close_output_logs(self):
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200296 for k, v in self.outputs.items():
297 path, f = v
298 if f:
299 f.flush()
300 f.close()
301 self.outputs[k] = (path, None)
302
303 def poll(self):
304 if self.process_obj is None:
305 return
306 if self.result is not None:
307 return
308 self.result = self.process_obj.poll()
309 if self.result is not None:
310 self.cleanup()
311
Neels Hofmeyr5356d0a2017-04-10 03:45:30 +0200312 def is_running(self, poll_first=True):
313 if poll_first:
314 self.poll()
Neels Hofmeyr85eb3242017-04-09 22:01:16 +0200315 return self.process_obj is not None and self.result is None
316
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200317 def get_output(self, which):
318 v = self.outputs.get(which)
319 if not v:
320 return None
321 path, f = v
322 with open(path, 'r') as f2:
323 return f2.read()
324
325 def get_output_tail(self, which, tail=10, prefix=''):
Neels Hofmeyr5356d0a2017-04-10 03:45:30 +0200326 out = self.get_output(which)
327 if not out:
328 return None
329 out = out.splitlines()
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200330 tail = min(len(out), tail)
Neels Hofmeyr5356d0a2017-04-10 03:45:30 +0200331 return prefix + ('\n' + prefix).join(out[-tail:])
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200332
333 def get_stdout(self):
334 return self.get_output('stdout')
335
336 def get_stderr(self):
337 return self.get_output('stderr')
338
339 def get_stdout_tail(self, tail=10, prefix=''):
340 return self.get_output_tail('stdout', tail, prefix)
341
342 def get_stderr_tail(self, tail=10, prefix=''):
343 return self.get_output_tail('stderr', tail, prefix)
344
Neels Hofmeyr5356d0a2017-04-10 03:45:30 +0200345 def terminated(self, poll_first=True):
346 if poll_first:
347 self.poll()
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200348 return self.result is not None
349
Neels Hofmeyr5356d0a2017-04-10 03:45:30 +0200350 def wait(self, timeout=300):
Pau Espin Pedrol9a4631c2018-03-28 19:17:34 +0200351 MainLoop.wait(self, self.terminated, timeout=timeout)
Neels Hofmeyrdae3d3c2017-03-28 12:16:58 +0200352
Andre Puschmann66272f82020-03-21 21:01:31 +0100353 def stdin_write(self, cmd):
354 '''
355 Send a cmd to the stdin of a process (convert to byte before)
356 '''
357 if self.process_obj.stdin is not None:
358 self.process_obj.stdin.write(cmd.encode("utf-8"))
359 self.process_obj.stdin.flush()
Neels Hofmeyrdae3d3c2017-03-28 12:16:58 +0200360
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200361class RemoteProcess(Process):
362
Pau Espin Pedrolf6d45ad2020-02-11 14:39:15 +0100363 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 +0200364 super().__init__(name, run_dir, popen_args, **popen_kwargs)
Pau Espin Pedrol3895fec2017-04-28 16:13:03 +0200365 self.remote_user = remote_user
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200366 self.remote_host = remote_host
367 self.remote_cwd = remote_cwd
Pau Espin Pedrolf6d45ad2020-02-11 14:39:15 +0100368 self.remote_env = remote_env
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200369
370 # hacky: instead of just prepending ssh, i.e. piping stdout and stderr
371 # over the ssh link, we should probably run on the remote side,
372 # monitoring the process remotely.
Neels Hofmeyr5356d0a2017-04-10 03:45:30 +0200373 if self.remote_cwd:
Pau Espin Pedrolf6d45ad2020-02-11 14:39:15 +0100374 cd = 'cd "%s";' % self.remote_cwd
Neels Hofmeyr5356d0a2017-04-10 03:45:30 +0200375 else:
376 cd = ''
Pau Espin Pedrol302c7562018-10-02 13:08:02 +0200377 # We need double -t to force tty and be able to forward signals to
378 # processes (SIGHUP) when we close ssh on the local side. As a result,
379 # stderr seems to be merged into stdout in ssh client.
380 self.popen_args = ['ssh', '-t', '-t', self.remote_user+'@'+self.remote_host,
Pau Espin Pedrolf6d45ad2020-02-11 14:39:15 +0100381 '%s %s %s' % (cd,
382 ' '.join(['%s=%r'%(k,v) for k,v in self.remote_env.items()]),
383 ' '.join(self.popen_args))]
384 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 +0200385
Pau Espin Pedrolfd4c1442018-10-25 17:37:23 +0200386class NetNSProcess(Process):
387 NETNS_EXEC_BIN = 'osmo-gsm-tester_netns_exec.sh'
388 def __init__(self, name, run_dir, netns, popen_args, **popen_kwargs):
389 super().__init__(name, run_dir, popen_args, **popen_kwargs)
390 self.netns = netns
391
392 self.popen_args = ['sudo', self.NETNS_EXEC_BIN, self.netns] + list(popen_args)
393 self.dbg(self.popen_args, dir=self.run_dir, conf=self.popen_kwargs)
394
395 # HACK: Since we run under sudo, only way to kill root-owned process is to kill as root...
396 # This function is overwritten from Process.
397 def send_signal(self, sig):
Pau Espin Pedrole159cd22019-04-03 17:53:54 +0200398 if sig == signal.SIGKILL:
399 # if we kill sudo, its children (bash running NETNS_EXEC_BIN +
400 # tcpdump under it) are kept alive. Let's instead tell the script to
401 # kill tcpdump:
402 sig = signal.SIGUSR1
Pau Espin Pedrolfd4c1442018-10-25 17:37:23 +0200403 kill_cmd = ('kill', '-%d' % int(sig), str(self.process_obj.pid))
Pau Espin Pedrol17a4ed92019-04-03 17:10:31 +0200404 run_local_netns_sync(self.run_dir, self.name()+"-kill"+str(sig), self.netns, kill_cmd)
Pau Espin Pedrolfd4c1442018-10-25 17:37:23 +0200405
Pau Espin Pedrol14022d32020-02-11 14:20:00 +0100406class RemoteNetNSProcess(RemoteProcess):
407 NETNS_EXEC_BIN = 'osmo-gsm-tester_netns_exec.sh'
408 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 +0100409 self.netns = netns
Pau Espin Pedrol14022d32020-02-11 14:20:00 +0100410 args = ['sudo', self.NETNS_EXEC_BIN, self.netns] + list(popen_args)
411 super().__init__(name, run_dir, remote_user, remote_host, remote_cwd, args, **popen_kwargs)
Pau Espin Pedrolfd4c1442018-10-25 17:37:23 +0200412
Pau Espin Pedrole4358a92018-10-01 11:27:55 +0200413def run_local_sync(run_dir, name, popen_args):
414 run_dir =run_dir.new_dir(name)
415 proc = Process(name, run_dir, popen_args)
Pau Espin Pedrol79df7392018-11-12 18:15:30 +0100416 proc.launch_sync()
Pau Espin Pedrol12c5ea42019-11-26 14:25:33 +0100417 return proc
Pau Espin Pedrole4358a92018-10-01 11:27:55 +0200418
Pau Espin Pedrolfd4c1442018-10-25 17:37:23 +0200419def run_local_netns_sync(run_dir, name, netns, popen_args):
420 run_dir =run_dir.new_dir(name)
421 proc = NetNSProcess(name, run_dir, netns, popen_args)
Pau Espin Pedrol79df7392018-11-12 18:15:30 +0100422 proc.launch_sync()
Pau Espin Pedrol12c5ea42019-11-26 14:25:33 +0100423 return proc
Neels Hofmeyrdae3d3c2017-03-28 12:16:58 +0200424# vim: expandtab tabstop=4 shiftwidth=4