blob: c6d2e5f204b15b505b16dcb22f150c8449c4b407 [file] [log] [blame]
Patrick Williamsc124f4f2015-09-15 14:41:29 -05001# 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 provides a place to collect various wic-related utils
22# for the OpenEmbedded Image Tools.
23#
24# AUTHORS
25# Tom Zanussi <tom.zanussi (at] linux.intel.com>
26#
27"""Miscellaneous functions."""
28
29import os
30from collections import defaultdict
31
32from wic import msger
33from wic.utils import runner
34
35# executable -> recipe pairs for exec_native_cmd
36NATIVE_RECIPES = {"mcopy": "mtools",
37 "mkdosfs": "dosfstools",
38 "mkfs.btrfs": "btrfs-tools",
39 "mkfs.ext2": "e2fsprogs",
40 "mkfs.ext3": "e2fsprogs",
41 "mkfs.ext4": "e2fsprogs",
42 "mkfs.vfat": "dosfstools",
43 "mksquashfs": "squashfs-tools",
44 "mkswap": "util-linux",
45 "parted": "parted",
46 "sgdisk": "gptfdisk",
47 "syslinux": "syslinux"
48 }
49
50def _exec_cmd(cmd_and_args, as_shell=False, catch=3):
51 """
52 Execute command, catching stderr, stdout
53
54 Need to execute as_shell if the command uses wildcards
55 """
56 msger.debug("_exec_cmd: %s" % cmd_and_args)
57 args = cmd_and_args.split()
58 msger.debug(args)
59
60 if as_shell:
61 ret, out = runner.runtool(cmd_and_args, catch)
62 else:
63 ret, out = runner.runtool(args, catch)
64 out = out.strip()
65 msger.debug("_exec_cmd: output for %s (rc = %d): %s" % \
66 (cmd_and_args, ret, out))
67
68 return (ret, out)
69
70
71def exec_cmd(cmd_and_args, as_shell=False, catch=3):
72 """
73 Execute command, catching stderr, stdout
74
75 Exits if rc non-zero
76 """
77 ret, out = _exec_cmd(cmd_and_args, as_shell, catch)
78
79 if ret != 0:
80 msger.error("exec_cmd: %s returned '%s' instead of 0" % \
81 (cmd_and_args, ret))
82
83 return out
84
Patrick Williamsf1e5d692016-03-30 15:21:19 -050085def cmd_in_path(cmd, path):
86 import scriptpath
87
88 scriptpath.add_bitbake_lib_path()
89
90 return bb.utils.which(path, cmd) != "" or False
Patrick Williamsc124f4f2015-09-15 14:41:29 -050091
92def exec_native_cmd(cmd_and_args, native_sysroot, catch=3):
93 """
94 Execute native command, catching stderr, stdout
95
96 Need to execute as_shell if the command uses wildcards
97
98 Always need to execute native commands as_shell
99 """
100 native_paths = \
Patrick Williamsf1e5d692016-03-30 15:21:19 -0500101 "%s/sbin:%s/usr/sbin:%s/usr/bin" % \
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500102 (native_sysroot, native_sysroot, native_sysroot)
Patrick Williamsf1e5d692016-03-30 15:21:19 -0500103 native_cmd_and_args = "export PATH=%s:$PATH;%s" % \
104 (native_paths, cmd_and_args)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500105 msger.debug("exec_native_cmd: %s" % cmd_and_args)
106
Patrick Williamsf1e5d692016-03-30 15:21:19 -0500107 # The reason -1 is used is because there may be "export" commands.
108 args = cmd_and_args.split(';')[-1].split()
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500109 msger.debug(args)
110
Patrick Williamsf1e5d692016-03-30 15:21:19 -0500111 # If the command isn't in the native sysroot say we failed.
112 if cmd_in_path(args[0], native_paths):
113 ret, out = _exec_cmd(native_cmd_and_args, True, catch)
114 else:
115 ret = 127
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500116
117 if ret == 127: # shell command-not-found
118 prog = args[0]
119 msg = "A native program %s required to build the image "\
120 "was not found (see details above).\n\n" % prog
121 recipe = NATIVE_RECIPES.get(prog)
122 if recipe:
123 msg += "Please bake it with 'bitbake %s-native' "\
124 "and try again.\n" % recipe
125 else:
126 msg += "Wic failed to find a recipe to build native %s. Please "\
127 "file a bug against wic.\n" % prog
128 msger.error(msg)
129 if out:
130 msger.debug('"%s" output: %s' % (args[0], out))
131
132 if ret != 0:
133 msger.error("exec_cmd: '%s' returned '%s' instead of 0" % \
134 (cmd_and_args, ret))
135
136 return ret, out
137
138BOOTDD_EXTRA_SPACE = 16384
139
140class BitbakeVars(defaultdict):
141 """
142 Container for Bitbake variables.
143 """
144 def __init__(self):
145 defaultdict.__init__(self, dict)
146
147 # default_image and vars_dir attributes should be set from outside
148 self.default_image = None
149 self.vars_dir = None
150
151 def _parse_line(self, line, image):
152 """
153 Parse one line from bitbake -e output or from .env file.
154 Put result key-value pair into the storage.
155 """
156 if "=" not in line:
157 return
158 try:
159 key, val = line.split("=")
160 except ValueError:
161 return
162 key = key.strip()
163 val = val.strip()
164 if key.replace('_', '').isalnum():
165 self[image][key] = val.strip('"')
166
167 def get_var(self, var, image=None):
168 """
169 Get bitbake variable from 'bitbake -e' output or from .env file.
170 This is a lazy method, i.e. it runs bitbake or parses file only when
171 only when variable is requested. It also caches results.
172 """
173 if not image:
174 image = self.default_image
175
176 if image not in self:
177 if image and self.vars_dir:
178 fname = os.path.join(self.vars_dir, image + '.env')
179 if os.path.isfile(fname):
180 # parse .env file
181 with open(fname) as varsfile:
182 for line in varsfile:
183 self._parse_line(line, image)
184 else:
185 print "Couldn't get bitbake variable from %s." % fname
186 print "File %s doesn't exist." % fname
187 return
188 else:
189 # Get bitbake -e output
190 cmd = "bitbake -e"
191 if image:
192 cmd += " %s" % image
193
194 log_level = msger.get_loglevel()
195 msger.set_loglevel('normal')
196 ret, lines = _exec_cmd(cmd)
197 msger.set_loglevel(log_level)
198
199 if ret:
200 print "Couldn't get '%s' output." % cmd
201 print "Bitbake failed with error:\n%s\n" % lines
202 return
203
204 # Parse bitbake -e output
205 for line in lines.split('\n'):
206 self._parse_line(line, image)
207
208 # Make first image a default set of variables
209 images = [key for key in self if key]
210 if len(images) == 1:
211 self[None] = self[image]
212
213 return self[image].get(var)
214
215# Create BB_VARS singleton
216BB_VARS = BitbakeVars()
217
218def get_bitbake_var(var, image=None):
219 """
220 Provide old get_bitbake_var API by wrapping
221 get_var method of BB_VARS singleton.
222 """
223 return BB_VARS.get_var(var, image)
224
225def parse_sourceparams(sourceparams):
226 """
227 Split sourceparams string of the form key1=val1[,key2=val2,...]
228 into a dict. Also accepts valueless keys i.e. without =.
229
230 Returns dict of param key/val pairs (note that val may be None).
231 """
232 params_dict = {}
233
234 params = sourceparams.split(',')
235 if params:
236 for par in params:
237 if not par:
238 continue
239 if not '=' in par:
240 key = par
241 val = None
242 else:
243 key, val = par.split('=')
244 params_dict[key] = val
245
246 return params_dict