eiwd

no dbus iwd with iwctl functionality
git clone https://git.daat.foo/repos/eiwd.git
Log | Files | Refs | Submodules | README | LICENSE

runner.py (16202B)


      1 #!/usr/bin/python3
      2 
      3 from argparse import ArgumentParser, Namespace, SUPPRESS
      4 from configparser import ConfigParser
      5 from collections import namedtuple
      6 from shutil import copy, copytree, which, rmtree
      7 from glob import glob
      8 
      9 import os
     10 import ctypes
     11 import fcntl
     12 import sys
     13 
     14 libc = ctypes.cdll['libc.so.6']
     15 libc.mount.argtypes = (ctypes.c_char_p, ctypes.c_char_p, ctypes.c_char_p, \
     16 			ctypes.c_ulong, ctypes.c_char_p)
     17 
     18 # Using ctypes to load the libc library is somewhat low level. Because of this
     19 # we need to define our own flags/options for use with mounting.
     20 MS_NOSUID = 2
     21 MS_NODEV = 4
     22 MS_NOEXEC = 8
     23 MS_STRICTATIME = 1 << 24
     24 STDIN_FILENO = 0
     25 TIOCSTTY = 0x540E
     26 
     27 MountInfo = namedtuple('MountInfo', 'fstype source target options flags')
     28 DevInfo = namedtuple('DevInfo', 'target linkpath')
     29 
     30 mounts_common = [
     31 	MountInfo('sysfs', 'sysfs', '/sys', '', MS_NOSUID|MS_NOEXEC|MS_NODEV),
     32 	MountInfo('proc', 'proc', '/proc', '', MS_NOSUID|MS_NOEXEC|MS_NODEV),
     33 	MountInfo('devpts', 'devpts', '/dev/pts', 'mode=0620', MS_NOSUID|MS_NOEXEC),
     34 	MountInfo('tmpfs', 'tmpfs', '/dev/shm', 'mode=1777',
     35 					MS_NOSUID|MS_NODEV|MS_STRICTATIME),
     36 	MountInfo('tmpfs', 'tmpfs', '/run', 'mode=0755',
     37 					MS_NOSUID|MS_NODEV|MS_STRICTATIME),
     38 	MountInfo('tmpfs', 'tmpfs', '/tmp', '', 0),
     39 	MountInfo('tmpfs', 'tmpfs', '/etc', '', 0),
     40 	MountInfo('tmpfs', 'tmpfs', '/usr/share/dbus-1', 'mode=0755',
     41 					MS_NOSUID|MS_NOEXEC|MS_NODEV|MS_STRICTATIME),
     42 ]
     43 
     44 dev_table = [
     45 	DevInfo('/proc/self/fd', '/dev/fd'),
     46 	DevInfo('/proc/self/fd/0', '/dev/stdin'),
     47 	DevInfo('/proc/self/fd/1', '/dev/stdout'),
     48 	DevInfo('/proc/self/fd/2', '/dev/stderr')
     49 ]
     50 
     51 def mount(source, target, fs, flags, options=''):
     52 	'''
     53 		Python wrapper for libc mount()
     54 	'''
     55 	ret = libc.mount(source.encode(), target.encode(), fs.encode(), flags,
     56 				options.encode())
     57 	if ret < 0:
     58 		errno = ctypes.get_errno()
     59 		raise Exception("Could not mount %s (%d)" % (target, errno))
     60 
     61 #
     62 # Custom argparse.Namespace class to stringify arguments in a way that can be
     63 # directly passed to the test environment as kernel arguments. This also removes
     64 # any None, False, or [] arguments.
     65 #
     66 class RunnerNamespace(Namespace):
     67 	def __init__(self, *args, **kwargs):
     68 		super().__init__(*args, **kwargs)
     69 
     70 	def to_cmd(self):
     71 		ret = ''
     72 		for k, v in self.__dict__.items():
     73 			if v in [None, False, [], '']:
     74 				continue
     75 
     76 			if type(v) is list:
     77 				ret += '%s=%s ' % (k, ','.join(v))
     78 			else:
     79 				ret += '%s=%s ' % (k, str(v))
     80 
     81 		return ret.strip()
     82 
     83 #
     84 # The core arguments needed both inside and outside the test environment
     85 #
     86 class RunnerCoreArgParse(ArgumentParser):
     87 	def __init__(self, *args, **kwargs):
     88 		ArgumentParser.__init__(self, *args, **kwargs)
     89 
     90 		self.add_argument('--start', '-s',
     91 				help='Custom init process in virtual environment',
     92 				dest='start',
     93 				default=None,
     94 				type=os.path.abspath)
     95 		self.add_argument('--verbose', '-v', metavar='<list>',
     96 				type=lambda x: x.split(','),
     97 				help='Comma separated list of applications',
     98 				dest='verbose',
     99 				default=[])
    100 		self.add_argument('--debug', '--dbg', '-d',
    101 				action='store_true',
    102 				help='Enable test-runner debugging',
    103 				dest='dbg')
    104 		self.add_argument('--log', '-l',
    105 				type=os.path.abspath,
    106 				help='Directory for log files')
    107 		self.add_argument('--monitor', '-m',
    108 				type=os.path.abspath,
    109 				help='Enables iwmon output to file')
    110 		self.add_argument('--sub-tests', '-S',
    111 				metavar='<subtests>',
    112 				type=str, help='List of subtests to run',
    113 				default=None, dest='sub_tests')
    114 		self.add_argument('--result', '-e',
    115 				type=os.path.abspath,
    116 				help='Writes PASS/FAIL to results file')
    117 		self.add_argument('--hw', '-w',
    118 				type=str,
    119 				nargs='?',
    120 				const=True,
    121 				action='store',
    122 				help='Use physical adapters for tests (passthrough)')
    123 
    124 		# Hidden options only meant to be passed to the kernel
    125 		self.add_argument('--testhome', help=SUPPRESS)
    126 		self.add_argument('--monitor-parent', help=SUPPRESS)
    127 		self.add_argument('--result-parent', help=SUPPRESS)
    128 		self.add_argument('--timeout', help=SUPPRESS)
    129 
    130 		# Prevent --autotest/--unittest from being used together
    131 		auto_unit_group = self.add_mutually_exclusive_group()
    132 		auto_unit_group.add_argument('--autotests', '-A',
    133 				metavar='<tests>',
    134 				type=str,
    135 				help='List of tests to run',
    136 				default=None,
    137 				dest='autotests')
    138 		auto_unit_group.add_argument('--unit-tests', '-U',
    139 				metavar='<tests>',
    140 				type=str,
    141 				help='List of unit tests to run',
    142 				dest='unit_tests')
    143 
    144 		# Prevent --valgrind/--gdb from being used together
    145 		valgrind_gdb_group = self.add_mutually_exclusive_group()
    146 		valgrind_gdb_group.add_argument('--gdb', '-g',
    147 				metavar='<exec>',
    148 				type=str,
    149 				help='Run gdb on specified executable',
    150 				dest='gdb')
    151 		valgrind_gdb_group.add_argument('--valgrind', '-V',
    152 				action='store_true',
    153 				help='Run valgrind on IWD',
    154 				dest='valgrind')
    155 
    156 	# Overwrite to use a custom namespace class and parse from env
    157 	def parse_args(self, *args):
    158 		if len(sys.argv) > 1:
    159 			return super().parse_args(*args, namespace=RunnerNamespace())
    160 
    161 		options = []
    162 		for k, v in os.environ.items():
    163 			options.append('--' + k.replace('_', '-'))
    164 			options.append(v)
    165 
    166 		return self.parse_known_args(args=options, namespace=RunnerNamespace())[0]
    167 
    168 #
    169 # Arguments only needed outside the test environment
    170 #
    171 class RunnerArgParse(RunnerCoreArgParse):
    172 	def __init__(self, *args, **kwargs):
    173 		RunnerCoreArgParse.__init__(self, *args, **kwargs)
    174 
    175 		self.add_argument('--runner', '-r',
    176 				metavar='<runner type>',
    177 				type=str,
    178 				help='Type of runner to use (qemu, uml, host)',
    179 				dest='runner',
    180 				default=None)
    181 		self.add_argument('--kernel', '-k',
    182 				metavar='<kernel>',
    183 				type=os.path.abspath,
    184 				help='Path to kernel/uml image',
    185 				dest='kernel',
    186 				default=None)
    187 
    188 #
    189 # Class to sort out what type of runner this is, returns the RunnerAbstract
    190 # implementation.
    191 #
    192 class Runner:
    193 	def __new__(self):
    194 		parser = RunnerArgParse(description='IWD Test Runner')
    195 
    196 		args = parser.parse_args()
    197 
    198 		# Common options
    199 		args.PATH = os.environ['PATH']
    200 
    201 		if 'testhome' not in args.to_cmd():
    202 			if os.getcwd().endswith('tools'):
    203 				args.testhome = '%s/../' % os.getcwd()
    204 			else:
    205 				args.testhome = os.getcwd()
    206 
    207 		# If no runner is specified but we have a kernel image assume
    208 		# if the kernel is executable its UML, otherwise qemu
    209 		if not args.runner:
    210 			if not args.kernel:
    211 				raise Exception("Please specify --runner/--kernel")
    212 
    213 			if os.access(args.kernel, os.X_OK):
    214 				args.runner = 'uml'
    215 			else:
    216 				args.runner = 'qemu'
    217 
    218 		if args.runner == 'uml':
    219 			return UmlRunner(args)
    220 		elif args.runner == 'qemu':
    221 			return QemuRunner(args)
    222 		else:
    223 			raise Exception("Unknown runner %s" % args.runner)
    224 
    225 class RunnerAbstract:
    226 	cmdline = []
    227 	env = None
    228 	name = "unnamed"
    229 
    230 	def __init__(self, args):
    231 		self.args = args
    232 
    233 		if len(sys.argv) <= 1:
    234 			return
    235 
    236 		if os.path.exists('run-tests'):
    237 			self.init = os.path.abspath('run-tests')
    238 		elif os.path.exists('tools/run-tests'):
    239 			self.init = os.path.abspath('tools/run-tests')
    240 		else:
    241 			raise Exception("Cannot locate run-tests binary")
    242 
    243 	def start(self):
    244 		print("Starting %s" % self.name)
    245 		os.execlpe(self.cmdline[0], *self.cmdline, self.env)
    246 
    247 	def prepare_environment(self):
    248 		path = os.environ['PATH']
    249 		os.environ['PATH'] = '%s/src' % self.args.testhome
    250 		os.environ['PATH'] += ':%s/tools' % self.args.testhome
    251 		os.environ['PATH'] += ':%s/client' % self.args.testhome
    252 		os.environ['PATH'] += ':%s/monitor' % self.args.testhome
    253 		os.environ['PATH'] += ':%s/wired' % self.args.testhome
    254 		os.environ['PATH'] += ':' + path
    255 
    256 		sys.path.append(self.args.testhome + '/autotests/util')
    257 
    258 		if not os.path.exists('/tmp/iwd'):
    259 			os.mkdir('/tmp/iwd')
    260 
    261 		#
    262 		# This prevents any print() calls in this script from printing unless
    263 		# --debug is passed. For an 'always print' option use dbg()
    264 		#
    265 		if not self.args.dbg:
    266 			sys.stdout = open(os.devnull, 'w')
    267 
    268 		# Copy autotests/misc/{certs,secrets,phonesim} so any test can refer to them
    269 		if os.path.exists('/tmp/certs'):
    270 			rmtree('/tmp/certs')
    271 
    272 		if os.path.exists('/tmp/secrets'):
    273 			rmtree('/tmp/secrets')
    274 
    275 		copytree(self.args.testhome + '/autotests/misc/certs', '/tmp/certs')
    276 		copytree(self.args.testhome + '/autotests/misc/secrets', '/tmp/secrets')
    277 		copy(self.args.testhome + '/autotests/misc/phonesim/phonesim.conf', '/tmp')
    278 
    279 		# Clear out any log files from other test runs
    280 		if self.args.log:
    281 			for f in [os.path.join(self.args.log, file) for file in os.listdir(self.args.log)]:
    282 				print("removing %s" % f)
    283 
    284 				if os.path.isdir(f):
    285 					rmtree(f)
    286 				else:
    287 					os.remove(f)
    288 
    289 		fcntl.ioctl(STDIN_FILENO, TIOCSTTY, 1)
    290 
    291 		os.system('ip link set dev lo up')
    292 
    293 	def cleanup_environment(self):
    294 		rmtree('/tmp/iwd')
    295 		rmtree('/tmp/certs')
    296 		rmtree('/tmp/secrets')
    297 		os.remove('/tmp/phonesim.conf')
    298 
    299 		os.sync()
    300 
    301 	# For QEMU/UML runners
    302 	def _prepare_mounts(self, extra=[]):
    303 		mounted = []
    304 
    305 		for entry in mounts_common + extra:
    306 			if entry.target in mounted:
    307 				print("%s already mounted, skipping" % entry.target)
    308 				continue
    309 
    310 			try:
    311 				os.lstat(entry.target)
    312 			except:
    313 				os.mkdir(entry.target, 755)
    314 
    315 			mount(entry.source, entry.target, entry.fstype, entry.flags,
    316 				entry.options)
    317 
    318 			mounted.append(entry.target)
    319 
    320 		for entry in dev_table:
    321 			os.symlink(entry.target, entry.linkpath)
    322 
    323 		os.setsid()
    324 
    325 	# For QEMU/UML --log, --monitor, --result
    326 	def _prepare_outfiles(self):
    327 		append_gid_uid = False
    328 
    329 		uid = int(os.environ.get('SUDO_UID', os.getuid()))
    330 		gid = int(os.environ.get('SUDO_GID', os.getgid()))
    331 
    332 		if self.args.log:
    333 			if self.args.log == '/tmp':
    334 				raise Exception('Log directly cannot be /tmp')
    335 
    336 			append_gid_uid = True
    337 
    338 			if not os.path.exists(self.args.log):
    339 				os.mkdir(self.args.log)
    340 
    341 			if gid:
    342 				os.chown(self.args.log, uid, gid)
    343 
    344 		if self.args.monitor:
    345 			append_gid_uid = True
    346 
    347 			self.args.monitor_parent = os.path.abspath(
    348 						os.path.join(self.args.monitor, os.pardir))
    349 			if self.args.monitor_parent == '/tmp':
    350 				raise Exception('--monitor cannot be directly under /tmp')
    351 
    352 		if self.args.result:
    353 			append_gid_uid = True
    354 
    355 			self.args.result_parent = os.path.abspath(
    356 						os.path.join(self.args.result, os.pardir))
    357 			if self.args.result_parent == '/tmp':
    358 				raise Exception('--result cannot be directly under /tmp')
    359 
    360 		if append_gid_uid:
    361 			self.args.SUDO_UID = uid
    362 			self.args.SUDO_GID = gid
    363 
    364 	def stop(self):
    365 		exit()
    366 
    367 class QemuRunner(RunnerAbstract):
    368 	name = "Qemu Runner"
    369 
    370 	def __init__(self, args):
    371 		def mount_options(id):
    372 			return 'mount_tag=%s,security_model=passthrough,id=%s' % (id, id)
    373 
    374 		usb_adapters = None
    375 		pci_adapters = None
    376 		ram = 256
    377 
    378 		super().__init__(args)
    379 
    380 		if len(sys.argv) <= 1:
    381 			return
    382 
    383 		if not which('qemu-system-x86_64'):
    384 			raise Exception('Cannot locate qemu binary')
    385 
    386 		if not args.kernel or not os.path.exists(args.kernel):
    387 			raise Exception('Cannot locate kernel image %s' % args.kernel)
    388 
    389 		self._prepare_outfiles()
    390 
    391 		self.args.timeout = 240
    392 
    393 		if args.hw:
    394 			if os.path.isfile(args.hw):
    395 				hw_conf = ConfigParser()
    396 				hw_conf.read(args.hw)
    397 
    398 				if hw_conf.has_section('USBAdapters'):
    399 					# The actual key name of the adapter
    400 					# doesn't matter since all we need is the
    401 					# bus/address. This gets named by the kernel
    402 					# anyways once in the VM.
    403 					usb_adapters = [v for v in hw_conf['USBAdapters'].values()]
    404 
    405 			pci_adapters = self._find_pci_adapters()
    406 
    407 		kern_log = "ignore_loglevel" if "kernel" in args.verbose else "quiet"
    408 
    409 		if args.valgrind:
    410 			ram *= 2
    411 
    412 		qemu_cmdline = [
    413 			'qemu-system-x86_64',
    414 			'-machine', 'type=q35,accel=kvm:tcg',
    415 			'-nodefaults', '-no-user-config', '-monitor', 'none',
    416 			'-display', 'none', '-m', '%dM' % ram, '-nographic', '-vga',
    417 			'none',
    418 			'-no-reboot', '-fsdev',
    419 			'local,id=fsdev-root,path=/,readonly=on,security_model=none,multidevs=remap',
    420 			'-device',
    421 			'virtio-9p-pci,fsdev=fsdev-root,mount_tag=/dev/root',
    422 			'-chardev', 'stdio,id=chardev-serial0,signal=off',
    423 			'-device', 'pci-serial,chardev=chardev-serial0',
    424 			'-device', 'virtio-rng-pci',
    425 			'-kernel', args.kernel,
    426 			'-smp', '2',
    427 			'-append',
    428 			'console=ttyS0,115200n8 earlyprintk=serial \
    429 				rootfstype=9p root=/dev/root \
    430 				rootflags=trans=virtio \
    431 				acpi=off pci=noacpi %s ro \
    432 				mac80211_hwsim.radios=0 init=%s %s' %
    433 						(kern_log, self.init, args.to_cmd()),
    434 		]
    435 
    436 		# Add two ethernet devices for testing EAD
    437 		qemu_cmdline.extend([
    438 				'-net', 'nic,model=virtio',
    439 				'-net', 'nic,model=virtio',
    440 				'-net', 'user'
    441 		])
    442 
    443 		if usb_adapters:
    444 			for bus, addr in [s.split(',') for s in usb_adapters]:
    445 				qemu_cmdline.extend(['-usb',
    446 							'-device',
    447 							'usb-host,hostbus=%s,hostaddr=%s' % \
    448 							(bus, addr)])
    449 		if pci_adapters:
    450 			qemu_cmdline.extend(['-enable-kvm'])
    451 			for addr in pci_adapters:
    452 				qemu_cmdline.extend(['-device', 'vfio-pci,host=%s' % addr])
    453 
    454 		qemu_cmdline.extend([
    455 			'-virtfs',
    456 			'local,path=%s,%s' % (args.testhome, mount_options('homedir'))
    457 		])
    458 
    459 		if args.log:
    460 			#
    461 			# Creates a virtfs device that can be mounted. This mount
    462 			# will point back to the provided log directory and is
    463 			# writable unlike the rest of the mounted file system.
    464 			#
    465 			qemu_cmdline.extend([
    466 				'-virtfs',
    467 				'local,path=%s,%s' % (args.log,
    468 							mount_options('logdir'))
    469 			])
    470 
    471 		if args.monitor:
    472 			qemu_cmdline.extend([
    473 				'-virtfs',
    474 				'local,path=%s,%s' % (self.args.monitor_parent,
    475 							mount_options('mondir'))
    476 			])
    477 
    478 		if args.result:
    479 			qemu_cmdline.extend([
    480 				'-virtfs',
    481 				'local,path=%s,%s' % (self.args.result_parent,
    482 							mount_options('resultdir'))
    483 			])
    484 
    485 
    486 		self.cmdline = qemu_cmdline
    487 
    488 	def _find_pci_adapters(self):
    489 		adapters = []
    490 
    491 		try:
    492 			files = os.listdir('/sys/module/vfio_pci/drivers/pci:vfio-pci')
    493 		except:
    494 			return None
    495 
    496 		for bus_addr in files:
    497 			if not bus_addr.startswith('0000:'):
    498 				continue
    499 
    500 			adapters.append(bus_addr.replace('0000:', ''))
    501 
    502 		if len(adapters) == 0:
    503 			return None
    504 
    505 		return adapters
    506 
    507 	def prepare_environment(self):
    508 		mounts = [ MountInfo('debugfs', 'debugfs', '/sys/kernel/debug', '', 0) ]
    509 
    510 		mounts.append(MountInfo('9p', 'homedir', self.args.testhome,
    511 					'trans=virtio,version=9p2000.L,msize=10240', 0))
    512 
    513 		if self.args.log:
    514 			mounts.append(MountInfo('9p', 'logdir', self.args.log,
    515 					'trans=virtio,version=9p2000.L,msize=10240', 0))
    516 
    517 		if self.args.monitor:
    518 			mounts.append(MountInfo('9p', 'mondir', self.args.monitor_parent,
    519 					'trans=virtio,version=9p2000.L,msize=10240', 0))
    520 
    521 		if self.args.result:
    522 			mounts.append(MountInfo('9p', 'resultdir', self.args.result_parent,
    523 					'trans=virtio,version=9p2000.L,msize=10240', 0))
    524 
    525 		self._prepare_mounts(extra=mounts)
    526 
    527 		super().prepare_environment()
    528 
    529 	def stop(self):
    530 		RB_AUTOBOOT = 0x01234567
    531 		#
    532 		# Killing init() results in a kernel panic. For QEMU a graceful
    533 		# exit is achieved with RB_AUTOBOOT
    534 		#
    535 		libc.reboot(RB_AUTOBOOT)
    536 
    537 class UmlRunner(RunnerAbstract):
    538 	name = "UML Runner"
    539 
    540 	def __init__(self, args):
    541 		super().__init__(args)
    542 
    543 		if len(sys.argv) <= 1:
    544 			return
    545 
    546 		if not which(args.kernel):
    547 			raise Exception('Cannot locate UML binary %s' % args.kernel)
    548 
    549 		self._prepare_outfiles()
    550 
    551 		self.args.timeout = 1000
    552 
    553 		kern_log = "ignore_loglevel" if "kernel" in args.verbose else "quiet"
    554 
    555 		if self.args.valgrind:
    556 			ram = 512
    557 		else:
    558 			ram = 256
    559 
    560 		cmd = [args.kernel, 'rootfstype=hostfs', 'ro', f'mem={ram}M', 'mac80211_hwsim.radios=0',
    561 				'time-travel=inf-cpu', 'eth0=mcast', 'eth1=mcast',
    562 				'%s' % kern_log, 'init=%s' % self.init]
    563 		cmd.extend(args.to_cmd().split(' '))
    564 
    565 		self.cmdline = cmd
    566 
    567 	def prepare_environment(self):
    568 		mounts = []
    569 
    570 		if self.args.log:
    571 			mounts.append(MountInfo('hostfs', 'hostfs', self.args.log,
    572 						self.args.log, 0))
    573 
    574 		if self.args.monitor:
    575 			mounts.append(MountInfo('hostfs', 'hostfs', self.args.monitor_parent,
    576 						self.args.monitor_parent, 0))
    577 
    578 		if self.args.result:
    579 			mounts.append(MountInfo('hostfs', 'hostfs', self.args.result_parent,
    580 						self.args.result_parent, 0))
    581 
    582 		mounts.append(MountInfo('hostfs', 'hostfs', self.args.testhome,
    583 					self.args.testhome, 0))
    584 
    585 		self._prepare_mounts(extra=mounts)
    586 
    587 		super().prepare_environment()
    588 
    589 	def stop(self):
    590 		RB_POWER_OFF = 0x4321fedc
    591 		#
    592 		# Killing init() results in a kernel panic. For UML a graceful
    593 		# exit is achieved with RB_POWER_OFF
    594 		#
    595 		libc.reboot(RB_POWER_OFF)