Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 1 | # |
| 2 | # Copyright (c) 2013, Intel Corporation. |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 3 | # |
Brad Bishop | c342db3 | 2019-05-15 21:57:59 -0400 | [diff] [blame] | 4 | # SPDX-License-Identifier: GPL-2.0-only |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 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 | |
Brad Bishop | 6e60e8b | 2018-02-01 10:27:11 -0500 | [diff] [blame] | 17 | import logging |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 18 | import os |
Brad Bishop | d7bf8c1 | 2018-02-25 22:55:05 -0500 | [diff] [blame] | 19 | import tempfile |
| 20 | import json |
| 21 | import subprocess |
Brad Bishop | 6dbb316 | 2019-11-25 09:41:34 -0500 | [diff] [blame] | 22 | import re |
Brad Bishop | d7bf8c1 | 2018-02-25 22:55:05 -0500 | [diff] [blame] | 23 | |
| 24 | from collections import namedtuple, OrderedDict |
| 25 | from distutils.spawn import find_executable |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 26 | |
Brad Bishop | 6e60e8b | 2018-02-01 10:27:11 -0500 | [diff] [blame] | 27 | from wic import WicError |
Brad Bishop | d7bf8c1 | 2018-02-25 22:55:05 -0500 | [diff] [blame] | 28 | from wic.filemap import sparse_copy |
Brad Bishop | 6e60e8b | 2018-02-01 10:27:11 -0500 | [diff] [blame] | 29 | from wic.pluginbase import PluginMgr |
Brad Bishop | d7bf8c1 | 2018-02-25 22:55:05 -0500 | [diff] [blame] | 30 | from wic.misc import get_bitbake_var, exec_cmd |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 31 | |
Brad Bishop | 6e60e8b | 2018-02-01 10:27:11 -0500 | [diff] [blame] | 32 | logger = logging.getLogger('wic') |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 33 | |
| 34 | def 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"): |
Brad Bishop | 6e60e8b | 2018-02-01 10:27:11 -0500 | [diff] [blame] | 41 | raise WicError("BUILDDIR not found, exiting. (Did you forget to source oe-init-build-env?)") |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 42 | |
| 43 | return True |
| 44 | |
| 45 | |
| 46 | CANNED_IMAGE_DIR = "lib/wic/canned-wks" # relative to scripts |
| 47 | SCRIPTS_CANNED_IMAGE_DIR = "scripts/" + CANNED_IMAGE_DIR |
Brad Bishop | 6e60e8b | 2018-02-01 10:27:11 -0500 | [diff] [blame] | 48 | WIC_DIR = "wic" |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 49 | |
| 50 | def build_canned_image_list(path): |
Brad Bishop | 6e60e8b | 2018-02-01 10:27:11 -0500 | [diff] [blame] | 51 | layers_path = get_bitbake_var("BBLAYERS") |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 52 | canned_wks_layer_dirs = [] |
| 53 | |
| 54 | if layers_path is not None: |
| 55 | for layer_path in layers_path.split(): |
Brad Bishop | 6e60e8b | 2018-02-01 10:27:11 -0500 | [diff] [blame] | 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) |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 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 | |
| 66 | def 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 |
Brad Bishop | 15ae250 | 2019-06-18 21:44:24 -0400 | [diff] [blame] | 79 | if ((fname.endswith(".wks") and wks_file + ".wks" == fname) or \ |
| 80 | (fname.endswith(".wks.in") and wks_file + ".wks.in" == fname)): |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 81 | fullpath = os.path.join(canned_wks_dir, fname) |
| 82 | return fullpath |
| 83 | return None |
| 84 | |
| 85 | |
| 86 | def 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 |
Brad Bishop | 15ae250 | 2019-06-18 21:44:24 -0400 | [diff] [blame] | 97 | if fname.endswith(".wks") or fname.endswith(".wks.in"): |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 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 |
Brad Bishop | 15ae250 | 2019-06-18 21:44:24 -0400 | [diff] [blame] | 106 | basename = fname.split('.')[0] |
Patrick Williams | c0f7c04 | 2017-02-23 20:41:17 -0600 | [diff] [blame] | 107 | print(" %s\t\t%s" % (basename.ljust(30), desc)) |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 108 | |
| 109 | |
| 110 | def 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: |
Patrick Williams | c0f7c04 | 2017-02-23 20:41:17 -0600 | [diff] [blame] | 120 | print() |
| 121 | print(line[idx + len("long-description:"):].strip()) |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 122 | found = True |
| 123 | continue |
| 124 | if not line.strip(): |
| 125 | break |
| 126 | idx = line.find("#") |
| 127 | if idx != -1: |
Patrick Williams | c0f7c04 | 2017-02-23 20:41:17 -0600 | [diff] [blame] | 128 | print(line[idx + len("#:"):].rstrip()) |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 129 | else: |
| 130 | break |
| 131 | |
| 132 | |
| 133 | def list_source_plugins(): |
| 134 | """ |
| 135 | List the available source plugins i.e. plugins available for --source. |
| 136 | """ |
Brad Bishop | 6e60e8b | 2018-02-01 10:27:11 -0500 | [diff] [blame] | 137 | plugins = PluginMgr.get_plugins('source') |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 138 | |
| 139 | for plugin in plugins: |
Patrick Williams | c0f7c04 | 2017-02-23 20:41:17 -0600 | [diff] [blame] | 140 | print(" %s" % plugin) |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 141 | |
| 142 | |
| 143 | def wic_create(wks_file, rootfs_dir, bootimg_dir, kernel_dir, |
Brad Bishop | 6e60e8b | 2018-02-01 10:27:11 -0500 | [diff] [blame] | 144 | native_sysroot, options): |
| 145 | """ |
| 146 | Create image |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 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 |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 153 | image_output_dir - dirname to create for image |
Brad Bishop | 6e60e8b | 2018-02-01 10:27:11 -0500 | [diff] [blame] | 154 | options - wic command line options (debug, bmap, etc) |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 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: |
Brad Bishop | 6e60e8b | 2018-02-01 10:27:11 -0500 | [diff] [blame] | 177 | raise WicError("BUILDDIR not found, exiting. (Did you forget to source oe-init-build-env?)") |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 178 | |
Brad Bishop | 6e60e8b | 2018-02-01 10:27:11 -0500 | [diff] [blame] | 179 | if not os.path.exists(options.outdir): |
| 180 | os.makedirs(options.outdir) |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 181 | |
Brad Bishop | 1a4b7ee | 2018-12-16 17:11:34 -0800 | [diff] [blame] | 182 | pname = options.imager |
Brad Bishop | 6e60e8b | 2018-02-01 10:27:11 -0500 | [diff] [blame] | 183 | plugin_class = PluginMgr.get_plugins('imager').get(pname) |
| 184 | if not plugin_class: |
| 185 | raise WicError('Unknown plugin: %s' % pname) |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 186 | |
Brad Bishop | 6e60e8b | 2018-02-01 10:27:11 -0500 | [diff] [blame] | 187 | plugin = plugin_class(wks_file, rootfs_dir, bootimg_dir, kernel_dir, |
| 188 | native_sysroot, oe_builddir, options) |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 189 | |
Brad Bishop | 6e60e8b | 2018-02-01 10:27:11 -0500 | [diff] [blame] | 190 | plugin.do_create() |
Patrick Williams | c0f7c04 | 2017-02-23 20:41:17 -0600 | [diff] [blame] | 191 | |
Brad Bishop | 6e60e8b | 2018-02-01 10:27:11 -0500 | [diff] [blame] | 192 | logger.info("The image(s) were created using OE kickstart file:\n %s", wks_file) |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 193 | |
| 194 | |
| 195 | def wic_list(args, scripts_path): |
| 196 | """ |
| 197 | Print the list of images or source plugins. |
| 198 | """ |
Brad Bishop | d7bf8c1 | 2018-02-25 22:55:05 -0500 | [diff] [blame] | 199 | if args.list_type is None: |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 200 | return False |
| 201 | |
Brad Bishop | d7bf8c1 | 2018-02-25 22:55:05 -0500 | [diff] [blame] | 202 | if args.list_type == "images": |
| 203 | |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 204 | list_canned_images(scripts_path) |
| 205 | return True |
Brad Bishop | d7bf8c1 | 2018-02-25 22:55:05 -0500 | [diff] [blame] | 206 | elif args.list_type == "source-plugins": |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 207 | list_source_plugins() |
| 208 | return True |
Brad Bishop | d7bf8c1 | 2018-02-25 22:55:05 -0500 | [diff] [blame] | 209 | elif len(args.help_for) == 1 and args.help_for[0] == 'help': |
| 210 | wks_file = args.list_type |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 211 | fullpath = find_canned_image(scripts_path, wks_file) |
| 212 | if not fullpath: |
Brad Bishop | 6e60e8b | 2018-02-01 10:27:11 -0500 | [diff] [blame] | 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 | |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 218 | list_canned_image_help(scripts_path, fullpath) |
| 219 | return True |
| 220 | |
| 221 | return False |
Brad Bishop | 6e60e8b | 2018-02-01 10:27:11 -0500 | [diff] [blame] | 222 | |
Brad Bishop | d7bf8c1 | 2018-02-25 22:55:05 -0500 | [diff] [blame] | 223 | |
| 224 | class 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 |
Andrew Geissler | 99467da | 2019-02-25 18:54:23 -0600 | [diff] [blame] | 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 | |
Brad Bishop | d7bf8c1 | 2018-02-25 22:55:05 -0500 | [diff] [blame] | 244 | if native_sysroot: |
Andrew Geissler | 99467da | 2019-02-25 18:54:23 -0600 | [diff] [blame] | 245 | for path in pathlist.split(':'): |
Brad Bishop | d7bf8c1 | 2018-02-25 22:55:05 -0500 | [diff] [blame] | 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() |
Brad Bishop | 1a4b7ee | 2018-12-16 17:11:34 -0800 | [diff] [blame] | 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] |
Brad Bishop | d7bf8c1 | 2018-02-25 22:55:05 -0500 | [diff] [blame] | 270 | self._lsector_size = int(lsector_size) |
| 271 | self._psector_size = int(psector_size) |
Brad Bishop | 1a4b7ee | 2018-12-16 17:11:34 -0800 | [diff] [blame] | 272 | for line in splitted[idx + 2:]: |
Brad Bishop | d7bf8c1 | 2018-02-25 22:55:05 -0500 | [diff] [blame] | 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)) |
Brad Bishop | d5ae7d9 | 2018-06-14 09:52:03 -0700 | [diff] [blame] | 287 | if aname not in self.__dict__ or self.__dict__[aname] is None: |
| 288 | raise WicError("Can't find executable '{}'".format(name)) |
Brad Bishop | d7bf8c1 | 2018-02-25 22:55:05 -0500 | [diff] [blame] | 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'): |
Brad Bishop | 1932369 | 2019-04-05 15:28:33 -0400 | [diff] [blame] | 329 | cmd = "printf 'cd {}\nwrite {} {}\n' | {} -w {}".\ |
Brad Bishop | d7bf8c1 | 2018-02-25 22:55:05 -0500 | [diff] [blame] | 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 | |
Brad Bishop | 6dbb316 | 2019-11-25 09:41:34 -0500 | [diff] [blame] | 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): |
Brad Bishop | d7bf8c1 | 2018-02-25 22:55:05 -0500 | [diff] [blame] | 380 | """Remove files/dirs from the partition.""" |
| 381 | partimg = self._get_part_image(pnum) |
| 382 | if self.partitions[pnum].fstype.startswith('ext'): |
Brad Bishop | 6dbb316 | 2019-11-25 09:41:34 -0500 | [diff] [blame] | 383 | self.remove_ext(pnum, path, recursive) |
| 384 | |
Brad Bishop | d7bf8c1 | 2018-02-25 22:55:05 -0500 | [diff] [blame] | 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) |
Brad Bishop | d5ae7d9 | 2018-06-14 09:52:03 -0700 | [diff] [blame] | 433 | cmd = "{} --no-reread {} < {} ".format(self.sfdisk, target, outf.name) |
| 434 | exec_cmd(cmd, as_shell=True) |
Brad Bishop | d7bf8c1 | 2018-02-25 22:55:05 -0500 | [diff] [blame] | 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]) |
Brad Bishop | d5ae7d9 | 2018-06-14 09:52:03 -0700 | [diff] [blame] | 451 | # Align free space to a 2048 sector boundary. YOCTO #12840. |
| 452 | free = free - (free % 2048) |
Brad Bishop | d7bf8c1 | 2018-02-25 22:55:05 -0500 | [diff] [blame] | 453 | if free is None: |
| 454 | raise WicError("Can't get size of unpartitioned space") |
| 455 | |
| 456 | # calculate expanded partitions sizes |
| 457 | sizes = {} |
Brad Bishop | d5ae7d9 | 2018-06-14 09:52:03 -0700 | [diff] [blame] | 458 | num_auto_resize = 0 |
Brad Bishop | d7bf8c1 | 2018-02-25 22:55:05 -0500 | [diff] [blame] | 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 |
Brad Bishop | d5ae7d9 | 2018-06-14 09:52:03 -0700 | [diff] [blame] | 468 | num_auto_resize += 1 |
Brad Bishop | d7bf8c1 | 2018-02-25 22:55:05 -0500 | [diff] [blame] | 469 | |
| 470 | for num, part in enumerate(parts['partitiontable']['partitions'], 1): |
| 471 | if sizes.get(num) == -1: |
Brad Bishop | d5ae7d9 | 2018-06-14 09:52:03 -0700 | [diff] [blame] | 472 | part['size'] += free // num_auto_resize |
Brad Bishop | d7bf8c1 | 2018-02-25 22:55:05 -0500 | [diff] [blame] | 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': |
Brad Bishop | 1a4b7ee | 2018-12-16 17:11:34 -0800 | [diff] [blame] | 536 | logger.warning("skipping partition {}: unsupported fstype {}".format(pnum, fstype)) |
Brad Bishop | d7bf8c1 | 2018-02-25 22:55:05 -0500 | [diff] [blame] | 537 | |
| 538 | def 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 | |
| 552 | def 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 | |
| 560 | def 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) |
Brad Bishop | 6dbb316 | 2019-11-25 09:41:34 -0500 | [diff] [blame] | 566 | disk.remove(args.path.part, args.path.path, args.recursive_delete) |
Brad Bishop | d7bf8c1 | 2018-02-25 22:55:05 -0500 | [diff] [blame] | 567 | |
| 568 | def wic_write(args, native_sysroot): |
| 569 | """ |
| 570 | Write image to a target device. |
| 571 | """ |
Brad Bishop | 64c979e | 2019-11-04 13:55:29 -0500 | [diff] [blame] | 572 | disk = Disk(args.image, native_sysroot, ('fat', 'ext', 'linux-swap')) |
Brad Bishop | d7bf8c1 | 2018-02-25 22:55:05 -0500 | [diff] [blame] | 573 | disk.write(args.target, args.expand) |
| 574 | |
Brad Bishop | 6e60e8b | 2018-02-01 10:27:11 -0500 | [diff] [blame] | 575 | def 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 | |
| 592 | def 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 |