1# 2# Copyright (c) 2013, Intel Corporation. 3# 4# SPDX-License-Identifier: GPL-2.0-only 5# 6# DESCRIPTION 7 8# This module implements the image creation engine used by 'wic' to 9# create images. The engine parses through the OpenEmbedded kickstart 10# (wks) file specified and generates images that can then be directly 11# written onto media. 12# 13# AUTHORS 14# Tom Zanussi <tom.zanussi (at] linux.intel.com> 15# 16 17import logging 18import os 19import tempfile 20import json 21import subprocess 22import re 23 24from collections import namedtuple, OrderedDict 25from distutils.spawn import find_executable 26 27from wic import WicError 28from wic.filemap import sparse_copy 29from wic.pluginbase import PluginMgr 30from wic.misc import get_bitbake_var, exec_cmd 31 32logger = logging.getLogger('wic') 33 34def verify_build_env(): 35 """ 36 Verify that the build environment is sane. 37 38 Returns True if it is, false otherwise 39 """ 40 if not os.environ.get("BUILDDIR"): 41 raise WicError("BUILDDIR not found, exiting. (Did you forget to source oe-init-build-env?)") 42 43 return True 44 45 46CANNED_IMAGE_DIR = "lib/wic/canned-wks" # relative to scripts 47SCRIPTS_CANNED_IMAGE_DIR = "scripts/" + CANNED_IMAGE_DIR 48WIC_DIR = "wic" 49 50def build_canned_image_list(path): 51 layers_path = get_bitbake_var("BBLAYERS") 52 canned_wks_layer_dirs = [] 53 54 if layers_path is not None: 55 for layer_path in layers_path.split(): 56 for wks_path in (WIC_DIR, SCRIPTS_CANNED_IMAGE_DIR): 57 cpath = os.path.join(layer_path, wks_path) 58 if os.path.isdir(cpath): 59 canned_wks_layer_dirs.append(cpath) 60 61 cpath = os.path.join(path, CANNED_IMAGE_DIR) 62 canned_wks_layer_dirs.append(cpath) 63 64 return canned_wks_layer_dirs 65 66def find_canned_image(scripts_path, wks_file): 67 """ 68 Find a .wks file with the given name in the canned files dir. 69 70 Return False if not found 71 """ 72 layers_canned_wks_dir = build_canned_image_list(scripts_path) 73 74 for canned_wks_dir in layers_canned_wks_dir: 75 for root, dirs, files in os.walk(canned_wks_dir): 76 for fname in files: 77 if fname.endswith("~") or fname.endswith("#"): 78 continue 79 if ((fname.endswith(".wks") and wks_file + ".wks" == fname) or \ 80 (fname.endswith(".wks.in") and wks_file + ".wks.in" == fname)): 81 fullpath = os.path.join(canned_wks_dir, fname) 82 return fullpath 83 return None 84 85 86def list_canned_images(scripts_path): 87 """ 88 List the .wks files in the canned image dir, minus the extension. 89 """ 90 layers_canned_wks_dir = build_canned_image_list(scripts_path) 91 92 for canned_wks_dir in layers_canned_wks_dir: 93 for root, dirs, files in os.walk(canned_wks_dir): 94 for fname in files: 95 if fname.endswith("~") or fname.endswith("#"): 96 continue 97 if fname.endswith(".wks") or fname.endswith(".wks.in"): 98 fullpath = os.path.join(canned_wks_dir, fname) 99 with open(fullpath) as wks: 100 for line in wks: 101 desc = "" 102 idx = line.find("short-description:") 103 if idx != -1: 104 desc = line[idx + len("short-description:"):].strip() 105 break 106 basename = fname.split('.')[0] 107 print(" %s\t\t%s" % (basename.ljust(30), desc)) 108 109 110def list_canned_image_help(scripts_path, fullpath): 111 """ 112 List the help and params in the specified canned image. 113 """ 114 found = False 115 with open(fullpath) as wks: 116 for line in wks: 117 if not found: 118 idx = line.find("long-description:") 119 if idx != -1: 120 print() 121 print(line[idx + len("long-description:"):].strip()) 122 found = True 123 continue 124 if not line.strip(): 125 break 126 idx = line.find("#") 127 if idx != -1: 128 print(line[idx + len("#:"):].rstrip()) 129 else: 130 break 131 132 133def list_source_plugins(): 134 """ 135 List the available source plugins i.e. plugins available for --source. 136 """ 137 plugins = PluginMgr.get_plugins('source') 138 139 for plugin in plugins: 140 print(" %s" % plugin) 141 142 143def wic_create(wks_file, rootfs_dir, bootimg_dir, kernel_dir, 144 native_sysroot, options): 145 """ 146 Create image 147 148 wks_file - user-defined OE kickstart file 149 rootfs_dir - absolute path to the build's /rootfs dir 150 bootimg_dir - absolute path to the build's boot artifacts directory 151 kernel_dir - absolute path to the build's kernel directory 152 native_sysroot - absolute path to the build's native sysroots dir 153 image_output_dir - dirname to create for image 154 options - wic command line options (debug, bmap, etc) 155 156 Normally, the values for the build artifacts values are determined 157 by 'wic -e' from the output of the 'bitbake -e' command given an 158 image name e.g. 'core-image-minimal' and a given machine set in 159 local.conf. If that's the case, the variables get the following 160 values from the output of 'bitbake -e': 161 162 rootfs_dir: IMAGE_ROOTFS 163 kernel_dir: DEPLOY_DIR_IMAGE 164 native_sysroot: STAGING_DIR_NATIVE 165 166 In the above case, bootimg_dir remains unset and the 167 plugin-specific image creation code is responsible for finding the 168 bootimg artifacts. 169 170 In the case where the values are passed in explicitly i.e 'wic -e' 171 is not used but rather the individual 'wic' options are used to 172 explicitly specify these values. 173 """ 174 try: 175 oe_builddir = os.environ["BUILDDIR"] 176 except KeyError: 177 raise WicError("BUILDDIR not found, exiting. (Did you forget to source oe-init-build-env?)") 178 179 if not os.path.exists(options.outdir): 180 os.makedirs(options.outdir) 181 182 pname = options.imager 183 plugin_class = PluginMgr.get_plugins('imager').get(pname) 184 if not plugin_class: 185 raise WicError('Unknown plugin: %s' % pname) 186 187 plugin = plugin_class(wks_file, rootfs_dir, bootimg_dir, kernel_dir, 188 native_sysroot, oe_builddir, options) 189 190 plugin.do_create() 191 192 logger.info("The image(s) were created using OE kickstart file:\n %s", wks_file) 193 194 195def wic_list(args, scripts_path): 196 """ 197 Print the list of images or source plugins. 198 """ 199 if args.list_type is None: 200 return False 201 202 if args.list_type == "images": 203 204 list_canned_images(scripts_path) 205 return True 206 elif args.list_type == "source-plugins": 207 list_source_plugins() 208 return True 209 elif len(args.help_for) == 1 and args.help_for[0] == 'help': 210 wks_file = args.list_type 211 fullpath = find_canned_image(scripts_path, wks_file) 212 if not fullpath: 213 raise WicError("No image named %s found, exiting. " 214 "(Use 'wic list images' to list available images, " 215 "or specify a fully-qualified OE kickstart (.wks) " 216 "filename)" % wks_file) 217 218 list_canned_image_help(scripts_path, fullpath) 219 return True 220 221 return False 222 223 224class Disk: 225 def __init__(self, imagepath, native_sysroot, fstypes=('fat', 'ext')): 226 self.imagepath = imagepath 227 self.native_sysroot = native_sysroot 228 self.fstypes = fstypes 229 self._partitions = None 230 self._partimages = {} 231 self._lsector_size = None 232 self._psector_size = None 233 self._ptable_format = None 234 235 # find parted 236 # read paths from $PATH environment variable 237 # if it fails, use hardcoded paths 238 pathlist = "/bin:/usr/bin:/usr/sbin:/sbin/" 239 try: 240 self.paths = os.environ['PATH'] + ":" + pathlist 241 except KeyError: 242 self.paths = pathlist 243 244 if native_sysroot: 245 for path in pathlist.split(':'): 246 self.paths = "%s%s:%s" % (native_sysroot, path, self.paths) 247 248 self.parted = find_executable("parted", self.paths) 249 if not self.parted: 250 raise WicError("Can't find executable parted") 251 252 self.partitions = self.get_partitions() 253 254 def __del__(self): 255 for path in self._partimages.values(): 256 os.unlink(path) 257 258 def get_partitions(self): 259 if self._partitions is None: 260 self._partitions = OrderedDict() 261 out = exec_cmd("%s -sm %s unit B print" % (self.parted, self.imagepath)) 262 parttype = namedtuple("Part", "pnum start end size fstype") 263 splitted = out.splitlines() 264 # skip over possible errors in exec_cmd output 265 try: 266 idx =splitted.index("BYT;") 267 except ValueError: 268 raise WicError("Error getting partition information from %s" % (self.parted)) 269 lsector_size, psector_size, self._ptable_format = splitted[idx + 1].split(":")[3:6] 270 self._lsector_size = int(lsector_size) 271 self._psector_size = int(psector_size) 272 for line in splitted[idx + 2:]: 273 pnum, start, end, size, fstype = line.split(':')[:5] 274 partition = parttype(int(pnum), int(start[:-1]), int(end[:-1]), 275 int(size[:-1]), fstype) 276 self._partitions[pnum] = partition 277 278 return self._partitions 279 280 def __getattr__(self, name): 281 """Get path to the executable in a lazy way.""" 282 if name in ("mdir", "mcopy", "mdel", "mdeltree", "sfdisk", "e2fsck", 283 "resize2fs", "mkswap", "mkdosfs", "debugfs"): 284 aname = "_%s" % name 285 if aname not in self.__dict__: 286 setattr(self, aname, find_executable(name, self.paths)) 287 if aname not in self.__dict__ or self.__dict__[aname] is None: 288 raise WicError("Can't find executable '{}'".format(name)) 289 return self.__dict__[aname] 290 return self.__dict__[name] 291 292 def _get_part_image(self, pnum): 293 if pnum not in self.partitions: 294 raise WicError("Partition %s is not in the image") 295 part = self.partitions[pnum] 296 # check if fstype is supported 297 for fstype in self.fstypes: 298 if part.fstype.startswith(fstype): 299 break 300 else: 301 raise WicError("Not supported fstype: {}".format(part.fstype)) 302 if pnum not in self._partimages: 303 tmpf = tempfile.NamedTemporaryFile(prefix="wic-part") 304 dst_fname = tmpf.name 305 tmpf.close() 306 sparse_copy(self.imagepath, dst_fname, skip=part.start, length=part.size) 307 self._partimages[pnum] = dst_fname 308 309 return self._partimages[pnum] 310 311 def _put_part_image(self, pnum): 312 """Put partition image into partitioned image.""" 313 sparse_copy(self._partimages[pnum], self.imagepath, 314 seek=self.partitions[pnum].start) 315 316 def dir(self, pnum, path): 317 if self.partitions[pnum].fstype.startswith('ext'): 318 return exec_cmd("{} {} -R 'ls -l {}'".format(self.debugfs, 319 self._get_part_image(pnum), 320 path), as_shell=True) 321 else: # fat 322 return exec_cmd("{} -i {} ::{}".format(self.mdir, 323 self._get_part_image(pnum), 324 path)) 325 326 def copy(self, src, pnum, path): 327 """Copy partition image into wic image.""" 328 if self.partitions[pnum].fstype.startswith('ext'): 329 cmd = "printf 'cd {}\nwrite {} {}\n' | {} -w {}".\ 330 format(path, src, os.path.basename(src), 331 self.debugfs, self._get_part_image(pnum)) 332 else: # fat 333 cmd = "{} -i {} -snop {} ::{}".format(self.mcopy, 334 self._get_part_image(pnum), 335 src, path) 336 exec_cmd(cmd, as_shell=True) 337 self._put_part_image(pnum) 338 339 def remove_ext(self, pnum, path, recursive): 340 """ 341 Remove files/dirs and their contents from the partition. 342 This only applies to ext* partition. 343 """ 344 abs_path = re.sub('\/\/+', '/', path) 345 cmd = "{} {} -wR 'rm \"{}\"'".format(self.debugfs, 346 self._get_part_image(pnum), 347 abs_path) 348 out = exec_cmd(cmd , as_shell=True) 349 for line in out.splitlines(): 350 if line.startswith("rm:"): 351 if "file is a directory" in line: 352 if recursive: 353 # loop through content and delete them one by one if 354 # flaged with -r 355 subdirs = iter(self.dir(pnum, abs_path).splitlines()) 356 next(subdirs) 357 for subdir in subdirs: 358 dir = subdir.split(':')[1].split(" ", 1)[1] 359 if not dir == "." and not dir == "..": 360 self.remove_ext(pnum, "%s/%s" % (abs_path, dir), recursive) 361 362 rmdir_out = exec_cmd("{} {} -wR 'rmdir \"{}\"'".format(self.debugfs, 363 self._get_part_image(pnum), 364 abs_path.rstrip('/')) 365 , as_shell=True) 366 367 for rmdir_line in rmdir_out.splitlines(): 368 if "directory not empty" in rmdir_line: 369 raise WicError("Could not complete operation: \n%s \n" 370 "use -r to remove non-empty directory" % rmdir_line) 371 if rmdir_line.startswith("rmdir:"): 372 raise WicError("Could not complete operation: \n%s " 373 "\n%s" % (str(line), rmdir_line)) 374 375 else: 376 raise WicError("Could not complete operation: \n%s " 377 "\nUnable to remove %s" % (str(line), abs_path)) 378 379 def remove(self, pnum, path, recursive): 380 """Remove files/dirs from the partition.""" 381 partimg = self._get_part_image(pnum) 382 if self.partitions[pnum].fstype.startswith('ext'): 383 self.remove_ext(pnum, path, recursive) 384 385 else: # fat 386 cmd = "{} -i {} ::{}".format(self.mdel, partimg, path) 387 try: 388 exec_cmd(cmd) 389 except WicError as err: 390 if "not found" in str(err) or "non empty" in str(err): 391 # mdel outputs 'File ... not found' or 'directory .. non empty" 392 # try to use mdeltree as path could be a directory 393 cmd = "{} -i {} ::{}".format(self.mdeltree, 394 partimg, path) 395 exec_cmd(cmd) 396 else: 397 raise err 398 self._put_part_image(pnum) 399 400 def write(self, target, expand): 401 """Write disk image to the media or file.""" 402 def write_sfdisk_script(outf, parts): 403 for key, val in parts['partitiontable'].items(): 404 if key in ("partitions", "device", "firstlba", "lastlba"): 405 continue 406 if key == "id": 407 key = "label-id" 408 outf.write("{}: {}\n".format(key, val)) 409 outf.write("\n") 410 for part in parts['partitiontable']['partitions']: 411 line = '' 412 for name in ('attrs', 'name', 'size', 'type', 'uuid'): 413 if name == 'size' and part['type'] == 'f': 414 # don't write size for extended partition 415 continue 416 val = part.get(name) 417 if val: 418 line += '{}={}, '.format(name, val) 419 if line: 420 line = line[:-2] # strip ', ' 421 if part.get('bootable'): 422 line += ' ,bootable' 423 outf.write("{}\n".format(line)) 424 outf.flush() 425 426 def read_ptable(path): 427 out = exec_cmd("{} -dJ {}".format(self.sfdisk, path)) 428 return json.loads(out) 429 430 def write_ptable(parts, target): 431 with tempfile.NamedTemporaryFile(prefix="wic-sfdisk-", mode='w') as outf: 432 write_sfdisk_script(outf, parts) 433 cmd = "{} --no-reread {} < {} ".format(self.sfdisk, target, outf.name) 434 exec_cmd(cmd, as_shell=True) 435 436 if expand is None: 437 sparse_copy(self.imagepath, target) 438 else: 439 # copy first sectors that may contain bootloader 440 sparse_copy(self.imagepath, target, length=2048 * self._lsector_size) 441 442 # copy source partition table to the target 443 parts = read_ptable(self.imagepath) 444 write_ptable(parts, target) 445 446 # get size of unpartitioned space 447 free = None 448 for line in exec_cmd("{} -F {}".format(self.sfdisk, target)).splitlines(): 449 if line.startswith("Unpartitioned space ") and line.endswith("sectors"): 450 free = int(line.split()[-2]) 451 # Align free space to a 2048 sector boundary. YOCTO #12840. 452 free = free - (free % 2048) 453 if free is None: 454 raise WicError("Can't get size of unpartitioned space") 455 456 # calculate expanded partitions sizes 457 sizes = {} 458 num_auto_resize = 0 459 for num, part in enumerate(parts['partitiontable']['partitions'], 1): 460 if num in expand: 461 if expand[num] != 0: # don't resize partition if size is set to 0 462 sectors = expand[num] // self._lsector_size 463 free -= sectors - part['size'] 464 part['size'] = sectors 465 sizes[num] = sectors 466 elif part['type'] != 'f': 467 sizes[num] = -1 468 num_auto_resize += 1 469 470 for num, part in enumerate(parts['partitiontable']['partitions'], 1): 471 if sizes.get(num) == -1: 472 part['size'] += free // num_auto_resize 473 474 # write resized partition table to the target 475 write_ptable(parts, target) 476 477 # read resized partition table 478 parts = read_ptable(target) 479 480 # copy partitions content 481 for num, part in enumerate(parts['partitiontable']['partitions'], 1): 482 pnum = str(num) 483 fstype = self.partitions[pnum].fstype 484 485 # copy unchanged partition 486 if part['size'] == self.partitions[pnum].size // self._lsector_size: 487 logger.info("copying unchanged partition {}".format(pnum)) 488 sparse_copy(self._get_part_image(pnum), target, seek=part['start'] * self._lsector_size) 489 continue 490 491 # resize or re-create partitions 492 if fstype.startswith('ext') or fstype.startswith('fat') or \ 493 fstype.startswith('linux-swap'): 494 495 partfname = None 496 with tempfile.NamedTemporaryFile(prefix="wic-part{}-".format(pnum)) as partf: 497 partfname = partf.name 498 499 if fstype.startswith('ext'): 500 logger.info("resizing ext partition {}".format(pnum)) 501 partimg = self._get_part_image(pnum) 502 sparse_copy(partimg, partfname) 503 exec_cmd("{} -pf {}".format(self.e2fsck, partfname)) 504 exec_cmd("{} {} {}s".format(\ 505 self.resize2fs, partfname, part['size'])) 506 elif fstype.startswith('fat'): 507 logger.info("copying content of the fat partition {}".format(pnum)) 508 with tempfile.TemporaryDirectory(prefix='wic-fatdir-') as tmpdir: 509 # copy content to the temporary directory 510 cmd = "{} -snompi {} :: {}".format(self.mcopy, 511 self._get_part_image(pnum), 512 tmpdir) 513 exec_cmd(cmd) 514 # create new msdos partition 515 label = part.get("name") 516 label_str = "-n {}".format(label) if label else '' 517 518 cmd = "{} {} -C {} {}".format(self.mkdosfs, label_str, partfname, 519 part['size']) 520 exec_cmd(cmd) 521 # copy content from the temporary directory to the new partition 522 cmd = "{} -snompi {} {}/* ::".format(self.mcopy, partfname, tmpdir) 523 exec_cmd(cmd, as_shell=True) 524 elif fstype.startswith('linux-swap'): 525 logger.info("creating swap partition {}".format(pnum)) 526 label = part.get("name") 527 label_str = "-L {}".format(label) if label else '' 528 uuid = part.get("uuid") 529 uuid_str = "-U {}".format(uuid) if uuid else '' 530 with open(partfname, 'w') as sparse: 531 os.ftruncate(sparse.fileno(), part['size'] * self._lsector_size) 532 exec_cmd("{} {} {} {}".format(self.mkswap, label_str, uuid_str, partfname)) 533 sparse_copy(partfname, target, seek=part['start'] * self._lsector_size) 534 os.unlink(partfname) 535 elif part['type'] != 'f': 536 logger.warning("skipping partition {}: unsupported fstype {}".format(pnum, fstype)) 537 538def wic_ls(args, native_sysroot): 539 """List contents of partitioned image or vfat partition.""" 540 disk = Disk(args.path.image, native_sysroot) 541 if not args.path.part: 542 if disk.partitions: 543 print('Num Start End Size Fstype') 544 for part in disk.partitions.values(): 545 print("{:2d} {:12d} {:12d} {:12d} {}".format(\ 546 part.pnum, part.start, part.end, 547 part.size, part.fstype)) 548 else: 549 path = args.path.path or '/' 550 print(disk.dir(args.path.part, path)) 551 552def wic_cp(args, native_sysroot): 553 """ 554 Copy local file or directory to the vfat partition of 555 partitioned image. 556 """ 557 disk = Disk(args.dest.image, native_sysroot) 558 disk.copy(args.src, args.dest.part, args.dest.path) 559 560def wic_rm(args, native_sysroot): 561 """ 562 Remove files or directories from the vfat partition of 563 partitioned image. 564 """ 565 disk = Disk(args.path.image, native_sysroot) 566 disk.remove(args.path.part, args.path.path, args.recursive_delete) 567 568def wic_write(args, native_sysroot): 569 """ 570 Write image to a target device. 571 """ 572 disk = Disk(args.image, native_sysroot, ('fat', 'ext', 'linux-swap')) 573 disk.write(args.target, args.expand) 574 575def find_canned(scripts_path, file_name): 576 """ 577 Find a file either by its path or by name in the canned files dir. 578 579 Return None if not found 580 """ 581 if os.path.exists(file_name): 582 return file_name 583 584 layers_canned_wks_dir = build_canned_image_list(scripts_path) 585 for canned_wks_dir in layers_canned_wks_dir: 586 for root, dirs, files in os.walk(canned_wks_dir): 587 for fname in files: 588 if fname == file_name: 589 fullpath = os.path.join(canned_wks_dir, fname) 590 return fullpath 591 592def get_custom_config(boot_file): 593 """ 594 Get the custom configuration to be used for the bootloader. 595 596 Return None if the file can't be found. 597 """ 598 # Get the scripts path of poky 599 scripts_path = os.path.abspath("%s/../.." % os.path.dirname(__file__)) 600 601 cfg_file = find_canned(scripts_path, boot_file) 602 if cfg_file: 603 with open(cfg_file, "r") as f: 604 config = f.read() 605 return config 606