Patrick Williams | c0f7c04 | 2017-02-23 20:41:17 -0600 | [diff] [blame] | 1 | #!/usr/bin/env python3 |
| 2 | |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 3 | # Handle running OE images standalone with QEMU |
| 4 | # |
| 5 | # Copyright (C) 2006-2011 Linux Foundation |
Patrick Williams | c0f7c04 | 2017-02-23 20:41:17 -0600 | [diff] [blame] | 6 | # Copyright (c) 2016 Wind River Systems, Inc. |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 7 | # |
| 8 | # This program is free software; you can redistribute it and/or modify |
| 9 | # it under the terms of the GNU General Public License version 2 as |
| 10 | # published by the Free Software Foundation. |
| 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 |
| 15 | # GNU General Public License for more details. |
| 16 | # |
| 17 | # You should have received a copy of the GNU General Public License along |
| 18 | # with this program; if not, write to the Free Software Foundation, Inc., |
| 19 | # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. |
| 20 | |
Patrick Williams | c0f7c04 | 2017-02-23 20:41:17 -0600 | [diff] [blame] | 21 | import os |
| 22 | import sys |
| 23 | import logging |
| 24 | import subprocess |
| 25 | import re |
| 26 | import fcntl |
| 27 | import shutil |
| 28 | import glob |
| 29 | import configparser |
Patrick Williams | d8c66bc | 2016-06-20 12:57:21 -0500 | [diff] [blame] | 30 | |
Patrick Williams | c0f7c04 | 2017-02-23 20:41:17 -0600 | [diff] [blame] | 31 | class OEPathError(Exception): |
| 32 | """Custom Exception to give better guidance on missing binaries""" |
| 33 | def __init__(self, message): |
| 34 | self.message = "In order for this script to dynamically infer paths\n \ |
| 35 | kernels or filesystem images, you either need bitbake in your PATH\n \ |
| 36 | or to source oe-init-build-env before running this script.\n\n \ |
| 37 | Dynamic path inference can be avoided by passing a *.qemuboot.conf to\n \ |
| 38 | runqemu, i.e. `runqemu /path/to/my-image-name.qemuboot.conf`\n\n %s" % message |
| 39 | |
| 40 | |
| 41 | def create_logger(): |
| 42 | logger = logging.getLogger('runqemu') |
| 43 | logger.setLevel(logging.INFO) |
| 44 | |
| 45 | # create console handler and set level to debug |
| 46 | ch = logging.StreamHandler() |
| 47 | ch.setLevel(logging.INFO) |
| 48 | |
| 49 | # create formatter |
| 50 | formatter = logging.Formatter('%(name)s - %(levelname)s - %(message)s') |
| 51 | |
| 52 | # add formatter to ch |
| 53 | ch.setFormatter(formatter) |
| 54 | |
| 55 | # add ch to logger |
| 56 | logger.addHandler(ch) |
| 57 | |
| 58 | return logger |
| 59 | |
| 60 | logger = create_logger() |
| 61 | |
| 62 | def print_usage(): |
| 63 | print(""" |
Patrick Williams | d8c66bc | 2016-06-20 12:57:21 -0500 | [diff] [blame] | 64 | Usage: you can run this script with any valid combination |
| 65 | of the following environment variables (in any order): |
| 66 | KERNEL - the kernel image file to use |
| 67 | ROOTFS - the rootfs image file or nfsroot directory to use |
| 68 | MACHINE - the machine name (optional, autodetected from KERNEL filename if unspecified) |
| 69 | Simplified QEMU command-line options can be passed with: |
Patrick Williams | c0f7c04 | 2017-02-23 20:41:17 -0600 | [diff] [blame] | 70 | nographic - disable video console |
| 71 | serial - enable a serial console on /dev/ttyS0 |
| 72 | slirp - enable user networking, no root privileges is required |
| 73 | kvm - enable KVM when running x86/x86_64 (VT-capable CPU required) |
| 74 | kvm-vhost - enable KVM with vhost when running x86/x86_64 (VT-capable CPU required) |
Patrick Williams | d8c66bc | 2016-06-20 12:57:21 -0500 | [diff] [blame] | 75 | publicvnc - enable a VNC server open to all hosts |
Patrick Williams | c0f7c04 | 2017-02-23 20:41:17 -0600 | [diff] [blame] | 76 | audio - enable audio |
| 77 | tcpserial=<port> - specify tcp serial port number |
| 78 | biosdir=<dir> - specify custom bios dir |
| 79 | biosfilename=<filename> - specify bios filename |
| 80 | qemuparams=<xyz> - specify custom parameters to QEMU |
| 81 | bootparams=<xyz> - specify custom kernel parameters during boot |
| 82 | help: print this text |
Patrick Williams | d8c66bc | 2016-06-20 12:57:21 -0500 | [diff] [blame] | 83 | |
| 84 | Examples: |
Patrick Williams | c0f7c04 | 2017-02-23 20:41:17 -0600 | [diff] [blame] | 85 | runqemu qemuarm |
| 86 | runqemu tmp/deploy/images/qemuarm |
| 87 | runqemu tmp/deploy/images/qemux86/.qemuboot.conf |
| 88 | runqemu qemux86-64 core-image-sato ext4 |
| 89 | runqemu qemux86-64 wic-image-minimal wic |
| 90 | runqemu path/to/bzImage-qemux86.bin path/to/nfsrootdir/ serial |
| 91 | runqemu qemux86 iso/hddimg/vmdk/qcow2/vdi/ramfs/cpio.gz... |
| 92 | runqemu qemux86 qemuparams="-m 256" |
| 93 | runqemu qemux86 bootparams="psplash=false" |
| 94 | runqemu path/to/<image>-<machine>.vmdk |
| 95 | runqemu path/to/<image>-<machine>.wic |
| 96 | """) |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 97 | |
Patrick Williams | c0f7c04 | 2017-02-23 20:41:17 -0600 | [diff] [blame] | 98 | def check_tun(): |
| 99 | """Check /dev/net/run""" |
| 100 | dev_tun = '/dev/net/tun' |
| 101 | if not os.path.exists(dev_tun): |
| 102 | raise Exception("TUN control device %s is unavailable; you may need to enable TUN (e.g. sudo modprobe tun)" % dev_tun) |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 103 | |
Patrick Williams | c0f7c04 | 2017-02-23 20:41:17 -0600 | [diff] [blame] | 104 | if not os.access(dev_tun, os.W_OK): |
| 105 | raise Exception("TUN control device %s is not writable, please fix (e.g. sudo chmod 666 %s)" % (dev_tun, dev_tun)) |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 106 | |
Patrick Williams | c0f7c04 | 2017-02-23 20:41:17 -0600 | [diff] [blame] | 107 | def check_libgl(qemu_bin): |
| 108 | cmd = 'ldd %s' % qemu_bin |
| 109 | logger.info('Running %s...' % cmd) |
| 110 | need_gl = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE).stdout.read().decode('utf-8') |
| 111 | if re.search('libGLU', need_gl): |
| 112 | # We can't run without a libGL.so |
| 113 | libgl = False |
| 114 | check_files = (('/usr/lib/libGL.so', '/usr/lib/libGLU.so'), \ |
| 115 | ('/usr/lib64/libGL.so', '/usr/lib64/libGLU.so'), \ |
| 116 | ('/usr/lib/*-linux-gnu/libGL.so', '/usr/lib/*-linux-gnu/libGLU.so')) |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 117 | |
Patrick Williams | c0f7c04 | 2017-02-23 20:41:17 -0600 | [diff] [blame] | 118 | for (f1, f2) in check_files: |
| 119 | if re.search('\*', f1): |
| 120 | for g1 in glob.glob(f1): |
| 121 | if libgl: |
| 122 | break |
| 123 | if os.path.exists(g1): |
| 124 | for g2 in glob.glob(f2): |
| 125 | if os.path.exists(g2): |
| 126 | libgl = True |
| 127 | break |
| 128 | if libgl: |
| 129 | break |
| 130 | else: |
| 131 | if os.path.exists(f1) and os.path.exists(f2): |
| 132 | libgl = True |
| 133 | break |
| 134 | if not libgl: |
| 135 | logger.error("You need libGL.so and libGLU.so to exist in your library path to run the QEMU emulator.") |
| 136 | logger.error("Ubuntu package names are: libgl1-mesa-dev and libglu1-mesa-dev.") |
| 137 | logger.error("Fedora package names are: mesa-libGL-devel mesa-libGLU-devel.") |
| 138 | raise Exception('%s requires libGLU, but not found' % qemu_bin) |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 139 | |
Patrick Williams | c0f7c04 | 2017-02-23 20:41:17 -0600 | [diff] [blame] | 140 | def get_first_file(cmds): |
| 141 | """Return first file found in wildcard cmds""" |
| 142 | for cmd in cmds: |
| 143 | all_files = glob.glob(cmd) |
| 144 | if all_files: |
| 145 | for f in all_files: |
| 146 | if not os.path.isdir(f): |
| 147 | return f |
| 148 | return '' |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 149 | |
Patrick Williams | c0f7c04 | 2017-02-23 20:41:17 -0600 | [diff] [blame] | 150 | class BaseConfig(object): |
| 151 | def __init__(self): |
| 152 | # Vars can be merged with .qemuboot.conf, use a dict to manage them. |
| 153 | self.d = { |
| 154 | 'MACHINE': '', |
| 155 | 'DEPLOY_DIR_IMAGE': '', |
| 156 | 'QB_KERNEL_ROOT': '/dev/vda', |
| 157 | } |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 158 | |
Patrick Williams | c0f7c04 | 2017-02-23 20:41:17 -0600 | [diff] [blame] | 159 | self.qemu_opt = '' |
| 160 | self.qemu_opt_script = '' |
| 161 | self.nfs_dir = '' |
| 162 | self.clean_nfs_dir = False |
| 163 | self.nfs_server = '' |
| 164 | self.rootfs = '' |
| 165 | self.qemuboot = '' |
| 166 | self.qbconfload = False |
| 167 | self.kernel = '' |
| 168 | self.kernel_cmdline = '' |
| 169 | self.kernel_cmdline_script = '' |
Brad Bishop | 37a0e4d | 2017-12-04 01:01:44 -0500 | [diff] [blame] | 170 | self.bootparams = '' |
Patrick Williams | c0f7c04 | 2017-02-23 20:41:17 -0600 | [diff] [blame] | 171 | self.dtb = '' |
| 172 | self.fstype = '' |
| 173 | self.kvm_enabled = False |
| 174 | self.vhost_enabled = False |
| 175 | self.slirp_enabled = False |
| 176 | self.nfs_instance = 0 |
| 177 | self.nfs_running = False |
| 178 | self.serialstdio = False |
| 179 | self.cleantap = False |
| 180 | self.saved_stty = '' |
| 181 | self.audio_enabled = False |
| 182 | self.tcpserial_portnum = '' |
| 183 | self.custombiosdir = '' |
| 184 | self.lock = '' |
| 185 | self.lock_descriptor = '' |
| 186 | self.bitbake_e = '' |
| 187 | self.snapshot = False |
| 188 | self.fstypes = ('ext2', 'ext3', 'ext4', 'jffs2', 'nfs', 'btrfs', 'cpio.gz', 'cpio', 'ramfs') |
| 189 | self.vmtypes = ('hddimg', 'hdddirect', 'wic', 'vmdk', 'qcow2', 'vdi', 'iso') |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 190 | |
Patrick Williams | c0f7c04 | 2017-02-23 20:41:17 -0600 | [diff] [blame] | 191 | def acquire_lock(self): |
| 192 | logger.info("Acquiring lockfile %s..." % self.lock) |
| 193 | try: |
| 194 | self.lock_descriptor = open(self.lock, 'w') |
| 195 | fcntl.flock(self.lock_descriptor, fcntl.LOCK_EX|fcntl.LOCK_NB) |
| 196 | except Exception as e: |
| 197 | logger.info("Acquiring lockfile %s failed: %s" % (self.lock, e)) |
| 198 | if self.lock_descriptor: |
| 199 | self.lock_descriptor.close() |
| 200 | return False |
| 201 | return True |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 202 | |
Patrick Williams | c0f7c04 | 2017-02-23 20:41:17 -0600 | [diff] [blame] | 203 | def release_lock(self): |
| 204 | fcntl.flock(self.lock_descriptor, fcntl.LOCK_UN) |
| 205 | self.lock_descriptor.close() |
| 206 | os.remove(self.lock) |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 207 | |
Patrick Williams | c0f7c04 | 2017-02-23 20:41:17 -0600 | [diff] [blame] | 208 | def get(self, key): |
| 209 | if key in self.d: |
| 210 | return self.d.get(key) |
| 211 | else: |
| 212 | return '' |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 213 | |
Patrick Williams | c0f7c04 | 2017-02-23 20:41:17 -0600 | [diff] [blame] | 214 | def set(self, key, value): |
| 215 | self.d[key] = value |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 216 | |
Patrick Williams | c0f7c04 | 2017-02-23 20:41:17 -0600 | [diff] [blame] | 217 | def is_deploy_dir_image(self, p): |
| 218 | if os.path.isdir(p): |
| 219 | if not re.search('.qemuboot.conf$', '\n'.join(os.listdir(p)), re.M): |
| 220 | logger.info("Can't find required *.qemuboot.conf in %s" % p) |
| 221 | return False |
| 222 | if not re.search('-image-', '\n'.join(os.listdir(p))): |
| 223 | logger.info("Can't find *-image-* in %s" % p) |
| 224 | return False |
| 225 | return True |
| 226 | else: |
| 227 | return False |
Patrick Williams | f1e5d69 | 2016-03-30 15:21:19 -0500 | [diff] [blame] | 228 | |
Patrick Williams | c0f7c04 | 2017-02-23 20:41:17 -0600 | [diff] [blame] | 229 | def check_arg_fstype(self, fst): |
| 230 | """Check and set FSTYPE""" |
| 231 | if fst not in self.fstypes + self.vmtypes: |
| 232 | logger.warn("Maybe unsupported FSTYPE: %s" % fst) |
| 233 | if not self.fstype or self.fstype == fst: |
| 234 | if fst == 'ramfs': |
| 235 | fst = 'cpio.gz' |
| 236 | self.fstype = fst |
| 237 | else: |
| 238 | raise Exception("Conflicting: FSTYPE %s and %s" % (self.fstype, fst)) |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 239 | |
Patrick Williams | c0f7c04 | 2017-02-23 20:41:17 -0600 | [diff] [blame] | 240 | def set_machine_deploy_dir(self, machine, deploy_dir_image): |
| 241 | """Set MACHINE and DEPLOY_DIR_IMAGE""" |
| 242 | logger.info('MACHINE: %s' % machine) |
| 243 | self.set("MACHINE", machine) |
| 244 | logger.info('DEPLOY_DIR_IMAGE: %s' % deploy_dir_image) |
| 245 | self.set("DEPLOY_DIR_IMAGE", deploy_dir_image) |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 246 | |
Patrick Williams | c0f7c04 | 2017-02-23 20:41:17 -0600 | [diff] [blame] | 247 | def check_arg_nfs(self, p): |
| 248 | if os.path.isdir(p): |
| 249 | self.nfs_dir = p |
| 250 | else: |
| 251 | m = re.match('(.*):(.*)', p) |
| 252 | self.nfs_server = m.group(1) |
| 253 | self.nfs_dir = m.group(2) |
| 254 | self.rootfs = "" |
| 255 | self.check_arg_fstype('nfs') |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 256 | |
Patrick Williams | c0f7c04 | 2017-02-23 20:41:17 -0600 | [diff] [blame] | 257 | def check_arg_path(self, p): |
| 258 | """ |
| 259 | - Check whether it is <image>.qemuboot.conf or contains <image>.qemuboot.conf |
| 260 | - Check whether is a kernel file |
| 261 | - Check whether is a image file |
| 262 | - Check whether it is a nfs dir |
| 263 | """ |
| 264 | if p.endswith('.qemuboot.conf'): |
| 265 | self.qemuboot = p |
| 266 | self.qbconfload = True |
| 267 | elif re.search('\.bin$', p) or re.search('bzImage', p) or \ |
| 268 | re.search('zImage', p) or re.search('vmlinux', p) or \ |
| 269 | re.search('fitImage', p) or re.search('uImage', p): |
| 270 | self.kernel = p |
| 271 | elif os.path.exists(p) and (not os.path.isdir(p)) and re.search('-image-', os.path.basename(p)): |
| 272 | self.rootfs = p |
| 273 | dirpath = os.path.dirname(p) |
| 274 | m = re.search('(.*)\.(.*)$', p) |
| 275 | if m: |
| 276 | qb = '%s%s' % (re.sub('\.rootfs$', '', m.group(1)), '.qemuboot.conf') |
| 277 | if os.path.exists(qb): |
| 278 | self.qemuboot = qb |
| 279 | self.qbconfload = True |
| 280 | else: |
| 281 | logger.warn("%s doesn't exist" % qb) |
| 282 | fst = m.group(2) |
| 283 | self.check_arg_fstype(fst) |
| 284 | else: |
| 285 | raise Exception("Can't find FSTYPE from: %s" % p) |
| 286 | elif os.path.isdir(p) or re.search(':', arg) and re.search('/', arg): |
| 287 | if self.is_deploy_dir_image(p): |
| 288 | logger.info('DEPLOY_DIR_IMAGE: %s' % p) |
| 289 | self.set("DEPLOY_DIR_IMAGE", p) |
| 290 | else: |
| 291 | logger.info("Assuming %s is an nfs rootfs" % p) |
| 292 | self.check_arg_nfs(p) |
| 293 | else: |
| 294 | raise Exception("Unknown path arg %s" % p) |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 295 | |
Patrick Williams | c0f7c04 | 2017-02-23 20:41:17 -0600 | [diff] [blame] | 296 | def check_arg_machine(self, arg): |
| 297 | """Check whether it is a machine""" |
| 298 | if self.get('MACHINE') and self.get('MACHINE') != arg or re.search('/', arg): |
| 299 | raise Exception("Unknown arg: %s" % arg) |
| 300 | elif self.get('MACHINE') == arg: |
| 301 | return |
| 302 | logger.info('Assuming MACHINE = %s' % arg) |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 303 | |
Patrick Williams | c0f7c04 | 2017-02-23 20:41:17 -0600 | [diff] [blame] | 304 | # if we're running under testimage, or similarly as a child |
| 305 | # of an existing bitbake invocation, we can't invoke bitbake |
| 306 | # to validate the MACHINE setting and must assume it's correct... |
| 307 | # FIXME: testimage.bbclass exports these two variables into env, |
| 308 | # are there other scenarios in which we need to support being |
| 309 | # invoked by bitbake? |
| 310 | deploy = os.environ.get('DEPLOY_DIR_IMAGE') |
| 311 | bbchild = deploy and os.environ.get('OE_TMPDIR') |
| 312 | if bbchild: |
| 313 | self.set_machine_deploy_dir(arg, deploy) |
| 314 | return |
| 315 | # also check whether we're running under a sourced toolchain |
| 316 | # environment file |
| 317 | if os.environ.get('OECORE_NATIVE_SYSROOT'): |
| 318 | self.set("MACHINE", arg) |
| 319 | return |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 320 | |
Patrick Williams | c0f7c04 | 2017-02-23 20:41:17 -0600 | [diff] [blame] | 321 | cmd = 'MACHINE=%s bitbake -e' % arg |
| 322 | logger.info('Running %s...' % cmd) |
| 323 | self.bitbake_e = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE).stdout.read().decode('utf-8') |
| 324 | # bitbake -e doesn't report invalid MACHINE as an error, so |
| 325 | # let's check DEPLOY_DIR_IMAGE to make sure that it is a valid |
| 326 | # MACHINE. |
| 327 | s = re.search('^DEPLOY_DIR_IMAGE="(.*)"', self.bitbake_e, re.M) |
| 328 | if s: |
| 329 | deploy_dir_image = s.group(1) |
| 330 | else: |
| 331 | raise Exception("bitbake -e %s" % self.bitbake_e) |
| 332 | if self.is_deploy_dir_image(deploy_dir_image): |
| 333 | self.set_machine_deploy_dir(arg, deploy_dir_image) |
| 334 | else: |
| 335 | logger.error("%s not a directory valid DEPLOY_DIR_IMAGE" % deploy_dir_image) |
| 336 | self.set("MACHINE", arg) |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 337 | |
Patrick Williams | c0f7c04 | 2017-02-23 20:41:17 -0600 | [diff] [blame] | 338 | def check_args(self): |
| 339 | unknown_arg = "" |
| 340 | for arg in sys.argv[1:]: |
| 341 | if arg in self.fstypes + self.vmtypes: |
| 342 | self.check_arg_fstype(arg) |
| 343 | elif arg == 'nographic': |
| 344 | self.qemu_opt_script += ' -nographic' |
| 345 | self.kernel_cmdline_script += ' console=ttyS0' |
| 346 | elif arg == 'serial': |
| 347 | self.kernel_cmdline_script += ' console=ttyS0' |
| 348 | self.serialstdio = True |
| 349 | elif arg == 'audio': |
| 350 | logger.info("Enabling audio in qemu") |
| 351 | logger.info("Please install sound drivers in linux host") |
| 352 | self.audio_enabled = True |
| 353 | elif arg == 'kvm': |
| 354 | self.kvm_enabled = True |
| 355 | elif arg == 'kvm-vhost': |
| 356 | self.vhost_enabled = True |
| 357 | elif arg == 'slirp': |
| 358 | self.slirp_enabled = True |
| 359 | elif arg == 'snapshot': |
| 360 | self.snapshot = True |
| 361 | elif arg == 'publicvnc': |
| 362 | self.qemu_opt_script += ' -vnc :0' |
| 363 | elif arg.startswith('tcpserial='): |
| 364 | self.tcpserial_portnum = arg[len('tcpserial='):] |
| 365 | elif arg.startswith('biosdir='): |
| 366 | self.custombiosdir = arg[len('biosdir='):] |
| 367 | elif arg.startswith('biosfilename='): |
| 368 | self.qemu_opt_script += ' -bios %s' % arg[len('biosfilename='):] |
| 369 | elif arg.startswith('qemuparams='): |
| 370 | self.qemu_opt_script += ' %s' % arg[len('qemuparams='):] |
| 371 | elif arg.startswith('bootparams='): |
Brad Bishop | 37a0e4d | 2017-12-04 01:01:44 -0500 | [diff] [blame] | 372 | self.bootparams = arg[len('bootparams='):] |
Patrick Williams | c0f7c04 | 2017-02-23 20:41:17 -0600 | [diff] [blame] | 373 | elif os.path.exists(arg) or (re.search(':', arg) and re.search('/', arg)): |
| 374 | self.check_arg_path(os.path.abspath(arg)) |
| 375 | elif re.search('-image-', arg): |
| 376 | # Lazy rootfs |
| 377 | self.rootfs = arg |
| 378 | else: |
| 379 | # At last, assume is it the MACHINE |
| 380 | if (not unknown_arg) or unknown_arg == arg: |
| 381 | unknown_arg = arg |
| 382 | else: |
| 383 | raise Exception("Can't handle two unknown args: %s %s" % (unknown_arg, arg)) |
| 384 | # Check to make sure it is a valid machine |
| 385 | if unknown_arg: |
| 386 | if self.get('MACHINE') == unknown_arg: |
| 387 | return |
| 388 | if not self.get('DEPLOY_DIR_IMAGE'): |
| 389 | # Trying to get DEPLOY_DIR_IMAGE from env. |
| 390 | p = os.getenv('DEPLOY_DIR_IMAGE') |
| 391 | if p and self.is_deploy_dir_image(p): |
| 392 | machine = os.path.basename(p) |
| 393 | if unknown_arg == machine: |
| 394 | self.set_machine_deploy_dir(machine, p) |
| 395 | return |
| 396 | else: |
| 397 | logger.info('DEPLOY_DIR_IMAGE: %s' % p) |
| 398 | self.set("DEPLOY_DIR_IMAGE", p) |
| 399 | self.check_arg_machine(unknown_arg) |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 400 | |
Patrick Williams | c0f7c04 | 2017-02-23 20:41:17 -0600 | [diff] [blame] | 401 | def check_kvm(self): |
| 402 | """Check kvm and kvm-host""" |
| 403 | if not (self.kvm_enabled or self.vhost_enabled): |
| 404 | self.qemu_opt_script += ' %s %s' % (self.get('QB_MACHINE'), self.get('QB_CPU')) |
| 405 | return |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 406 | |
Patrick Williams | c0f7c04 | 2017-02-23 20:41:17 -0600 | [diff] [blame] | 407 | if not self.get('QB_CPU_KVM'): |
| 408 | raise Exception("QB_CPU_KVM is NULL, this board doesn't support kvm") |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 409 | |
Patrick Williams | c0f7c04 | 2017-02-23 20:41:17 -0600 | [diff] [blame] | 410 | self.qemu_opt_script += ' %s %s' % (self.get('QB_MACHINE'), self.get('QB_CPU_KVM')) |
| 411 | yocto_kvm_wiki = "https://wiki.yoctoproject.org/wiki/How_to_enable_KVM_for_Poky_qemu" |
| 412 | yocto_paravirt_kvm_wiki = "https://wiki.yoctoproject.org/wiki/Running_an_x86_Yocto_Linux_image_under_QEMU_KVM" |
| 413 | dev_kvm = '/dev/kvm' |
| 414 | dev_vhost = '/dev/vhost-net' |
| 415 | with open('/proc/cpuinfo', 'r') as f: |
| 416 | kvm_cap = re.search('vmx|svm', "".join(f.readlines())) |
| 417 | if not kvm_cap: |
| 418 | logger.error("You are trying to enable KVM on a cpu without VT support.") |
| 419 | logger.error("Remove kvm from the command-line, or refer:") |
| 420 | raise Exception(yocto_kvm_wiki) |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 421 | |
Patrick Williams | c0f7c04 | 2017-02-23 20:41:17 -0600 | [diff] [blame] | 422 | if not os.path.exists(dev_kvm): |
| 423 | logger.error("Missing KVM device. Have you inserted kvm modules?") |
| 424 | logger.error("For further help see:") |
| 425 | raise Exception(yocto_kvm_wiki) |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 426 | |
Patrick Williams | c0f7c04 | 2017-02-23 20:41:17 -0600 | [diff] [blame] | 427 | if os.access(dev_kvm, os.W_OK|os.R_OK): |
| 428 | self.qemu_opt_script += ' -enable-kvm' |
| 429 | else: |
| 430 | logger.error("You have no read or write permission on /dev/kvm.") |
| 431 | logger.error("Please change the ownership of this file as described at:") |
| 432 | raise Exception(yocto_kvm_wiki) |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 433 | |
Patrick Williams | c0f7c04 | 2017-02-23 20:41:17 -0600 | [diff] [blame] | 434 | if self.vhost_enabled: |
| 435 | if not os.path.exists(dev_vhost): |
| 436 | logger.error("Missing virtio net device. Have you inserted vhost-net module?") |
| 437 | logger.error("For further help see:") |
| 438 | raise Exception(yocto_paravirt_kvm_wiki) |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 439 | |
Patrick Williams | c0f7c04 | 2017-02-23 20:41:17 -0600 | [diff] [blame] | 440 | if not os.access(dev_kvm, os.W_OK|os.R_OK): |
| 441 | logger.error("You have no read or write permission on /dev/vhost-net.") |
| 442 | logger.error("Please change the ownership of this file as described at:") |
| 443 | raise Exception(yocto_kvm_wiki) |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 444 | |
Patrick Williams | c0f7c04 | 2017-02-23 20:41:17 -0600 | [diff] [blame] | 445 | def check_fstype(self): |
| 446 | """Check and setup FSTYPE""" |
| 447 | if not self.fstype: |
| 448 | fstype = self.get('QB_DEFAULT_FSTYPE') |
| 449 | if fstype: |
| 450 | self.fstype = fstype |
| 451 | else: |
| 452 | raise Exception("FSTYPE is NULL!") |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 453 | |
Patrick Williams | c0f7c04 | 2017-02-23 20:41:17 -0600 | [diff] [blame] | 454 | def check_rootfs(self): |
| 455 | """Check and set rootfs""" |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 456 | |
Patrick Williams | c0f7c04 | 2017-02-23 20:41:17 -0600 | [diff] [blame] | 457 | if self.fstype == 'nfs': |
| 458 | return |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 459 | |
Patrick Williams | c0f7c04 | 2017-02-23 20:41:17 -0600 | [diff] [blame] | 460 | if self.rootfs and not os.path.exists(self.rootfs): |
| 461 | # Lazy rootfs |
| 462 | self.rootfs = "%s/%s-%s.%s" % (self.get('DEPLOY_DIR_IMAGE'), |
| 463 | self.rootfs, self.get('MACHINE'), |
| 464 | self.fstype) |
| 465 | elif not self.rootfs: |
| 466 | cmd_name = '%s/%s*.%s' % (self.get('DEPLOY_DIR_IMAGE'), self.get('IMAGE_NAME'), self.fstype) |
| 467 | cmd_link = '%s/%s*.%s' % (self.get('DEPLOY_DIR_IMAGE'), self.get('IMAGE_LINK_NAME'), self.fstype) |
| 468 | cmds = (cmd_name, cmd_link) |
| 469 | self.rootfs = get_first_file(cmds) |
| 470 | if not self.rootfs: |
| 471 | raise Exception("Failed to find rootfs: %s or %s" % cmds) |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 472 | |
Patrick Williams | c0f7c04 | 2017-02-23 20:41:17 -0600 | [diff] [blame] | 473 | if not os.path.exists(self.rootfs): |
| 474 | raise Exception("Can't find rootfs: %s" % self.rootfs) |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 475 | |
Patrick Williams | c0f7c04 | 2017-02-23 20:41:17 -0600 | [diff] [blame] | 476 | def check_kernel(self): |
| 477 | """Check and set kernel, dtb""" |
| 478 | # The vm image doesn't need a kernel |
| 479 | if self.fstype in self.vmtypes: |
| 480 | return |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 481 | |
Patrick Williams | c0f7c04 | 2017-02-23 20:41:17 -0600 | [diff] [blame] | 482 | deploy_dir_image = self.get('DEPLOY_DIR_IMAGE') |
| 483 | if not self.kernel: |
| 484 | kernel_match_name = "%s/%s" % (deploy_dir_image, self.get('QB_DEFAULT_KERNEL')) |
| 485 | kernel_match_link = "%s/%s" % (deploy_dir_image, self.get('KERNEL_IMAGETYPE')) |
| 486 | kernel_startswith = "%s/%s*" % (deploy_dir_image, self.get('KERNEL_IMAGETYPE')) |
| 487 | cmds = (kernel_match_name, kernel_match_link, kernel_startswith) |
| 488 | self.kernel = get_first_file(cmds) |
| 489 | if not self.kernel: |
| 490 | raise Exception('KERNEL not found: %s, %s or %s' % cmds) |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 491 | |
Patrick Williams | c0f7c04 | 2017-02-23 20:41:17 -0600 | [diff] [blame] | 492 | if not os.path.exists(self.kernel): |
| 493 | raise Exception("KERNEL %s not found" % self.kernel) |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 494 | |
Patrick Williams | c0f7c04 | 2017-02-23 20:41:17 -0600 | [diff] [blame] | 495 | dtb = self.get('QB_DTB') |
| 496 | if dtb: |
| 497 | cmd_match = "%s/%s" % (deploy_dir_image, dtb) |
| 498 | cmd_startswith = "%s/%s*" % (deploy_dir_image, dtb) |
| 499 | cmd_wild = "%s/*.dtb" % deploy_dir_image |
| 500 | cmds = (cmd_match, cmd_startswith, cmd_wild) |
| 501 | self.dtb = get_first_file(cmds) |
| 502 | if not os.path.exists(self.dtb): |
| 503 | raise Exception('DTB not found: %s, %s or %s' % cmds) |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 504 | |
Patrick Williams | c0f7c04 | 2017-02-23 20:41:17 -0600 | [diff] [blame] | 505 | def check_biosdir(self): |
| 506 | """Check custombiosdir""" |
| 507 | if not self.custombiosdir: |
| 508 | return |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 509 | |
Patrick Williams | c0f7c04 | 2017-02-23 20:41:17 -0600 | [diff] [blame] | 510 | biosdir = "" |
| 511 | biosdir_native = "%s/%s" % (self.get('STAGING_DIR_NATIVE'), self.custombiosdir) |
| 512 | biosdir_host = "%s/%s" % (self.get('STAGING_DIR_HOST'), self.custombiosdir) |
| 513 | for i in (self.custombiosdir, biosdir_native, biosdir_host): |
| 514 | if os.path.isdir(i): |
| 515 | biosdir = i |
| 516 | break |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 517 | |
Patrick Williams | c0f7c04 | 2017-02-23 20:41:17 -0600 | [diff] [blame] | 518 | if biosdir: |
| 519 | logger.info("Assuming biosdir is: %s" % biosdir) |
| 520 | self.qemu_opt_script += ' -L %s' % biosdir |
| 521 | else: |
| 522 | logger.error("Custom BIOS directory not found. Tried: %s, %s, and %s" % (self.custombiosdir, biosdir_native, biosdir_host)) |
| 523 | raise Exception("Invalid custombiosdir: %s" % self.custombiosdir) |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 524 | |
Patrick Williams | c0f7c04 | 2017-02-23 20:41:17 -0600 | [diff] [blame] | 525 | def check_mem(self): |
| 526 | s = re.search('-m +([0-9]+)', self.qemu_opt_script) |
| 527 | if s: |
| 528 | self.set('QB_MEM', '-m %s' % s.group(1)) |
| 529 | elif not self.get('QB_MEM'): |
| 530 | logger.info('QB_MEM is not set, use 512M by default') |
| 531 | self.set('QB_MEM', '-m 512') |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 532 | |
Patrick Williams | c0f7c04 | 2017-02-23 20:41:17 -0600 | [diff] [blame] | 533 | self.kernel_cmdline_script += ' mem=%s' % self.get('QB_MEM').replace('-m','').strip() + 'M' |
| 534 | self.qemu_opt_script += ' %s' % self.get('QB_MEM') |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 535 | |
Patrick Williams | c0f7c04 | 2017-02-23 20:41:17 -0600 | [diff] [blame] | 536 | def check_tcpserial(self): |
| 537 | if self.tcpserial_portnum: |
| 538 | if self.get('QB_TCPSERIAL_OPT'): |
| 539 | self.qemu_opt_script += ' ' + self.get('QB_TCPSERIAL_OPT').replace('@PORT@', self.tcpserial_portnum) |
| 540 | else: |
| 541 | self.qemu_opt_script += ' -serial tcp:127.0.0.1:%s' % self.tcpserial_portnum |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 542 | |
Patrick Williams | c0f7c04 | 2017-02-23 20:41:17 -0600 | [diff] [blame] | 543 | def check_and_set(self): |
| 544 | """Check configs sanity and set when needed""" |
| 545 | self.validate_paths() |
| 546 | check_tun() |
| 547 | # Check audio |
| 548 | if self.audio_enabled: |
| 549 | if not self.get('QB_AUDIO_DRV'): |
| 550 | raise Exception("QB_AUDIO_DRV is NULL, this board doesn't support audio") |
| 551 | if not self.get('QB_AUDIO_OPT'): |
| 552 | logger.warn('QB_AUDIO_OPT is NULL, you may need define it to make audio work') |
| 553 | else: |
| 554 | self.qemu_opt_script += ' %s' % self.get('QB_AUDIO_OPT') |
| 555 | os.putenv('QEMU_AUDIO_DRV', self.get('QB_AUDIO_DRV')) |
| 556 | else: |
| 557 | os.putenv('QEMU_AUDIO_DRV', 'none') |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 558 | |
Patrick Williams | c0f7c04 | 2017-02-23 20:41:17 -0600 | [diff] [blame] | 559 | self.check_kvm() |
| 560 | self.check_fstype() |
| 561 | self.check_rootfs() |
| 562 | self.check_kernel() |
| 563 | self.check_biosdir() |
| 564 | self.check_mem() |
| 565 | self.check_tcpserial() |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 566 | |
Patrick Williams | c0f7c04 | 2017-02-23 20:41:17 -0600 | [diff] [blame] | 567 | def read_qemuboot(self): |
| 568 | if not self.qemuboot: |
| 569 | if self.get('DEPLOY_DIR_IMAGE'): |
| 570 | deploy_dir_image = self.get('DEPLOY_DIR_IMAGE') |
| 571 | elif os.getenv('DEPLOY_DIR_IMAGE'): |
| 572 | deploy_dir_image = os.getenv('DEPLOY_DIR_IMAGE') |
| 573 | else: |
| 574 | logger.info("Can't find qemuboot conf file, DEPLOY_DIR_IMAGE is NULL!") |
| 575 | return |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 576 | |
Patrick Williams | c0f7c04 | 2017-02-23 20:41:17 -0600 | [diff] [blame] | 577 | if self.rootfs and not os.path.exists(self.rootfs): |
| 578 | # Lazy rootfs |
| 579 | machine = self.get('MACHINE') |
| 580 | if not machine: |
| 581 | machine = os.path.basename(deploy_dir_image) |
| 582 | self.qemuboot = "%s/%s-%s.qemuboot.conf" % (deploy_dir_image, |
| 583 | self.rootfs, machine) |
| 584 | else: |
| 585 | cmd = 'ls -t %s/*.qemuboot.conf' % deploy_dir_image |
| 586 | logger.info('Running %s...' % cmd) |
| 587 | qbs = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE).stdout.read().decode('utf-8') |
| 588 | if qbs: |
| 589 | self.qemuboot = qbs.split()[0] |
| 590 | self.qbconfload = True |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 591 | |
Patrick Williams | c0f7c04 | 2017-02-23 20:41:17 -0600 | [diff] [blame] | 592 | if not self.qemuboot: |
| 593 | # If we haven't found a .qemuboot.conf at this point it probably |
| 594 | # doesn't exist, continue without |
| 595 | return |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 596 | |
Patrick Williams | c0f7c04 | 2017-02-23 20:41:17 -0600 | [diff] [blame] | 597 | if not os.path.exists(self.qemuboot): |
| 598 | raise Exception("Failed to find <image>.qemuboot.conf!") |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 599 | |
Patrick Williams | c0f7c04 | 2017-02-23 20:41:17 -0600 | [diff] [blame] | 600 | logger.info('CONFFILE: %s' % self.qemuboot) |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 601 | |
Patrick Williams | c0f7c04 | 2017-02-23 20:41:17 -0600 | [diff] [blame] | 602 | cf = configparser.ConfigParser() |
| 603 | cf.read(self.qemuboot) |
| 604 | for k, v in cf.items('config_bsp'): |
| 605 | k_upper = k.upper() |
| 606 | self.set(k_upper, v) |
| 607 | |
| 608 | def validate_paths(self): |
| 609 | """Ensure all relevant path variables are set""" |
| 610 | # When we're started with a *.qemuboot.conf arg assume that image |
| 611 | # artefacts are relative to that file, rather than in whatever |
| 612 | # directory DEPLOY_DIR_IMAGE in the conf file points to. |
| 613 | if self.qbconfload: |
| 614 | imgdir = os.path.dirname(self.qemuboot) |
| 615 | if imgdir != self.get('DEPLOY_DIR_IMAGE'): |
| 616 | logger.info('Setting DEPLOY_DIR_IMAGE to folder containing %s (%s)' % (self.qemuboot, imgdir)) |
| 617 | self.set('DEPLOY_DIR_IMAGE', imgdir) |
| 618 | |
| 619 | # If the STAGING_*_NATIVE directories from the config file don't exist |
| 620 | # and we're in a sourced OE build directory try to extract the paths |
| 621 | # from `bitbake -e` |
| 622 | havenative = os.path.exists(self.get('STAGING_DIR_NATIVE')) and \ |
| 623 | os.path.exists(self.get('STAGING_BINDIR_NATIVE')) |
| 624 | |
| 625 | if not havenative: |
| 626 | if not self.bitbake_e: |
| 627 | self.load_bitbake_env() |
| 628 | |
| 629 | if self.bitbake_e: |
| 630 | native_vars = ['STAGING_DIR_NATIVE', 'STAGING_BINDIR_NATIVE'] |
| 631 | for nv in native_vars: |
| 632 | s = re.search('^%s="(.*)"' % nv, self.bitbake_e, re.M) |
| 633 | if s and s.group(1) != self.get(nv): |
| 634 | logger.info('Overriding conf file setting of %s to %s from Bitbake environment' % (nv, s.group(1))) |
| 635 | self.set(nv, s.group(1)) |
| 636 | else: |
| 637 | # when we're invoked from a running bitbake instance we won't |
| 638 | # be able to call `bitbake -e`, then try: |
| 639 | # - get OE_TMPDIR from environment and guess paths based on it |
| 640 | # - get OECORE_NATIVE_SYSROOT from environment (for sdk) |
| 641 | tmpdir = os.environ.get('OE_TMPDIR', None) |
| 642 | oecore_native_sysroot = os.environ.get('OECORE_NATIVE_SYSROOT', None) |
| 643 | if tmpdir: |
| 644 | logger.info('Setting STAGING_DIR_NATIVE and STAGING_BINDIR_NATIVE relative to OE_TMPDIR (%s)' % tmpdir) |
| 645 | hostos, _, _, _, machine = os.uname() |
| 646 | buildsys = '%s-%s' % (machine, hostos.lower()) |
| 647 | staging_dir_native = '%s/sysroots/%s' % (tmpdir, buildsys) |
| 648 | self.set('STAGING_DIR_NATIVE', staging_dir_native) |
| 649 | elif oecore_native_sysroot: |
| 650 | logger.info('Setting STAGING_DIR_NATIVE to OECORE_NATIVE_SYSROOT (%s)' % oecore_native_sysroot) |
| 651 | self.set('STAGING_DIR_NATIVE', oecore_native_sysroot) |
| 652 | if self.get('STAGING_DIR_NATIVE'): |
| 653 | # we have to assume that STAGING_BINDIR_NATIVE is at usr/bin |
| 654 | staging_bindir_native = '%s/usr/bin' % self.get('STAGING_DIR_NATIVE') |
| 655 | logger.info('Setting STAGING_BINDIR_NATIVE to %s' % staging_bindir_native) |
| 656 | self.set('STAGING_BINDIR_NATIVE', '%s/usr/bin' % self.get('STAGING_DIR_NATIVE')) |
| 657 | |
| 658 | def print_config(self): |
| 659 | logger.info('Continuing with the following parameters:\n') |
| 660 | if not self.fstype in self.vmtypes: |
| 661 | print('KERNEL: [%s]' % self.kernel) |
| 662 | if self.dtb: |
| 663 | print('DTB: [%s]' % self.dtb) |
| 664 | print('MACHINE: [%s]' % self.get('MACHINE')) |
| 665 | print('FSTYPE: [%s]' % self.fstype) |
| 666 | if self.fstype == 'nfs': |
| 667 | print('NFS_DIR: [%s]' % self.nfs_dir) |
| 668 | else: |
| 669 | print('ROOTFS: [%s]' % self.rootfs) |
| 670 | print('CONFFILE: [%s]' % self.qemuboot) |
| 671 | print('') |
| 672 | |
| 673 | def setup_nfs(self): |
| 674 | if not self.nfs_server: |
| 675 | if self.slirp_enabled: |
| 676 | self.nfs_server = '10.0.2.2' |
| 677 | else: |
| 678 | self.nfs_server = '192.168.7.1' |
| 679 | |
Brad Bishop | 37a0e4d | 2017-12-04 01:01:44 -0500 | [diff] [blame] | 680 | # Figure out a new nfs_instance to allow multiple qemus running. |
| 681 | # CentOS 7.1's ps doesn't print full command line without "ww" |
| 682 | # when invoke by subprocess.Popen(). |
| 683 | cmd = "ps auxww" |
| 684 | ps = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE).stdout.read().decode('utf-8') |
| 685 | pattern = '/bin/unfsd .* -i .*\.pid -e .*/exports([0-9]+) ' |
| 686 | all_instances = re.findall(pattern, ps, re.M) |
| 687 | if all_instances: |
| 688 | all_instances.sort(key=int) |
| 689 | self.nfs_instance = int(all_instances.pop()) + 1 |
Patrick Williams | c0f7c04 | 2017-02-23 20:41:17 -0600 | [diff] [blame] | 690 | |
Brad Bishop | 37a0e4d | 2017-12-04 01:01:44 -0500 | [diff] [blame] | 691 | mountd_rpcport = 21111 + self.nfs_instance |
| 692 | nfsd_rpcport = 11111 + self.nfs_instance |
| 693 | nfsd_port = 3049 + 2 * self.nfs_instance |
| 694 | mountd_port = 3048 + 2 * self.nfs_instance |
Patrick Williams | c0f7c04 | 2017-02-23 20:41:17 -0600 | [diff] [blame] | 695 | |
Brad Bishop | 37a0e4d | 2017-12-04 01:01:44 -0500 | [diff] [blame] | 696 | # Export vars for runqemu-export-rootfs |
| 697 | export_dict = { |
| 698 | 'NFS_INSTANCE': self.nfs_instance, |
| 699 | 'MOUNTD_RPCPORT': mountd_rpcport, |
| 700 | 'NFSD_RPCPORT': nfsd_rpcport, |
| 701 | 'NFSD_PORT': nfsd_port, |
| 702 | 'MOUNTD_PORT': mountd_port, |
| 703 | } |
| 704 | for k, v in export_dict.items(): |
| 705 | # Use '%s' since they are integers |
| 706 | os.putenv(k, '%s' % v) |
| 707 | |
| 708 | self.unfs_opts="nfsvers=3,port=%s,mountprog=%s,nfsprog=%s,udp,mountport=%s" % (nfsd_port, mountd_rpcport, nfsd_rpcport, mountd_port) |
Patrick Williams | c0f7c04 | 2017-02-23 20:41:17 -0600 | [diff] [blame] | 709 | |
| 710 | # Extract .tar.bz2 or .tar.bz if no self.nfs_dir |
| 711 | if not self.nfs_dir: |
| 712 | src_prefix = '%s/%s' % (self.get('DEPLOY_DIR_IMAGE'), self.get('IMAGE_LINK_NAME')) |
| 713 | dest = "%s-nfsroot" % src_prefix |
| 714 | if os.path.exists('%s.pseudo_state' % dest): |
| 715 | logger.info('Use %s as NFS_DIR' % dest) |
| 716 | self.nfs_dir = dest |
| 717 | else: |
| 718 | src = "" |
| 719 | src1 = '%s.tar.bz2' % src_prefix |
| 720 | src2 = '%s.tar.gz' % src_prefix |
| 721 | if os.path.exists(src1): |
| 722 | src = src1 |
| 723 | elif os.path.exists(src2): |
| 724 | src = src2 |
| 725 | if not src: |
| 726 | raise Exception("No NFS_DIR is set, and can't find %s or %s to extract" % (src1, src2)) |
| 727 | logger.info('NFS_DIR not found, extracting %s to %s' % (src, dest)) |
| 728 | cmd = 'runqemu-extract-sdk %s %s' % (src, dest) |
| 729 | logger.info('Running %s...' % cmd) |
| 730 | if subprocess.call(cmd, shell=True) != 0: |
| 731 | raise Exception('Failed to run %s' % cmd) |
| 732 | self.clean_nfs_dir = True |
| 733 | self.nfs_dir = dest |
| 734 | |
| 735 | # Start the userspace NFS server |
Brad Bishop | 37a0e4d | 2017-12-04 01:01:44 -0500 | [diff] [blame] | 736 | cmd = 'runqemu-export-rootfs start %s' % self.nfs_dir |
Patrick Williams | c0f7c04 | 2017-02-23 20:41:17 -0600 | [diff] [blame] | 737 | logger.info('Running %s...' % cmd) |
| 738 | if subprocess.call(cmd, shell=True) != 0: |
| 739 | raise Exception('Failed to run %s' % cmd) |
| 740 | |
| 741 | self.nfs_running = True |
| 742 | |
| 743 | |
| 744 | def setup_slirp(self): |
Brad Bishop | 37a0e4d | 2017-12-04 01:01:44 -0500 | [diff] [blame] | 745 | """Setup user networking""" |
| 746 | |
Patrick Williams | c0f7c04 | 2017-02-23 20:41:17 -0600 | [diff] [blame] | 747 | if self.fstype == 'nfs': |
| 748 | self.setup_nfs() |
| 749 | self.kernel_cmdline_script += ' ip=dhcp' |
| 750 | self.set('NETWORK_CMD', self.get('QB_SLIRP_OPT')) |
| 751 | |
| 752 | def setup_tap(self): |
| 753 | """Setup tap""" |
| 754 | |
| 755 | # This file is created when runqemu-gen-tapdevs creates a bank of tap |
| 756 | # devices, indicating that the user should not bring up new ones using |
| 757 | # sudo. |
| 758 | nosudo_flag = '/etc/runqemu-nosudo' |
| 759 | self.qemuifup = shutil.which('runqemu-ifup') |
| 760 | self.qemuifdown = shutil.which('runqemu-ifdown') |
| 761 | ip = shutil.which('ip') |
| 762 | lockdir = "/tmp/qemu-tap-locks" |
| 763 | |
| 764 | if not (self.qemuifup and self.qemuifdown and ip): |
| 765 | raise OEPathError("runqemu-ifup, runqemu-ifdown or ip not found") |
| 766 | |
| 767 | if not os.path.exists(lockdir): |
| 768 | # There might be a race issue when multi runqemu processess are |
| 769 | # running at the same time. |
| 770 | try: |
| 771 | os.mkdir(lockdir) |
| 772 | except FileExistsError: |
| 773 | pass |
| 774 | |
| 775 | cmd = '%s link' % ip |
| 776 | logger.info('Running %s...' % cmd) |
| 777 | ip_link = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE).stdout.read().decode('utf-8') |
| 778 | # Matches line like: 6: tap0: <foo> |
| 779 | possibles = re.findall('^[1-9]+: +(tap[0-9]+): <.*', ip_link, re.M) |
| 780 | tap = "" |
| 781 | for p in possibles: |
| 782 | lockfile = os.path.join(lockdir, p) |
| 783 | if os.path.exists('%s.skip' % lockfile): |
| 784 | logger.info('Found %s.skip, skipping %s' % (lockfile, p)) |
| 785 | continue |
| 786 | self.lock = lockfile + '.lock' |
| 787 | if self.acquire_lock(): |
| 788 | tap = p |
| 789 | logger.info("Using preconfigured tap device %s" % tap) |
| 790 | logger.info("If this is not intended, touch %s.skip to make runqemu skip %s." %(lockfile, tap)) |
| 791 | break |
| 792 | |
| 793 | if not tap: |
| 794 | if os.path.exists(nosudo_flag): |
| 795 | logger.error("Error: There are no available tap devices to use for networking,") |
| 796 | logger.error("and I see %s exists, so I am not going to try creating" % nosudo_flag) |
| 797 | raise Exception("a new one with sudo.") |
| 798 | |
| 799 | gid = os.getgid() |
| 800 | uid = os.getuid() |
| 801 | logger.info("Setting up tap interface under sudo") |
| 802 | cmd = 'sudo %s %s %s %s' % (self.qemuifup, uid, gid, self.get('STAGING_DIR_NATIVE')) |
| 803 | tap = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE).stdout.read().decode('utf-8').rstrip('\n') |
| 804 | lockfile = os.path.join(lockdir, tap) |
| 805 | self.lock = lockfile + '.lock' |
| 806 | self.acquire_lock() |
| 807 | self.cleantap = True |
| 808 | logger.info('Created tap: %s' % tap) |
| 809 | |
| 810 | if not tap: |
| 811 | logger.error("Failed to setup tap device. Run runqemu-gen-tapdevs to manually create.") |
| 812 | return 1 |
| 813 | self.tap = tap |
Brad Bishop | 37a0e4d | 2017-12-04 01:01:44 -0500 | [diff] [blame] | 814 | tapnum = int(tap[3:]) |
| 815 | gateway = tapnum * 2 + 1 |
| 816 | client = gateway + 1 |
Patrick Williams | c0f7c04 | 2017-02-23 20:41:17 -0600 | [diff] [blame] | 817 | if self.fstype == 'nfs': |
| 818 | self.setup_nfs() |
Brad Bishop | 37a0e4d | 2017-12-04 01:01:44 -0500 | [diff] [blame] | 819 | self.kernel_cmdline_script += " ip=192.168.7.%s::192.168.7.%s:255.255.255.0" % (client, gateway) |
| 820 | mac = "52:54:00:12:34:%02x" % client |
Patrick Williams | c0f7c04 | 2017-02-23 20:41:17 -0600 | [diff] [blame] | 821 | qb_tap_opt = self.get('QB_TAP_OPT') |
| 822 | if qb_tap_opt: |
| 823 | qemu_tap_opt = qb_tap_opt.replace('@TAP@', tap).replace('@MAC@', mac) |
| 824 | else: |
| 825 | qemu_tap_opt = "-device virtio-net-pci,netdev=net0,mac=%s -netdev tap,id=net0,ifname=%s,script=no,downscript=no" % (mac, self.tap) |
| 826 | |
| 827 | if self.vhost_enabled: |
| 828 | qemu_tap_opt += ',vhost=on' |
| 829 | |
| 830 | self.set('NETWORK_CMD', qemu_tap_opt) |
| 831 | |
| 832 | def setup_network(self): |
| 833 | cmd = "stty -g" |
| 834 | self.saved_stty = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE).stdout.read().decode('utf-8') |
| 835 | if self.slirp_enabled: |
| 836 | self.setup_slirp() |
| 837 | else: |
| 838 | self.setup_tap() |
| 839 | |
| 840 | rootfs_format = self.fstype if self.fstype in ('vmdk', 'qcow2', 'vdi') else 'raw' |
| 841 | |
| 842 | qb_rootfs_opt = self.get('QB_ROOTFS_OPT') |
| 843 | if qb_rootfs_opt: |
| 844 | self.rootfs_options = qb_rootfs_opt.replace('@ROOTFS@', self.rootfs) |
| 845 | else: |
| 846 | self.rootfs_options = '-drive file=%s,if=virtio,format=%s' % (self.rootfs, rootfs_format) |
| 847 | |
| 848 | if self.fstype in ('cpio.gz', 'cpio'): |
| 849 | self.kernel_cmdline = 'root=/dev/ram0 rw debugshell' |
| 850 | self.rootfs_options = '-initrd %s' % self.rootfs |
| 851 | else: |
| 852 | if self.fstype in self.vmtypes: |
| 853 | if self.fstype == 'iso': |
| 854 | vm_drive = '-cdrom %s' % self.rootfs |
| 855 | else: |
| 856 | cmd1 = "grep -q 'root=/dev/sd' %s" % self.rootfs |
| 857 | cmd2 = "grep -q 'root=/dev/hd' %s" % self.rootfs |
| 858 | if subprocess.call(cmd1, shell=True) == 0: |
| 859 | logger.info('Using scsi drive') |
| 860 | vm_drive = '-drive if=none,id=hd,file=%s,format=%s -device virtio-scsi-pci,id=scsi -device scsi-hd,drive=hd' \ |
| 861 | % (self.rootfs, rootfs_format) |
| 862 | elif subprocess.call(cmd2, shell=True) == 0: |
Brad Bishop | 37a0e4d | 2017-12-04 01:01:44 -0500 | [diff] [blame] | 863 | logger.info('Using ide drive') |
Patrick Williams | c0f7c04 | 2017-02-23 20:41:17 -0600 | [diff] [blame] | 864 | vm_drive = "%s,format=%s" % (self.rootfs, rootfs_format) |
| 865 | else: |
| 866 | logger.warn("Can't detect drive type %s" % self.rootfs) |
Brad Bishop | 37a0e4d | 2017-12-04 01:01:44 -0500 | [diff] [blame] | 867 | logger.warn('Trying to use virtio block drive') |
Patrick Williams | c0f7c04 | 2017-02-23 20:41:17 -0600 | [diff] [blame] | 868 | vm_drive = '-drive if=virtio,file=%s,format=%s' % (self.rootfs, rootfs_format) |
| 869 | self.rootfs_options = '%s -no-reboot' % vm_drive |
| 870 | self.kernel_cmdline = 'root=%s rw highres=off' % (self.get('QB_KERNEL_ROOT')) |
| 871 | |
| 872 | if self.fstype == 'nfs': |
| 873 | self.rootfs_options = '' |
| 874 | k_root = '/dev/nfs nfsroot=%s:%s,%s' % (self.nfs_server, self.nfs_dir, self.unfs_opts) |
| 875 | self.kernel_cmdline = 'root=%s rw highres=off' % k_root |
| 876 | |
| 877 | self.set('ROOTFS_OPTIONS', self.rootfs_options) |
| 878 | |
| 879 | def guess_qb_system(self): |
| 880 | """attempt to determine the appropriate qemu-system binary""" |
| 881 | mach = self.get('MACHINE') |
| 882 | if not mach: |
| 883 | search = '.*(qemux86-64|qemux86|qemuarm64|qemuarm|qemumips64|qemumips64el|qemumipsel|qemumips|qemuppc).*' |
| 884 | if self.rootfs: |
| 885 | match = re.match(search, self.rootfs) |
| 886 | if match: |
| 887 | mach = match.group(1) |
| 888 | elif self.kernel: |
| 889 | match = re.match(search, self.kernel) |
| 890 | if match: |
| 891 | mach = match.group(1) |
| 892 | |
| 893 | if not mach: |
| 894 | return None |
| 895 | |
| 896 | if mach == 'qemuarm': |
| 897 | qbsys = 'arm' |
| 898 | elif mach == 'qemuarm64': |
| 899 | qbsys = 'aarch64' |
| 900 | elif mach == 'qemux86': |
| 901 | qbsys = 'i386' |
| 902 | elif mach == 'qemux86-64': |
| 903 | qbsys = 'x86_64' |
| 904 | elif mach == 'qemuppc': |
| 905 | qbsys = 'ppc' |
| 906 | elif mach == 'qemumips': |
| 907 | qbsys = 'mips' |
| 908 | elif mach == 'qemumips64': |
| 909 | qbsys = 'mips64' |
| 910 | elif mach == 'qemumipsel': |
| 911 | qbsys = 'mipsel' |
| 912 | elif mach == 'qemumips64el': |
| 913 | qbsys = 'mips64el' |
| 914 | |
| 915 | return 'qemu-system-%s' % qbsys |
| 916 | |
| 917 | def setup_final(self): |
| 918 | qemu_system = self.get('QB_SYSTEM_NAME') |
| 919 | if not qemu_system: |
| 920 | qemu_system = self.guess_qb_system() |
| 921 | if not qemu_system: |
| 922 | raise Exception("Failed to boot, QB_SYSTEM_NAME is NULL!") |
| 923 | |
| 924 | qemu_bin = '%s/%s' % (self.get('STAGING_BINDIR_NATIVE'), qemu_system) |
| 925 | if not os.access(qemu_bin, os.X_OK): |
| 926 | raise OEPathError("No QEMU binary '%s' could be found" % qemu_bin) |
| 927 | |
| 928 | check_libgl(qemu_bin) |
| 929 | |
| 930 | self.qemu_opt = "%s %s %s %s %s" % (qemu_bin, self.get('NETWORK_CMD'), self.qemu_opt_script, self.get('ROOTFS_OPTIONS'), self.get('QB_OPT_APPEND')) |
| 931 | |
| 932 | if self.snapshot: |
| 933 | self.qemu_opt += " -snapshot" |
| 934 | |
| 935 | if self.serialstdio: |
| 936 | logger.info("Interrupt character is '^]'") |
| 937 | cmd = "stty intr ^]" |
| 938 | subprocess.call(cmd, shell=True) |
| 939 | |
| 940 | first_serial = "" |
| 941 | if not re.search("-nographic", self.qemu_opt): |
| 942 | first_serial = "-serial mon:vc" |
| 943 | # We always want a ttyS1. Since qemu by default adds a serial |
| 944 | # port when nodefaults is not specified, it seems that all that |
| 945 | # would be needed is to make sure a "-serial" is there. However, |
| 946 | # it appears that when "-serial" is specified, it ignores the |
| 947 | # default serial port that is normally added. So here we make |
| 948 | # sure to add two -serial if there are none. And only one if |
| 949 | # there is one -serial already. |
| 950 | serial_num = len(re.findall("-serial", self.qemu_opt)) |
| 951 | if serial_num == 0: |
| 952 | self.qemu_opt += " %s %s" % (first_serial, self.get("QB_SERIAL_OPT")) |
| 953 | elif serial_num == 1: |
| 954 | self.qemu_opt += " %s" % self.get("QB_SERIAL_OPT") |
| 955 | |
| 956 | def start_qemu(self): |
| 957 | if self.kernel: |
Brad Bishop | 37a0e4d | 2017-12-04 01:01:44 -0500 | [diff] [blame] | 958 | kernel_opts = "-kernel %s -append '%s %s %s %s'" % (self.kernel, self.kernel_cmdline, |
| 959 | self.kernel_cmdline_script, self.get('QB_KERNEL_CMDLINE_APPEND'), |
| 960 | self.bootparams) |
Patrick Williams | c0f7c04 | 2017-02-23 20:41:17 -0600 | [diff] [blame] | 961 | if self.dtb: |
| 962 | kernel_opts += " -dtb %s" % self.dtb |
| 963 | else: |
| 964 | kernel_opts = "" |
| 965 | cmd = "%s %s" % (self.qemu_opt, kernel_opts) |
| 966 | logger.info('Running %s' % cmd) |
| 967 | if subprocess.call(cmd, shell=True) != 0: |
| 968 | raise Exception('Failed to run %s' % cmd) |
| 969 | |
| 970 | def cleanup(self): |
| 971 | if self.cleantap: |
| 972 | cmd = 'sudo %s %s %s' % (self.qemuifdown, self.tap, self.get('STAGING_DIR_NATIVE')) |
| 973 | logger.info('Running %s' % cmd) |
| 974 | subprocess.call(cmd, shell=True) |
| 975 | if self.lock_descriptor: |
| 976 | logger.info("Releasing lockfile for tap device '%s'" % self.tap) |
| 977 | self.release_lock() |
| 978 | |
| 979 | if self.nfs_running: |
| 980 | logger.info("Shutting down the userspace NFS server...") |
| 981 | cmd = "runqemu-export-rootfs stop %s" % self.nfs_dir |
| 982 | logger.info('Running %s' % cmd) |
| 983 | subprocess.call(cmd, shell=True) |
| 984 | |
| 985 | if self.saved_stty: |
| 986 | cmd = "stty %s" % self.saved_stty |
| 987 | subprocess.call(cmd, shell=True) |
| 988 | |
| 989 | if self.clean_nfs_dir: |
| 990 | logger.info('Removing %s' % self.nfs_dir) |
| 991 | shutil.rmtree(self.nfs_dir) |
| 992 | shutil.rmtree('%s.pseudo_state' % self.nfs_dir) |
| 993 | |
| 994 | def load_bitbake_env(self, mach=None): |
| 995 | if self.bitbake_e: |
| 996 | return |
| 997 | |
| 998 | bitbake = shutil.which('bitbake') |
| 999 | if not bitbake: |
| 1000 | return |
| 1001 | |
| 1002 | if not mach: |
| 1003 | mach = self.get('MACHINE') |
| 1004 | |
| 1005 | if mach: |
| 1006 | cmd = 'MACHINE=%s bitbake -e' % mach |
| 1007 | else: |
| 1008 | cmd = 'bitbake -e' |
| 1009 | |
| 1010 | logger.info('Running %s...' % cmd) |
| 1011 | try: |
| 1012 | self.bitbake_e = subprocess.check_output(cmd, shell=True).decode('utf-8') |
| 1013 | except subprocess.CalledProcessError as err: |
| 1014 | self.bitbake_e = '' |
| 1015 | logger.warn("Couldn't run 'bitbake -e' to gather environment information:\n%s" % err.output.decode('utf-8')) |
| 1016 | |
| 1017 | def main(): |
| 1018 | if len(sys.argv) == 1 or "help" in sys.argv: |
| 1019 | print_usage() |
| 1020 | return 0 |
| 1021 | config = BaseConfig() |
| 1022 | try: |
| 1023 | config.check_args() |
| 1024 | except Exception as esc: |
| 1025 | logger.error(esc) |
| 1026 | logger.error("Try 'runqemu help' on how to use it") |
| 1027 | return 1 |
| 1028 | config.read_qemuboot() |
| 1029 | config.check_and_set() |
| 1030 | config.print_config() |
| 1031 | try: |
| 1032 | config.setup_network() |
| 1033 | config.setup_final() |
| 1034 | config.start_qemu() |
| 1035 | finally: |
| 1036 | config.cleanup() |
| 1037 | return 0 |
| 1038 | |
| 1039 | if __name__ == "__main__": |
| 1040 | try: |
| 1041 | ret = main() |
| 1042 | except OEPathError as err: |
| 1043 | ret = 1 |
| 1044 | logger.error(err.message) |
| 1045 | except Exception as esc: |
| 1046 | ret = 1 |
| 1047 | import traceback |
| 1048 | traceback.print_exc() |
| 1049 | sys.exit(ret) |