blob: 4b08d649c6947a0405d53d482701195d27189030 [file] [log] [blame]
Brad Bishopd7bf8c12018-02-25 22:55:05 -05001#
2# Copyright (c) 2013, Intel Corporation.
Brad Bishopd7bf8c12018-02-25 22:55:05 -05003#
Brad Bishopc342db32019-05-15 21:57:59 -04004# SPDX-License-Identifier: GPL-2.0-only
Brad Bishopd7bf8c12018-02-25 22:55:05 -05005#
6# DESCRIPTION
7# This module provides a place to collect various wic-related utils
8# for the OpenEmbedded Image Tools.
9#
10# AUTHORS
11# Tom Zanussi <tom.zanussi (at] linux.intel.com>
12#
13"""Miscellaneous functions."""
14
15import logging
16import os
17import re
18import subprocess
19
20from collections import defaultdict
21from distutils import spawn
22
23from wic import WicError
24
25logger = logging.getLogger('wic')
26
27# executable -> recipe pairs for exec_native_cmd
28NATIVE_RECIPES = {"bmaptool": "bmap-tools",
29 "grub-mkimage": "grub-efi",
30 "isohybrid": "syslinux",
31 "mcopy": "mtools",
32 "mdel" : "mtools",
33 "mdeltree" : "mtools",
34 "mdir" : "mtools",
35 "mkdosfs": "dosfstools",
36 "mkisofs": "cdrtools",
37 "mkfs.btrfs": "btrfs-tools",
38 "mkfs.ext2": "e2fsprogs",
39 "mkfs.ext3": "e2fsprogs",
40 "mkfs.ext4": "e2fsprogs",
41 "mkfs.vfat": "dosfstools",
42 "mksquashfs": "squashfs-tools",
43 "mkswap": "util-linux",
44 "mmd": "mtools",
45 "parted": "parted",
46 "sfdisk": "util-linux",
47 "sgdisk": "gptfdisk",
Andrew Geissler82c905d2020-04-13 13:39:40 -050048 "syslinux": "syslinux",
49 "tar": "tar"
Brad Bishopd7bf8c12018-02-25 22:55:05 -050050 }
51
52def runtool(cmdln_or_args):
53 """ wrapper for most of the subprocess calls
54 input:
55 cmdln_or_args: can be both args and cmdln str (shell=True)
56 return:
57 rc, output
58 """
59 if isinstance(cmdln_or_args, list):
60 cmd = cmdln_or_args[0]
61 shell = False
62 else:
63 import shlex
64 cmd = shlex.split(cmdln_or_args)[0]
65 shell = True
66
67 sout = subprocess.PIPE
68 serr = subprocess.STDOUT
69
70 try:
71 process = subprocess.Popen(cmdln_or_args, stdout=sout,
72 stderr=serr, shell=shell)
73 sout, serr = process.communicate()
74 # combine stdout and stderr, filter None out and decode
75 out = ''.join([out.decode('utf-8') for out in [sout, serr] if out])
76 except OSError as err:
77 if err.errno == 2:
78 # [Errno 2] No such file or directory
79 raise WicError('Cannot run command: %s, lost dependency?' % cmd)
80 else:
81 raise # relay
82
83 return process.returncode, out
84
85def _exec_cmd(cmd_and_args, as_shell=False):
86 """
87 Execute command, catching stderr, stdout
88
89 Need to execute as_shell if the command uses wildcards
90 """
91 logger.debug("_exec_cmd: %s", cmd_and_args)
92 args = cmd_and_args.split()
93 logger.debug(args)
94
95 if as_shell:
96 ret, out = runtool(cmd_and_args)
97 else:
98 ret, out = runtool(args)
99 out = out.strip()
100 if ret != 0:
101 raise WicError("_exec_cmd: %s returned '%s' instead of 0\noutput: %s" % \
102 (cmd_and_args, ret, out))
103
104 logger.debug("_exec_cmd: output for %s (rc = %d): %s",
105 cmd_and_args, ret, out)
106
107 return ret, out
108
109
110def exec_cmd(cmd_and_args, as_shell=False):
111 """
112 Execute command, return output
113 """
114 return _exec_cmd(cmd_and_args, as_shell)[1]
115
Andrew Geissler82c905d2020-04-13 13:39:40 -0500116def find_executable(cmd, paths):
117 recipe = cmd
118 if recipe in NATIVE_RECIPES:
119 recipe = NATIVE_RECIPES[recipe]
120 provided = get_bitbake_var("ASSUME_PROVIDED")
121 if provided and "%s-native" % recipe in provided:
122 return True
123
124 return spawn.find_executable(cmd, paths)
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500125
126def exec_native_cmd(cmd_and_args, native_sysroot, pseudo=""):
127 """
128 Execute native command, catching stderr, stdout
129
130 Need to execute as_shell if the command uses wildcards
131
132 Always need to execute native commands as_shell
133 """
134 # The reason -1 is used is because there may be "export" commands.
135 args = cmd_and_args.split(';')[-1].split()
136 logger.debug(args)
137
138 if pseudo:
139 cmd_and_args = pseudo + cmd_and_args
140
Andrew Geisslerc9f78652020-09-18 14:11:35 -0500141 native_paths = "%s/sbin:%s/usr/sbin:%s/usr/bin:%s/bin" % \
142 (native_sysroot, native_sysroot,
143 native_sysroot, native_sysroot)
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500144
145 native_cmd_and_args = "export PATH=%s:$PATH;%s" % \
146 (native_paths, cmd_and_args)
147 logger.debug("exec_native_cmd: %s", native_cmd_and_args)
148
149 # If the command isn't in the native sysroot say we failed.
Andrew Geissler82c905d2020-04-13 13:39:40 -0500150 if find_executable(args[0], native_paths):
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500151 ret, out = _exec_cmd(native_cmd_and_args, True)
152 else:
153 ret = 127
154 out = "can't find native executable %s in %s" % (args[0], native_paths)
155
156 prog = args[0]
157 # shell command-not-found
158 if ret == 127 \
159 or (pseudo and ret == 1 and out == "Can't find '%s' in $PATH." % prog):
160 msg = "A native program %s required to build the image "\
161 "was not found (see details above).\n\n" % prog
162 recipe = NATIVE_RECIPES.get(prog)
163 if recipe:
164 msg += "Please make sure wic-tools have %s-native in its DEPENDS, "\
165 "build it with 'bitbake wic-tools' and try again.\n" % recipe
166 else:
167 msg += "Wic failed to find a recipe to build native %s. Please "\
168 "file a bug against wic.\n" % prog
169 raise WicError(msg)
170
171 return ret, out
172
173BOOTDD_EXTRA_SPACE = 16384
174
175class BitbakeVars(defaultdict):
176 """
177 Container for Bitbake variables.
178 """
179 def __init__(self):
180 defaultdict.__init__(self, dict)
181
182 # default_image and vars_dir attributes should be set from outside
183 self.default_image = None
184 self.vars_dir = None
185
186 def _parse_line(self, line, image, matcher=re.compile(r"^([a-zA-Z0-9\-_+./~]+)=(.*)")):
187 """
188 Parse one line from bitbake -e output or from .env file.
189 Put result key-value pair into the storage.
190 """
191 if "=" not in line:
192 return
193 match = matcher.match(line)
194 if not match:
195 return
196 key, val = match.groups()
197 self[image][key] = val.strip('"')
198
199 def get_var(self, var, image=None, cache=True):
200 """
201 Get bitbake variable from 'bitbake -e' output or from .env file.
202 This is a lazy method, i.e. it runs bitbake or parses file only when
203 only when variable is requested. It also caches results.
204 """
205 if not image:
206 image = self.default_image
207
208 if image not in self:
209 if image and self.vars_dir:
210 fname = os.path.join(self.vars_dir, image + '.env')
211 if os.path.isfile(fname):
212 # parse .env file
213 with open(fname) as varsfile:
214 for line in varsfile:
215 self._parse_line(line, image)
216 else:
217 print("Couldn't get bitbake variable from %s." % fname)
218 print("File %s doesn't exist." % fname)
219 return
220 else:
221 # Get bitbake -e output
222 cmd = "bitbake -e"
223 if image:
224 cmd += " %s" % image
225
226 log_level = logger.getEffectiveLevel()
227 logger.setLevel(logging.INFO)
228 ret, lines = _exec_cmd(cmd)
229 logger.setLevel(log_level)
230
231 if ret:
232 logger.error("Couldn't get '%s' output.", cmd)
233 logger.error("Bitbake failed with error:\n%s\n", lines)
234 return
235
236 # Parse bitbake -e output
237 for line in lines.split('\n'):
238 self._parse_line(line, image)
239
240 # Make first image a default set of variables
241 if cache:
242 images = [key for key in self if key]
243 if len(images) == 1:
244 self[None] = self[image]
245
246 result = self[image].get(var)
247 if not cache:
248 self.pop(image, None)
249
250 return result
251
252# Create BB_VARS singleton
253BB_VARS = BitbakeVars()
254
255def get_bitbake_var(var, image=None, cache=True):
256 """
257 Provide old get_bitbake_var API by wrapping
258 get_var method of BB_VARS singleton.
259 """
260 return BB_VARS.get_var(var, image, cache)