blob: 91975ba1516c81ad800926ef141e884bea21f544 [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
141 native_paths = "%s/sbin:%s/usr/sbin:%s/usr/bin" % \
142 (native_sysroot, native_sysroot, native_sysroot)
143
144 native_cmd_and_args = "export PATH=%s:$PATH;%s" % \
145 (native_paths, cmd_and_args)
146 logger.debug("exec_native_cmd: %s", native_cmd_and_args)
147
148 # If the command isn't in the native sysroot say we failed.
Andrew Geissler82c905d2020-04-13 13:39:40 -0500149 if find_executable(args[0], native_paths):
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500150 ret, out = _exec_cmd(native_cmd_and_args, True)
151 else:
152 ret = 127
153 out = "can't find native executable %s in %s" % (args[0], native_paths)
154
155 prog = args[0]
156 # shell command-not-found
157 if ret == 127 \
158 or (pseudo and ret == 1 and out == "Can't find '%s' in $PATH." % prog):
159 msg = "A native program %s required to build the image "\
160 "was not found (see details above).\n\n" % prog
161 recipe = NATIVE_RECIPES.get(prog)
162 if recipe:
163 msg += "Please make sure wic-tools have %s-native in its DEPENDS, "\
164 "build it with 'bitbake wic-tools' and try again.\n" % recipe
165 else:
166 msg += "Wic failed to find a recipe to build native %s. Please "\
167 "file a bug against wic.\n" % prog
168 raise WicError(msg)
169
170 return ret, out
171
172BOOTDD_EXTRA_SPACE = 16384
173
174class BitbakeVars(defaultdict):
175 """
176 Container for Bitbake variables.
177 """
178 def __init__(self):
179 defaultdict.__init__(self, dict)
180
181 # default_image and vars_dir attributes should be set from outside
182 self.default_image = None
183 self.vars_dir = None
184
185 def _parse_line(self, line, image, matcher=re.compile(r"^([a-zA-Z0-9\-_+./~]+)=(.*)")):
186 """
187 Parse one line from bitbake -e output or from .env file.
188 Put result key-value pair into the storage.
189 """
190 if "=" not in line:
191 return
192 match = matcher.match(line)
193 if not match:
194 return
195 key, val = match.groups()
196 self[image][key] = val.strip('"')
197
198 def get_var(self, var, image=None, cache=True):
199 """
200 Get bitbake variable from 'bitbake -e' output or from .env file.
201 This is a lazy method, i.e. it runs bitbake or parses file only when
202 only when variable is requested. It also caches results.
203 """
204 if not image:
205 image = self.default_image
206
207 if image not in self:
208 if image and self.vars_dir:
209 fname = os.path.join(self.vars_dir, image + '.env')
210 if os.path.isfile(fname):
211 # parse .env file
212 with open(fname) as varsfile:
213 for line in varsfile:
214 self._parse_line(line, image)
215 else:
216 print("Couldn't get bitbake variable from %s." % fname)
217 print("File %s doesn't exist." % fname)
218 return
219 else:
220 # Get bitbake -e output
221 cmd = "bitbake -e"
222 if image:
223 cmd += " %s" % image
224
225 log_level = logger.getEffectiveLevel()
226 logger.setLevel(logging.INFO)
227 ret, lines = _exec_cmd(cmd)
228 logger.setLevel(log_level)
229
230 if ret:
231 logger.error("Couldn't get '%s' output.", cmd)
232 logger.error("Bitbake failed with error:\n%s\n", lines)
233 return
234
235 # Parse bitbake -e output
236 for line in lines.split('\n'):
237 self._parse_line(line, image)
238
239 # Make first image a default set of variables
240 if cache:
241 images = [key for key in self if key]
242 if len(images) == 1:
243 self[None] = self[image]
244
245 result = self[image].get(var)
246 if not cache:
247 self.pop(image, None)
248
249 return result
250
251# Create BB_VARS singleton
252BB_VARS = BitbakeVars()
253
254def get_bitbake_var(var, image=None, cache=True):
255 """
256 Provide old get_bitbake_var API by wrapping
257 get_var method of BB_VARS singleton.
258 """
259 return BB_VARS.get_var(var, image, cache)