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