utils.py (14184B)
1 import os 2 import subprocess 3 import fcntl 4 import sys 5 import traceback 6 import shutil 7 import dbus 8 9 from datetime import datetime 10 from gi.repository import GLib 11 from weakref import WeakValueDictionary 12 from re import fullmatch 13 from time import sleep 14 15 from runner import RunnerCoreArgParse 16 17 class Process(subprocess.Popen): 18 processes = WeakValueDictionary() 19 testargs = RunnerCoreArgParse().parse_args() 20 21 def __new__(cls, *args, **kwargs): 22 obj = super().__new__(cls) 23 cls.processes[id(obj)] = obj 24 return obj 25 26 def __init__(self, args, namespace=None, outfile=None, env=None, check=False, cleanup=None): 27 self.write_fds = [] 28 self.io_watch = None 29 self.cleanup = cleanup 30 self.verbose = False 31 self.out = '' 32 self.hup = False 33 self.killed = False 34 self.namespace = namespace 35 36 logfile = args[0] 37 38 if not shutil.which(args[0]): 39 raise Exception("%s is not found on system" % args[0]) 40 41 if Process.is_verbose(args[0], log=False): 42 self.verbose = True 43 44 if namespace: 45 args = ['ip', 'netns', 'exec', namespace] + args 46 logfile += '-%s' % namespace 47 48 if outfile: 49 # outfile is only used by iwmon, in which case we don't want 50 # to append to an existing file. 51 self._append_outfile(outfile, append=False) 52 53 if self.testargs.log: 54 testdir = os.getcwd() 55 56 # Special case any processes started prior to a test 57 # (i.e. from testhome). Put these in the root log directory 58 if testdir == self.testargs.testhome: 59 testdir = '.' 60 else: 61 testdir = os.path.basename(testdir) 62 63 logfile = '%s/%s/%s' % (self.testargs.log, testdir, logfile) 64 self._append_outfile(logfile) 65 66 super().__init__(args, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, 67 env=env, cwd=os.getcwd()) 68 69 # Set as non-blocking so read() in the IO callback doesn't block forever 70 fl = fcntl.fcntl(self.stdout, fcntl.F_GETFL) 71 fcntl.fcntl(self.stdout, fcntl.F_SETFL, fl | os.O_NONBLOCK) 72 73 self.io_watch = GLib.io_add_watch(self.stdout, GLib.IO_IN | 74 GLib.IO_HUP | GLib.IO_ERR, self.process_io) 75 76 print("Starting process {}".format(self.args)) 77 78 if check: 79 self.wait(10) 80 self.killed = True 81 if self.returncode != 0: 82 raise subprocess.CalledProcessError(returncode=self.returncode, 83 cmd=args) 84 85 @staticmethod 86 def is_verbose(process, log=True): 87 exclude = ['iwd-rtnl'] 88 process = os.path.basename(process) 89 90 if Process.testargs is None: 91 return False 92 93 # every process is verbose when logging is enabled 94 if log and Process.testargs.log and process not in exclude: 95 return True 96 97 if process in Process.testargs.verbose: 98 return True 99 100 # Special case here to enable verbose output with valgrind running 101 if process == 'valgrind' and 'iwd' in Process.testargs.verbose: 102 return True 103 104 # Handle any regex matches 105 for item in Process.testargs.verbose: 106 try: 107 if fullmatch(item, process): 108 return True 109 except Exception as e: 110 print("%s is not a valid regex" % item) 111 112 return False 113 114 @classmethod 115 def get_all(cls): 116 return cls.processes.values() 117 118 @classmethod 119 def kill_all(cls): 120 for p in cls.processes.values(): 121 if p.args[0] == 'dmesg': 122 continue 123 124 p.kill() 125 126 @staticmethod 127 def _write_io(instance, data, stdout=True): 128 for f in instance.write_fds: 129 for c in data: 130 f.write(c) 131 if c == '\n': 132 stamp = datetime.strftime(datetime.now(), "%Y-%m-%d %H:%M:%S.%f") 133 f.write(stamp + ': ') 134 135 # Write out a separator so multiple process calls per 136 # test are easier to read. 137 if instance.hup: 138 f.write("Terminated: {}\n\n".format(instance.args)) 139 140 f.flush() 141 142 if instance.verbose and stdout: 143 sys.__stdout__.write(data) 144 sys.__stdout__.flush() 145 146 @classmethod 147 def write_separators(cls, test, sep): 148 # 149 # There are either log running processes (cls.processes) or 150 # processes that have terminated already but a log file exists 151 # on disk. We still want the separators to show for both cases 152 # so after writing separators for running processes, also 153 # write them in any additional log files. 154 # 155 nowrite = [] 156 157 for proc in cls.processes.values(): 158 if proc.killed: 159 continue 160 161 cls._write_io(proc, sep, stdout=False) 162 nowrite.append(proc.args[0]) 163 164 if cls.testargs.log: 165 logfiles = os.listdir('%s/%s' % (cls.testargs.log, test)) 166 167 extra = list(set(logfiles) - set(nowrite)) 168 169 for log in extra: 170 logfile = '%s/%s/%s' % (cls.testargs.log, test, log) 171 with open(logfile, 'a') as f: 172 f.write(sep) 173 f.close() 174 175 def process_io(self, source, condition): 176 if condition & GLib.IO_HUP: 177 self.hup = True 178 self.wait() 179 bt = self.out.partition("++++++++ backtrace ++++++++") 180 if bt[1]: 181 raise Exception(f"Process {self.args[0]} crashed!\n{bt[1] + bt[2]}") 182 183 data = source.read() 184 185 if not data: 186 return not self.hup 187 188 try: 189 data = data.decode('utf-8') 190 except: 191 return not self.hup 192 193 # Save data away in case the caller needs it (e.g. list_sta) 194 self.out += data 195 196 self._write_io(self, data) 197 198 return not self.hup 199 200 def _append_outfile(self, file, append=True): 201 gid = int(os.environ.get('SUDO_GID', os.getgid())) 202 uid = int(os.environ.get('SUDO_UID', os.getuid())) 203 dir = os.path.dirname(file) 204 205 if not os.path.exists(dir): 206 os.mkdir(dir) 207 os.chown(dir, uid, gid) 208 209 file = os.path.join(dir,file) 210 211 # If the out file exists, append. Useful for processes like 212 # hostapd_cli where it is called multiple times independently. 213 if os.path.isfile(file) and append: 214 mode = 'a' 215 else: 216 mode = 'w' 217 218 try: 219 f = open(file, mode) 220 except Exception as e: 221 traceback.print_exc() 222 sys.exit(0) 223 224 os.fchown(f.fileno(), uid, gid) 225 226 self.write_fds.append(f) 227 228 def wait_for_socket(self, socket, wait): 229 def _wait(socket): 230 if not os.path.exists(socket): 231 sleep(0.1) 232 return False 233 return True 234 235 Namespace.non_block_wait(_wait, wait, socket, 236 exception=Exception("Timed out waiting for %s" % socket)) 237 238 def wait_for_service(self, ns, service, wait): 239 def _wait(ns, service): 240 if not ns._bus.name_has_owner(service): 241 sleep(0.1) 242 return False 243 return True 244 245 Namespace.non_block_wait(_wait, wait, ns, service, 246 exception=Exception("Timed out waiting for %s" % service)) 247 248 # Wait for both process termination and HUP signal 249 def __wait(self, timeout): 250 try: 251 super().wait(timeout) 252 if not self.hup: 253 return False 254 255 return True 256 except: 257 return False 258 259 # Override wait() so it can do so non-blocking 260 def wait(self, timeout=10): 261 if timeout == None: 262 super().wait() 263 return 264 265 Namespace.non_block_wait(self.__wait, timeout, 1) 266 self._cleanup() 267 268 def _cleanup(self): 269 if self.cleanup: 270 self.cleanup() 271 272 self.write_fds = [] 273 274 if self.io_watch: 275 GLib.source_remove(self.io_watch) 276 self.io_watch = None 277 278 self.cleanup = None 279 self.killed = True 280 281 # Override kill() 282 def kill(self, force=False): 283 if self.killed: 284 return 285 286 print("Killing process {}".format(self.args)) 287 288 if force: 289 super().kill() 290 else: 291 self.terminate() 292 293 try: 294 self.wait(timeout=15) 295 except: 296 print("Process %s did not complete in 15 seconds!" % self.args[0]) 297 super().kill() 298 299 self._cleanup() 300 301 def __str__(self): 302 return str(self.args) + '\n' 303 304 dbus_count = 0 305 # Partial DBus config. The remainder (<listen>) will be filled in for each 306 # namespace that is created so each individual dbus-daemon has its own socket 307 # and address. 308 dbus_config = ''' 309 <!DOCTYPE busconfig PUBLIC \ 310 "-//freedesktop//DTD D-Bus Bus Configuration 1.0//EN" \ 311 "http://www.freedesktop.org/standards/dbus/1.0/\ 312 busconfig.dtd\"> 313 <busconfig> 314 <type>system</type> 315 <limit name=\"reply_timeout\">2147483647</limit> 316 <auth>ANONYMOUS</auth> 317 <allow_anonymous/> 318 <policy context=\"default\"> 319 <allow user=\"*\"/> 320 <allow own=\"*\"/> 321 <allow send_type=\"method_call\"/> 322 <allow send_type=\"signal\"/> 323 <allow send_type=\"method_return\"/> 324 <allow send_type=\"error\"/> 325 <allow receive_type=\"method_call\"/> 326 <allow receive_type=\"signal\"/> 327 <allow receive_type=\"method_return\"/> 328 <allow receive_type=\"error\"/> 329 <allow send_destination=\"*\" eavesdrop=\"true\"/> 330 <allow eavesdrop=\"true\"/> 331 </policy> 332 ''' 333 334 class Namespace: 335 def __init__(self, args, name, radios): 336 self.dbus_address = None 337 self.name = name 338 self.radios = radios 339 self.args = args 340 341 Process(['ip', 'netns', 'add', name]).wait() 342 for r in radios: 343 r.set_namespace(self) 344 345 self.start_dbus() 346 347 def reset(self): 348 self._bus = None 349 350 for r in self.radios: 351 r._radio = None 352 353 self.radios = [] 354 355 Process.kill_all() 356 357 def __del__(self): 358 if self.name: 359 print("Removing namespace %s" % self.name) 360 361 Process(['ip', 'netns', 'del', self.name]).wait() 362 363 def get_bus(self): 364 return self._bus 365 366 def start_process(self, args, env=None, **kwargs): 367 if not env: 368 env = os.environ.copy() 369 370 if hasattr(self, "dbus_address"): 371 # In case this process needs DBus... 372 env['DBUS_SYSTEM_BUS_ADDRESS'] = self.dbus_address 373 374 return Process(args, namespace=self.name, env=env, **kwargs) 375 376 def stop_process(self, p, force=False): 377 p.kill(force) 378 379 def _is_running(self, pid): 380 try: 381 os.kill(pid, 0) 382 except OSError: 383 return False 384 385 return True 386 387 def is_process_running(self, process): 388 for p in Process.get_all(): 389 # Namespace processes are actually started by 'ip' where 390 # the actual process name is at index 4 of the arguments. 391 idx = 0 if not p.namespace else 4 392 393 if p.namespace == self.name and p.args[idx] == process: 394 # The process object exists, but make sure its 395 # actually running. 396 return self._is_running(p.pid) 397 return False 398 399 def _cleanup_dbus(self): 400 try: 401 os.remove(self.dbus_address.split('=')[1]) 402 except: 403 pass 404 405 os.remove(self.dbus_cfg) 406 407 def start_dbus(self): 408 global dbus_count 409 410 self.dbus_address = 'unix:path=/tmp/dbus%d' % dbus_count 411 self.dbus_cfg = '/tmp/dbus%d.conf' % dbus_count 412 dbus_count += 1 413 414 with open(self.dbus_cfg, 'w+') as f: 415 f.write(dbus_config) 416 f.write('<listen>%s</listen>\n' % self.dbus_address) 417 f.write('</busconfig>\n') 418 419 p = self.start_process(['dbus-daemon', '--config-file=%s' % self.dbus_cfg], 420 cleanup=self._cleanup_dbus) 421 422 p.wait_for_socket(self.dbus_address.split('=')[1], 5) 423 424 self._bus = dbus.bus.BusConnection(address_or_type=self.dbus_address) 425 426 def start_iwd(self, config_dir = '/tmp', storage_dir = '/tmp/iwd', 427 developer_mode = True): 428 args = [] 429 iwd_radios = ','.join([r.name for r in self.radios if r.use == 'iwd']) 430 431 if self.args.valgrind: 432 args.extend(['valgrind', '--leak-check=full', '--track-origins=yes', 433 '--show-leak-kinds=all', 434 '--log-file=/tmp/valgrind.log.%p']) 435 436 args.append('iwd') 437 438 if developer_mode: 439 args.append('-E') 440 441 if iwd_radios != '': 442 args.extend(['-p', iwd_radios]) 443 444 if Process.is_verbose(args[0]): 445 args.append('-d') 446 447 env = os.environ.copy() 448 449 env['CONFIGURATION_DIRECTORY'] = config_dir 450 env['STATE_DIRECTORY'] = storage_dir 451 452 if Process.is_verbose('iwd-dhcp'): 453 env['IWD_DHCP_DEBUG'] = '1' 454 455 if Process.is_verbose('iwd-tls'): 456 env['IWD_TLS_DEBUG'] = '1' 457 458 if Process.is_verbose('iwd-acd'): 459 env['IWD_ACD_DEBUG'] = '1' 460 461 if Process.is_verbose('iwd-rtnl'): 462 env['IWD_RTNL_DEBUG'] = '1' 463 464 if Process.is_verbose('iwd-sae'): 465 env['IWD_SAE_DEBUG'] = '1' 466 467 proc = self.start_process(args, env=env) 468 469 proc.wait_for_service(self, 'net.connman.iwd', 20) 470 471 return proc 472 473 @staticmethod 474 def non_block_wait(func, timeout, *args, exception=True): 475 ''' 476 Convenience function for waiting in a non blocking 477 manor using GLibs context iteration i.e. does not block 478 the main loop while waiting. 479 480 'func' will be called at least once and repeatedly until 481 either it returns success, throws an exception, or the 482 'timeout' expires. 483 484 'timeout' is the ultimate timeout in seconds 485 486 '*args' will be passed to 'func' 487 488 If 'exception' is an Exception type it will be raised. 489 If 'exception' is True a generic TimeoutError will be raised. 490 Any other value will not result in an exception. 491 ''' 492 # Simple class for signaling the wait timeout 493 class Bool: 494 def __init__(self, value): 495 self.value = value 496 497 def wait_timeout_cb(done): 498 done.value = True 499 return False 500 501 mainloop = GLib.MainLoop() 502 done = Bool(False) 503 504 timeout = GLib.timeout_add_seconds(timeout, wait_timeout_cb, done) 505 context = mainloop.get_context() 506 507 while True: 508 try: 509 ret = func(*args) 510 if ret: 511 if not done.value: 512 GLib.source_remove(timeout) 513 return ret 514 except Exception as e: 515 if not done.value: 516 GLib.source_remove(timeout) 517 raise e 518 519 if done.value == True: 520 if isinstance(exception, Exception): 521 raise exception 522 elif type(exception) == bool and exception: 523 raise TimeoutError("Timeout on non_block_wait") 524 else: 525 return 526 527 context.iteration(may_block=True) 528 529 def __str__(self): 530 ret = 'Namespace: %s\n' % self.name 531 ret += 'Processes:\n' 532 for p in Process.get_all(): 533 ret += '\t%s' % str(p) 534 535 ret += 'Radios:\n' 536 if len(self.radios) > 0: 537 for r in self.radios: 538 ret += '\t%s\n' % str(r) 539 else: 540 ret += '\tNo Radios\n' 541 542 ret += 'DBus Address: %s\n' % self.dbus_address 543 ret += '===================================================\n\n' 544 545 return ret 546 547 class BarChart(): 548 def __init__(self, height=10, max_width=80): 549 self._height = height 550 self._max_width = max_width 551 self._values = [] 552 self._max_value = 0 553 self._min_value = 0 554 555 def add_value(self, value): 556 if len(self._values) == 0: 557 self._max_value = int(1.01 * value) 558 self._min_value = int(0.99 * value) 559 elif value > self._max_value: 560 self._max_value = int(1.01 * value) 561 elif value < self._min_value: 562 self._min_value = int(0.99 * value) 563 564 self._values.append(value) 565 566 def _value_to_stars(self, value): 567 # Need to scale value (range of min_value -> max_value) to 568 # a range of 0 -> height 569 # 570 # Scaled = ((value - min_value) / ( max_value - min_value)) * (Height - 0) + 0 571 572 return int(((value - self._min_value) / 573 (self._max_value - self._min_value)) * self._height) 574 575 def __str__(self): 576 # Need to map value from range 0 - self._height 577 ret = '' 578 579 for i, value in enumerate(self._values): 580 stars = self._value_to_stars(value) 581 ret += '[%3u] ' % i + '%-10s' % ('*' * stars) + '\t\t\t%d\n' % value 582 583 ret += '\n' 584 585 return ret