Neels Hofmeyr | dae3d3c | 2017-03-28 12:16:58 +0200 | [diff] [blame] | 1 | # 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 Welte | 2720534 | 2017-06-03 09:51:45 +0200 | [diff] [blame] | 8 | # it under the terms of the GNU General Public License as |
Neels Hofmeyr | dae3d3c | 2017-03-28 12:16:58 +0200 | [diff] [blame] | 9 | # 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 Welte | 2720534 | 2017-06-03 09:51:45 +0200 | [diff] [blame] | 15 | # GNU General Public License for more details. |
Neels Hofmeyr | dae3d3c | 2017-03-28 12:16:58 +0200 | [diff] [blame] | 16 | # |
Harald Welte | 2720534 | 2017-06-03 09:51:45 +0200 | [diff] [blame] | 17 | # You should have received a copy of the GNU General Public License |
Neels Hofmeyr | dae3d3c | 2017-03-28 12:16:58 +0200 | [diff] [blame] | 18 | # along with this program. If not, see <http://www.gnu.org/licenses/>. |
| 19 | |
Neels Hofmeyr | 3531a19 | 2017-03-28 14:30:28 +0200 | [diff] [blame] | 20 | import os |
| 21 | import time |
| 22 | import subprocess |
| 23 | import signal |
Holger Hans Peter Freyther | 20b52c1 | 2019-02-27 02:31:50 +0000 | [diff] [blame] | 24 | from abc import ABCMeta, abstractmethod |
Pau Espin Pedrol | 0d8deec | 2017-06-23 11:43:38 +0200 | [diff] [blame] | 25 | from datetime import datetime |
Neels Hofmeyr | fc38393 | 2020-11-30 22:04:11 +0100 | [diff] [blame] | 26 | import re |
Neels Hofmeyr | 3531a19 | 2017-03-28 14:30:28 +0200 | [diff] [blame] | 27 | |
Pau Espin Pedrol | 9a4631c | 2018-03-28 19:17:34 +0200 | [diff] [blame] | 28 | from . import log |
| 29 | from .event_loop import MainLoop |
Neels Hofmeyr | 3531a19 | 2017-03-28 14:30:28 +0200 | [diff] [blame] | 30 | from .util import Dir |
| 31 | |
Holger Hans Peter Freyther | 20b52c1 | 2019-02-27 02:31:50 +0000 | [diff] [blame] | 32 | class TerminationStrategy(log.Origin, metaclass=ABCMeta): |
| 33 | """A baseclass for terminating a collection of processes.""" |
| 34 | |
| 35 | def __init__(self): |
| 36 | self._processes = [] |
| 37 | |
| 38 | def add_process(self, process): |
| 39 | """Remembers a process that needs to be terminated.""" |
| 40 | self._processes.append(process) |
| 41 | |
| 42 | @abstractmethod |
| 43 | def terminate_all(self): |
| 44 | "Terminates all scheduled processes and waits for the termination.""" |
| 45 | pass |
| 46 | |
| 47 | |
| 48 | class ParallelTerminationStrategy(TerminationStrategy): |
| 49 | """Processes will be terminated in parallel.""" |
| 50 | |
Holger Hans Peter Freyther | 54b4fa9 | 2019-02-27 13:00:33 +0000 | [diff] [blame] | 51 | def _prune_dead_processes(self, poll_first): |
| 52 | """Removes all dead processes from the list.""" |
| 53 | # Remove all processes that terminated! |
| 54 | self._processes = list(filter(lambda proc: proc.is_running(poll_first), self._processes)) |
| 55 | |
| 56 | def _build_process_map(self): |
| 57 | """Builds a mapping from pid to process.""" |
| 58 | self._process_map = {} |
Holger Hans Peter Freyther | 20b52c1 | 2019-02-27 02:31:50 +0000 | [diff] [blame] | 59 | for process in self._processes: |
Holger Hans Peter Freyther | 54b4fa9 | 2019-02-27 13:00:33 +0000 | [diff] [blame] | 60 | pid = process.pid() |
| 61 | if pid is None: |
| 62 | continue |
| 63 | self._process_map[pid] = process |
| 64 | |
| 65 | def _poll_once(self): |
| 66 | """Polls for to be collected children once.""" |
| 67 | pid, result = os.waitpid(0, os.WNOHANG) |
| 68 | # Did some other process die? |
| 69 | if pid == 0: |
| 70 | return False |
| 71 | proc = self._process_map.get(pid) |
| 72 | if proc is None: |
| 73 | self.dbg("Unknown process with pid(%d) died." % pid) |
| 74 | return False |
| 75 | # Update the process state and forget about it |
| 76 | self.log("PID %d died..." % pid) |
| 77 | proc.result = result |
| 78 | proc.cleanup() |
| 79 | self._processes.remove(proc) |
| 80 | del self._process_map[pid] |
| 81 | return True |
| 82 | |
| 83 | def _poll_for_termination(self, time_to_wait_for_term=5): |
| 84 | """Waits for the termination of processes until timeout|all ended.""" |
| 85 | |
| 86 | wait_step = 0.001 |
| 87 | waited_time = 0 |
| 88 | while len(self._processes) > 0: |
| 89 | # Collect processes until there are none to be collected. |
| 90 | while True: |
| 91 | try: |
| 92 | if not self._poll_once(): |
| 93 | break |
| 94 | except ChildProcessError: |
| 95 | break |
| 96 | |
| 97 | # All processes died and we can return before sleeping |
| 98 | if len(self._processes) == 0: |
| 99 | break |
| 100 | waited_time += wait_step |
| 101 | # make wait_step approach 1.0 |
| 102 | wait_step = (1. + 5. * wait_step) / 6. |
| 103 | if waited_time >= time_to_wait_for_term: |
| 104 | break |
| 105 | time.sleep(wait_step) |
| 106 | |
| 107 | def terminate_all(self): |
Pau Espin Pedrol | 0409655 | 2019-04-04 16:43:12 +0200 | [diff] [blame] | 108 | num_processes = len(self._processes) |
| 109 | self.dbg("Scheduled to terminate %d processes." % num_processes) |
| 110 | if num_processes == 0: |
| 111 | return |
Holger Hans Peter Freyther | 54b4fa9 | 2019-02-27 13:00:33 +0000 | [diff] [blame] | 112 | self._prune_dead_processes(True) |
| 113 | self._build_process_map() |
| 114 | |
| 115 | # Iterate through all signals. |
| 116 | for sig in [signal.SIGTERM, signal.SIGINT, signal.SIGKILL]: |
| 117 | self.dbg("Starting to kill with %s" % sig.name) |
| 118 | for process in self._processes: |
| 119 | process.kill(sig) |
| 120 | if sig == signal.SIGKILL: |
| 121 | continue |
| 122 | self._poll_for_termination() |
Pau Espin Pedrol | 0409655 | 2019-04-04 16:43:12 +0200 | [diff] [blame] | 123 | if len(self._processes) == 0: |
| 124 | return |
Holger Hans Peter Freyther | 20b52c1 | 2019-02-27 02:31:50 +0000 | [diff] [blame] | 125 | |
| 126 | |
Neels Hofmeyr | 3531a19 | 2017-03-28 14:30:28 +0200 | [diff] [blame] | 127 | class Process(log.Origin): |
| 128 | |
Pau Espin Pedrol | a9bc93d | 2020-06-12 15:34:28 +0200 | [diff] [blame] | 129 | DEFAULT_WAIT_TIMEOUT = 300 # seconds |
| 130 | |
Neels Hofmeyr | 3531a19 | 2017-03-28 14:30:28 +0200 | [diff] [blame] | 131 | def __init__(self, name, run_dir, popen_args, **popen_kwargs): |
Neels Hofmeyr | 1a7a3f0 | 2017-06-10 01:18:27 +0200 | [diff] [blame] | 132 | super().__init__(log.C_RUN, name) |
Pau Espin Pedrol | 5860367 | 2018-08-09 13:45:55 +0200 | [diff] [blame] | 133 | self.process_obj = None |
| 134 | self.result = None |
| 135 | self.killed = None |
Pau Espin Pedrol | a9bc93d | 2020-06-12 15:34:28 +0200 | [diff] [blame] | 136 | self.default_wait_timeout = Process.DEFAULT_WAIT_TIMEOUT |
Neels Hofmeyr | 3531a19 | 2017-03-28 14:30:28 +0200 | [diff] [blame] | 137 | self.name_str = name |
Neels Hofmeyr | 3531a19 | 2017-03-28 14:30:28 +0200 | [diff] [blame] | 138 | self.run_dir = run_dir |
| 139 | self.popen_args = popen_args |
| 140 | self.popen_kwargs = popen_kwargs |
| 141 | self.outputs = {} |
| 142 | if not isinstance(self.run_dir, Dir): |
| 143 | self.run_dir = Dir(os.path.abspath(str(self.run_dir))) |
| 144 | |
| 145 | def set_env(self, key, value): |
| 146 | env = self.popen_kwargs.get('env') or {} |
| 147 | env[key] = value |
| 148 | self.popen_kwargs['env'] = env |
| 149 | |
Pau Espin Pedrol | a9bc93d | 2020-06-12 15:34:28 +0200 | [diff] [blame] | 150 | def set_default_wait_timeout(self, timeout): |
| 151 | assert timeout |
| 152 | self.default_wait_timeout = timeout |
| 153 | |
Neels Hofmeyr | 3531a19 | 2017-03-28 14:30:28 +0200 | [diff] [blame] | 154 | def make_output_log(self, name): |
| 155 | ''' |
| 156 | create a non-existing log output file in run_dir to pipe stdout and |
| 157 | stderr from this process to. |
| 158 | ''' |
| 159 | path = self.run_dir.new_child(name) |
| 160 | f = open(path, 'w') |
| 161 | self.dbg(path) |
Pau Espin Pedrol | 0d8deec | 2017-06-23 11:43:38 +0200 | [diff] [blame] | 162 | f.write('(launched: %s)\n' % datetime.now().strftime(log.LONG_DATEFMT)) |
Neels Hofmeyr | 3531a19 | 2017-03-28 14:30:28 +0200 | [diff] [blame] | 163 | f.flush() |
| 164 | self.outputs[name] = (path, f) |
| 165 | return f |
| 166 | |
| 167 | def launch(self): |
Pau Espin Pedrol | 3a479c2 | 2019-04-05 19:47:40 +0200 | [diff] [blame] | 168 | preexec_fn = None |
Neels Hofmeyr | 1a7a3f0 | 2017-06-10 01:18:27 +0200 | [diff] [blame] | 169 | log.dbg('cd %r; %s %s' % ( |
| 170 | os.path.abspath(str(self.run_dir)), |
| 171 | ' '.join(['%s=%r'%(k,v) for k,v in self.popen_kwargs.get('env', {}).items()]), |
| 172 | ' '.join(self.popen_args))) |
Neels Hofmeyr | 3531a19 | 2017-03-28 14:30:28 +0200 | [diff] [blame] | 173 | |
Pau Espin Pedrol | 3a479c2 | 2019-04-05 19:47:40 +0200 | [diff] [blame] | 174 | if self.popen_args[0] == "sudo": |
| 175 | # sudo drops forwarding of signals sent by processes of the same |
| 176 | # process group, which means by default will drop signals from |
| 177 | # parent and children processes. By moving it to another group, we |
| 178 | # will later be able to kill it. |
| 179 | # Note: sudo documentation is wrong, since it states it only drops |
| 180 | # signals from children. |
| 181 | preexec_fn = os.setpgrp |
| 182 | |
Neels Hofmeyr | 1a7a3f0 | 2017-06-10 01:18:27 +0200 | [diff] [blame] | 183 | self.process_obj = subprocess.Popen( |
| 184 | self.popen_args, |
| 185 | stdout=self.make_output_log('stdout'), |
| 186 | stderr=self.make_output_log('stderr'), |
| 187 | stdin=subprocess.PIPE, |
Pau Espin Pedrol | 3a479c2 | 2019-04-05 19:47:40 +0200 | [diff] [blame] | 188 | preexec_fn=preexec_fn, |
Neels Hofmeyr | 1a7a3f0 | 2017-06-10 01:18:27 +0200 | [diff] [blame] | 189 | shell=False, |
| 190 | cwd=self.run_dir.path, |
| 191 | **self.popen_kwargs) |
| 192 | self.set_name(self.name_str, pid=self.process_obj.pid) |
| 193 | self.log('Launched') |
Neels Hofmeyr | 3531a19 | 2017-03-28 14:30:28 +0200 | [diff] [blame] | 194 | |
Pau Espin Pedrol | 78087be | 2018-11-12 18:20:52 +0100 | [diff] [blame] | 195 | def launch_sync(self, raise_nonsuccess=True): |
Pau Espin Pedrol | 79df739 | 2018-11-12 18:15:30 +0100 | [diff] [blame] | 196 | ''' |
| 197 | calls launch() method and block waiting for it to finish, serving the |
| 198 | mainloop meanwhile. |
| 199 | ''' |
| 200 | try: |
| 201 | self.launch() |
| 202 | self.wait() |
| 203 | except Exception as e: |
| 204 | self.terminate() |
| 205 | raise e |
Pau Espin Pedrol | 78087be | 2018-11-12 18:20:52 +0100 | [diff] [blame] | 206 | if raise_nonsuccess and self.result != 0: |
Pau Espin Pedrol | 7e30d84 | 2020-06-04 16:23:46 +0200 | [diff] [blame] | 207 | raise self.RunError('launch_sync()') |
Pau Espin Pedrol | 78087be | 2018-11-12 18:20:52 +0100 | [diff] [blame] | 208 | return self.result |
Pau Espin Pedrol | 79df739 | 2018-11-12 18:15:30 +0100 | [diff] [blame] | 209 | |
Pau Espin Pedrol | b1526b9 | 2018-05-22 20:32:30 +0200 | [diff] [blame] | 210 | def respawn(self): |
| 211 | self.dbg('respawn') |
| 212 | assert not self.is_running() |
| 213 | self.result = None |
| 214 | self.killed = None |
Pau Espin Pedrol | 922ce5a | 2019-09-10 13:44:20 +0200 | [diff] [blame] | 215 | return self.launch() |
Pau Espin Pedrol | b1526b9 | 2018-05-22 20:32:30 +0200 | [diff] [blame] | 216 | |
Pau Espin Pedrol | dd7bb2c | 2019-09-10 13:44:39 +0200 | [diff] [blame] | 217 | def respawn_sync(self, raise_nonsuccess=True): |
| 218 | self.dbg('respawn_sync') |
| 219 | assert not self.is_running() |
| 220 | self.result = None |
| 221 | self.killed = None |
| 222 | return self.launch_sync(raise_nonsuccess) |
| 223 | |
Neels Hofmeyr | 3531a19 | 2017-03-28 14:30:28 +0200 | [diff] [blame] | 224 | def _poll_termination(self, time_to_wait_for_term=5): |
| 225 | wait_step = 0.001 |
| 226 | waited_time = 0 |
| 227 | while True: |
| 228 | # poll returns None if proc is still running |
| 229 | self.result = self.process_obj.poll() |
| 230 | if self.result is not None: |
| 231 | return True |
| 232 | waited_time += wait_step |
| 233 | # make wait_step approach 1.0 |
| 234 | wait_step = (1. + 5. * wait_step) / 6. |
| 235 | if waited_time >= time_to_wait_for_term: |
| 236 | break |
| 237 | time.sleep(wait_step) |
| 238 | return False |
| 239 | |
Pau Espin Pedrol | fd4c144 | 2018-10-25 17:37:23 +0200 | [diff] [blame] | 240 | def send_signal(self, sig): |
| 241 | os.kill(self.process_obj.pid, sig) |
| 242 | |
Holger Hans Peter Freyther | 54b4fa9 | 2019-02-27 13:00:33 +0000 | [diff] [blame] | 243 | def pid(self): |
| 244 | if self.process_obj is None: |
| 245 | return None |
| 246 | return self.process_obj.pid |
| 247 | |
Holger Hans Peter Freyther | 0d714c9 | 2019-02-27 09:50:52 +0000 | [diff] [blame] | 248 | def kill(self, sig): |
| 249 | """Kills the process with the given signal and remembers it.""" |
| 250 | self.log('Terminating (%s)' % sig.name) |
| 251 | self.send_signal(sig) |
| 252 | self.killed = sig |
| 253 | |
Neels Hofmeyr | 3531a19 | 2017-03-28 14:30:28 +0200 | [diff] [blame] | 254 | def terminate(self): |
| 255 | if self.process_obj is None: |
| 256 | return |
| 257 | if self.result is not None: |
| 258 | return |
| 259 | |
| 260 | while True: |
| 261 | # first try SIGINT to allow stdout+stderr flushing |
Holger Hans Peter Freyther | 0d714c9 | 2019-02-27 09:50:52 +0000 | [diff] [blame] | 262 | self.kill(signal.SIGINT) |
Neels Hofmeyr | 3531a19 | 2017-03-28 14:30:28 +0200 | [diff] [blame] | 263 | if self._poll_termination(): |
| 264 | break |
| 265 | |
| 266 | # SIGTERM maybe? |
Holger Hans Peter Freyther | 0d714c9 | 2019-02-27 09:50:52 +0000 | [diff] [blame] | 267 | self.kill(signal.SIGTERM) |
Neels Hofmeyr | 3531a19 | 2017-03-28 14:30:28 +0200 | [diff] [blame] | 268 | if self._poll_termination(): |
| 269 | break |
| 270 | |
| 271 | # out of patience |
Holger Hans Peter Freyther | 0d714c9 | 2019-02-27 09:50:52 +0000 | [diff] [blame] | 272 | self.kill(signal.SIGKILL) |
Neels Hofmeyr | 3531a19 | 2017-03-28 14:30:28 +0200 | [diff] [blame] | 273 | break; |
| 274 | |
| 275 | self.process_obj.wait() |
| 276 | self.cleanup() |
| 277 | |
| 278 | def cleanup(self): |
Pau Espin Pedrol | 06ada45 | 2018-05-22 19:20:41 +0200 | [diff] [blame] | 279 | self.dbg('Cleanup') |
Neels Hofmeyr | 3531a19 | 2017-03-28 14:30:28 +0200 | [diff] [blame] | 280 | self.close_output_logs() |
| 281 | if self.result == 0: |
| 282 | self.log('Terminated: ok', rc=self.result) |
| 283 | elif self.killed: |
| 284 | self.log('Terminated', rc=self.result) |
| 285 | else: |
| 286 | self.err('Terminated: ERROR', rc=self.result) |
Pau Espin Pedrol | 9dbdb62 | 2020-05-25 16:45:34 +0200 | [diff] [blame] | 287 | self.log_stdout_tail() |
Neels Hofmeyr | 85eb324 | 2017-04-09 22:01:16 +0200 | [diff] [blame] | 288 | self.log_stderr_tail() |
| 289 | |
| 290 | def log_stdout_tail(self): |
| 291 | m = self.get_stdout_tail(prefix='| ') |
| 292 | if not m: |
| 293 | return |
Neels Hofmeyr | e5e5df8 | 2020-12-02 05:12:15 +0100 | [diff] [blame] | 294 | self.log('stdout:', '\n' + m, '\n') |
Neels Hofmeyr | 85eb324 | 2017-04-09 22:01:16 +0200 | [diff] [blame] | 295 | |
| 296 | def log_stderr_tail(self): |
| 297 | m = self.get_stderr_tail(prefix='| ') |
| 298 | if not m: |
| 299 | return |
Neels Hofmeyr | e5e5df8 | 2020-12-02 05:12:15 +0100 | [diff] [blame] | 300 | self.log('stderr:', '\n' + m, '\n') |
Neels Hofmeyr | 3531a19 | 2017-03-28 14:30:28 +0200 | [diff] [blame] | 301 | |
| 302 | def close_output_logs(self): |
Neels Hofmeyr | 3531a19 | 2017-03-28 14:30:28 +0200 | [diff] [blame] | 303 | for k, v in self.outputs.items(): |
| 304 | path, f = v |
| 305 | if f: |
| 306 | f.flush() |
| 307 | f.close() |
| 308 | self.outputs[k] = (path, None) |
| 309 | |
| 310 | def poll(self): |
| 311 | if self.process_obj is None: |
| 312 | return |
| 313 | if self.result is not None: |
| 314 | return |
| 315 | self.result = self.process_obj.poll() |
| 316 | if self.result is not None: |
| 317 | self.cleanup() |
| 318 | |
Neels Hofmeyr | 5356d0a | 2017-04-10 03:45:30 +0200 | [diff] [blame] | 319 | def is_running(self, poll_first=True): |
| 320 | if poll_first: |
| 321 | self.poll() |
Neels Hofmeyr | 85eb324 | 2017-04-09 22:01:16 +0200 | [diff] [blame] | 322 | return self.process_obj is not None and self.result is None |
| 323 | |
Neels Hofmeyr | fc38393 | 2020-11-30 22:04:11 +0100 | [diff] [blame] | 324 | @staticmethod |
| 325 | def end_ansi_colors(txt): |
| 326 | '''Make sure no ANSI colors leak out of logging output''' |
| 327 | color_off = '\033[0;m' |
| 328 | color_any = '\033[' |
| 329 | if txt.rfind(color_any) > txt.rfind(color_off): |
| 330 | return txt + color_off |
| 331 | return txt |
| 332 | |
| 333 | def get_output(self, which, since_mark=0): |
| 334 | ''' Read process output. For since_mark, see get_output_mark(). ''' |
Andre Puschmann | 20087ad | 2020-06-19 15:44:34 +0200 | [diff] [blame] | 335 | path = self.get_output_file(which) |
| 336 | if path is None: |
| 337 | return None |
Neels Hofmeyr | fc38393 | 2020-11-30 22:04:11 +0100 | [diff] [blame] | 338 | with open(path, 'r') as f: |
| 339 | if since_mark > 0: |
| 340 | f.seek(since_mark) |
| 341 | return f.read() |
Andre Puschmann | 20087ad | 2020-06-19 15:44:34 +0200 | [diff] [blame] | 342 | |
| 343 | def get_output_file(self, which): |
| 344 | ''' Return filename for given output ''' |
Neels Hofmeyr | 3531a19 | 2017-03-28 14:30:28 +0200 | [diff] [blame] | 345 | v = self.outputs.get(which) |
| 346 | if not v: |
| 347 | return None |
| 348 | path, f = v |
Andre Puschmann | 20087ad | 2020-06-19 15:44:34 +0200 | [diff] [blame] | 349 | return path |
Neels Hofmeyr | 3531a19 | 2017-03-28 14:30:28 +0200 | [diff] [blame] | 350 | |
| 351 | def get_output_tail(self, which, tail=10, prefix=''): |
Neels Hofmeyr | 5356d0a | 2017-04-10 03:45:30 +0200 | [diff] [blame] | 352 | out = self.get_output(which) |
| 353 | if not out: |
| 354 | return None |
| 355 | out = out.splitlines() |
Neels Hofmeyr | 3531a19 | 2017-03-28 14:30:28 +0200 | [diff] [blame] | 356 | tail = min(len(out), tail) |
Neels Hofmeyr | 5356d0a | 2017-04-10 03:45:30 +0200 | [diff] [blame] | 357 | return prefix + ('\n' + prefix).join(out[-tail:]) |
Neels Hofmeyr | 3531a19 | 2017-03-28 14:30:28 +0200 | [diff] [blame] | 358 | |
Neels Hofmeyr | fc38393 | 2020-11-30 22:04:11 +0100 | [diff] [blame] | 359 | def get_output_mark(self, which): |
| 360 | '''Usage: |
| 361 | # remember a start marker |
| 362 | my_mark = my_process.get_output_mark('stderr') |
Neels Hofmeyr | 3531a19 | 2017-03-28 14:30:28 +0200 | [diff] [blame] | 363 | |
Neels Hofmeyr | fc38393 | 2020-11-30 22:04:11 +0100 | [diff] [blame] | 364 | do_actions_that_produce_log_output() |
| 365 | |
| 366 | my_log = my_process.get_output('stderr', since_mark=my_mark) |
| 367 | # my_log contains the stderr of that process since the start marker. |
| 368 | ''' |
| 369 | path = self.get_output_file(which) |
| 370 | if path is None: |
| 371 | return None |
| 372 | with open(path, 'r') as f: |
| 373 | return f.seek(0, 2) |
| 374 | |
| 375 | def grep_output(self, which, regex, since_mark=0, line_nrs=False): |
| 376 | lines = self.get_output(which, since_mark=since_mark).splitlines() |
| 377 | if not lines: |
| 378 | return None |
| 379 | matches = [] |
| 380 | r = re.compile(regex) |
| 381 | line_nr = since_mark |
| 382 | for line in lines: |
| 383 | line_nr += 1 |
| 384 | if r.search(line): |
| 385 | line = self.end_ansi_colors(line) |
| 386 | if line_nrs: |
| 387 | matches.append((line_nr, line)) |
| 388 | else: |
| 389 | matches.append(line) |
| 390 | return matches |
| 391 | |
| 392 | def get_stdout(self, since_mark=0): |
| 393 | return self.get_output('stdout', since_mark=since_mark) |
| 394 | |
| 395 | def get_stderr(self, since_mark=0): |
| 396 | return self.get_output('stderr', since_mark=since_mark) |
Neels Hofmeyr | 3531a19 | 2017-03-28 14:30:28 +0200 | [diff] [blame] | 397 | |
| 398 | def get_stdout_tail(self, tail=10, prefix=''): |
| 399 | return self.get_output_tail('stdout', tail, prefix) |
| 400 | |
| 401 | def get_stderr_tail(self, tail=10, prefix=''): |
| 402 | return self.get_output_tail('stderr', tail, prefix) |
| 403 | |
Neels Hofmeyr | 5356d0a | 2017-04-10 03:45:30 +0200 | [diff] [blame] | 404 | def terminated(self, poll_first=True): |
| 405 | if poll_first: |
| 406 | self.poll() |
Neels Hofmeyr | 3531a19 | 2017-03-28 14:30:28 +0200 | [diff] [blame] | 407 | return self.result is not None |
| 408 | |
Pau Espin Pedrol | a9bc93d | 2020-06-12 15:34:28 +0200 | [diff] [blame] | 409 | def wait(self, timeout=None): |
| 410 | if timeout is None: |
| 411 | timeout = self.default_wait_timeout |
Pau Espin Pedrol | 664e383 | 2020-06-10 19:30:33 +0200 | [diff] [blame] | 412 | MainLoop.wait(self.terminated, timeout=timeout) |
Neels Hofmeyr | dae3d3c | 2017-03-28 12:16:58 +0200 | [diff] [blame] | 413 | |
Andre Puschmann | 66272f8 | 2020-03-21 21:01:31 +0100 | [diff] [blame] | 414 | def stdin_write(self, cmd): |
| 415 | ''' |
| 416 | Send a cmd to the stdin of a process (convert to byte before) |
| 417 | ''' |
| 418 | if self.process_obj.stdin is not None: |
| 419 | self.process_obj.stdin.write(cmd.encode("utf-8")) |
| 420 | self.process_obj.stdin.flush() |
Neels Hofmeyr | dae3d3c | 2017-03-28 12:16:58 +0200 | [diff] [blame] | 421 | |
Pau Espin Pedrol | 7e30d84 | 2020-06-04 16:23:46 +0200 | [diff] [blame] | 422 | def RunError(self, msg_prefix): |
| 423 | 'Get a log.Error filled in with Result information. Use when program is terminated and result !=0' |
| 424 | msg = '%s: local process exited with status %d' % (msg_prefix, self.result) |
| 425 | return log.Error(msg) |
| 426 | |
Neels Hofmeyr | 3531a19 | 2017-03-28 14:30:28 +0200 | [diff] [blame] | 427 | class RemoteProcess(Process): |
| 428 | |
Nils Fürste | 2af2b15 | 2020-11-23 11:57:41 +0100 | [diff] [blame] | 429 | def __init__(self, name, run_dir, remote_user, remote_host, remote_cwd, popen_args, |
| 430 | remote_env={}, remote_port=None, **popen_kwargs): |
Neels Hofmeyr | 5356d0a | 2017-04-10 03:45:30 +0200 | [diff] [blame] | 431 | super().__init__(name, run_dir, popen_args, **popen_kwargs) |
Pau Espin Pedrol | 3895fec | 2017-04-28 16:13:03 +0200 | [diff] [blame] | 432 | self.remote_user = remote_user |
Neels Hofmeyr | 3531a19 | 2017-03-28 14:30:28 +0200 | [diff] [blame] | 433 | self.remote_host = remote_host |
| 434 | self.remote_cwd = remote_cwd |
Pau Espin Pedrol | f6d45ad | 2020-02-11 14:39:15 +0100 | [diff] [blame] | 435 | self.remote_env = remote_env |
Nils Fürste | 2af2b15 | 2020-11-23 11:57:41 +0100 | [diff] [blame] | 436 | self.remote_port = remote_port |
Neels Hofmeyr | 3531a19 | 2017-03-28 14:30:28 +0200 | [diff] [blame] | 437 | |
| 438 | # hacky: instead of just prepending ssh, i.e. piping stdout and stderr |
| 439 | # over the ssh link, we should probably run on the remote side, |
| 440 | # monitoring the process remotely. |
Neels Hofmeyr | 5356d0a | 2017-04-10 03:45:30 +0200 | [diff] [blame] | 441 | if self.remote_cwd: |
Pau Espin Pedrol | f6d45ad | 2020-02-11 14:39:15 +0100 | [diff] [blame] | 442 | cd = 'cd "%s";' % self.remote_cwd |
Neels Hofmeyr | 5356d0a | 2017-04-10 03:45:30 +0200 | [diff] [blame] | 443 | else: |
| 444 | cd = '' |
Pau Espin Pedrol | 302c756 | 2018-10-02 13:08:02 +0200 | [diff] [blame] | 445 | # We need double -t to force tty and be able to forward signals to |
| 446 | # processes (SIGHUP) when we close ssh on the local side. As a result, |
| 447 | # stderr seems to be merged into stdout in ssh client. |
| 448 | self.popen_args = ['ssh', '-t', '-t', self.remote_user+'@'+self.remote_host, |
Pau Espin Pedrol | f6d45ad | 2020-02-11 14:39:15 +0100 | [diff] [blame] | 449 | '%s %s %s' % (cd, |
| 450 | ' '.join(['%s=%r'%(k,v) for k,v in self.remote_env.items()]), |
| 451 | ' '.join(self.popen_args))] |
Nils Fürste | 2af2b15 | 2020-11-23 11:57:41 +0100 | [diff] [blame] | 452 | if self.remote_port: |
| 453 | self.popen_args.insert(1, '-p') |
| 454 | self.popen_args.insert(2, self.remote_port) |
| 455 | |
Pau Espin Pedrol | f6d45ad | 2020-02-11 14:39:15 +0100 | [diff] [blame] | 456 | self.dbg(self.popen_args, dir=self.run_dir, conf=self.popen_kwargs, remote_env=self.remote_env) |
Neels Hofmeyr | dae3d3c | 2017-03-28 12:16:58 +0200 | [diff] [blame] | 457 | |
Pau Espin Pedrol | 7e30d84 | 2020-06-04 16:23:46 +0200 | [diff] [blame] | 458 | def RunError(self, msg_prefix): |
| 459 | 'Overwrite Process method with ssh extra information' |
| 460 | # man ssh states it returns 255 if an ssh error occurred: |
| 461 | msg = msg_prefix + ': ' |
| 462 | if self.result == 255: |
| 463 | tail = ' (' + (self.get_stderr_tail(tail=1, prefix='') or '').rstrip() + ')' |
| 464 | msg += 'local ssh process exited with status %d%s' % (self.result, tail if 'ssh' in tail else '') |
| 465 | else: |
| 466 | msg += 'remote process exited with status %d' % (self.result) |
| 467 | return log.Error(msg) |
| 468 | |
Pau Espin Pedrol | fd4c144 | 2018-10-25 17:37:23 +0200 | [diff] [blame] | 469 | class NetNSProcess(Process): |
| 470 | NETNS_EXEC_BIN = 'osmo-gsm-tester_netns_exec.sh' |
| 471 | def __init__(self, name, run_dir, netns, popen_args, **popen_kwargs): |
| 472 | super().__init__(name, run_dir, popen_args, **popen_kwargs) |
| 473 | self.netns = netns |
| 474 | |
| 475 | self.popen_args = ['sudo', self.NETNS_EXEC_BIN, self.netns] + list(popen_args) |
| 476 | self.dbg(self.popen_args, dir=self.run_dir, conf=self.popen_kwargs) |
| 477 | |
| 478 | # HACK: Since we run under sudo, only way to kill root-owned process is to kill as root... |
| 479 | # This function is overwritten from Process. |
| 480 | def send_signal(self, sig): |
Pau Espin Pedrol | e159cd2 | 2019-04-03 17:53:54 +0200 | [diff] [blame] | 481 | if sig == signal.SIGKILL: |
| 482 | # if we kill sudo, its children (bash running NETNS_EXEC_BIN + |
| 483 | # tcpdump under it) are kept alive. Let's instead tell the script to |
| 484 | # kill tcpdump: |
| 485 | sig = signal.SIGUSR1 |
Pau Espin Pedrol | fd4c144 | 2018-10-25 17:37:23 +0200 | [diff] [blame] | 486 | kill_cmd = ('kill', '-%d' % int(sig), str(self.process_obj.pid)) |
Pau Espin Pedrol | 17a4ed9 | 2019-04-03 17:10:31 +0200 | [diff] [blame] | 487 | run_local_netns_sync(self.run_dir, self.name()+"-kill"+str(sig), self.netns, kill_cmd) |
Pau Espin Pedrol | fd4c144 | 2018-10-25 17:37:23 +0200 | [diff] [blame] | 488 | |
Pau Espin Pedrol | 14022d3 | 2020-02-11 14:20:00 +0100 | [diff] [blame] | 489 | class RemoteNetNSProcess(RemoteProcess): |
| 490 | NETNS_EXEC_BIN = 'osmo-gsm-tester_netns_exec.sh' |
| 491 | def __init__(self, name, run_dir, remote_user, remote_host, remote_cwd, netns, popen_args, **popen_kwargs): |
Pau Espin Pedrol | 4983eb5 | 2020-02-11 19:16:06 +0100 | [diff] [blame] | 492 | self.netns = netns |
Pau Espin Pedrol | 14022d3 | 2020-02-11 14:20:00 +0100 | [diff] [blame] | 493 | args = ['sudo', self.NETNS_EXEC_BIN, self.netns] + list(popen_args) |
| 494 | super().__init__(name, run_dir, remote_user, remote_host, remote_cwd, args, **popen_kwargs) |
Pau Espin Pedrol | fd4c144 | 2018-10-25 17:37:23 +0200 | [diff] [blame] | 495 | |
Pau Espin Pedrol | e4358a9 | 2018-10-01 11:27:55 +0200 | [diff] [blame] | 496 | def run_local_sync(run_dir, name, popen_args): |
| 497 | run_dir =run_dir.new_dir(name) |
| 498 | proc = Process(name, run_dir, popen_args) |
Pau Espin Pedrol | 79df739 | 2018-11-12 18:15:30 +0100 | [diff] [blame] | 499 | proc.launch_sync() |
Pau Espin Pedrol | 12c5ea4 | 2019-11-26 14:25:33 +0100 | [diff] [blame] | 500 | return proc |
Pau Espin Pedrol | e4358a9 | 2018-10-01 11:27:55 +0200 | [diff] [blame] | 501 | |
Pau Espin Pedrol | fd4c144 | 2018-10-25 17:37:23 +0200 | [diff] [blame] | 502 | def run_local_netns_sync(run_dir, name, netns, popen_args): |
| 503 | run_dir =run_dir.new_dir(name) |
| 504 | proc = NetNSProcess(name, run_dir, netns, popen_args) |
Pau Espin Pedrol | 79df739 | 2018-11-12 18:15:30 +0100 | [diff] [blame] | 505 | proc.launch_sync() |
Pau Espin Pedrol | 12c5ea4 | 2019-11-26 14:25:33 +0100 | [diff] [blame] | 506 | return proc |
Neels Hofmeyr | dae3d3c | 2017-03-28 12:16:58 +0200 | [diff] [blame] | 507 | # vim: expandtab tabstop=4 shiftwidth=4 |