blob: e69a10f452161d829e2766c1064cf33f3c5a4f5c [file] [log] [blame]
Brad Bishopd7bf8c12018-02-25 22:55:05 -05001# Yocto Project layer check tool
2#
3# Copyright (C) 2017 Intel Corporation
Brad Bishopc342db32019-05-15 21:57:59 -04004#
5# SPDX-License-Identifier: MIT
6#
Brad Bishopd7bf8c12018-02-25 22:55:05 -05007
8import os
9import re
10import subprocess
11from enum import Enum
12
13import bb.tinfoil
14
15class LayerType(Enum):
16 BSP = 0
17 DISTRO = 1
18 SOFTWARE = 2
19 ERROR_NO_LAYER_CONF = 98
20 ERROR_BSP_DISTRO = 99
21
22def _get_configurations(path):
23 configs = []
24
25 for f in os.listdir(path):
26 file_path = os.path.join(path, f)
27 if os.path.isfile(file_path) and f.endswith('.conf'):
28 configs.append(f[:-5]) # strip .conf
29 return configs
30
31def _get_layer_collections(layer_path, lconf=None, data=None):
32 import bb.parse
33 import bb.data
34
35 if lconf is None:
36 lconf = os.path.join(layer_path, 'conf', 'layer.conf')
37
38 if data is None:
39 ldata = bb.data.init()
40 bb.parse.init_parser(ldata)
41 else:
42 ldata = data.createCopy()
43
44 ldata.setVar('LAYERDIR', layer_path)
45 try:
46 ldata = bb.parse.handle(lconf, ldata, include=True)
Brad Bishop00111322018-04-01 22:23:53 -040047 except:
48 raise RuntimeError("Parsing of layer.conf from layer: %s failed" % layer_path)
Brad Bishopd7bf8c12018-02-25 22:55:05 -050049 ldata.expandVarref('LAYERDIR')
50
51 collections = (ldata.getVar('BBFILE_COLLECTIONS') or '').split()
52 if not collections:
53 name = os.path.basename(layer_path)
54 collections = [name]
55
56 collections = {c: {} for c in collections}
57 for name in collections:
58 priority = ldata.getVar('BBFILE_PRIORITY_%s' % name)
59 pattern = ldata.getVar('BBFILE_PATTERN_%s' % name)
60 depends = ldata.getVar('LAYERDEPENDS_%s' % name)
Brad Bishop316dfdd2018-06-25 12:45:53 -040061 compat = ldata.getVar('LAYERSERIES_COMPAT_%s' % name)
Andrew Geissler475cb722020-07-10 16:00:51 -050062 try:
63 depDict = bb.utils.explode_dep_versions2(depends or "")
64 except bb.utils.VersionStringException as vse:
65 bb.fatal('Error parsing LAYERDEPENDS_%s: %s' % (name, str(vse)))
66
Brad Bishopd7bf8c12018-02-25 22:55:05 -050067 collections[name]['priority'] = priority
68 collections[name]['pattern'] = pattern
Andrew Geissler475cb722020-07-10 16:00:51 -050069 collections[name]['depends'] = ' '.join(depDict.keys())
Brad Bishop316dfdd2018-06-25 12:45:53 -040070 collections[name]['compat'] = compat
Brad Bishopd7bf8c12018-02-25 22:55:05 -050071
72 return collections
73
74def _detect_layer(layer_path):
75 """
76 Scans layer directory to detect what type of layer
77 is BSP, Distro or Software.
78
79 Returns a dictionary with layer name, type and path.
80 """
81
82 layer = {}
83 layer_name = os.path.basename(layer_path)
84
85 layer['name'] = layer_name
86 layer['path'] = layer_path
87 layer['conf'] = {}
88
89 if not os.path.isfile(os.path.join(layer_path, 'conf', 'layer.conf')):
90 layer['type'] = LayerType.ERROR_NO_LAYER_CONF
91 return layer
92
93 machine_conf = os.path.join(layer_path, 'conf', 'machine')
94 distro_conf = os.path.join(layer_path, 'conf', 'distro')
95
96 is_bsp = False
97 is_distro = False
98
99 if os.path.isdir(machine_conf):
100 machines = _get_configurations(machine_conf)
101 if machines:
102 is_bsp = True
103
104 if os.path.isdir(distro_conf):
105 distros = _get_configurations(distro_conf)
106 if distros:
107 is_distro = True
108
109 if is_bsp and is_distro:
110 layer['type'] = LayerType.ERROR_BSP_DISTRO
111 elif is_bsp:
112 layer['type'] = LayerType.BSP
113 layer['conf']['machines'] = machines
114 elif is_distro:
115 layer['type'] = LayerType.DISTRO
116 layer['conf']['distros'] = distros
117 else:
118 layer['type'] = LayerType.SOFTWARE
119
120 layer['collections'] = _get_layer_collections(layer['path'])
121
122 return layer
123
124def detect_layers(layer_directories, no_auto):
125 layers = []
126
127 for directory in layer_directories:
128 directory = os.path.realpath(directory)
129 if directory[-1] == '/':
130 directory = directory[0:-1]
131
132 if no_auto:
133 conf_dir = os.path.join(directory, 'conf')
134 if os.path.isdir(conf_dir):
135 layer = _detect_layer(directory)
136 if layer:
137 layers.append(layer)
138 else:
139 for root, dirs, files in os.walk(directory):
140 dir_name = os.path.basename(root)
141 conf_dir = os.path.join(root, 'conf')
142 if os.path.isdir(conf_dir):
143 layer = _detect_layer(root)
144 if layer:
145 layers.append(layer)
146
147 return layers
148
Patrick Williams213cb262021-08-07 19:21:33 -0500149def _find_layer(depend, layers):
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500150 for layer in layers:
Andrew Geissler1e34c2d2020-05-29 16:02:59 -0500151 if 'collections' not in layer:
152 continue
153
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500154 for collection in layer['collections']:
155 if depend == collection:
156 return layer
157 return None
158
Patrick Williams213cb262021-08-07 19:21:33 -0500159def get_layer_dependencies(layer, layers, logger):
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500160 def recurse_dependencies(depends, layer, layers, logger, ret = []):
161 logger.debug('Processing dependencies %s for layer %s.' % \
162 (depends, layer['name']))
163
164 for depend in depends.split():
165 # core (oe-core) is suppose to be provided
166 if depend == 'core':
167 continue
168
Patrick Williams213cb262021-08-07 19:21:33 -0500169 layer_depend = _find_layer(depend, layers)
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500170 if not layer_depend:
171 logger.error('Layer %s depends on %s and isn\'t found.' % \
172 (layer['name'], depend))
173 ret = None
174 continue
175
176 # We keep processing, even if ret is None, this allows us to report
177 # multiple errors at once
178 if ret is not None and layer_depend not in ret:
179 ret.append(layer_depend)
Brad Bishop004d4992018-10-02 23:54:45 +0200180 else:
181 # we might have processed this dependency already, in which case
182 # we should not do it again (avoid recursive loop)
183 continue
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500184
185 # Recursively process...
186 if 'collections' not in layer_depend:
187 continue
188
189 for collection in layer_depend['collections']:
190 collect_deps = layer_depend['collections'][collection]['depends']
191 if not collect_deps:
192 continue
193 ret = recurse_dependencies(collect_deps, layer_depend, layers, logger, ret)
194
195 return ret
196
197 layer_depends = []
198 for collection in layer['collections']:
199 depends = layer['collections'][collection]['depends']
200 if not depends:
201 continue
202
203 layer_depends = recurse_dependencies(depends, layer, layers, logger, layer_depends)
204
205 # Note: [] (empty) is allowed, None is not!
Patrick Williams213cb262021-08-07 19:21:33 -0500206 return layer_depends
207
208def add_layer_dependencies(bblayersconf, layer, layers, logger):
209
210 layer_depends = get_layer_dependencies(layer, layers, logger)
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500211 if layer_depends is None:
212 return False
213 else:
Andrew Geissler99467da2019-02-25 18:54:23 -0600214 add_layers(bblayersconf, layer_depends, logger)
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500215
Andrew Geissler99467da2019-02-25 18:54:23 -0600216 return True
217
218def add_layers(bblayersconf, layers, logger):
219 # Don't add a layer that is already present.
220 added = set()
221 output = check_command('Getting existing layers failed.', 'bitbake-layers show-layers').decode('utf-8')
222 for layer, path, pri in re.findall(r'^(\S+) +([^\n]*?) +(\d+)$', output, re.MULTILINE):
223 added.add(path)
224
225 with open(bblayersconf, 'a+') as f:
226 for layer in layers:
227 logger.info('Adding layer %s' % layer['name'])
228 name = layer['name']
229 path = layer['path']
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500230 if path in added:
Andrew Geissler99467da2019-02-25 18:54:23 -0600231 logger.info('%s is already in %s' % (name, bblayersconf))
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500232 else:
233 added.add(path)
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500234 f.write("\nBBLAYERS += \"%s\"\n" % path)
235 return True
236
Andrew Geissler635e0e42020-08-21 15:58:33 -0500237def check_bblayers(bblayersconf, layer_path, logger):
238 '''
239 If layer_path found in BBLAYERS return True
240 '''
241 import bb.parse
242 import bb.data
243
244 ldata = bb.parse.handle(bblayersconf, bb.data.init(), include=True)
245 for bblayer in (ldata.getVar('BBLAYERS') or '').split():
246 if os.path.normpath(bblayer) == os.path.normpath(layer_path):
247 return True
248
249 return False
250
Andrew Geissler99467da2019-02-25 18:54:23 -0600251def check_command(error_msg, cmd, cwd=None):
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500252 '''
253 Run a command under a shell, capture stdout and stderr in a single stream,
254 throw an error when command returns non-zero exit code. Returns the output.
255 '''
256
Andrew Geissler99467da2019-02-25 18:54:23 -0600257 p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, cwd=cwd)
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500258 output, _ = p.communicate()
259 if p.returncode:
260 msg = "%s\nCommand: %s\nOutput:\n%s" % (error_msg, cmd, output.decode('utf-8'))
261 raise RuntimeError(msg)
262 return output
263
264def get_signatures(builddir, failsafe=False, machine=None):
265 import re
266
267 # some recipes needs to be excluded like meta-world-pkgdata
268 # because a layer can add recipes to a world build so signature
269 # will be change
270 exclude_recipes = ('meta-world-pkgdata',)
271
272 sigs = {}
273 tune2tasks = {}
274
Brad Bishopc68388fc2019-08-26 01:33:31 -0400275 cmd = 'BB_ENV_EXTRAWHITE="$BB_ENV_EXTRAWHITE BB_SIGNATURE_HANDLER" BB_SIGNATURE_HANDLER="OEBasicHash" '
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500276 if machine:
277 cmd += 'MACHINE=%s ' % machine
278 cmd += 'bitbake '
279 if failsafe:
280 cmd += '-k '
281 cmd += '-S none world'
282 sigs_file = os.path.join(builddir, 'locked-sigs.inc')
283 if os.path.exists(sigs_file):
284 os.unlink(sigs_file)
285 try:
286 check_command('Generating signatures failed. This might be due to some parse error and/or general layer incompatibilities.',
Andrew Geissler99467da2019-02-25 18:54:23 -0600287 cmd, builddir)
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500288 except RuntimeError as ex:
289 if failsafe and os.path.exists(sigs_file):
290 # Ignore the error here. Most likely some recipes active
291 # in a world build lack some dependencies. There is a
292 # separate test_machine_world_build which exposes the
293 # failure.
294 pass
295 else:
296 raise
297
298 sig_regex = re.compile("^(?P<task>.*:.*):(?P<hash>.*) .$")
299 tune_regex = re.compile("(^|\s)SIGGEN_LOCKEDSIGS_t-(?P<tune>\S*)\s*=\s*")
300 current_tune = None
301 with open(sigs_file, 'r') as f:
302 for line in f.readlines():
303 line = line.strip()
304 t = tune_regex.search(line)
305 if t:
306 current_tune = t.group('tune')
307 s = sig_regex.match(line)
308 if s:
309 exclude = False
310 for er in exclude_recipes:
311 (recipe, task) = s.group('task').split(':')
312 if er == recipe:
313 exclude = True
314 break
315 if exclude:
316 continue
317
318 sigs[s.group('task')] = s.group('hash')
319 tune2tasks.setdefault(current_tune, []).append(s.group('task'))
320
321 if not sigs:
322 raise RuntimeError('Can\'t load signatures from %s' % sigs_file)
323
324 return (sigs, tune2tasks)
325
326def get_depgraph(targets=['world'], failsafe=False):
327 '''
328 Returns the dependency graph for the given target(s).
329 The dependency graph is taken directly from DepTreeEvent.
330 '''
331 depgraph = None
332 with bb.tinfoil.Tinfoil() as tinfoil:
333 tinfoil.prepare(config_only=False)
334 tinfoil.set_event_mask(['bb.event.NoProvider', 'bb.event.DepTreeGenerated', 'bb.command.CommandCompleted'])
335 if not tinfoil.run_command('generateDepTreeEvent', targets, 'do_build'):
336 raise RuntimeError('starting generateDepTreeEvent failed')
337 while True:
338 event = tinfoil.wait_event(timeout=1000)
339 if event:
340 if isinstance(event, bb.command.CommandFailed):
341 raise RuntimeError('Generating dependency information failed: %s' % event.error)
342 elif isinstance(event, bb.command.CommandCompleted):
343 break
344 elif isinstance(event, bb.event.NoProvider):
345 if failsafe:
346 # The event is informational, we will get information about the
347 # remaining dependencies eventually and thus can ignore this
348 # here like we do in get_signatures(), if desired.
349 continue
350 if event._reasons:
351 raise RuntimeError('Nothing provides %s: %s' % (event._item, event._reasons))
352 else:
353 raise RuntimeError('Nothing provides %s.' % (event._item))
354 elif isinstance(event, bb.event.DepTreeGenerated):
355 depgraph = event._depgraph
356
357 if depgraph is None:
358 raise RuntimeError('Could not retrieve the depgraph.')
359 return depgraph
360
361def compare_signatures(old_sigs, curr_sigs):
362 '''
363 Compares the result of two get_signatures() calls. Returns None if no
364 problems found, otherwise a string that can be used as additional
365 explanation in self.fail().
366 '''
367 # task -> (old signature, new signature)
368 sig_diff = {}
369 for task in old_sigs:
370 if task in curr_sigs and \
371 old_sigs[task] != curr_sigs[task]:
372 sig_diff[task] = (old_sigs[task], curr_sigs[task])
373
374 if not sig_diff:
375 return None
376
377 # Beware, depgraph uses task=<pn>.<taskname> whereas get_signatures()
378 # uses <pn>:<taskname>. Need to convert sometimes. The output follows
379 # the convention from get_signatures() because that seems closer to
380 # normal bitbake output.
381 def sig2graph(task):
382 pn, taskname = task.rsplit(':', 1)
383 return pn + '.' + taskname
384 def graph2sig(task):
385 pn, taskname = task.rsplit('.', 1)
386 return pn + ':' + taskname
387 depgraph = get_depgraph(failsafe=True)
388 depends = depgraph['tdepends']
389
390 # If a task A has a changed signature, but none of its
391 # dependencies, then we need to report it because it is
392 # the one which introduces a change. Any task depending on
393 # A (directly or indirectly) will also have a changed
394 # signature, but we don't need to report it. It might have
395 # its own changes, which will become apparent once the
396 # issues that we do report are fixed and the test gets run
397 # again.
398 sig_diff_filtered = []
399 for task, (old_sig, new_sig) in sig_diff.items():
400 deps_tainted = False
401 for dep in depends.get(sig2graph(task), ()):
402 if graph2sig(dep) in sig_diff:
403 deps_tainted = True
404 break
405 if not deps_tainted:
406 sig_diff_filtered.append((task, old_sig, new_sig))
407
408 msg = []
409 msg.append('%d signatures changed, initial differences (first hash before, second after):' %
410 len(sig_diff))
411 for diff in sorted(sig_diff_filtered):
412 recipe, taskname = diff[0].rsplit(':', 1)
413 cmd = 'bitbake-diffsigs --task %s %s --signature %s %s' % \
414 (recipe, taskname, diff[1], diff[2])
415 msg.append(' %s: %s -> %s' % diff)
416 msg.append(' %s' % cmd)
417 try:
418 output = check_command('Determining signature difference failed.',
419 cmd).decode('utf-8')
420 except RuntimeError as error:
421 output = str(error)
422 if output:
423 msg.extend([' ' + line for line in output.splitlines()])
424 msg.append('')
425 return '\n'.join(msg)