blob: 671c0cb0e2df2505c416be960ca3f654552049dd [file] [log] [blame]
Patrick Williamsc124f4f2015-09-15 14:41:29 -05001#!/usr/bin/env python
2# ex:ts=4:sw=4:sts=4:et
3# -*- tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*-
4#
5# Copyright (C) 2003, 2004 Chris Larson
6# Copyright (C) 2003, 2004 Phil Blundell
7# Copyright (C) 2003 - 2005 Michael 'Mickey' Lauer
8# Copyright (C) 2005 Holger Hans Peter Freyther
9# Copyright (C) 2005 ROAD GmbH
10# Copyright (C) 2006 Richard Purdie
11#
12# This program is free software; you can redistribute it and/or modify
13# it under the terms of the GNU General Public License version 2 as
14# published by the Free Software Foundation.
15#
16# This program is distributed in the hope that it will be useful,
17# but WITHOUT ANY WARRANTY; without even the implied warranty of
18# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19# GNU General Public License for more details.
20#
21# You should have received a copy of the GNU General Public License along
22# with this program; if not, write to the Free Software Foundation, Inc.,
23# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
24
25import os, sys
26from functools import wraps
27import logging
28import bb
29from bb import data
30import bb.parse
31
32logger = logging.getLogger("BitBake")
33parselog = logging.getLogger("BitBake.Parsing")
34
35class ConfigParameters(object):
36 def __init__(self, argv=sys.argv):
37 self.options, targets = self.parseCommandLine(argv)
38 self.environment = self.parseEnvironment()
39
40 self.options.pkgs_to_build = targets or []
41
42 self.options.tracking = False
43 if hasattr(self.options, "show_environment") and self.options.show_environment:
44 self.options.tracking = True
45
46 for key, val in self.options.__dict__.items():
47 setattr(self, key, val)
48
49 def parseCommandLine(self, argv=sys.argv):
50 raise Exception("Caller must implement commandline option parsing")
51
52 def parseEnvironment(self):
53 return os.environ.copy()
54
55 def updateFromServer(self, server):
56 if not self.options.cmd:
57 defaulttask, error = server.runCommand(["getVariable", "BB_DEFAULT_TASK"])
58 if error:
59 raise Exception("Unable to get the value of BB_DEFAULT_TASK from the server: %s" % error)
60 self.options.cmd = defaulttask or "build"
61 _, error = server.runCommand(["setConfig", "cmd", self.options.cmd])
62 if error:
63 raise Exception("Unable to set configuration option 'cmd' on the server: %s" % error)
64
65 if not self.options.pkgs_to_build:
Patrick Williamsf1e5d692016-03-30 15:21:19 -050066 bbpkgs, error = server.runCommand(["getVariable", "BBTARGETS"])
Patrick Williamsc124f4f2015-09-15 14:41:29 -050067 if error:
Patrick Williamsf1e5d692016-03-30 15:21:19 -050068 raise Exception("Unable to get the value of BBTARGETS from the server: %s" % error)
Patrick Williamsc124f4f2015-09-15 14:41:29 -050069 if bbpkgs:
70 self.options.pkgs_to_build.extend(bbpkgs.split())
71
72 def updateToServer(self, server, environment):
73 options = {}
74 for o in ["abort", "tryaltconfigs", "force", "invalidate_stamp",
75 "verbose", "debug", "dry_run", "dump_signatures",
76 "debug_domains", "extra_assume_provided", "profile",
77 "prefile", "postfile"]:
78 options[o] = getattr(self.options, o)
79
80 ret, error = server.runCommand(["updateConfig", options, environment])
81 if error:
82 raise Exception("Unable to update the server configuration with local parameters: %s" % error)
83
84 def parseActions(self):
85 # Parse any commandline into actions
86 action = {'action':None, 'msg':None}
87 if self.options.show_environment:
88 if 'world' in self.options.pkgs_to_build:
89 action['msg'] = "'world' is not a valid target for --environment."
90 elif 'universe' in self.options.pkgs_to_build:
91 action['msg'] = "'universe' is not a valid target for --environment."
92 elif len(self.options.pkgs_to_build) > 1:
93 action['msg'] = "Only one target can be used with the --environment option."
94 elif self.options.buildfile and len(self.options.pkgs_to_build) > 0:
95 action['msg'] = "No target should be used with the --environment and --buildfile options."
96 elif len(self.options.pkgs_to_build) > 0:
97 action['action'] = ["showEnvironmentTarget", self.options.pkgs_to_build]
98 else:
99 action['action'] = ["showEnvironment", self.options.buildfile]
100 elif self.options.buildfile is not None:
101 action['action'] = ["buildFile", self.options.buildfile, self.options.cmd]
102 elif self.options.revisions_changed:
103 action['action'] = ["compareRevisions"]
104 elif self.options.show_versions:
105 action['action'] = ["showVersions"]
106 elif self.options.parse_only:
107 action['action'] = ["parseFiles"]
108 elif self.options.dot_graph:
109 if self.options.pkgs_to_build:
110 action['action'] = ["generateDotGraph", self.options.pkgs_to_build, self.options.cmd]
111 else:
112 action['msg'] = "Please specify a package name for dependency graph generation."
113 else:
114 if self.options.pkgs_to_build:
115 action['action'] = ["buildTargets", self.options.pkgs_to_build, self.options.cmd]
116 else:
117 #action['msg'] = "Nothing to do. Use 'bitbake world' to build everything, or run 'bitbake --help' for usage information."
118 action = None
119 self.options.initialaction = action
120 return action
121
122class CookerConfiguration(object):
123 """
124 Manages build options and configurations for one run
125 """
126
127 def __init__(self):
128 self.debug_domains = []
129 self.extra_assume_provided = []
130 self.prefile = []
131 self.postfile = []
Patrick Williamsf1e5d692016-03-30 15:21:19 -0500132 self.prefile_server = []
133 self.postfile_server = []
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500134 self.debug = 0
135 self.cmd = None
136 self.abort = True
137 self.force = False
138 self.profile = False
139 self.nosetscene = False
140 self.invalidate_stamp = False
141 self.dump_signatures = []
142 self.dry_run = False
143 self.tracking = False
144 self.interface = []
145 self.writeeventlog = False
146
147 self.env = {}
148
149 def setConfigParameters(self, parameters):
150 for key in self.__dict__.keys():
151 if key in parameters.options.__dict__:
152 setattr(self, key, parameters.options.__dict__[key])
153 self.env = parameters.environment.copy()
154 self.tracking = parameters.tracking
155
156 def setServerRegIdleCallback(self, srcb):
157 self.server_register_idlecallback = srcb
158
159 def __getstate__(self):
160 state = {}
161 for key in self.__dict__.keys():
162 if key == "server_register_idlecallback":
163 state[key] = None
164 else:
165 state[key] = getattr(self, key)
166 return state
167
168 def __setstate__(self,state):
169 for k in state:
170 setattr(self, k, state[k])
171
172
173def catch_parse_error(func):
174 """Exception handling bits for our parsing"""
175 @wraps(func)
176 def wrapped(fn, *args):
177 try:
178 return func(fn, *args)
179 except IOError as exc:
180 import traceback
181 parselog.critical(traceback.format_exc())
182 parselog.critical("Unable to parse %s: %s" % (fn, exc))
183 sys.exit(1)
184 except (bb.parse.ParseError, bb.data_smart.ExpansionError) as exc:
185 import traceback
186
187 bbdir = os.path.dirname(__file__) + os.sep
188 exc_class, exc, tb = sys.exc_info()
189 for tb in iter(lambda: tb.tb_next, None):
190 # Skip frames in bitbake itself, we only want the metadata
191 fn, _, _, _ = traceback.extract_tb(tb, 1)[0]
192 if not fn.startswith(bbdir):
193 break
194 parselog.critical("Unable to parse %s", fn, exc_info=(exc_class, exc, tb))
195 sys.exit(1)
196 return wrapped
197
198@catch_parse_error
199def parse_config_file(fn, data, include=True):
200 return bb.parse.handle(fn, data, include)
201
202@catch_parse_error
203def _inherit(bbclass, data):
204 bb.parse.BBHandler.inherit(bbclass, "configuration INHERITs", 0, data)
205 return data
206
207def findConfigFile(configfile, data):
208 search = []
209 bbpath = data.getVar("BBPATH", True)
210 if bbpath:
211 for i in bbpath.split(":"):
212 search.append(os.path.join(i, "conf", configfile))
213 path = os.getcwd()
214 while path != "/":
215 search.append(os.path.join(path, "conf", configfile))
216 path, _ = os.path.split(path)
217
218 for i in search:
219 if os.path.exists(i):
220 return i
221
222 return None
223
224class CookerDataBuilder(object):
225
226 def __init__(self, cookercfg, worker = False):
227
228 self.prefiles = cookercfg.prefile
229 self.postfiles = cookercfg.postfile
230 self.tracking = cookercfg.tracking
231
232 bb.utils.set_context(bb.utils.clean_context())
233 bb.event.set_class_handlers(bb.event.clean_class_handlers())
234 self.data = bb.data.init()
235 if self.tracking:
236 self.data.enableTracking()
237
238 # Keep a datastore of the initial environment variables and their
239 # values from when BitBake was launched to enable child processes
240 # to use environment variables which have been cleaned from the
241 # BitBake processes env
242 self.savedenv = bb.data.init()
243 for k in cookercfg.env:
244 self.savedenv.setVar(k, cookercfg.env[k])
245
246 filtered_keys = bb.utils.approved_variables()
247 bb.data.inheritFromOS(self.data, self.savedenv, filtered_keys)
248 self.data.setVar("BB_ORIGENV", self.savedenv)
249
250 if worker:
251 self.data.setVar("BB_WORKERCONTEXT", "1")
252
253 def parseBaseConfiguration(self):
254 try:
255 self.parseConfigurationFiles(self.prefiles, self.postfiles)
256 except SyntaxError:
257 raise bb.BBHandledException
258 except bb.data_smart.ExpansionError as e:
259 logger.error(str(e))
260 raise bb.BBHandledException
261 except Exception:
262 logger.exception("Error parsing configuration files")
263 raise bb.BBHandledException
264
265 def _findLayerConf(self, data):
266 return findConfigFile("bblayers.conf", data)
267
268 def parseConfigurationFiles(self, prefiles, postfiles):
269 data = self.data
270 bb.parse.init_parser(data)
271
272 # Parse files for loading *before* bitbake.conf and any includes
273 for f in prefiles:
274 data = parse_config_file(f, data)
275
276 layerconf = self._findLayerConf(data)
277 if layerconf:
278 parselog.debug(2, "Found bblayers.conf (%s)", layerconf)
279 # By definition bblayers.conf is in conf/ of TOPDIR.
280 # We may have been called with cwd somewhere else so reset TOPDIR
281 data.setVar("TOPDIR", os.path.dirname(os.path.dirname(layerconf)))
282 data = parse_config_file(layerconf, data)
283
284 layers = (data.getVar('BBLAYERS', True) or "").split()
285
286 data = bb.data.createCopy(data)
287 approved = bb.utils.approved_variables()
288 for layer in layers:
289 parselog.debug(2, "Adding layer %s", layer)
290 if 'HOME' in approved and '~' in layer:
291 layer = os.path.expanduser(layer)
292 data.setVar('LAYERDIR', layer)
293 data = parse_config_file(os.path.join(layer, "conf", "layer.conf"), data)
294 data.expandVarref('LAYERDIR')
295
296 data.delVar('LAYERDIR')
297
298 if not data.getVar("BBPATH", True):
299 msg = "The BBPATH variable is not set"
300 if not layerconf:
301 msg += (" and bitbake did not find a conf/bblayers.conf file in"
302 " the expected location.\nMaybe you accidentally"
303 " invoked bitbake from the wrong directory?")
304 raise SystemExit(msg)
305
306 data = parse_config_file(os.path.join("conf", "bitbake.conf"), data)
307
308 # Parse files for loading *after* bitbake.conf and any includes
309 for p in postfiles:
310 data = parse_config_file(p, data)
311
312 # Handle any INHERITs and inherit the base class
313 bbclasses = ["base"] + (data.getVar('INHERIT', True) or "").split()
314 for bbclass in bbclasses:
315 data = _inherit(bbclass, data)
316
317 # Nomally we only register event handlers at the end of parsing .bb files
318 # We register any handlers we've found so far here...
319 for var in data.getVar('__BBHANDLERS', False) or []:
320 bb.event.register(var, data.getVar(var, False), (data.getVarFlag(var, "eventmask", True) or "").split())
321
322 if data.getVar("BB_WORKERCONTEXT", False) is None:
323 bb.fetch.fetcher_init(data)
324 bb.codeparser.parser_cache_init(data)
325 bb.event.fire(bb.event.ConfigParsed(), data)
326
327 if data.getVar("BB_INVALIDCONF", False) is True:
328 data.setVar("BB_INVALIDCONF", False)
329 self.parseConfigurationFiles(self.prefiles, self.postfiles)
330 return
331
332 bb.parse.init_parser(data)
333 data.setVar('BBINCLUDED',bb.parse.get_file_depends(data))
334 self.data = data
335 self.data_hash = data.get_hash()
336
337
338