blob: 7370d93136ed00859b285f1b70a90e9d817d5fae [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
85
86def exec_native_cmd(cmd_and_args, native_sysroot, catch=3):
87 """
88 Execute native command, catching stderr, stdout
89
90 Need to execute as_shell if the command uses wildcards
91
92 Always need to execute native commands as_shell
93 """
94 native_paths = \
95 "export PATH=%s/sbin:%s/usr/sbin:%s/usr/bin" % \
96 (native_sysroot, native_sysroot, native_sysroot)
97 native_cmd_and_args = "%s;%s" % (native_paths, cmd_and_args)
98 msger.debug("exec_native_cmd: %s" % cmd_and_args)
99
100 args = cmd_and_args.split()
101 msger.debug(args)
102
103 ret, out = _exec_cmd(native_cmd_and_args, True, catch)
104
105 if ret == 127: # shell command-not-found
106 prog = args[0]
107 msg = "A native program %s required to build the image "\
108 "was not found (see details above).\n\n" % prog
109 recipe = NATIVE_RECIPES.get(prog)
110 if recipe:
111 msg += "Please bake it with 'bitbake %s-native' "\
112 "and try again.\n" % recipe
113 else:
114 msg += "Wic failed to find a recipe to build native %s. Please "\
115 "file a bug against wic.\n" % prog
116 msger.error(msg)
117 if out:
118 msger.debug('"%s" output: %s' % (args[0], out))
119
120 if ret != 0:
121 msger.error("exec_cmd: '%s' returned '%s' instead of 0" % \
122 (cmd_and_args, ret))
123
124 return ret, out
125
126BOOTDD_EXTRA_SPACE = 16384
127
128class BitbakeVars(defaultdict):
129 """
130 Container for Bitbake variables.
131 """
132 def __init__(self):
133 defaultdict.__init__(self, dict)
134
135 # default_image and vars_dir attributes should be set from outside
136 self.default_image = None
137 self.vars_dir = None
138
139 def _parse_line(self, line, image):
140 """
141 Parse one line from bitbake -e output or from .env file.
142 Put result key-value pair into the storage.
143 """
144 if "=" not in line:
145 return
146 try:
147 key, val = line.split("=")
148 except ValueError:
149 return
150 key = key.strip()
151 val = val.strip()
152 if key.replace('_', '').isalnum():
153 self[image][key] = val.strip('"')
154
155 def get_var(self, var, image=None):
156 """
157 Get bitbake variable from 'bitbake -e' output or from .env file.
158 This is a lazy method, i.e. it runs bitbake or parses file only when
159 only when variable is requested. It also caches results.
160 """
161 if not image:
162 image = self.default_image
163
164 if image not in self:
165 if image and self.vars_dir:
166 fname = os.path.join(self.vars_dir, image + '.env')
167 if os.path.isfile(fname):
168 # parse .env file
169 with open(fname) as varsfile:
170 for line in varsfile:
171 self._parse_line(line, image)
172 else:
173 print "Couldn't get bitbake variable from %s." % fname
174 print "File %s doesn't exist." % fname
175 return
176 else:
177 # Get bitbake -e output
178 cmd = "bitbake -e"
179 if image:
180 cmd += " %s" % image
181
182 log_level = msger.get_loglevel()
183 msger.set_loglevel('normal')
184 ret, lines = _exec_cmd(cmd)
185 msger.set_loglevel(log_level)
186
187 if ret:
188 print "Couldn't get '%s' output." % cmd
189 print "Bitbake failed with error:\n%s\n" % lines
190 return
191
192 # Parse bitbake -e output
193 for line in lines.split('\n'):
194 self._parse_line(line, image)
195
196 # Make first image a default set of variables
197 images = [key for key in self if key]
198 if len(images) == 1:
199 self[None] = self[image]
200
201 return self[image].get(var)
202
203# Create BB_VARS singleton
204BB_VARS = BitbakeVars()
205
206def get_bitbake_var(var, image=None):
207 """
208 Provide old get_bitbake_var API by wrapping
209 get_var method of BB_VARS singleton.
210 """
211 return BB_VARS.get_var(var, image)
212
213def parse_sourceparams(sourceparams):
214 """
215 Split sourceparams string of the form key1=val1[,key2=val2,...]
216 into a dict. Also accepts valueless keys i.e. without =.
217
218 Returns dict of param key/val pairs (note that val may be None).
219 """
220 params_dict = {}
221
222 params = sourceparams.split(',')
223 if params:
224 for par in params:
225 if not par:
226 continue
227 if not '=' in par:
228 key = par
229 val = None
230 else:
231 key, val = par.split('=')
232 params_dict[key] = val
233
234 return params_dict