blob: fe545607bb4c2bd02e098b0c523ee69a5f019785 [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
149def _find_layer_depends(depend, layers):
150 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
159def add_layer_dependencies(bblayersconf, layer, layers, logger):
160 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
169 layer_depend = _find_layer_depends(depend, layers)
170 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!
206 if layer_depends is None:
207 return False
208 else:
Andrew Geissler99467da2019-02-25 18:54:23 -0600209 add_layers(bblayersconf, layer_depends, logger)
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500210
Andrew Geissler99467da2019-02-25 18:54:23 -0600211 return True
212
213def add_layers(bblayersconf, layers, logger):
214 # Don't add a layer that is already present.
215 added = set()
216 output = check_command('Getting existing layers failed.', 'bitbake-layers show-layers').decode('utf-8')
217 for layer, path, pri in re.findall(r'^(\S+) +([^\n]*?) +(\d+)$', output, re.MULTILINE):
218 added.add(path)
219
220 with open(bblayersconf, 'a+') as f:
221 for layer in layers:
222 logger.info('Adding layer %s' % layer['name'])
223 name = layer['name']
224 path = layer['path']
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500225 if path in added:
Andrew Geissler99467da2019-02-25 18:54:23 -0600226 logger.info('%s is already in %s' % (name, bblayersconf))
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500227 else:
228 added.add(path)
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500229 f.write("\nBBLAYERS += \"%s\"\n" % path)
230 return True
231
Andrew Geissler635e0e42020-08-21 15:58:33 -0500232def check_bblayers(bblayersconf, layer_path, logger):
233 '''
234 If layer_path found in BBLAYERS return True
235 '''
236 import bb.parse
237 import bb.data
238
239 ldata = bb.parse.handle(bblayersconf, bb.data.init(), include=True)
240 for bblayer in (ldata.getVar('BBLAYERS') or '').split():
241 if os.path.normpath(bblayer) == os.path.normpath(layer_path):
242 return True
243
244 return False
245
Andrew Geissler99467da2019-02-25 18:54:23 -0600246def check_command(error_msg, cmd, cwd=None):
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500247 '''
248 Run a command under a shell, capture stdout and stderr in a single stream,
249 throw an error when command returns non-zero exit code. Returns the output.
250 '''
251
Andrew Geissler99467da2019-02-25 18:54:23 -0600252 p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, cwd=cwd)
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500253 output, _ = p.communicate()
254 if p.returncode:
255 msg = "%s\nCommand: %s\nOutput:\n%s" % (error_msg, cmd, output.decode('utf-8'))
256 raise RuntimeError(msg)
257 return output
258
259def get_signatures(builddir, failsafe=False, machine=None):
260 import re
261
262 # some recipes needs to be excluded like meta-world-pkgdata
263 # because a layer can add recipes to a world build so signature
264 # will be change
265 exclude_recipes = ('meta-world-pkgdata',)
266
267 sigs = {}
268 tune2tasks = {}
269
Brad Bishopc68388fc2019-08-26 01:33:31 -0400270 cmd = 'BB_ENV_EXTRAWHITE="$BB_ENV_EXTRAWHITE BB_SIGNATURE_HANDLER" BB_SIGNATURE_HANDLER="OEBasicHash" '
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500271 if machine:
272 cmd += 'MACHINE=%s ' % machine
273 cmd += 'bitbake '
274 if failsafe:
275 cmd += '-k '
276 cmd += '-S none world'
277 sigs_file = os.path.join(builddir, 'locked-sigs.inc')
278 if os.path.exists(sigs_file):
279 os.unlink(sigs_file)
280 try:
281 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 -0600282 cmd, builddir)
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500283 except RuntimeError as ex:
284 if failsafe and os.path.exists(sigs_file):
285 # Ignore the error here. Most likely some recipes active
286 # in a world build lack some dependencies. There is a
287 # separate test_machine_world_build which exposes the
288 # failure.
289 pass
290 else:
291 raise
292
293 sig_regex = re.compile("^(?P<task>.*:.*):(?P<hash>.*) .$")
294 tune_regex = re.compile("(^|\s)SIGGEN_LOCKEDSIGS_t-(?P<tune>\S*)\s*=\s*")
295 current_tune = None
296 with open(sigs_file, 'r') as f:
297 for line in f.readlines():
298 line = line.strip()
299 t = tune_regex.search(line)
300 if t:
301 current_tune = t.group('tune')
302 s = sig_regex.match(line)
303 if s:
304 exclude = False
305 for er in exclude_recipes:
306 (recipe, task) = s.group('task').split(':')
307 if er == recipe:
308 exclude = True
309 break
310 if exclude:
311 continue
312
313 sigs[s.group('task')] = s.group('hash')
314 tune2tasks.setdefault(current_tune, []).append(s.group('task'))
315
316 if not sigs:
317 raise RuntimeError('Can\'t load signatures from %s' % sigs_file)
318
319 return (sigs, tune2tasks)
320
321def get_depgraph(targets=['world'], failsafe=False):
322 '''
323 Returns the dependency graph for the given target(s).
324 The dependency graph is taken directly from DepTreeEvent.
325 '''
326 depgraph = None
327 with bb.tinfoil.Tinfoil() as tinfoil:
328 tinfoil.prepare(config_only=False)
329 tinfoil.set_event_mask(['bb.event.NoProvider', 'bb.event.DepTreeGenerated', 'bb.command.CommandCompleted'])
330 if not tinfoil.run_command('generateDepTreeEvent', targets, 'do_build'):
331 raise RuntimeError('starting generateDepTreeEvent failed')
332 while True:
333 event = tinfoil.wait_event(timeout=1000)
334 if event:
335 if isinstance(event, bb.command.CommandFailed):
336 raise RuntimeError('Generating dependency information failed: %s' % event.error)
337 elif isinstance(event, bb.command.CommandCompleted):
338 break
339 elif isinstance(event, bb.event.NoProvider):
340 if failsafe:
341 # The event is informational, we will get information about the
342 # remaining dependencies eventually and thus can ignore this
343 # here like we do in get_signatures(), if desired.
344 continue
345 if event._reasons:
346 raise RuntimeError('Nothing provides %s: %s' % (event._item, event._reasons))
347 else:
348 raise RuntimeError('Nothing provides %s.' % (event._item))
349 elif isinstance(event, bb.event.DepTreeGenerated):
350 depgraph = event._depgraph
351
352 if depgraph is None:
353 raise RuntimeError('Could not retrieve the depgraph.')
354 return depgraph
355
356def compare_signatures(old_sigs, curr_sigs):
357 '''
358 Compares the result of two get_signatures() calls. Returns None if no
359 problems found, otherwise a string that can be used as additional
360 explanation in self.fail().
361 '''
362 # task -> (old signature, new signature)
363 sig_diff = {}
364 for task in old_sigs:
365 if task in curr_sigs and \
366 old_sigs[task] != curr_sigs[task]:
367 sig_diff[task] = (old_sigs[task], curr_sigs[task])
368
369 if not sig_diff:
370 return None
371
372 # Beware, depgraph uses task=<pn>.<taskname> whereas get_signatures()
373 # uses <pn>:<taskname>. Need to convert sometimes. The output follows
374 # the convention from get_signatures() because that seems closer to
375 # normal bitbake output.
376 def sig2graph(task):
377 pn, taskname = task.rsplit(':', 1)
378 return pn + '.' + taskname
379 def graph2sig(task):
380 pn, taskname = task.rsplit('.', 1)
381 return pn + ':' + taskname
382 depgraph = get_depgraph(failsafe=True)
383 depends = depgraph['tdepends']
384
385 # If a task A has a changed signature, but none of its
386 # dependencies, then we need to report it because it is
387 # the one which introduces a change. Any task depending on
388 # A (directly or indirectly) will also have a changed
389 # signature, but we don't need to report it. It might have
390 # its own changes, which will become apparent once the
391 # issues that we do report are fixed and the test gets run
392 # again.
393 sig_diff_filtered = []
394 for task, (old_sig, new_sig) in sig_diff.items():
395 deps_tainted = False
396 for dep in depends.get(sig2graph(task), ()):
397 if graph2sig(dep) in sig_diff:
398 deps_tainted = True
399 break
400 if not deps_tainted:
401 sig_diff_filtered.append((task, old_sig, new_sig))
402
403 msg = []
404 msg.append('%d signatures changed, initial differences (first hash before, second after):' %
405 len(sig_diff))
406 for diff in sorted(sig_diff_filtered):
407 recipe, taskname = diff[0].rsplit(':', 1)
408 cmd = 'bitbake-diffsigs --task %s %s --signature %s %s' % \
409 (recipe, taskname, diff[1], diff[2])
410 msg.append(' %s: %s -> %s' % diff)
411 msg.append(' %s' % cmd)
412 try:
413 output = check_command('Determining signature difference failed.',
414 cmd).decode('utf-8')
415 except RuntimeError as error:
416 output = str(error)
417 if output:
418 msg.extend([' ' + line for line in output.splitlines()])
419 msg.append('')
420 return '\n'.join(msg)