engine.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566
  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 = 'direct'
  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. lsector_size, psector_size, self._ptable_format = splitted[1].split(":")[3:6]
  220. self._lsector_size = int(lsector_size)
  221. self._psector_size = int(psector_size)
  222. for line in splitted[2:]:
  223. pnum, start, end, size, fstype = line.split(':')[:5]
  224. partition = parttype(int(pnum), int(start[:-1]), int(end[:-1]),
  225. int(size[:-1]), fstype)
  226. self._partitions[pnum] = partition
  227. return self._partitions
  228. def __getattr__(self, name):
  229. """Get path to the executable in a lazy way."""
  230. if name in ("mdir", "mcopy", "mdel", "mdeltree", "sfdisk", "e2fsck",
  231. "resize2fs", "mkswap", "mkdosfs", "debugfs"):
  232. aname = "_%s" % name
  233. if aname not in self.__dict__:
  234. setattr(self, aname, find_executable(name, self.paths))
  235. if aname not in self.__dict__ or self.__dict__[aname] is None:
  236. raise WicError("Can't find executable '{}'".format(name))
  237. return self.__dict__[aname]
  238. return self.__dict__[name]
  239. def _get_part_image(self, pnum):
  240. if pnum not in self.partitions:
  241. raise WicError("Partition %s is not in the image")
  242. part = self.partitions[pnum]
  243. # check if fstype is supported
  244. for fstype in self.fstypes:
  245. if part.fstype.startswith(fstype):
  246. break
  247. else:
  248. raise WicError("Not supported fstype: {}".format(part.fstype))
  249. if pnum not in self._partimages:
  250. tmpf = tempfile.NamedTemporaryFile(prefix="wic-part")
  251. dst_fname = tmpf.name
  252. tmpf.close()
  253. sparse_copy(self.imagepath, dst_fname, skip=part.start, length=part.size)
  254. self._partimages[pnum] = dst_fname
  255. return self._partimages[pnum]
  256. def _put_part_image(self, pnum):
  257. """Put partition image into partitioned image."""
  258. sparse_copy(self._partimages[pnum], self.imagepath,
  259. seek=self.partitions[pnum].start)
  260. def dir(self, pnum, path):
  261. if self.partitions[pnum].fstype.startswith('ext'):
  262. return exec_cmd("{} {} -R 'ls -l {}'".format(self.debugfs,
  263. self._get_part_image(pnum),
  264. path), as_shell=True)
  265. else: # fat
  266. return exec_cmd("{} -i {} ::{}".format(self.mdir,
  267. self._get_part_image(pnum),
  268. path))
  269. def copy(self, src, pnum, path):
  270. """Copy partition image into wic image."""
  271. if self.partitions[pnum].fstype.startswith('ext'):
  272. cmd = "echo -e 'cd {}\nwrite {} {}' | {} -w {}".\
  273. format(path, src, os.path.basename(src),
  274. self.debugfs, self._get_part_image(pnum))
  275. else: # fat
  276. cmd = "{} -i {} -snop {} ::{}".format(self.mcopy,
  277. self._get_part_image(pnum),
  278. src, path)
  279. exec_cmd(cmd, as_shell=True)
  280. self._put_part_image(pnum)
  281. def remove(self, pnum, path):
  282. """Remove files/dirs from the partition."""
  283. partimg = self._get_part_image(pnum)
  284. if self.partitions[pnum].fstype.startswith('ext'):
  285. exec_cmd("{} {} -wR 'rm {}'".format(self.debugfs,
  286. self._get_part_image(pnum),
  287. path), as_shell=True)
  288. else: # fat
  289. cmd = "{} -i {} ::{}".format(self.mdel, partimg, path)
  290. try:
  291. exec_cmd(cmd)
  292. except WicError as err:
  293. if "not found" in str(err) or "non empty" in str(err):
  294. # mdel outputs 'File ... not found' or 'directory .. non empty"
  295. # try to use mdeltree as path could be a directory
  296. cmd = "{} -i {} ::{}".format(self.mdeltree,
  297. partimg, path)
  298. exec_cmd(cmd)
  299. else:
  300. raise err
  301. self._put_part_image(pnum)
  302. def write(self, target, expand):
  303. """Write disk image to the media or file."""
  304. def write_sfdisk_script(outf, parts):
  305. for key, val in parts['partitiontable'].items():
  306. if key in ("partitions", "device", "firstlba", "lastlba"):
  307. continue
  308. if key == "id":
  309. key = "label-id"
  310. outf.write("{}: {}\n".format(key, val))
  311. outf.write("\n")
  312. for part in parts['partitiontable']['partitions']:
  313. line = ''
  314. for name in ('attrs', 'name', 'size', 'type', 'uuid'):
  315. if name == 'size' and part['type'] == 'f':
  316. # don't write size for extended partition
  317. continue
  318. val = part.get(name)
  319. if val:
  320. line += '{}={}, '.format(name, val)
  321. if line:
  322. line = line[:-2] # strip ', '
  323. if part.get('bootable'):
  324. line += ' ,bootable'
  325. outf.write("{}\n".format(line))
  326. outf.flush()
  327. def read_ptable(path):
  328. out = exec_cmd("{} -dJ {}".format(self.sfdisk, path))
  329. return json.loads(out)
  330. def write_ptable(parts, target):
  331. with tempfile.NamedTemporaryFile(prefix="wic-sfdisk-", mode='w') as outf:
  332. write_sfdisk_script(outf, parts)
  333. cmd = "{} --no-reread {} < {} ".format(self.sfdisk, target, outf.name)
  334. exec_cmd(cmd, as_shell=True)
  335. if expand is None:
  336. sparse_copy(self.imagepath, target)
  337. else:
  338. # copy first sectors that may contain bootloader
  339. sparse_copy(self.imagepath, target, length=2048 * self._lsector_size)
  340. # copy source partition table to the target
  341. parts = read_ptable(self.imagepath)
  342. write_ptable(parts, target)
  343. # get size of unpartitioned space
  344. free = None
  345. for line in exec_cmd("{} -F {}".format(self.sfdisk, target)).splitlines():
  346. if line.startswith("Unpartitioned space ") and line.endswith("sectors"):
  347. free = int(line.split()[-2])
  348. # Align free space to a 2048 sector boundary. YOCTO #12840.
  349. free = free - (free % 2048)
  350. if free is None:
  351. raise WicError("Can't get size of unpartitioned space")
  352. # calculate expanded partitions sizes
  353. sizes = {}
  354. num_auto_resize = 0
  355. for num, part in enumerate(parts['partitiontable']['partitions'], 1):
  356. if num in expand:
  357. if expand[num] != 0: # don't resize partition if size is set to 0
  358. sectors = expand[num] // self._lsector_size
  359. free -= sectors - part['size']
  360. part['size'] = sectors
  361. sizes[num] = sectors
  362. elif part['type'] != 'f':
  363. sizes[num] = -1
  364. num_auto_resize += 1
  365. for num, part in enumerate(parts['partitiontable']['partitions'], 1):
  366. if sizes.get(num) == -1:
  367. part['size'] += free // num_auto_resize
  368. # write resized partition table to the target
  369. write_ptable(parts, target)
  370. # read resized partition table
  371. parts = read_ptable(target)
  372. # copy partitions content
  373. for num, part in enumerate(parts['partitiontable']['partitions'], 1):
  374. pnum = str(num)
  375. fstype = self.partitions[pnum].fstype
  376. # copy unchanged partition
  377. if part['size'] == self.partitions[pnum].size // self._lsector_size:
  378. logger.info("copying unchanged partition {}".format(pnum))
  379. sparse_copy(self._get_part_image(pnum), target, seek=part['start'] * self._lsector_size)
  380. continue
  381. # resize or re-create partitions
  382. if fstype.startswith('ext') or fstype.startswith('fat') or \
  383. fstype.startswith('linux-swap'):
  384. partfname = None
  385. with tempfile.NamedTemporaryFile(prefix="wic-part{}-".format(pnum)) as partf:
  386. partfname = partf.name
  387. if fstype.startswith('ext'):
  388. logger.info("resizing ext partition {}".format(pnum))
  389. partimg = self._get_part_image(pnum)
  390. sparse_copy(partimg, partfname)
  391. exec_cmd("{} -pf {}".format(self.e2fsck, partfname))
  392. exec_cmd("{} {} {}s".format(\
  393. self.resize2fs, partfname, part['size']))
  394. elif fstype.startswith('fat'):
  395. logger.info("copying content of the fat partition {}".format(pnum))
  396. with tempfile.TemporaryDirectory(prefix='wic-fatdir-') as tmpdir:
  397. # copy content to the temporary directory
  398. cmd = "{} -snompi {} :: {}".format(self.mcopy,
  399. self._get_part_image(pnum),
  400. tmpdir)
  401. exec_cmd(cmd)
  402. # create new msdos partition
  403. label = part.get("name")
  404. label_str = "-n {}".format(label) if label else ''
  405. cmd = "{} {} -C {} {}".format(self.mkdosfs, label_str, partfname,
  406. part['size'])
  407. exec_cmd(cmd)
  408. # copy content from the temporary directory to the new partition
  409. cmd = "{} -snompi {} {}/* ::".format(self.mcopy, partfname, tmpdir)
  410. exec_cmd(cmd, as_shell=True)
  411. elif fstype.startswith('linux-swap'):
  412. logger.info("creating swap partition {}".format(pnum))
  413. label = part.get("name")
  414. label_str = "-L {}".format(label) if label else ''
  415. uuid = part.get("uuid")
  416. uuid_str = "-U {}".format(uuid) if uuid else ''
  417. with open(partfname, 'w') as sparse:
  418. os.ftruncate(sparse.fileno(), part['size'] * self._lsector_size)
  419. exec_cmd("{} {} {} {}".format(self.mkswap, label_str, uuid_str, partfname))
  420. sparse_copy(partfname, target, seek=part['start'] * self._lsector_size)
  421. os.unlink(partfname)
  422. elif part['type'] != 'f':
  423. logger.warning("skipping partition {}: unsupported fstype {}".format(pnum, fstype))
  424. def wic_ls(args, native_sysroot):
  425. """List contents of partitioned image or vfat partition."""
  426. disk = Disk(args.path.image, native_sysroot)
  427. if not args.path.part:
  428. if disk.partitions:
  429. print('Num Start End Size Fstype')
  430. for part in disk.partitions.values():
  431. print("{:2d} {:12d} {:12d} {:12d} {}".format(\
  432. part.pnum, part.start, part.end,
  433. part.size, part.fstype))
  434. else:
  435. path = args.path.path or '/'
  436. print(disk.dir(args.path.part, path))
  437. def wic_cp(args, native_sysroot):
  438. """
  439. Copy local file or directory to the vfat partition of
  440. partitioned image.
  441. """
  442. disk = Disk(args.dest.image, native_sysroot)
  443. disk.copy(args.src, args.dest.part, args.dest.path)
  444. def wic_rm(args, native_sysroot):
  445. """
  446. Remove files or directories from the vfat partition of
  447. partitioned image.
  448. """
  449. disk = Disk(args.path.image, native_sysroot)
  450. disk.remove(args.path.part, args.path.path)
  451. def wic_write(args, native_sysroot):
  452. """
  453. Write image to a target device.
  454. """
  455. disk = Disk(args.image, native_sysroot, ('fat', 'ext', 'swap'))
  456. disk.write(args.target, args.expand)
  457. def find_canned(scripts_path, file_name):
  458. """
  459. Find a file either by its path or by name in the canned files dir.
  460. Return None if not found
  461. """
  462. if os.path.exists(file_name):
  463. return file_name
  464. layers_canned_wks_dir = build_canned_image_list(scripts_path)
  465. for canned_wks_dir in layers_canned_wks_dir:
  466. for root, dirs, files in os.walk(canned_wks_dir):
  467. for fname in files:
  468. if fname == file_name:
  469. fullpath = os.path.join(canned_wks_dir, fname)
  470. return fullpath
  471. def get_custom_config(boot_file):
  472. """
  473. Get the custom configuration to be used for the bootloader.
  474. Return None if the file can't be found.
  475. """
  476. # Get the scripts path of poky
  477. scripts_path = os.path.abspath("%s/../.." % os.path.dirname(__file__))
  478. cfg_file = find_canned(scripts_path, boot_file)
  479. if cfg_file:
  480. with open(cfg_file, "r") as f:
  481. config = f.read()
  482. return config