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