PageRenderTime 58ms CodeModel.GetById 28ms RepoModel.GetById 1ms app.codeStats 0ms

/scripts/lib/wic/engine.py

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