context.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445
  1. #
  2. # Copyright (C) 2017 Intel Corporation
  3. #
  4. # SPDX-License-Identifier: MIT
  5. #
  6. import os
  7. import time
  8. import glob
  9. import sys
  10. import importlib
  11. import subprocess
  12. import unittest
  13. from random import choice
  14. import oeqa
  15. import oe
  16. import bb.utils
  17. import bb.tinfoil
  18. from oeqa.core.context import OETestContext, OETestContextExecutor
  19. from oeqa.core.exception import OEQAPreRun, OEQATestNotFound
  20. from oeqa.utils.commands import runCmd, get_bb_vars, get_test_layer
  21. OESELFTEST_METADATA=["run_all_tests", "run_tests", "skips", "machine", "select_tags", "exclude_tags"]
  22. def get_oeselftest_metadata(args):
  23. result = {}
  24. raw_args = vars(args)
  25. for metadata in OESELFTEST_METADATA:
  26. if metadata in raw_args:
  27. result[metadata] = raw_args[metadata]
  28. return result
  29. class NonConcurrentTestSuite(unittest.TestSuite):
  30. def __init__(self, suite, processes, setupfunc, removefunc):
  31. super().__init__([suite])
  32. self.processes = processes
  33. self.suite = suite
  34. self.setupfunc = setupfunc
  35. self.removefunc = removefunc
  36. def run(self, result):
  37. (builddir, newbuilddir) = self.setupfunc("-st", None, self.suite)
  38. ret = super().run(result)
  39. os.chdir(builddir)
  40. if newbuilddir and ret.wasSuccessful() and self.removefunc:
  41. self.removefunc(newbuilddir)
  42. def removebuilddir(d):
  43. delay = 5
  44. while delay and (os.path.exists(d + "/bitbake.lock") or os.path.exists(d + "/cache/hashserv.db-wal")):
  45. time.sleep(1)
  46. delay = delay - 1
  47. # Deleting these directories takes a lot of time, use autobuilder
  48. # clobberdir if its available
  49. clobberdir = os.path.expanduser("~/yocto-autobuilder-helper/janitor/clobberdir")
  50. if os.path.exists(clobberdir):
  51. try:
  52. subprocess.check_call([clobberdir, d])
  53. return
  54. except subprocess.CalledProcessError:
  55. pass
  56. bb.utils.prunedir(d, ionice=True)
  57. class OESelftestTestContext(OETestContext):
  58. def __init__(self, td=None, logger=None, machines=None, config_paths=None, newbuilddir=None, keep_builddir=None):
  59. super(OESelftestTestContext, self).__init__(td, logger)
  60. self.machines = machines
  61. self.custommachine = None
  62. self.config_paths = config_paths
  63. self.newbuilddir = newbuilddir
  64. if keep_builddir:
  65. self.removebuilddir = None
  66. else:
  67. self.removebuilddir = removebuilddir
  68. def setup_builddir(self, suffix, selftestdir, suite):
  69. # Get SSTATE_DIR from the parent build dir
  70. with bb.tinfoil.Tinfoil(tracking=True) as tinfoil:
  71. tinfoil.prepare(quiet=2, config_only=True)
  72. d = tinfoil.config_data
  73. sstatedir = str(d.getVar('SSTATE_DIR'))
  74. builddir = os.environ['BUILDDIR']
  75. if not selftestdir:
  76. selftestdir = get_test_layer()
  77. if self.newbuilddir:
  78. newbuilddir = os.path.join(self.newbuilddir, 'build' + suffix)
  79. else:
  80. newbuilddir = builddir + suffix
  81. newselftestdir = newbuilddir + "/meta-selftest"
  82. if os.path.exists(newbuilddir):
  83. self.logger.error("Build directory %s already exists, aborting" % newbuilddir)
  84. sys.exit(1)
  85. bb.utils.mkdirhier(newbuilddir)
  86. oe.path.copytree(builddir + "/conf", newbuilddir + "/conf")
  87. oe.path.copytree(builddir + "/cache", newbuilddir + "/cache")
  88. oe.path.copytree(selftestdir, newselftestdir)
  89. subprocess.check_output("git init; git add *; git commit -a -m 'initial'", cwd=newselftestdir, shell=True)
  90. # Tried to used bitbake-layers add/remove but it requires recipe parsing and hence is too slow
  91. subprocess.check_output("sed %s/conf/bblayers.conf -i -e 's#%s#%s#g'" % (newbuilddir, selftestdir, newselftestdir), cwd=newbuilddir, shell=True)
  92. # Relative paths in BBLAYERS only works when the new build dir share the same ascending node
  93. if self.newbuilddir:
  94. bblayers = subprocess.check_output("bitbake-getvar --value BBLAYERS | tail -1", cwd=builddir, shell=True, text=True)
  95. if '..' in bblayers:
  96. bblayers_abspath = [os.path.abspath(path) for path in bblayers.split()]
  97. with open("%s/conf/bblayers.conf" % newbuilddir, "a") as f:
  98. newbblayers = "# new bblayers to be used by selftest in the new build dir '%s'\n" % newbuilddir
  99. newbblayers += 'BBLAYERS = "%s"\n' % ' '.join(bblayers_abspath)
  100. f.write(newbblayers)
  101. for e in os.environ:
  102. if builddir + "/" in os.environ[e]:
  103. os.environ[e] = os.environ[e].replace(builddir + "/", newbuilddir + "/")
  104. if os.environ[e].endswith(builddir):
  105. os.environ[e] = os.environ[e].replace(builddir, newbuilddir)
  106. # Set SSTATE_DIR to match the parent SSTATE_DIR
  107. subprocess.check_output("echo 'SSTATE_DIR ?= \"%s\"' >> %s/conf/local.conf" % (sstatedir, newbuilddir), cwd=newbuilddir, shell=True)
  108. os.chdir(newbuilddir)
  109. def patch_test(t):
  110. if not hasattr(t, "tc"):
  111. return
  112. cp = t.tc.config_paths
  113. for p in cp:
  114. if selftestdir in cp[p] and newselftestdir not in cp[p]:
  115. cp[p] = cp[p].replace(selftestdir, newselftestdir)
  116. if builddir in cp[p] and newbuilddir not in cp[p]:
  117. cp[p] = cp[p].replace(builddir, newbuilddir)
  118. def patch_suite(s):
  119. for x in s:
  120. if isinstance(x, unittest.TestSuite):
  121. patch_suite(x)
  122. else:
  123. patch_test(x)
  124. patch_suite(suite)
  125. return (builddir, newbuilddir)
  126. def prepareSuite(self, suites, processes):
  127. if processes:
  128. from oeqa.core.utils.concurrencytest import ConcurrentTestSuite
  129. return ConcurrentTestSuite(suites, processes, self.setup_builddir, self.removebuilddir)
  130. else:
  131. return NonConcurrentTestSuite(suites, processes, self.setup_builddir, self.removebuilddir)
  132. def runTests(self, processes=None, machine=None, skips=[]):
  133. if machine:
  134. self.custommachine = machine
  135. if machine == 'random':
  136. self.custommachine = choice(self.machines)
  137. self.logger.info('Run tests with custom MACHINE set to: %s' % \
  138. self.custommachine)
  139. return super(OESelftestTestContext, self).runTests(processes, skips)
  140. def listTests(self, display_type, machine=None):
  141. return super(OESelftestTestContext, self).listTests(display_type)
  142. class OESelftestTestContextExecutor(OETestContextExecutor):
  143. _context_class = OESelftestTestContext
  144. _script_executor = 'oe-selftest'
  145. name = 'oe-selftest'
  146. help = 'oe-selftest test component'
  147. description = 'Executes selftest tests'
  148. def register_commands(self, logger, parser):
  149. group = parser.add_mutually_exclusive_group(required=True)
  150. group.add_argument('-a', '--run-all-tests', default=False,
  151. action="store_true", dest="run_all_tests",
  152. help='Run all (unhidden) tests')
  153. group.add_argument('-r', '--run-tests', required=False, action='store',
  154. nargs='+', dest="run_tests", default=None,
  155. help='Select what tests to run (modules, classes or test methods). Format should be: <module>.<class>.<test_method>')
  156. group.add_argument('-m', '--list-modules', required=False,
  157. action="store_true", default=False,
  158. help='List all available test modules.')
  159. group.add_argument('--list-classes', required=False,
  160. action="store_true", default=False,
  161. help='List all available test classes.')
  162. group.add_argument('-l', '--list-tests', required=False,
  163. action="store_true", default=False,
  164. help='List all available tests.')
  165. parser.add_argument('-R', '--skip-tests', required=False, action='store',
  166. nargs='+', dest="skips", default=None,
  167. help='Skip the tests specified. Format should be <module>[.<class>[.<test_method>]]')
  168. parser.add_argument('-j', '--num-processes', dest='processes', action='store',
  169. type=int, help="number of processes to execute in parallel with")
  170. parser.add_argument('--machine', required=False, choices=['random', 'all'],
  171. help='Run tests on different machines (random/all).')
  172. parser.add_argument('-t', '--select-tag', dest="select_tags",
  173. action='append', default=None,
  174. help='Filter all (unhidden) tests to any that match any of the specified tag(s).')
  175. parser.add_argument('-T', '--exclude-tag', dest="exclude_tags",
  176. action='append', default=None,
  177. help='Exclude all (unhidden) tests that match any of the specified tag(s). (exclude applies before select)')
  178. parser.add_argument('-K', '--keep-builddir', action='store_true',
  179. help='Keep the test build directory even if all tests pass')
  180. parser.add_argument('-B', '--newbuilddir', help='New build directory to use for tests.')
  181. parser.add_argument('-v', '--verbose', action='store_true')
  182. parser.set_defaults(func=self.run)
  183. def _get_available_machines(self):
  184. machines = []
  185. bbpath = self.tc_kwargs['init']['td']['BBPATH'].split(':')
  186. for path in bbpath:
  187. found_machines = glob.glob(os.path.join(path, 'conf', 'machine', '*.conf'))
  188. if found_machines:
  189. for i in found_machines:
  190. # eg: '/home/<user>/poky/meta-intel/conf/machine/intel-core2-32.conf'
  191. machines.append(os.path.splitext(os.path.basename(i))[0])
  192. return machines
  193. def _get_cases_paths(self, bbpath):
  194. cases_paths = []
  195. for layer in bbpath:
  196. cases_dir = os.path.join(layer, 'lib', 'oeqa', 'selftest', 'cases')
  197. if os.path.isdir(cases_dir):
  198. cases_paths.append(cases_dir)
  199. return cases_paths
  200. def _process_args(self, logger, args):
  201. args.test_start_time = time.strftime("%Y%m%d%H%M%S")
  202. args.test_data_file = None
  203. args.CASES_PATHS = None
  204. bbvars = get_bb_vars()
  205. logdir = os.environ.get("BUILDDIR")
  206. if 'LOG_DIR' in bbvars:
  207. logdir = bbvars['LOG_DIR']
  208. bb.utils.mkdirhier(logdir)
  209. args.output_log = logdir + '/%s-results-%s.log' % (self.name, args.test_start_time)
  210. super(OESelftestTestContextExecutor, self)._process_args(logger, args)
  211. if args.list_modules:
  212. args.list_tests = 'module'
  213. elif args.list_classes:
  214. args.list_tests = 'class'
  215. elif args.list_tests:
  216. args.list_tests = 'name'
  217. self.tc_kwargs['init']['td'] = bbvars
  218. self.tc_kwargs['init']['machines'] = self._get_available_machines()
  219. builddir = os.environ.get("BUILDDIR")
  220. self.tc_kwargs['init']['config_paths'] = {}
  221. self.tc_kwargs['init']['config_paths']['testlayer_path'] = get_test_layer()
  222. self.tc_kwargs['init']['config_paths']['builddir'] = builddir
  223. self.tc_kwargs['init']['config_paths']['localconf'] = os.path.join(builddir, "conf/local.conf")
  224. self.tc_kwargs['init']['config_paths']['bblayers'] = os.path.join(builddir, "conf/bblayers.conf")
  225. self.tc_kwargs['init']['newbuilddir'] = args.newbuilddir
  226. self.tc_kwargs['init']['keep_builddir'] = args.keep_builddir
  227. def tag_filter(tags):
  228. if args.exclude_tags:
  229. if any(tag in args.exclude_tags for tag in tags):
  230. return True
  231. if args.select_tags:
  232. if not tags or not any(tag in args.select_tags for tag in tags):
  233. return True
  234. return False
  235. if args.select_tags or args.exclude_tags:
  236. self.tc_kwargs['load']['tags_filter'] = tag_filter
  237. self.tc_kwargs['run']['skips'] = args.skips
  238. self.tc_kwargs['run']['processes'] = args.processes
  239. def _pre_run(self):
  240. def _check_required_env_variables(vars):
  241. for var in vars:
  242. if not os.environ.get(var):
  243. self.tc.logger.error("%s is not set. Did you forget to source your build environment setup script?" % var)
  244. raise OEQAPreRun
  245. def _check_presence_meta_selftest():
  246. builddir = os.environ.get("BUILDDIR")
  247. if os.getcwd() != builddir:
  248. self.tc.logger.info("Changing cwd to %s" % builddir)
  249. os.chdir(builddir)
  250. if not "meta-selftest" in self.tc.td["BBLAYERS"]:
  251. self.tc.logger.info("meta-selftest layer not found in BBLAYERS, adding it")
  252. meta_selftestdir = os.path.join(
  253. self.tc.td["BBLAYERS_FETCH_DIR"], 'meta-selftest')
  254. if os.path.isdir(meta_selftestdir):
  255. runCmd("bitbake-layers add-layer %s" %meta_selftestdir)
  256. # reload data is needed because a meta-selftest layer was add
  257. self.tc.td = get_bb_vars()
  258. self.tc.config_paths['testlayer_path'] = get_test_layer()
  259. else:
  260. self.tc.logger.error("could not locate meta-selftest in:\n%s" % meta_selftestdir)
  261. raise OEQAPreRun
  262. def _add_layer_libs():
  263. bbpath = self.tc.td['BBPATH'].split(':')
  264. layer_libdirs = [p for p in (os.path.join(l, 'lib') \
  265. for l in bbpath) if os.path.exists(p)]
  266. if layer_libdirs:
  267. self.tc.logger.info("Adding layer libraries:")
  268. for l in layer_libdirs:
  269. self.tc.logger.info("\t%s" % l)
  270. sys.path.extend(layer_libdirs)
  271. importlib.reload(oeqa.selftest)
  272. _check_required_env_variables(["BUILDDIR"])
  273. _check_presence_meta_selftest()
  274. if "buildhistory.bbclass" in self.tc.td["BBINCLUDED"]:
  275. self.tc.logger.error("You have buildhistory enabled already and this isn't recommended for selftest, please disable it first.")
  276. raise OEQAPreRun
  277. if "rm_work.bbclass" in self.tc.td["BBINCLUDED"]:
  278. self.tc.logger.error("You have rm_work enabled which isn't recommended while running oe-selftest. Please disable it before continuing.")
  279. raise OEQAPreRun
  280. if "PRSERV_HOST" in self.tc.td:
  281. self.tc.logger.error("Please unset PRSERV_HOST in order to run oe-selftest")
  282. raise OEQAPreRun
  283. if "SANITY_TESTED_DISTROS" in self.tc.td:
  284. self.tc.logger.error("Please unset SANITY_TESTED_DISTROS in order to run oe-selftest")
  285. raise OEQAPreRun
  286. _add_layer_libs()
  287. self.tc.logger.info("Running bitbake -e to test the configuration is valid/parsable")
  288. runCmd("bitbake -e")
  289. def get_json_result_dir(self, args):
  290. json_result_dir = os.path.join(self.tc.td["LOG_DIR"], 'oeqa')
  291. if "OEQA_JSON_RESULT_DIR" in self.tc.td:
  292. json_result_dir = self.tc.td["OEQA_JSON_RESULT_DIR"]
  293. return json_result_dir
  294. def get_configuration(self, args):
  295. import platform
  296. from oeqa.utils.metadata import metadata_from_bb
  297. metadata = metadata_from_bb()
  298. oeselftest_metadata = get_oeselftest_metadata(args)
  299. configuration = {'TEST_TYPE': 'oeselftest',
  300. 'STARTTIME': args.test_start_time,
  301. 'MACHINE': self.tc.td["MACHINE"],
  302. 'HOST_DISTRO': oe.lsb.distro_identifier().replace(' ', '-'),
  303. 'HOST_NAME': metadata['hostname'],
  304. 'LAYERS': metadata['layers'],
  305. 'OESELFTEST_METADATA': oeselftest_metadata}
  306. return configuration
  307. def get_result_id(self, configuration):
  308. return '%s_%s_%s_%s' % (configuration['TEST_TYPE'], configuration['HOST_DISTRO'], configuration['MACHINE'], configuration['STARTTIME'])
  309. def _internal_run(self, logger, args):
  310. self.module_paths = self._get_cases_paths(
  311. self.tc_kwargs['init']['td']['BBPATH'].split(':'))
  312. self.tc = self._context_class(**self.tc_kwargs['init'])
  313. try:
  314. self.tc.loadTests(self.module_paths, **self.tc_kwargs['load'])
  315. except OEQATestNotFound as ex:
  316. logger.error(ex)
  317. sys.exit(1)
  318. if args.list_tests:
  319. rc = self.tc.listTests(args.list_tests, **self.tc_kwargs['list'])
  320. else:
  321. self._pre_run()
  322. rc = self.tc.runTests(**self.tc_kwargs['run'])
  323. configuration = self.get_configuration(args)
  324. rc.logDetails(self.get_json_result_dir(args),
  325. configuration,
  326. self.get_result_id(configuration))
  327. rc.logSummary(self.name)
  328. return rc
  329. def run(self, logger, args):
  330. self._process_args(logger, args)
  331. rc = None
  332. try:
  333. if args.machine:
  334. logger.info('Custom machine mode enabled. MACHINE set to %s' %
  335. args.machine)
  336. if args.machine == 'all':
  337. results = []
  338. for m in self.tc_kwargs['init']['machines']:
  339. self.tc_kwargs['run']['machine'] = m
  340. results.append(self._internal_run(logger, args))
  341. # XXX: the oe-selftest script only needs to know if one
  342. # machine run fails
  343. for r in results:
  344. rc = r
  345. if not r.wasSuccessful():
  346. break
  347. else:
  348. self.tc_kwargs['run']['machine'] = args.machine
  349. return self._internal_run(logger, args)
  350. else:
  351. self.tc_kwargs['run']['machine'] = args.machine
  352. rc = self._internal_run(logger, args)
  353. finally:
  354. config_paths = self.tc_kwargs['init']['config_paths']
  355. output_link = os.path.join(os.path.dirname(args.output_log),
  356. "%s-results.log" % self.name)
  357. if os.path.lexists(output_link):
  358. os.remove(output_link)
  359. os.symlink(args.output_log, output_link)
  360. return rc
  361. _executor_class = OESelftestTestContextExecutor