blob: ef6bca1dcb39f065b48728f3ab97d0f1fc6fd083 [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
353
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200354class RemoteProcess(Process):
355
Pau Espin Pedrol3895fec2017-04-28 16:13:03 +0200356 def __init__(self, name, run_dir, remote_user, remote_host, remote_cwd, popen_args, **popen_kwargs):
Neels Hofmeyr5356d0a2017-04-10 03:45:30 +0200357 super().__init__(name, run_dir, popen_args, **popen_kwargs)
Pau Espin Pedrol3895fec2017-04-28 16:13:03 +0200358 self.remote_user = remote_user
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200359 self.remote_host = remote_host
360 self.remote_cwd = remote_cwd
361
362 # hacky: instead of just prepending ssh, i.e. piping stdout and stderr
363 # over the ssh link, we should probably run on the remote side,
364 # monitoring the process remotely.
Neels Hofmeyr5356d0a2017-04-10 03:45:30 +0200365 if self.remote_cwd:
366 cd = 'cd "%s"; ' % self.remote_cwd
367 else:
368 cd = ''
Pau Espin Pedrol302c7562018-10-02 13:08:02 +0200369 # We need double -t to force tty and be able to forward signals to
370 # processes (SIGHUP) when we close ssh on the local side. As a result,
371 # stderr seems to be merged into stdout in ssh client.
372 self.popen_args = ['ssh', '-t', '-t', self.remote_user+'@'+self.remote_host,
Neels Hofmeyr5356d0a2017-04-10 03:45:30 +0200373 '%s%s' % (cd,
374 ' '.join(self.popen_args))]
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200375 self.dbg(self.popen_args, dir=self.run_dir, conf=self.popen_kwargs)
Neels Hofmeyrdae3d3c2017-03-28 12:16:58 +0200376
Pau Espin Pedrolfd4c1442018-10-25 17:37:23 +0200377class NetNSProcess(Process):
378 NETNS_EXEC_BIN = 'osmo-gsm-tester_netns_exec.sh'
379 def __init__(self, name, run_dir, netns, popen_args, **popen_kwargs):
380 super().__init__(name, run_dir, popen_args, **popen_kwargs)
381 self.netns = netns
382
383 self.popen_args = ['sudo', self.NETNS_EXEC_BIN, self.netns] + list(popen_args)
384 self.dbg(self.popen_args, dir=self.run_dir, conf=self.popen_kwargs)
385
386 # HACK: Since we run under sudo, only way to kill root-owned process is to kill as root...
387 # This function is overwritten from Process.
388 def send_signal(self, sig):
Pau Espin Pedrole159cd22019-04-03 17:53:54 +0200389 if sig == signal.SIGKILL:
390 # if we kill sudo, its children (bash running NETNS_EXEC_BIN +
391 # tcpdump under it) are kept alive. Let's instead tell the script to
392 # kill tcpdump:
393 sig = signal.SIGUSR1
Pau Espin Pedrolfd4c1442018-10-25 17:37:23 +0200394 kill_cmd = ('kill', '-%d' % int(sig), str(self.process_obj.pid))
Pau Espin Pedrol17a4ed92019-04-03 17:10:31 +0200395 run_local_netns_sync(self.run_dir, self.name()+"-kill"+str(sig), self.netns, kill_cmd)
Pau Espin Pedrolfd4c1442018-10-25 17:37:23 +0200396
397
Pau Espin Pedrole4358a92018-10-01 11:27:55 +0200398def run_local_sync(run_dir, name, popen_args):
399 run_dir =run_dir.new_dir(name)
400 proc = Process(name, run_dir, popen_args)
Pau Espin Pedrol79df7392018-11-12 18:15:30 +0100401 proc.launch_sync()
Pau Espin Pedrol12c5ea42019-11-26 14:25:33 +0100402 return proc
Pau Espin Pedrole4358a92018-10-01 11:27:55 +0200403
Pau Espin Pedrolfd4c1442018-10-25 17:37:23 +0200404def run_local_netns_sync(run_dir, name, netns, popen_args):
405 run_dir =run_dir.new_dir(name)
406 proc = NetNSProcess(name, run_dir, netns, popen_args)
Pau Espin Pedrol79df7392018-11-12 18:15:30 +0100407 proc.launch_sync()
Pau Espin Pedrol12c5ea42019-11-26 14:25:33 +0100408 return proc
Pau Espin Pedrolfd4c1442018-10-25 17:37:23 +0200409
Pau Espin Pedrole4358a92018-10-01 11:27:55 +0200410def run_remote_sync(run_dir, remote_user, remote_addr, name, popen_args, remote_cwd=None):
411 run_dir = run_dir.new_dir(name)
Pau Espin Pedrol8aca1f32018-10-25 18:31:50 +0200412 proc = RemoteProcess(name, run_dir, remote_user, remote_addr, remote_cwd, popen_args)
Pau Espin Pedrol79df7392018-11-12 18:15:30 +0100413 proc.launch_sync()
Pau Espin Pedrol12c5ea42019-11-26 14:25:33 +0100414 return proc
Pau Espin Pedrole4358a92018-10-01 11:27:55 +0200415
416def scp(run_dir, remote_user, remote_addr, name, local_path, remote_path):
417 run_local_sync(run_dir, name, ('scp', '-r', local_path, '%s@%s:%s' % (remote_user, remote_addr, remote_path)))
418
419def copy_inst_ssh(run_dir, inst, remote_dir, remote_user, remote_addr, remote_rundir_append, cfg_file_name):
420 remote_inst = Dir(remote_dir.child(os.path.basename(str(inst))))
421 remote_dir_str = str(remote_dir)
422 run_remote_sync(run_dir, remote_user, remote_addr, 'rm-remote-dir', ('test', '!', '-d', remote_dir_str, '||', 'rm', '-rf', remote_dir_str))
423 run_remote_sync(run_dir, remote_user, remote_addr, 'mk-remote-dir', ('mkdir', '-p', remote_dir_str))
424 scp(run_dir, remote_user, remote_addr, 'scp-inst-to-remote', str(inst), remote_dir_str)
425
426 remote_run_dir = remote_dir.child(remote_rundir_append)
427 run_remote_sync(run_dir, remote_user, remote_addr, 'mk-remote-run-dir', ('mkdir', '-p', remote_run_dir))
428
429 remote_config_file = remote_dir.child(os.path.basename(cfg_file_name))
430 scp(run_dir, remote_user, remote_addr, 'scp-cfg-to-remote', cfg_file_name, remote_config_file)
431 return remote_inst
432
Neels Hofmeyrdae3d3c2017-03-28 12:16:58 +0200433# vim: expandtab tabstop=4 shiftwidth=4