engine.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349
  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. from collections import namedtuple, OrderedDict
  33. from distutils.spawn import find_executable
  34. from wic import WicError
  35. from wic.filemap import sparse_copy
  36. from wic.pluginbase import PluginMgr
  37. from wic.utils.misc import get_bitbake_var, exec_cmd
  38. logger = logging.getLogger('wic')
  39. def verify_build_env():
  40. """
  41. Verify that the build environment is sane.
  42. Returns True if it is, false otherwise
  43. """
  44. if not os.environ.get("BUILDDIR"):
  45. raise WicError("BUILDDIR not found, exiting. (Did you forget to source oe-init-build-env?)")
  46. return True
  47. CANNED_IMAGE_DIR = "lib/wic/canned-wks" # relative to scripts
  48. SCRIPTS_CANNED_IMAGE_DIR = "scripts/" + CANNED_IMAGE_DIR
  49. WIC_DIR = "wic"
  50. def build_canned_image_list(path):
  51. layers_path = get_bitbake_var("BBLAYERS")
  52. canned_wks_layer_dirs = []
  53. if layers_path is not None:
  54. for layer_path in layers_path.split():
  55. for wks_path in (WIC_DIR, SCRIPTS_CANNED_IMAGE_DIR):
  56. cpath = os.path.join(layer_path, wks_path)
  57. if os.path.isdir(cpath):
  58. canned_wks_layer_dirs.append(cpath)
  59. cpath = os.path.join(path, CANNED_IMAGE_DIR)
  60. canned_wks_layer_dirs.append(cpath)
  61. return canned_wks_layer_dirs
  62. def find_canned_image(scripts_path, wks_file):
  63. """
  64. Find a .wks file with the given name in the canned files dir.
  65. Return False if not found
  66. """
  67. layers_canned_wks_dir = build_canned_image_list(scripts_path)
  68. for canned_wks_dir in layers_canned_wks_dir:
  69. for root, dirs, files in os.walk(canned_wks_dir):
  70. for fname in files:
  71. if fname.endswith("~") or fname.endswith("#"):
  72. continue
  73. if fname.endswith(".wks") and wks_file + ".wks" == fname:
  74. fullpath = os.path.join(canned_wks_dir, fname)
  75. return fullpath
  76. return None
  77. def list_canned_images(scripts_path):
  78. """
  79. List the .wks files in the canned image dir, minus the extension.
  80. """
  81. layers_canned_wks_dir = build_canned_image_list(scripts_path)
  82. for canned_wks_dir in layers_canned_wks_dir:
  83. for root, dirs, files in os.walk(canned_wks_dir):
  84. for fname in files:
  85. if fname.endswith("~") or fname.endswith("#"):
  86. continue
  87. if fname.endswith(".wks"):
  88. fullpath = os.path.join(canned_wks_dir, fname)
  89. with open(fullpath) as wks:
  90. for line in wks:
  91. desc = ""
  92. idx = line.find("short-description:")
  93. if idx != -1:
  94. desc = line[idx + len("short-description:"):].strip()
  95. break
  96. basename = os.path.splitext(fname)[0]
  97. print(" %s\t\t%s" % (basename.ljust(30), desc))
  98. def list_canned_image_help(scripts_path, fullpath):
  99. """
  100. List the help and params in the specified canned image.
  101. """
  102. found = False
  103. with open(fullpath) as wks:
  104. for line in wks:
  105. if not found:
  106. idx = line.find("long-description:")
  107. if idx != -1:
  108. print()
  109. print(line[idx + len("long-description:"):].strip())
  110. found = True
  111. continue
  112. if not line.strip():
  113. break
  114. idx = line.find("#")
  115. if idx != -1:
  116. print(line[idx + len("#:"):].rstrip())
  117. else:
  118. break
  119. def list_source_plugins():
  120. """
  121. List the available source plugins i.e. plugins available for --source.
  122. """
  123. plugins = PluginMgr.get_plugins('source')
  124. for plugin in plugins:
  125. print(" %s" % plugin)
  126. def wic_create(wks_file, rootfs_dir, bootimg_dir, kernel_dir,
  127. native_sysroot, options):
  128. """
  129. Create image
  130. wks_file - user-defined OE kickstart file
  131. rootfs_dir - absolute path to the build's /rootfs dir
  132. bootimg_dir - absolute path to the build's boot artifacts directory
  133. kernel_dir - absolute path to the build's kernel directory
  134. native_sysroot - absolute path to the build's native sysroots dir
  135. image_output_dir - dirname to create for image
  136. options - wic command line options (debug, bmap, etc)
  137. Normally, the values for the build artifacts values are determined
  138. by 'wic -e' from the output of the 'bitbake -e' command given an
  139. image name e.g. 'core-image-minimal' and a given machine set in
  140. local.conf. If that's the case, the variables get the following
  141. values from the output of 'bitbake -e':
  142. rootfs_dir: IMAGE_ROOTFS
  143. kernel_dir: DEPLOY_DIR_IMAGE
  144. native_sysroot: STAGING_DIR_NATIVE
  145. In the above case, bootimg_dir remains unset and the
  146. plugin-specific image creation code is responsible for finding the
  147. bootimg artifacts.
  148. In the case where the values are passed in explicitly i.e 'wic -e'
  149. is not used but rather the individual 'wic' options are used to
  150. explicitly specify these values.
  151. """
  152. try:
  153. oe_builddir = os.environ["BUILDDIR"]
  154. except KeyError:
  155. raise WicError("BUILDDIR not found, exiting. (Did you forget to source oe-init-build-env?)")
  156. if not os.path.exists(options.outdir):
  157. os.makedirs(options.outdir)
  158. pname = 'direct'
  159. plugin_class = PluginMgr.get_plugins('imager').get(pname)
  160. if not plugin_class:
  161. raise WicError('Unknown plugin: %s' % pname)
  162. plugin = plugin_class(wks_file, rootfs_dir, bootimg_dir, kernel_dir,
  163. native_sysroot, oe_builddir, options)
  164. plugin.do_create()
  165. logger.info("The image(s) were created using OE kickstart file:\n %s", wks_file)
  166. def wic_list(args, scripts_path):
  167. """
  168. Print the list of images or source plugins.
  169. """
  170. if args.list_type is None:
  171. return False
  172. if args.list_type == "images":
  173. list_canned_images(scripts_path)
  174. return True
  175. elif args.list_type == "source-plugins":
  176. list_source_plugins()
  177. return True
  178. elif len(args.help_for) == 1 and args.help_for[0] == 'help':
  179. wks_file = args.list_type
  180. fullpath = find_canned_image(scripts_path, wks_file)
  181. if not fullpath:
  182. raise WicError("No image named %s found, exiting. "
  183. "(Use 'wic list images' to list available images, "
  184. "or specify a fully-qualified OE kickstart (.wks) "
  185. "filename)" % wks_file)
  186. list_canned_image_help(scripts_path, fullpath)
  187. return True
  188. return False
  189. class Disk:
  190. def __init__(self, imagepath, native_sysroot):
  191. self.imagepath = imagepath
  192. self.native_sysroot = native_sysroot
  193. self._partitions = None
  194. self._mdir = None
  195. self._partimages = {}
  196. # find parted
  197. self.paths = "/bin:/usr/bin:/usr/sbin:/sbin/"
  198. if native_sysroot:
  199. for path in self.paths.split(':'):
  200. self.paths = "%s%s:%s" % (native_sysroot, path, self.paths)
  201. self.parted = find_executable("parted", self.paths)
  202. if not self.parted:
  203. raise WicError("Can't find executable parted")
  204. def __del__(self):
  205. for path in self._partimages.values():
  206. os.unlink(path)
  207. @property
  208. def partitions(self):
  209. if self._partitions is None:
  210. self._partitions = OrderedDict()
  211. out = exec_cmd("%s -sm %s unit B print" % (self.parted, self.imagepath))
  212. parttype = namedtuple("Part", "pnum start end size fstype")
  213. for line in out.splitlines()[2:]:
  214. pnum, start, end, size, fstype = line.split(':')[:5]
  215. partition = parttype(pnum, int(start[:-1]), int(end[:-1]),
  216. int(size[:-1]), fstype)
  217. self._partitions[pnum] = partition
  218. return self._partitions
  219. @property
  220. def mdir(self):
  221. if self._mdir is None:
  222. self._mdir = find_executable("mdir", self.paths)
  223. if not self._mdir:
  224. raise WicError("Can't find executable mdir")
  225. return self._mdir
  226. def _get_part_image(self, pnum):
  227. if pnum not in self.partitions:
  228. raise WicError("Partition %s is not in the image")
  229. part = self.partitions[pnum]
  230. if not part.fstype.startswith("fat"):
  231. raise WicError("Not supported fstype: {}".format(part.fstype))
  232. if pnum not in self._partimages:
  233. tmpf = tempfile.NamedTemporaryFile(prefix="wic-part")
  234. dst_fname = tmpf.name
  235. tmpf.close()
  236. sparse_copy(self.imagepath, dst_fname, skip=part.start, length=part.size)
  237. self._partimages[pnum] = dst_fname
  238. return self._partimages[pnum]
  239. def dir(self, pnum, path):
  240. return exec_cmd("{} -i {} ::{}".format(self.mdir,
  241. self._get_part_image(pnum),
  242. path))
  243. def wic_ls(args, native_sysroot):
  244. """List contents of partitioned image or vfat partition."""
  245. disk = Disk(args.path.image, native_sysroot)
  246. if not args.path.part:
  247. if disk.partitions:
  248. print('Num Start End Size Fstype')
  249. for part in disk.partitions.values():
  250. print("{:2s} {:12d} {:12d} {:12d} {}".format(\
  251. part.pnum, part.start, part.end,
  252. part.size, part.fstype))
  253. else:
  254. path = args.path.path or '/'
  255. print(disk.dir(args.path.part, path))
  256. def wic_cp(args, native_sysroot):
  257. """
  258. Copy local file or directory to the vfat partition of
  259. partitioned image.
  260. """
  261. pass
  262. def find_canned(scripts_path, file_name):
  263. """
  264. Find a file either by its path or by name in the canned files dir.
  265. Return None if not found
  266. """
  267. if os.path.exists(file_name):
  268. return file_name
  269. layers_canned_wks_dir = build_canned_image_list(scripts_path)
  270. for canned_wks_dir in layers_canned_wks_dir:
  271. for root, dirs, files in os.walk(canned_wks_dir):
  272. for fname in files:
  273. if fname == file_name:
  274. fullpath = os.path.join(canned_wks_dir, fname)
  275. return fullpath
  276. def get_custom_config(boot_file):
  277. """
  278. Get the custom configuration to be used for the bootloader.
  279. Return None if the file can't be found.
  280. """
  281. # Get the scripts path of poky
  282. scripts_path = os.path.abspath("%s/../.." % os.path.dirname(__file__))
  283. cfg_file = find_canned(scripts_path, boot_file)
  284. if cfg_file:
  285. with open(cfg_file, "r") as f:
  286. config = f.read()
  287. return config