wic 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538
  1. #!/usr/bin/env python3
  2. # ex:ts=4:sw=4:sts=4:et
  3. # -*- tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*-
  4. #
  5. # Copyright (c) 2013, Intel Corporation.
  6. # All rights reserved.
  7. #
  8. # This program is free software; you can redistribute it and/or modify
  9. # it under the terms of the GNU General Public License version 2 as
  10. # published by the Free Software Foundation.
  11. #
  12. # This program is distributed in the hope that it will be useful,
  13. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. # GNU General Public License for more details.
  16. #
  17. # You should have received a copy of the GNU General Public License along
  18. # with this program; if not, write to the Free Software Foundation, Inc.,
  19. # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  20. #
  21. # DESCRIPTION 'wic' is the OpenEmbedded Image Creator that users can
  22. # use to generate bootable images. Invoking it without any arguments
  23. # will display help screens for the 'wic' command and list the
  24. # available 'wic' subcommands. Invoking a subcommand without any
  25. # arguments will likewise display help screens for the specified
  26. # subcommand. Please use that interface for detailed help.
  27. #
  28. # AUTHORS
  29. # Tom Zanussi <tom.zanussi (at] linux.intel.com>
  30. #
  31. __version__ = "0.2.0"
  32. # Python Standard Library modules
  33. import os
  34. import sys
  35. import argparse
  36. import logging
  37. import subprocess
  38. from collections import namedtuple
  39. from distutils import spawn
  40. # External modules
  41. scripts_path = os.path.dirname(os.path.realpath(__file__))
  42. lib_path = scripts_path + '/lib'
  43. sys.path.insert(0, lib_path)
  44. import scriptpath
  45. scriptpath.add_oe_lib_path()
  46. # Check whether wic is running within eSDK environment
  47. sdkroot = scripts_path
  48. if os.environ.get('SDKTARGETSYSROOT'):
  49. while sdkroot != '' and sdkroot != os.sep:
  50. if os.path.exists(os.path.join(sdkroot, '.devtoolbase')):
  51. # Set BUILDDIR for wic to work within eSDK
  52. os.environ['BUILDDIR'] = sdkroot
  53. # .devtoolbase only exists within eSDK
  54. # If found, initialize bitbake path for eSDK environment and append to PATH
  55. sdkroot = os.path.join(os.path.dirname(scripts_path), 'bitbake', 'bin')
  56. os.environ['PATH'] += ":" + sdkroot
  57. break
  58. sdkroot = os.path.dirname(sdkroot)
  59. bitbake_exe = spawn.find_executable('bitbake')
  60. if bitbake_exe:
  61. bitbake_path = scriptpath.add_bitbake_lib_path()
  62. import bb
  63. from wic import WicError
  64. from wic.misc import get_bitbake_var, BB_VARS
  65. from wic import engine
  66. from wic import help as hlp
  67. def wic_logger():
  68. """Create and convfigure wic logger."""
  69. logger = logging.getLogger('wic')
  70. logger.setLevel(logging.INFO)
  71. handler = logging.StreamHandler()
  72. formatter = logging.Formatter('%(levelname)s: %(message)s')
  73. handler.setFormatter(formatter)
  74. logger.addHandler(handler)
  75. return logger
  76. logger = wic_logger()
  77. def rootfs_dir_to_args(krootfs_dir):
  78. """
  79. Get a rootfs_dir dict and serialize to string
  80. """
  81. rootfs_dir = ''
  82. for key, val in krootfs_dir.items():
  83. rootfs_dir += ' '
  84. rootfs_dir += '='.join([key, val])
  85. return rootfs_dir.strip()
  86. class RootfsArgAction(argparse.Action):
  87. def __init__(self, **kwargs):
  88. super().__init__(**kwargs)
  89. def __call__(self, parser, namespace, value, option_string=None):
  90. if not "rootfs_dir" in vars(namespace) or \
  91. not type(namespace.__dict__['rootfs_dir']) is dict:
  92. namespace.__dict__['rootfs_dir'] = {}
  93. if '=' in value:
  94. (key, rootfs_dir) = value.split('=')
  95. else:
  96. key = 'ROOTFS_DIR'
  97. rootfs_dir = value
  98. namespace.__dict__['rootfs_dir'][key] = rootfs_dir
  99. def wic_create_subcommand(options, usage_str):
  100. """
  101. Command-line handling for image creation. The real work is done
  102. by image.engine.wic_create()
  103. """
  104. if options.build_rootfs and not bitbake_exe:
  105. raise WicError("Can't build rootfs as bitbake is not in the $PATH")
  106. if not options.image_name:
  107. missed = []
  108. for val, opt in [(options.rootfs_dir, 'rootfs-dir'),
  109. (options.bootimg_dir, 'bootimg-dir'),
  110. (options.kernel_dir, 'kernel-dir'),
  111. (options.native_sysroot, 'native-sysroot')]:
  112. if not val:
  113. missed.append(opt)
  114. if missed:
  115. raise WicError("The following build artifacts are not specified: %s" %
  116. ", ".join(missed))
  117. if options.image_name:
  118. BB_VARS.default_image = options.image_name
  119. else:
  120. options.build_check = False
  121. if options.vars_dir:
  122. BB_VARS.vars_dir = options.vars_dir
  123. if options.build_check and not engine.verify_build_env():
  124. raise WicError("Couldn't verify build environment, exiting")
  125. if options.debug:
  126. logger.setLevel(logging.DEBUG)
  127. if options.image_name:
  128. if options.build_rootfs:
  129. argv = ["bitbake", options.image_name]
  130. if options.debug:
  131. argv.append("--debug")
  132. logger.info("Building rootfs...\n")
  133. subprocess.check_call(argv)
  134. rootfs_dir = get_bitbake_var("IMAGE_ROOTFS", options.image_name)
  135. kernel_dir = get_bitbake_var("DEPLOY_DIR_IMAGE", options.image_name)
  136. bootimg_dir = get_bitbake_var("STAGING_DATADIR", options.image_name)
  137. native_sysroot = options.native_sysroot
  138. if options.vars_dir and not native_sysroot:
  139. native_sysroot = get_bitbake_var("RECIPE_SYSROOT_NATIVE", options.image_name)
  140. else:
  141. if options.build_rootfs:
  142. raise WicError("Image name is not specified, exiting. "
  143. "(Use -e/--image-name to specify it)")
  144. native_sysroot = options.native_sysroot
  145. if not options.vars_dir and (not native_sysroot or not os.path.isdir(native_sysroot)):
  146. logger.info("Building wic-tools...\n")
  147. subprocess.check_call(["bitbake", "wic-tools"])
  148. native_sysroot = get_bitbake_var("RECIPE_SYSROOT_NATIVE", "wic-tools")
  149. if not native_sysroot:
  150. raise WicError("Unable to find the location of the native tools sysroot")
  151. wks_file = options.wks_file
  152. if not wks_file.endswith(".wks"):
  153. wks_file = engine.find_canned_image(scripts_path, wks_file)
  154. if not wks_file:
  155. raise WicError("No image named %s found, exiting. (Use 'wic list images' "
  156. "to list available images, or specify a fully-qualified OE "
  157. "kickstart (.wks) filename)" % options.wks_file)
  158. if not options.image_name:
  159. rootfs_dir = ''
  160. if 'ROOTFS_DIR' in options.rootfs_dir:
  161. rootfs_dir = options.rootfs_dir['ROOTFS_DIR']
  162. bootimg_dir = options.bootimg_dir
  163. kernel_dir = options.kernel_dir
  164. native_sysroot = options.native_sysroot
  165. if rootfs_dir and not os.path.isdir(rootfs_dir):
  166. raise WicError("--rootfs-dir (-r) not found, exiting")
  167. if not os.path.isdir(bootimg_dir):
  168. raise WicError("--bootimg-dir (-b) not found, exiting")
  169. if not os.path.isdir(kernel_dir):
  170. raise WicError("--kernel-dir (-k) not found, exiting")
  171. if not os.path.isdir(native_sysroot):
  172. raise WicError("--native-sysroot (-n) not found, exiting")
  173. else:
  174. not_found = not_found_dir = ""
  175. if not os.path.isdir(rootfs_dir):
  176. (not_found, not_found_dir) = ("rootfs-dir", rootfs_dir)
  177. elif not os.path.isdir(kernel_dir):
  178. (not_found, not_found_dir) = ("kernel-dir", kernel_dir)
  179. elif not os.path.isdir(native_sysroot):
  180. (not_found, not_found_dir) = ("native-sysroot", native_sysroot)
  181. if not_found:
  182. if not not_found_dir:
  183. not_found_dir = "Completely missing artifact - wrong image (.wks) used?"
  184. logger.info("Build artifacts not found, exiting.")
  185. logger.info(" (Please check that the build artifacts for the machine")
  186. logger.info(" selected in local.conf actually exist and that they")
  187. logger.info(" are the correct artifacts for the image (.wks file)).\n")
  188. raise WicError("The artifact that couldn't be found was %s:\n %s", not_found, not_found_dir)
  189. krootfs_dir = options.rootfs_dir
  190. if krootfs_dir is None:
  191. krootfs_dir = {}
  192. krootfs_dir['ROOTFS_DIR'] = rootfs_dir
  193. rootfs_dir = rootfs_dir_to_args(krootfs_dir)
  194. logger.info("Creating image(s)...\n")
  195. engine.wic_create(wks_file, rootfs_dir, bootimg_dir, kernel_dir,
  196. native_sysroot, options)
  197. def wic_list_subcommand(args, usage_str):
  198. """
  199. Command-line handling for listing available images.
  200. The real work is done by image.engine.wic_list()
  201. """
  202. if not engine.wic_list(args, scripts_path):
  203. raise WicError("Bad list arguments, exiting")
  204. def wic_ls_subcommand(args, usage_str):
  205. """
  206. Command-line handling for list content of images.
  207. The real work is done by engine.wic_ls()
  208. """
  209. engine.wic_ls(args, args.native_sysroot)
  210. def wic_cp_subcommand(args, usage_str):
  211. """
  212. Command-line handling for copying files/dirs to images.
  213. The real work is done by engine.wic_cp()
  214. """
  215. engine.wic_cp(args, args.native_sysroot)
  216. def wic_rm_subcommand(args, usage_str):
  217. """
  218. Command-line handling for removing files/dirs from images.
  219. The real work is done by engine.wic_rm()
  220. """
  221. engine.wic_rm(args, args.native_sysroot)
  222. def wic_write_subcommand(args, usage_str):
  223. """
  224. Command-line handling for writing images.
  225. The real work is done by engine.wic_write()
  226. """
  227. engine.wic_write(args, args.native_sysroot)
  228. def wic_help_subcommand(args, usage_str):
  229. """
  230. Command-line handling for help subcommand to keep the current
  231. structure of the function definitions.
  232. """
  233. pass
  234. def wic_help_topic_subcommand(usage_str, help_str):
  235. """
  236. Display function for help 'sub-subcommands'.
  237. """
  238. print(help_str)
  239. return
  240. wic_help_topic_usage = """
  241. """
  242. helptopics = {
  243. "plugins": [wic_help_topic_subcommand,
  244. wic_help_topic_usage,
  245. hlp.wic_plugins_help],
  246. "overview": [wic_help_topic_subcommand,
  247. wic_help_topic_usage,
  248. hlp.wic_overview_help],
  249. "kickstart": [wic_help_topic_subcommand,
  250. wic_help_topic_usage,
  251. hlp.wic_kickstart_help],
  252. "create": [wic_help_topic_subcommand,
  253. wic_help_topic_usage,
  254. hlp.wic_create_help],
  255. "ls": [wic_help_topic_subcommand,
  256. wic_help_topic_usage,
  257. hlp.wic_ls_help],
  258. "cp": [wic_help_topic_subcommand,
  259. wic_help_topic_usage,
  260. hlp.wic_cp_help],
  261. "rm": [wic_help_topic_subcommand,
  262. wic_help_topic_usage,
  263. hlp.wic_rm_help],
  264. "write": [wic_help_topic_subcommand,
  265. wic_help_topic_usage,
  266. hlp.wic_write_help],
  267. "list": [wic_help_topic_subcommand,
  268. wic_help_topic_usage,
  269. hlp.wic_list_help]
  270. }
  271. def wic_init_parser_create(subparser):
  272. subparser.add_argument("wks_file")
  273. subparser.add_argument("-o", "--outdir", dest="outdir", default='.',
  274. help="name of directory to create image in")
  275. subparser.add_argument("-e", "--image-name", dest="image_name",
  276. help="name of the image to use the artifacts from "
  277. "e.g. core-image-sato")
  278. subparser.add_argument("-r", "--rootfs-dir", action=RootfsArgAction,
  279. help="path to the /rootfs dir to use as the "
  280. ".wks rootfs source")
  281. subparser.add_argument("-b", "--bootimg-dir", dest="bootimg_dir",
  282. help="path to the dir containing the boot artifacts "
  283. "(e.g. /EFI or /syslinux dirs) to use as the "
  284. ".wks bootimg source")
  285. subparser.add_argument("-k", "--kernel-dir", dest="kernel_dir",
  286. help="path to the dir containing the kernel to use "
  287. "in the .wks bootimg")
  288. subparser.add_argument("-n", "--native-sysroot", dest="native_sysroot",
  289. help="path to the native sysroot containing the tools "
  290. "to use to build the image")
  291. subparser.add_argument("-s", "--skip-build-check", dest="build_check",
  292. action="store_false", default=True, help="skip the build check")
  293. subparser.add_argument("-f", "--build-rootfs", action="store_true", help="build rootfs")
  294. subparser.add_argument("-c", "--compress-with", choices=("gzip", "bzip2", "xz"),
  295. dest='compressor',
  296. help="compress image with specified compressor")
  297. subparser.add_argument("-m", "--bmap", action="store_true", help="generate .bmap")
  298. subparser.add_argument("--no-fstab-update" ,action="store_true",
  299. help="Do not change fstab file.")
  300. subparser.add_argument("-v", "--vars", dest='vars_dir',
  301. help="directory with <image>.env files that store "
  302. "bitbake variables")
  303. subparser.add_argument("-D", "--debug", dest="debug", action="store_true",
  304. default=False, help="output debug information")
  305. subparser.add_argument("-i", "--imager", dest="imager",
  306. default="direct", help="the wic imager plugin")
  307. return
  308. def wic_init_parser_list(subparser):
  309. subparser.add_argument("list_type",
  310. help="can be 'images' or 'source-plugins' "
  311. "to obtain a list. "
  312. "If value is a valid .wks image file")
  313. subparser.add_argument("help_for", default=[], nargs='*',
  314. help="If 'list_type' is a valid .wks image file "
  315. "this value can be 'help' to show the help information "
  316. "defined inside the .wks file")
  317. return
  318. def imgtype(arg):
  319. """
  320. Custom type for ArgumentParser
  321. Converts path spec to named tuple: (image, partition, path)
  322. """
  323. image = arg
  324. part = path = None
  325. if ':' in image:
  326. image, part = image.split(':')
  327. if '/' in part:
  328. part, path = part.split('/', 1)
  329. if not path:
  330. path = '/'
  331. if not os.path.isfile(image):
  332. err = "%s is not a regular file or symlink" % image
  333. raise argparse.ArgumentTypeError(err)
  334. return namedtuple('ImgType', 'image part path')(image, part, path)
  335. def wic_init_parser_ls(subparser):
  336. subparser.add_argument("path", type=imgtype,
  337. help="image spec: <image>[:<vfat partition>[<path>]]")
  338. subparser.add_argument("-n", "--native-sysroot",
  339. help="path to the native sysroot containing the tools")
  340. def imgpathtype(arg):
  341. img = imgtype(arg)
  342. if img.part is None:
  343. raise argparse.ArgumentTypeError("partition number is not specified")
  344. return img
  345. def wic_init_parser_cp(subparser):
  346. subparser.add_argument("src",
  347. help="source spec")
  348. subparser.add_argument("dest", type=imgpathtype,
  349. help="image spec: <image>:<vfat partition>[<path>]")
  350. subparser.add_argument("-n", "--native-sysroot",
  351. help="path to the native sysroot containing the tools")
  352. def wic_init_parser_rm(subparser):
  353. subparser.add_argument("path", type=imgpathtype,
  354. help="path: <image>:<vfat partition><path>")
  355. subparser.add_argument("-n", "--native-sysroot",
  356. help="path to the native sysroot containing the tools")
  357. def expandtype(rules):
  358. """
  359. Custom type for ArgumentParser
  360. Converts expand rules to the dictionary {<partition>: size}
  361. """
  362. if rules == 'auto':
  363. return {}
  364. result = {}
  365. for rule in rules.split(','):
  366. try:
  367. part, size = rule.split(':')
  368. except ValueError:
  369. raise argparse.ArgumentTypeError("Incorrect rule format: %s" % rule)
  370. if not part.isdigit():
  371. raise argparse.ArgumentTypeError("Rule '%s': partition number must be integer" % rule)
  372. # validate size
  373. multiplier = 1
  374. for suffix, mult in [('K', 1024), ('M', 1024 * 1024), ('G', 1024 * 1024 * 1024)]:
  375. if size.upper().endswith(suffix):
  376. multiplier = mult
  377. size = size[:-1]
  378. break
  379. if not size.isdigit():
  380. raise argparse.ArgumentTypeError("Rule '%s': size must be integer" % rule)
  381. result[int(part)] = int(size) * multiplier
  382. return result
  383. def wic_init_parser_write(subparser):
  384. subparser.add_argument("image",
  385. help="path to the wic image")
  386. subparser.add_argument("target",
  387. help="target file or device")
  388. subparser.add_argument("-e", "--expand", type=expandtype,
  389. help="expand rules: auto or <partition>:<size>[,<partition>:<size>]")
  390. subparser.add_argument("-n", "--native-sysroot",
  391. help="path to the native sysroot containing the tools")
  392. def wic_init_parser_help(subparser):
  393. helpparsers = subparser.add_subparsers(dest='help_topic', help=hlp.wic_usage)
  394. for helptopic in helptopics:
  395. helpparsers.add_parser(helptopic, help=helptopics[helptopic][2])
  396. return
  397. subcommands = {
  398. "create": [wic_create_subcommand,
  399. hlp.wic_create_usage,
  400. hlp.wic_create_help,
  401. wic_init_parser_create],
  402. "list": [wic_list_subcommand,
  403. hlp.wic_list_usage,
  404. hlp.wic_list_help,
  405. wic_init_parser_list],
  406. "ls": [wic_ls_subcommand,
  407. hlp.wic_ls_usage,
  408. hlp.wic_ls_help,
  409. wic_init_parser_ls],
  410. "cp": [wic_cp_subcommand,
  411. hlp.wic_cp_usage,
  412. hlp.wic_cp_help,
  413. wic_init_parser_cp],
  414. "rm": [wic_rm_subcommand,
  415. hlp.wic_rm_usage,
  416. hlp.wic_rm_help,
  417. wic_init_parser_rm],
  418. "write": [wic_write_subcommand,
  419. hlp.wic_write_usage,
  420. hlp.wic_write_help,
  421. wic_init_parser_write],
  422. "help": [wic_help_subcommand,
  423. wic_help_topic_usage,
  424. hlp.wic_help_help,
  425. wic_init_parser_help]
  426. }
  427. def init_parser(parser):
  428. parser.add_argument("--version", action="version",
  429. version="%(prog)s {version}".format(version=__version__))
  430. subparsers = parser.add_subparsers(dest='command', help=hlp.wic_usage)
  431. for subcmd in subcommands:
  432. subparser = subparsers.add_parser(subcmd, help=subcommands[subcmd][2])
  433. subcommands[subcmd][3](subparser)
  434. def main(argv):
  435. parser = argparse.ArgumentParser(
  436. description="wic version %s" % __version__)
  437. init_parser(parser)
  438. args = parser.parse_args(argv)
  439. if "command" in vars(args):
  440. if args.command == "help":
  441. if args.help_topic is None:
  442. parser.print_help()
  443. print()
  444. print("Please specify a help topic")
  445. elif args.help_topic in helptopics:
  446. hlpt = helptopics[args.help_topic]
  447. hlpt[0](hlpt[1], hlpt[2])
  448. return 0
  449. return hlp.invoke_subcommand(args, parser, hlp.wic_help_usage, subcommands)
  450. if __name__ == "__main__":
  451. try:
  452. sys.exit(main(sys.argv[1:]))
  453. except WicError as err:
  454. print()
  455. logger.error(err)
  456. sys.exit(1)