blob: d48b03e6996c6eebec7ba5f5ddf6558108fd3312 [file] [log] [blame]
Matthew Barthccb7f852016-11-23 17:43:02 -06001#!/usr/bin/env python
2
3"""
4This script determines the given package's openbmc dependencies from its
5configure.ac file where it downloads, configures, builds, and installs each of
6these dependencies. Then the given package is configured, built, and installed
7prior to executing its unit tests.
8"""
9
Matthew Barthd1810372016-12-19 16:57:21 -060010from git import Repo
Matthew Barthccb7f852016-11-23 17:43:02 -060011from urlparse import urljoin
Andrew Jefferya4e31c62018-03-08 13:45:28 +103012from subprocess import check_call, call, CalledProcessError
Matthew Barthccb7f852016-11-23 17:43:02 -060013import os
14import sys
Matthew Barth33df8792016-12-19 14:30:17 -060015import argparse
William A. Kennington IIIa2156732018-06-30 18:38:09 -070016import multiprocessing
Leonel Gonzaleza62a1a12017-03-24 11:03:47 -050017import re
William A. Kennington III9a32d5e2018-12-06 17:38:53 -080018import sets
William A. Kennington IIIe67f5fc2018-12-06 17:40:30 -080019import subprocess
William A. Kennington III3f1d1202018-12-06 18:02:07 -080020import shutil
William A. Kennington III4e1d0a12018-07-16 12:04:03 -070021import platform
Leonel Gonzaleza62a1a12017-03-24 11:03:47 -050022
23
24class DepTree():
25 """
26 Represents package dependency tree, where each node is a DepTree with a
27 name and DepTree children.
28 """
29
30 def __init__(self, name):
31 """
32 Create new DepTree.
33
34 Parameter descriptions:
35 name Name of new tree node.
36 """
37 self.name = name
38 self.children = list()
39
40 def AddChild(self, name):
41 """
42 Add new child node to current node.
43
44 Parameter descriptions:
45 name Name of new child
46 """
47 new_child = DepTree(name)
48 self.children.append(new_child)
49 return new_child
50
51 def AddChildNode(self, node):
52 """
53 Add existing child node to current node.
54
55 Parameter descriptions:
56 node Tree node to add
57 """
58 self.children.append(node)
59
60 def RemoveChild(self, name):
61 """
62 Remove child node.
63
64 Parameter descriptions:
65 name Name of child to remove
66 """
67 for child in self.children:
68 if child.name == name:
69 self.children.remove(child)
70 return
71
72 def GetNode(self, name):
73 """
74 Return node with matching name. Return None if not found.
75
76 Parameter descriptions:
77 name Name of node to return
78 """
79 if self.name == name:
80 return self
81 for child in self.children:
82 node = child.GetNode(name)
83 if node:
84 return node
85 return None
86
87 def GetParentNode(self, name, parent_node=None):
88 """
89 Return parent of node with matching name. Return none if not found.
90
91 Parameter descriptions:
92 name Name of node to get parent of
93 parent_node Parent of current node
94 """
95 if self.name == name:
96 return parent_node
97 for child in self.children:
98 found_node = child.GetParentNode(name, self)
99 if found_node:
100 return found_node
101 return None
102
103 def GetPath(self, name, path=None):
104 """
105 Return list of node names from head to matching name.
106 Return None if not found.
107
108 Parameter descriptions:
109 name Name of node
110 path List of node names from head to current node
111 """
112 if not path:
113 path = []
114 if self.name == name:
115 path.append(self.name)
116 return path
117 for child in self.children:
118 match = child.GetPath(name, path + [self.name])
119 if match:
120 return match
121 return None
122
123 def GetPathRegex(self, name, regex_str, path=None):
124 """
125 Return list of node paths that end in name, or match regex_str.
126 Return empty list if not found.
127
128 Parameter descriptions:
129 name Name of node to search for
130 regex_str Regex string to match node names
131 path Path of node names from head to current node
132 """
133 new_paths = []
134 if not path:
135 path = []
136 match = re.match(regex_str, self.name)
137 if (self.name == name) or (match):
138 new_paths.append(path + [self.name])
139 for child in self.children:
140 return_paths = None
141 full_path = path + [self.name]
142 return_paths = child.GetPathRegex(name, regex_str, full_path)
143 for i in return_paths:
144 new_paths.append(i)
145 return new_paths
146
147 def MoveNode(self, from_name, to_name):
148 """
149 Mode existing from_name node to become child of to_name node.
150
151 Parameter descriptions:
152 from_name Name of node to make a child of to_name
153 to_name Name of node to make parent of from_name
154 """
155 parent_from_node = self.GetParentNode(from_name)
156 from_node = self.GetNode(from_name)
157 parent_from_node.RemoveChild(from_name)
158 to_node = self.GetNode(to_name)
159 to_node.AddChildNode(from_node)
160
161 def ReorderDeps(self, name, regex_str):
162 """
163 Reorder dependency tree. If tree contains nodes with names that
164 match 'name' and 'regex_str', move 'regex_str' nodes that are
165 to the right of 'name' node, so that they become children of the
166 'name' node.
167
168 Parameter descriptions:
169 name Name of node to look for
170 regex_str Regex string to match names to
171 """
172 name_path = self.GetPath(name)
173 if not name_path:
174 return
175 paths = self.GetPathRegex(name, regex_str)
176 is_name_in_paths = False
177 name_index = 0
178 for i in range(len(paths)):
179 path = paths[i]
180 if path[-1] == name:
181 is_name_in_paths = True
182 name_index = i
183 break
184 if not is_name_in_paths:
185 return
186 for i in range(name_index + 1, len(paths)):
187 path = paths[i]
188 if name in path:
189 continue
190 from_name = path[-1]
191 self.MoveNode(from_name, name)
192
193 def GetInstallList(self):
194 """
195 Return post-order list of node names.
196
197 Parameter descriptions:
198 """
199 install_list = []
200 for child in self.children:
201 child_install_list = child.GetInstallList()
202 install_list.extend(child_install_list)
203 install_list.append(self.name)
204 return install_list
205
206 def PrintTree(self, level=0):
207 """
208 Print pre-order node names with indentation denoting node depth level.
209
210 Parameter descriptions:
211 level Current depth level
212 """
213 INDENT_PER_LEVEL = 4
214 print ' ' * (level * INDENT_PER_LEVEL) + self.name
215 for child in self.children:
216 child.PrintTree(level + 1)
Matthew Barth33df8792016-12-19 14:30:17 -0600217
218
William A. Kennington III1fddb972019-02-06 18:03:53 -0800219def check_call_cmd(*cmd):
Matthew Barth33df8792016-12-19 14:30:17 -0600220 """
221 Verbose prints the directory location the given command is called from and
222 the command, then executes the command using check_call.
223
224 Parameter descriptions:
225 dir Directory location command is to be called from
226 cmd List of parameters constructing the complete command
227 """
William A. Kennington III1fddb972019-02-06 18:03:53 -0800228 printline(os.getcwd(), ">", " ".join(cmd))
Matthew Barth33df8792016-12-19 14:30:17 -0600229 check_call(cmd)
Matthew Barthccb7f852016-11-23 17:43:02 -0600230
231
Andrew Geisslera61acb52019-01-03 16:32:44 -0600232def clone_pkg(pkg, branch):
Matthew Barth33df8792016-12-19 14:30:17 -0600233 """
234 Clone the given openbmc package's git repository from gerrit into
235 the WORKSPACE location
236
237 Parameter descriptions:
238 pkg Name of the package to clone
Andrew Geisslera61acb52019-01-03 16:32:44 -0600239 branch Branch to clone from pkg
Matthew Barth33df8792016-12-19 14:30:17 -0600240 """
Andrew Jeffery7be94ca2018-03-08 13:15:33 +1030241 pkg_dir = os.path.join(WORKSPACE, pkg)
242 if os.path.exists(os.path.join(pkg_dir, '.git')):
243 return pkg_dir
Matthew Barthccb7f852016-11-23 17:43:02 -0600244 pkg_repo = urljoin('https://gerrit.openbmc-project.xyz/openbmc/', pkg)
Andrew Jeffery7be94ca2018-03-08 13:15:33 +1030245 os.mkdir(pkg_dir)
Andrew Geisslera61acb52019-01-03 16:32:44 -0600246 printline(pkg_dir, "> git clone", pkg_repo, branch, "./")
247 try:
248 # first try the branch
249 repo_inst = Repo.clone_from(pkg_repo, pkg_dir,
250 branch=branch).working_dir
251 except:
252 printline("Input branch not found, default to master")
253 repo_inst = Repo.clone_from(pkg_repo, pkg_dir,
254 branch="master").working_dir
255 return repo_inst
Matthew Barth33df8792016-12-19 14:30:17 -0600256
257
William A. Kennington IIIc048cc02018-12-06 15:39:18 -0800258def get_autoconf_deps(pkgdir):
259 """
260 Parse the given 'configure.ac' file for package dependencies and return
261 a list of the dependencies found. If the package is not autoconf it is just
262 ignored.
263
264 Parameter descriptions:
265 pkgdir Directory where package source is located
266 """
267 configure_ac = os.path.join(pkgdir, 'configure.ac')
268 if not os.path.exists(configure_ac):
269 return []
270
William A. Kennington IIIe67f5fc2018-12-06 17:40:30 -0800271 configure_ac_contents = ''
272 # Prepend some special function overrides so we can parse out dependencies
273 for macro in DEPENDENCIES.iterkeys():
274 configure_ac_contents += ('m4_define([' + macro + '], [' +
275 macro + '_START$' + str(DEPENDENCIES_OFFSET[macro] + 1) +
276 macro + '_END])\n')
William A. Kennington IIIc048cc02018-12-06 15:39:18 -0800277 with open(configure_ac, "rt") as f:
William A. Kennington IIIe67f5fc2018-12-06 17:40:30 -0800278 configure_ac_contents += f.read()
279
280 autoconf_process = subprocess.Popen(['autoconf', '-Wno-undefined', '-'],
281 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
282 stderr=subprocess.PIPE)
283 (stdout, stderr) = autoconf_process.communicate(input=configure_ac_contents)
284 if not stdout:
285 print(stderr)
286 raise Exception("Failed to run autoconf for parsing dependencies")
287
288 # Parse out all of the dependency text
289 matches = []
290 for macro in DEPENDENCIES.iterkeys():
291 pattern = '(' + macro + ')_START(.*?)' + macro + '_END'
292 for match in re.compile(pattern).finditer(stdout):
293 matches.append((match.group(1), match.group(2)))
294
295 # Look up dependencies from the text
296 found_deps = []
297 for macro, deptext in matches:
298 for potential_dep in deptext.split(' '):
299 for known_dep in DEPENDENCIES[macro].iterkeys():
300 if potential_dep.startswith(known_dep):
301 found_deps.append(DEPENDENCIES[macro][known_dep])
302
303 return found_deps
Matthew Barthccb7f852016-11-23 17:43:02 -0600304
William A. Kennington III3f1d1202018-12-06 18:02:07 -0800305def get_meson_deps(pkgdir):
306 """
307 Parse the given 'meson.build' file for package dependencies and return
308 a list of the dependencies found. If the package is not meson compatible
309 it is just ignored.
310
311 Parameter descriptions:
312 pkgdir Directory where package source is located
313 """
314 meson_build = os.path.join(pkgdir, 'meson.build')
315 if not os.path.exists(meson_build):
316 return []
317
318 found_deps = []
319 for root, dirs, files in os.walk(pkgdir):
320 if 'meson.build' not in files:
321 continue
322 with open(os.path.join(root, 'meson.build'), 'rt') as f:
323 build_contents = f.read()
324 for match in re.finditer(r"dependency\('([^']*)'.*?\)\n", build_contents):
325 maybe_dep = DEPENDENCIES['PKG_CHECK_MODULES'].get(match.group(1))
326 if maybe_dep is not None:
327 found_deps.append(maybe_dep)
328
329 return found_deps
330
William A. Kennington IIIa2156732018-06-30 18:38:09 -0700331make_parallel = [
332 'make',
333 # Run enough jobs to saturate all the cpus
334 '-j', str(multiprocessing.cpu_count()),
335 # Don't start more jobs if the load avg is too high
336 '-l', str(multiprocessing.cpu_count()),
337 # Synchronize the output so logs aren't intermixed in stdout / stderr
338 '-O',
339]
340
William A. Kennington IIIa0454912018-12-06 14:47:16 -0800341def enFlag(flag, enabled):
342 """
343 Returns an configure flag as a string
344
345 Parameters:
346 flag The name of the flag
347 enabled Whether the flag is enabled or disabled
348 """
349 return '--' + ('enable' if enabled else 'disable') + '-' + flag
350
William A. Kennington III3f1d1202018-12-06 18:02:07 -0800351def mesonFeature(val):
352 """
353 Returns the meson flag which signifies the value
354
355 True is enabled which requires the feature.
356 False is disabled which disables the feature.
357 None is auto which autodetects the feature.
358
359 Parameters:
360 val The value being converted
361 """
362 if val is True:
363 return "enabled"
364 elif val is False:
365 return "disabled"
366 elif val is None:
367 return "auto"
368 else:
369 raise Exception("Bad meson feature value")
370
William A. Kennington III6764d5f2018-12-13 12:27:03 -0800371def parse_meson_options(options_file):
372 """
373 Returns a set of options defined in the provides meson_options.txt file
374
375 Parameters:
376 options_file The file containing options
377 """
378 options_contents = ''
379 with open(options_file, "rt") as f:
380 options_contents += f.read()
381 options = sets.Set()
382 pattern = 'option\\(\\s*\'([^\']*)\''
383 for match in re.compile(pattern).finditer(options_contents):
384 options.add(match.group(1))
385 return options
William A. Kennington III3f1d1202018-12-06 18:02:07 -0800386
William A. Kennington IIIa0454912018-12-06 14:47:16 -0800387def build_and_install(pkg, build_for_testing=False):
William A. Kennington III780ec092018-12-06 14:46:50 -0800388 """
389 Builds and installs the package in the environment. Optionally
390 builds the examples and test cases for package.
391
392 Parameter description:
393 pkg The package we are building
William A. Kennington IIIa0454912018-12-06 14:47:16 -0800394 build_for_testing Enable options related to testing on the package?
William A. Kennington III780ec092018-12-06 14:46:50 -0800395 """
William A. Kennington III90b106a2019-02-06 18:08:24 -0800396 os.chdir(os.path.join(WORKSPACE, pkg))
William A. Kennington III54d4faf2018-12-06 17:46:24 -0800397
398 # Refresh dynamic linker run time bindings for dependencies
William A. Kennington III1fddb972019-02-06 18:03:53 -0800399 check_call_cmd('sudo', '-n', '--', 'ldconfig')
William A. Kennington III54d4faf2018-12-06 17:46:24 -0800400
William A. Kennington III780ec092018-12-06 14:46:50 -0800401 # Build & install this package
William A. Kennington III3f1d1202018-12-06 18:02:07 -0800402 # Always try using meson first
403 if os.path.exists('meson.build'):
William A. Kennington III6764d5f2018-12-13 12:27:03 -0800404 meson_options = parse_meson_options("meson_options.txt")
William A. Kennington III3f1d1202018-12-06 18:02:07 -0800405 meson_flags = [
406 '-Db_colorout=never',
William A. Kennington III73b0d6e2019-01-17 14:35:41 -0800407 '-Dwerror=true',
408 '-Dwarning_level=3',
William A. Kennington III3f1d1202018-12-06 18:02:07 -0800409 ]
William A. Kennington III25e58142018-12-13 14:30:43 -0800410 if build_for_testing:
411 meson_flags.append('--buildtype=debug')
412 else:
413 meson_flags.append('--buildtype=debugoptimized')
William A. Kennington III6764d5f2018-12-13 12:27:03 -0800414 if 'tests' in meson_options:
415 meson_flags.append('-Dtests=' + mesonFeature(build_for_testing))
416 if 'examples' in meson_options:
417 meson_flags.append('-Dexamples=' + str(build_for_testing).lower())
William A. Kennington III3f1d1202018-12-06 18:02:07 -0800418 if MESON_FLAGS.get(pkg) is not None:
419 meson_flags.extend(MESON_FLAGS.get(pkg))
420 try:
William A. Kennington III1fddb972019-02-06 18:03:53 -0800421 check_call_cmd('meson', 'setup', '--reconfigure', 'build', *meson_flags)
William A. Kennington III3f1d1202018-12-06 18:02:07 -0800422 except:
423 shutil.rmtree('build')
William A. Kennington III1fddb972019-02-06 18:03:53 -0800424 check_call_cmd('meson', 'setup', 'build', *meson_flags)
425 check_call_cmd('ninja', '-C', 'build')
426 check_call_cmd('sudo', '-n', '--', 'ninja', '-C', 'build', 'install')
William A. Kennington III3f1d1202018-12-06 18:02:07 -0800427 # Assume we are autoconf otherwise
428 else:
429 conf_flags = [
430 enFlag('silent-rules', False),
431 enFlag('examples', build_for_testing),
432 enFlag('tests', build_for_testing),
William A. Kennington III3f1d1202018-12-06 18:02:07 -0800433 ]
William A. Kennington III65b37fa2019-01-31 15:15:17 -0800434 if not TEST_ONLY:
435 conf_flags.extend([
436 enFlag('code-coverage', build_for_testing),
437 enFlag('valgrind', build_for_testing),
438 ])
William A. Kennington III3f1d1202018-12-06 18:02:07 -0800439 # Add any necessary configure flags for package
440 if CONFIGURE_FLAGS.get(pkg) is not None:
441 conf_flags.extend(CONFIGURE_FLAGS.get(pkg))
442 for bootstrap in ['bootstrap.sh', 'bootstrap', 'autogen.sh']:
443 if os.path.exists(bootstrap):
William A. Kennington III1fddb972019-02-06 18:03:53 -0800444 check_call_cmd('./' + bootstrap)
William A. Kennington III3f1d1202018-12-06 18:02:07 -0800445 break
William A. Kennington III1fddb972019-02-06 18:03:53 -0800446 check_call_cmd('./configure', *conf_flags)
447 check_call_cmd(*make_parallel)
448 check_call_cmd('sudo', '-n', '--', *(make_parallel + [ 'install' ]))
William A. Kennington III780ec092018-12-06 14:46:50 -0800449
Andrew Geisslera61acb52019-01-03 16:32:44 -0600450def build_dep_tree(pkg, pkgdir, dep_added, head, branch, dep_tree=None):
Leonel Gonzaleza62a1a12017-03-24 11:03:47 -0500451 """
452 For each package(pkg), starting with the package to be unit tested,
453 parse its 'configure.ac' file from within the package's directory(pkgdir)
454 for each package dependency defined recursively doing the same thing
455 on each package found as a dependency.
456
457 Parameter descriptions:
458 pkg Name of the package
459 pkgdir Directory where package source is located
William A. Kennington IIIc048cc02018-12-06 15:39:18 -0800460 dep_added Current dict of dependencies and added status
Leonel Gonzaleza62a1a12017-03-24 11:03:47 -0500461 head Head node of the dependency tree
Andrew Geisslera61acb52019-01-03 16:32:44 -0600462 branch Branch to clone from pkg
Leonel Gonzaleza62a1a12017-03-24 11:03:47 -0500463 dep_tree Current dependency tree node
464 """
465 if not dep_tree:
466 dep_tree = head
William A. Kennington IIIc048cc02018-12-06 15:39:18 -0800467
William A. Kennington IIIbe6aab22018-12-06 15:01:54 -0800468 with open("/tmp/depcache", "r") as depcache:
William A. Kennington IIIc048cc02018-12-06 15:39:18 -0800469 cache = depcache.readline()
470
471 # Read out pkg dependencies
472 pkg_deps = []
473 pkg_deps += get_autoconf_deps(pkgdir)
William A. Kennington III3f1d1202018-12-06 18:02:07 -0800474 pkg_deps += get_meson_deps(pkgdir)
William A. Kennington IIIc048cc02018-12-06 15:39:18 -0800475
William A. Kennington III9a32d5e2018-12-06 17:38:53 -0800476 for dep in sets.Set(pkg_deps):
William A. Kennington IIIc048cc02018-12-06 15:39:18 -0800477 if dep in cache:
478 continue
479 # Dependency package not already known
480 if dep_added.get(dep) is None:
481 # Dependency package not added
482 new_child = dep_tree.AddChild(dep)
483 dep_added[dep] = False
Andrew Geisslera61acb52019-01-03 16:32:44 -0600484 dep_pkgdir = clone_pkg(dep,branch)
William A. Kennington IIIc048cc02018-12-06 15:39:18 -0800485 # Determine this dependency package's
486 # dependencies and add them before
487 # returning to add this package
488 dep_added = build_dep_tree(dep,
489 dep_pkgdir,
490 dep_added,
491 head,
Andrew Geisslera61acb52019-01-03 16:32:44 -0600492 branch,
William A. Kennington IIIc048cc02018-12-06 15:39:18 -0800493 new_child)
494 else:
495 # Dependency package known and added
496 if dep_added[dep]:
Andrew Jeffery2cb0c7a2018-03-08 13:19:08 +1030497 continue
Leonel Gonzaleza62a1a12017-03-24 11:03:47 -0500498 else:
William A. Kennington IIIc048cc02018-12-06 15:39:18 -0800499 # Cyclic dependency failure
500 raise Exception("Cyclic dependencies found in "+pkg)
Leonel Gonzaleza62a1a12017-03-24 11:03:47 -0500501
502 if not dep_added[pkg]:
503 dep_added[pkg] = True
504
505 return dep_added
Matthew Barthccb7f852016-11-23 17:43:02 -0600506
William A. Kennington III0f0a6802018-07-16 11:52:33 -0700507def make_target_exists(target):
508 """
509 Runs a check against the makefile in the current directory to determine
510 if the target exists so that it can be built.
511
512 Parameter descriptions:
513 target The make target we are checking
514 """
515 try:
516 cmd = [ 'make', '-n', target ]
517 with open(os.devnull, 'w') as devnull:
518 check_call(cmd, stdout=devnull, stderr=devnull)
519 return True
520 except CalledProcessError:
521 return False
522
William A. Kennington III90b106a2019-02-06 18:08:24 -0800523def run_unit_tests():
William A. Kennington III0f0a6802018-07-16 11:52:33 -0700524 """
525 Runs the unit tests for the package via `make check`
William A. Kennington III0f0a6802018-07-16 11:52:33 -0700526 """
527 try:
528 cmd = make_parallel + [ 'check' ]
529 for i in range(0, args.repeat):
William A. Kennington III1fddb972019-02-06 18:03:53 -0800530 check_call_cmd(*cmd)
William A. Kennington III0f0a6802018-07-16 11:52:33 -0700531 except CalledProcessError:
William A. Kennington III90b106a2019-02-06 18:08:24 -0800532 for root, _, files in os.walk(os.getcwd()):
William A. Kennington III0f0a6802018-07-16 11:52:33 -0700533 if 'test-suite.log' not in files:
534 continue
William A. Kennington III1fddb972019-02-06 18:03:53 -0800535 check_call_cmd('cat', os.path.join(root, 'test-suite.log'))
William A. Kennington III0f0a6802018-07-16 11:52:33 -0700536 raise Exception('Unit tests failed')
537
William A. Kennington III90b106a2019-02-06 18:08:24 -0800538def run_cppcheck():
Patrick Venturead4354e2018-10-12 16:59:54 -0700539 try:
540 # http://cppcheck.sourceforge.net/manual.pdf
William A. Kennington III90b106a2019-02-06 18:08:24 -0800541 ignore_list = ['-i%s' % path for path in os.listdir(os.getcwd()) \
Patrick Venturead4354e2018-10-12 16:59:54 -0700542 if path.endswith('-src') or path.endswith('-build')]
543 ignore_list.extend(('-itest', '-iscripts'))
544 params = ['cppcheck', '-j', str(multiprocessing.cpu_count()),
545 '--enable=all']
546 params.extend(ignore_list)
547 params.append('.')
548
William A. Kennington III1fddb972019-02-06 18:03:53 -0800549 check_call_cmd(*params)
Patrick Venturead4354e2018-10-12 16:59:54 -0700550 except CalledProcessError:
551 raise Exception('Cppcheck failed')
William A. Kennington III0f0a6802018-07-16 11:52:33 -0700552
William A. Kennington III37a89a22018-12-13 14:32:02 -0800553def is_valgrind_safe():
554 """
555 Returns whether it is safe to run valgrind on our platform
556 """
557 return re.match('ppc64', platform.machine()) is None
558
William A. Kennington III282e3302019-02-04 16:55:05 -0800559def is_sanitize_safe():
560 """
561 Returns whether it is safe to run sanitizers on our platform
562 """
563 return re.match('ppc64', platform.machine()) is None
564
William A. Kennington IIIeaff24a2019-02-06 16:57:42 -0800565def maybe_make_valgrind():
William A. Kennington III0f0a6802018-07-16 11:52:33 -0700566 """
567 Potentially runs the unit tests through valgrind for the package
568 via `make check-valgrind`. If the package does not have valgrind testing
569 then it just skips over this.
William A. Kennington III0f0a6802018-07-16 11:52:33 -0700570 """
William A. Kennington III4e1d0a12018-07-16 12:04:03 -0700571 # Valgrind testing is currently broken by an aggressive strcmp optimization
572 # that is inlined into optimized code for POWER by gcc 7+. Until we find
573 # a workaround, just don't run valgrind tests on POWER.
574 # https://github.com/openbmc/openbmc/issues/3315
William A. Kennington III37a89a22018-12-13 14:32:02 -0800575 if not is_valgrind_safe():
William A. Kennington III4e1d0a12018-07-16 12:04:03 -0700576 return
William A. Kennington III0f0a6802018-07-16 11:52:33 -0700577 if not make_target_exists('check-valgrind'):
578 return
579
580 try:
581 cmd = make_parallel + [ 'check-valgrind' ]
William A. Kennington III1fddb972019-02-06 18:03:53 -0800582 check_call_cmd(*cmd)
William A. Kennington III0f0a6802018-07-16 11:52:33 -0700583 except CalledProcessError:
William A. Kennington III90b106a2019-02-06 18:08:24 -0800584 for root, _, files in os.walk(os.getcwd()):
William A. Kennington III0f0a6802018-07-16 11:52:33 -0700585 for f in files:
586 if re.search('test-suite-[a-z]+.log', f) is None:
587 continue
William A. Kennington III1fddb972019-02-06 18:03:53 -0800588 check_call_cmd('cat', os.path.join(root, f))
William A. Kennington III0f0a6802018-07-16 11:52:33 -0700589 raise Exception('Valgrind tests failed')
590
William A. Kennington IIIeaff24a2019-02-06 16:57:42 -0800591def maybe_make_coverage():
William A. Kennington III0f0a6802018-07-16 11:52:33 -0700592 """
593 Potentially runs the unit tests through code coverage for the package
594 via `make check-code-coverage`. If the package does not have code coverage
595 testing then it just skips over this.
William A. Kennington III0f0a6802018-07-16 11:52:33 -0700596 """
597 if not make_target_exists('check-code-coverage'):
598 return
599
600 # Actually run code coverage
601 try:
602 cmd = make_parallel + [ 'check-code-coverage' ]
William A. Kennington III1fddb972019-02-06 18:03:53 -0800603 check_call_cmd(*cmd)
William A. Kennington III0f0a6802018-07-16 11:52:33 -0700604 except CalledProcessError:
605 raise Exception('Code coverage failed')
Matthew Barthccb7f852016-11-23 17:43:02 -0600606
607if __name__ == '__main__':
608 # CONFIGURE_FLAGS = [GIT REPO]:[CONFIGURE FLAGS]
609 CONFIGURE_FLAGS = {
Adriana Kobylak43c31e82017-02-13 09:28:35 -0600610 'phosphor-objmgr': ['--enable-unpatched-systemd'],
Matthew Barth1d1c6732017-03-24 10:00:28 -0500611 'sdbusplus': ['--enable-transaction'],
612 'phosphor-logging':
613 ['--enable-metadata-processing',
Deepak Kodihalli3a4e1b42017-06-08 09:52:35 -0500614 'YAML_DIR=/usr/local/share/phosphor-dbus-yaml/yaml']
Matthew Barthccb7f852016-11-23 17:43:02 -0600615 }
616
William A. Kennington III3f1d1202018-12-06 18:02:07 -0800617 # MESON_FLAGS = [GIT REPO]:[MESON FLAGS]
618 MESON_FLAGS = {
619 }
620
Matthew Barthccb7f852016-11-23 17:43:02 -0600621 # DEPENDENCIES = [MACRO]:[library/header]:[GIT REPO]
622 DEPENDENCIES = {
623 'AC_CHECK_LIB': {'mapper': 'phosphor-objmgr'},
Matthew Barth710f3f02017-01-18 15:20:19 -0600624 'AC_CHECK_HEADER': {
625 'host-ipmid': 'phosphor-host-ipmid',
Patrick Ventureb41a4462018-10-03 17:27:38 -0700626 'blobs-ipmid': 'phosphor-ipmi-blobs',
Matthew Barth710f3f02017-01-18 15:20:19 -0600627 'sdbusplus': 'sdbusplus',
William A. Kennington IIIb4f730a2018-09-12 11:21:20 -0700628 'sdeventplus': 'sdeventplus',
Patrick Venture22329962018-09-14 10:23:04 -0700629 'gpioplus': 'gpioplus',
Saqib Khan66145052017-02-14 12:02:07 -0600630 'phosphor-logging/log.hpp': 'phosphor-logging',
Patrick Williamseab8a372017-01-30 11:21:32 -0600631 },
Brad Bishopebb49112017-02-13 11:07:26 -0500632 'AC_PATH_PROG': {'sdbus++': 'sdbusplus'},
Patrick Williamseab8a372017-01-30 11:21:32 -0600633 'PKG_CHECK_MODULES': {
Matthew Barth19e261e2017-02-01 12:55:22 -0600634 'phosphor-dbus-interfaces': 'phosphor-dbus-interfaces',
Patrick Williamsf128b402017-03-29 06:45:59 -0500635 'openpower-dbus-interfaces': 'openpower-dbus-interfaces',
Matt Spinler7be19032018-04-13 09:43:14 -0500636 'ibm-dbus-interfaces': 'ibm-dbus-interfaces',
William A. Kennington III993ab332019-02-07 02:12:31 -0800637 'libipmid': 'phosphor-host-ipmid',
638 'libipmid-host': 'phosphor-host-ipmid',
Brad Bishopebb49112017-02-13 11:07:26 -0500639 'sdbusplus': 'sdbusplus',
William A. Kennington IIIb4f730a2018-09-12 11:21:20 -0700640 'sdeventplus': 'sdeventplus',
Patrick Venture22329962018-09-14 10:23:04 -0700641 'gpioplus': 'gpioplus',
Brad Bishopebb49112017-02-13 11:07:26 -0500642 'phosphor-logging': 'phosphor-logging',
Marri Devender Raoa3eee8a2018-08-13 05:34:27 -0500643 'phosphor-snmp': 'phosphor-snmp',
Brad Bishopebb49112017-02-13 11:07:26 -0500644 },
Matthew Barthccb7f852016-11-23 17:43:02 -0600645 }
646
William A. Kennington IIIe67f5fc2018-12-06 17:40:30 -0800647 # Offset into array of macro parameters MACRO(0, 1, ...N)
648 DEPENDENCIES_OFFSET = {
649 'AC_CHECK_LIB': 0,
650 'AC_CHECK_HEADER': 0,
651 'AC_PATH_PROG': 1,
652 'PKG_CHECK_MODULES': 1,
653 }
654
Leonel Gonzaleza62a1a12017-03-24 11:03:47 -0500655 # DEPENDENCIES_REGEX = [GIT REPO]:[REGEX STRING]
656 DEPENDENCIES_REGEX = {
Patrick Ventured37b8052018-10-16 16:03:03 -0700657 'phosphor-logging': r'\S+-dbus-interfaces$'
Leonel Gonzaleza62a1a12017-03-24 11:03:47 -0500658 }
659
Matthew Barth33df8792016-12-19 14:30:17 -0600660 # Set command line arguments
661 parser = argparse.ArgumentParser()
662 parser.add_argument("-w", "--workspace", dest="WORKSPACE", required=True,
663 help="Workspace directory location(i.e. /home)")
664 parser.add_argument("-p", "--package", dest="PACKAGE", required=True,
665 help="OpenBMC package to be unit tested")
William A. Kennington III65b37fa2019-01-31 15:15:17 -0800666 parser.add_argument("-t", "--test-only", dest="TEST_ONLY",
667 action="store_true", required=False, default=False,
668 help="Only run test cases, no other validation")
Matthew Barth33df8792016-12-19 14:30:17 -0600669 parser.add_argument("-v", "--verbose", action="store_true",
670 help="Print additional package status messages")
Andrew Jeffery468309d2018-03-08 13:46:33 +1030671 parser.add_argument("-r", "--repeat", help="Repeat tests N times",
672 type=int, default=1)
Andrew Geisslera61acb52019-01-03 16:32:44 -0600673 parser.add_argument("-b", "--branch", dest="BRANCH", required=False,
674 help="Branch to target for dependent repositories",
675 default="master")
Matthew Barth33df8792016-12-19 14:30:17 -0600676 args = parser.parse_args(sys.argv[1:])
677 WORKSPACE = args.WORKSPACE
678 UNIT_TEST_PKG = args.PACKAGE
William A. Kennington III65b37fa2019-01-31 15:15:17 -0800679 TEST_ONLY = args.TEST_ONLY
Andrew Geisslera61acb52019-01-03 16:32:44 -0600680 BRANCH = args.BRANCH
Matthew Barth33df8792016-12-19 14:30:17 -0600681 if args.verbose:
682 def printline(*line):
683 for arg in line:
684 print arg,
685 print
686 else:
687 printline = lambda *l: None
Matthew Barthccb7f852016-11-23 17:43:02 -0600688
James Feist878df5c2018-07-26 14:54:28 -0700689 # First validate code formatting if repo has style formatting files.
Adriana Kobylakbcee22b2018-01-10 16:58:27 -0600690 # The format-code.sh checks for these files.
Andrew Geisslera28286d2018-01-10 11:00:00 -0800691 CODE_SCAN_DIR = WORKSPACE + "/" + UNIT_TEST_PKG
William A. Kennington III1fddb972019-02-06 18:03:53 -0800692 check_call_cmd("./format-code.sh", CODE_SCAN_DIR)
Andrew Geisslera28286d2018-01-10 11:00:00 -0800693
William A. Kennington III3f1d1202018-12-06 18:02:07 -0800694 # Automake and meson
695 if (os.path.isfile(CODE_SCAN_DIR + "/configure.ac") or
696 os.path.isfile(CODE_SCAN_DIR + '/meson.build')):
James Feist878df5c2018-07-26 14:54:28 -0700697 prev_umask = os.umask(000)
698 # Determine dependencies and add them
699 dep_added = dict()
700 dep_added[UNIT_TEST_PKG] = False
701 # Create dependency tree
702 dep_tree = DepTree(UNIT_TEST_PKG)
703 build_dep_tree(UNIT_TEST_PKG,
704 os.path.join(WORKSPACE, UNIT_TEST_PKG),
705 dep_added,
Andrew Geisslera61acb52019-01-03 16:32:44 -0600706 dep_tree,
707 BRANCH)
James Feist878df5c2018-07-26 14:54:28 -0700708
709 # Reorder Dependency Tree
710 for pkg_name, regex_str in DEPENDENCIES_REGEX.iteritems():
711 dep_tree.ReorderDeps(pkg_name, regex_str)
712 if args.verbose:
713 dep_tree.PrintTree()
714 install_list = dep_tree.GetInstallList()
William A. Kennington IIId61316d2018-12-06 14:56:12 -0800715 # We don't want to treat our package as a dependency
716 install_list.remove(UNIT_TEST_PKG)
James Feist878df5c2018-07-26 14:54:28 -0700717 # install reordered dependencies
William A. Kennington IIId61316d2018-12-06 14:56:12 -0800718 for dep in install_list:
719 build_and_install(dep, False)
William A. Kennington III90b106a2019-02-06 18:08:24 -0800720 os.chdir(os.path.join(WORKSPACE, UNIT_TEST_PKG))
James Feist878df5c2018-07-26 14:54:28 -0700721 # Run package unit tests
William A. Kennington IIId61316d2018-12-06 14:56:12 -0800722 build_and_install(UNIT_TEST_PKG, True)
William A. Kennington III3f1d1202018-12-06 18:02:07 -0800723 if os.path.isfile(CODE_SCAN_DIR + '/meson.build'):
William A. Kennington III65b37fa2019-01-31 15:15:17 -0800724 if not TEST_ONLY:
725 # Run valgrind if it is supported
726 if is_valgrind_safe():
William A. Kennington III1fddb972019-02-06 18:03:53 -0800727 check_call_cmd('meson', 'test', '-C', 'build',
William A. Kennington III65b37fa2019-01-31 15:15:17 -0800728 '--wrap', 'valgrind')
William A. Kennington III40d5c7c2018-12-13 14:37:59 -0800729
William A. Kennington III65b37fa2019-01-31 15:15:17 -0800730 # Run clang-tidy only if the project has a configuration
731 if os.path.isfile('.clang-tidy'):
William A. Kennington III1fddb972019-02-06 18:03:53 -0800732 check_call_cmd('run-clang-tidy-6.0.py', '-p',
William A. Kennington III65b37fa2019-01-31 15:15:17 -0800733 'build')
734 # Run the basic clang static analyzer otherwise
735 else:
736 os.environ['SCANBUILD'] = 'scan-build-6.0'
William A. Kennington III1fddb972019-02-06 18:03:53 -0800737 check_call_cmd('ninja', '-C', 'build',
William A. Kennington III65b37fa2019-01-31 15:15:17 -0800738 'scan-build')
739
740 # Run tests through sanitizers
741 # b_lundef is needed if clang++ is CXX since it resolves the
742 # asan symbols at runtime only. We don't want to set it earlier
743 # in the build process to ensure we don't have undefined
744 # runtime code.
William A. Kennington III282e3302019-02-04 16:55:05 -0800745 if is_sanitize_safe():
William A. Kennington III1fddb972019-02-06 18:03:53 -0800746 check_call_cmd('meson', 'configure', 'build',
William A. Kennington III282e3302019-02-04 16:55:05 -0800747 '-Db_sanitize=address,undefined',
748 '-Db_lundef=false')
William A. Kennington III1fddb972019-02-06 18:03:53 -0800749 check_call_cmd('meson', 'test', '-C', 'build',
William A. Kennington III282e3302019-02-04 16:55:05 -0800750 '--logbase', 'testlog-ubasan')
751 # TODO: Fix memory sanitizer
William A. Kennington III1fddb972019-02-06 18:03:53 -0800752 #check_call_cmd('meson', 'configure', 'build',
William A. Kennington III282e3302019-02-04 16:55:05 -0800753 # '-Db_sanitize=memory')
William A. Kennington III1fddb972019-02-06 18:03:53 -0800754 #check_call_cmd('meson', 'test', '-C', 'build'
William A. Kennington III282e3302019-02-04 16:55:05 -0800755 # '--logbase', 'testlog-msan')
William A. Kennington III1fddb972019-02-06 18:03:53 -0800756 check_call_cmd('meson', 'configure', 'build',
William A. Kennington III282e3302019-02-04 16:55:05 -0800757 '-Db_sanitize=none', '-Db_lundef=true')
William A. Kennington III65b37fa2019-01-31 15:15:17 -0800758
759 # Run coverage checks
William A. Kennington III1fddb972019-02-06 18:03:53 -0800760 check_call_cmd('meson', 'configure', 'build',
William A. Kennington III65b37fa2019-01-31 15:15:17 -0800761 '-Db_coverage=true')
William A. Kennington III1fddb972019-02-06 18:03:53 -0800762 check_call_cmd('meson', 'test', '-C', 'build')
William A. Kennington III65b37fa2019-01-31 15:15:17 -0800763 # Only build coverage HTML if coverage files were produced
764 for root, dirs, files in os.walk('build'):
765 if any([f.endswith('.gcda') for f in files]):
William A. Kennington III1fddb972019-02-06 18:03:53 -0800766 check_call_cmd('ninja', '-C', 'build',
William A. Kennington III65b37fa2019-01-31 15:15:17 -0800767 'coverage-html')
768 break
William A. Kennington III1fddb972019-02-06 18:03:53 -0800769 check_call_cmd('meson', 'configure', 'build',
William A. Kennington III65b37fa2019-01-31 15:15:17 -0800770 '-Db_coverage=false')
771 else:
William A. Kennington III1fddb972019-02-06 18:03:53 -0800772 check_call_cmd('meson', 'test', '-C', 'build')
William A. Kennington III3f1d1202018-12-06 18:02:07 -0800773 else:
William A. Kennington III90b106a2019-02-06 18:08:24 -0800774 run_unit_tests()
William A. Kennington III65b37fa2019-01-31 15:15:17 -0800775 if not TEST_ONLY:
William A. Kennington IIIeaff24a2019-02-06 16:57:42 -0800776 maybe_make_valgrind()
777 maybe_make_coverage()
William A. Kennington III65b37fa2019-01-31 15:15:17 -0800778 if not TEST_ONLY:
William A. Kennington III90b106a2019-02-06 18:08:24 -0800779 run_cppcheck()
James Feist878df5c2018-07-26 14:54:28 -0700780
781 os.umask(prev_umask)
782
783 # Cmake
784 elif os.path.isfile(CODE_SCAN_DIR + "/CMakeLists.txt"):
William A. Kennington III90b106a2019-02-06 18:08:24 -0800785 os.chdir(os.path.join(WORKSPACE, UNIT_TEST_PKG))
William A. Kennington III1fddb972019-02-06 18:03:53 -0800786 check_call_cmd('cmake', '-DCMAKE_EXPORT_COMPILE_COMMANDS=ON', '.')
787 check_call_cmd('cmake', '--build', '.', '--', '-j',
James Feist878df5c2018-07-26 14:54:28 -0700788 str(multiprocessing.cpu_count()))
789 if make_target_exists('test'):
William A. Kennington III1fddb972019-02-06 18:03:53 -0800790 check_call_cmd('ctest', '.')
William A. Kennington III65b37fa2019-01-31 15:15:17 -0800791 if not TEST_ONLY:
William A. Kennington IIIeaff24a2019-02-06 16:57:42 -0800792 maybe_make_valgrind()
793 maybe_make_coverage()
William A. Kennington III90b106a2019-02-06 18:08:24 -0800794 run_cppcheck()
William A. Kennington III65b37fa2019-01-31 15:15:17 -0800795 if os.path.isfile('.clang-tidy'):
William A. Kennington III1fddb972019-02-06 18:03:53 -0800796 check_call_cmd('run-clang-tidy-6.0.py', '-p', '.')
James Feist878df5c2018-07-26 14:54:28 -0700797
798 else:
Andrew Geissler71a7cc12018-01-31 14:18:37 -0800799 print "Not a supported repo for CI Tests, exit"
800 quit()