test-remote-image 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347
  1. #!/usr/bin/env python3
  2. #
  3. # Copyright (c) 2014 Intel Corporation
  4. #
  5. # SPDX-License-Identifier: GPL-2.0-only
  6. #
  7. # DESCRIPTION
  8. # This script is used to test public autobuilder images on remote hardware.
  9. # The script is called from a machine that is able download the images from the remote images repository and to connect to the test hardware.
  10. #
  11. # test-remote-image --image-type core-image-sato --repo-link http://192.168.10.2/images --required-packages rpm psplash
  12. #
  13. # Translation: Build the 'rpm' and 'pslash' packages and test a remote core-image-sato image using the http://192.168.10.2/images repository.
  14. #
  15. # You can also use the '-h' option to see some help information.
  16. import os
  17. import sys
  18. import argparse
  19. import logging
  20. import shutil
  21. from abc import ABCMeta, abstractmethod
  22. # Add path to scripts/lib in sys.path;
  23. scripts_path = os.path.abspath(os.path.dirname(os.path.abspath(sys.argv[0])))
  24. lib_path = scripts_path + '/lib'
  25. sys.path = sys.path + [lib_path]
  26. import scriptpath
  27. import argparse_oe
  28. # Add meta/lib to sys.path
  29. scriptpath.add_oe_lib_path()
  30. import oeqa.utils.ftools as ftools
  31. from oeqa.utils.commands import runCmd, bitbake, get_bb_var
  32. # Add all lib paths relative to BBPATH to sys.path; this is used to find and import the target controllers.
  33. for path in get_bb_var('BBPATH').split(":"):
  34. sys.path.insert(0, os.path.abspath(os.path.join(path, 'lib')))
  35. # In order to import modules that contain target controllers, we need the bitbake libraries in sys.path .
  36. bitbakepath = scriptpath.add_bitbake_lib_path()
  37. if not bitbakepath:
  38. sys.stderr.write("Unable to find bitbake by searching parent directory of this script or PATH\n")
  39. sys.exit(1)
  40. # create a logger
  41. def logger_create():
  42. log = logging.getLogger('hwauto')
  43. log.setLevel(logging.DEBUG)
  44. fh = logging.FileHandler(filename='hwauto.log', mode='w')
  45. fh.setLevel(logging.DEBUG)
  46. ch = logging.StreamHandler(sys.stdout)
  47. ch.setLevel(logging.INFO)
  48. formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
  49. fh.setFormatter(formatter)
  50. ch.setFormatter(formatter)
  51. log.addHandler(fh)
  52. log.addHandler(ch)
  53. return log
  54. # instantiate the logger
  55. log = logger_create()
  56. # Define and return the arguments parser for the script
  57. def get_args_parser():
  58. description = "This script is used to run automated runtime tests using remotely published image files. You should prepare the build environment just like building local images and running the tests."
  59. parser = argparse_oe.ArgumentParser(description=description)
  60. parser.add_argument('--image-types', required=True, action="store", nargs='*', dest="image_types", default=None, help='The image types to test(ex: core-image-minimal).')
  61. parser.add_argument('--repo-link', required=True, action="store", type=str, dest="repo_link", default=None, help='The link to the remote images repository.')
  62. parser.add_argument('--required-packages', required=False, action="store", nargs='*', dest="required_packages", default=None, help='Required packages for the tests. They will be built before the testing begins.')
  63. parser.add_argument('--targetprofile', required=False, action="store", nargs=1, dest="targetprofile", default='AutoTargetProfile', help='The target profile to be used.')
  64. parser.add_argument('--repoprofile', required=False, action="store", nargs=1, dest="repoprofile", default='PublicAB', help='The repo profile to be used.')
  65. parser.add_argument('--skip-download', required=False, action="store_true", dest="skip_download", default=False, help='Skip downloading the images completely. This needs the correct files to be present in the directory specified by the target profile.')
  66. return parser
  67. class BaseTargetProfile(object, metaclass=ABCMeta):
  68. """
  69. This class defines the meta profile for a specific target (MACHINE type + image type).
  70. """
  71. def __init__(self, image_type):
  72. self.image_type = image_type
  73. self.kernel_file = None
  74. self.rootfs_file = None
  75. self.manifest_file = None
  76. self.extra_download_files = [] # Extra files (full name) to be downloaded. They should be situated in repo_link
  77. # This method is used as the standard interface with the target profile classes.
  78. # It returns a dictionary containing a list of files and their meaning/description.
  79. def get_files_dict(self):
  80. files_dict = {}
  81. if self.kernel_file:
  82. files_dict['kernel_file'] = self.kernel_file
  83. else:
  84. log.error('The target profile did not set a kernel file.')
  85. sys.exit(1)
  86. if self.rootfs_file:
  87. files_dict['rootfs_file'] = self.rootfs_file
  88. else:
  89. log.error('The target profile did not set a rootfs file.')
  90. sys.exit(1)
  91. if self.manifest_file:
  92. files_dict['manifest_file'] = self.manifest_file
  93. else:
  94. log.error('The target profile did not set a manifest file.')
  95. sys.exit(1)
  96. for idx, f in enumerate(self.extra_download_files):
  97. files_dict['extra_download_file' + str(idx)] = f
  98. return files_dict
  99. class AutoTargetProfile(BaseTargetProfile):
  100. def __init__(self, image_type):
  101. super(AutoTargetProfile, self).__init__(image_type)
  102. self.image_name = get_bb_var('IMAGE_LINK_NAME', target=image_type)
  103. self.kernel_type = get_bb_var('KERNEL_IMAGETYPE', target=image_type)
  104. self.controller = self.get_controller()
  105. self.set_kernel_file()
  106. self.set_rootfs_file()
  107. self.set_manifest_file()
  108. self.set_extra_download_files()
  109. # Get the controller object that will be used by bitbake.
  110. def get_controller(self):
  111. from oeqa.controllers.testtargetloader import TestTargetLoader
  112. target_controller = get_bb_var('TEST_TARGET')
  113. bbpath = get_bb_var('BBPATH').split(':')
  114. if target_controller == "qemu":
  115. from oeqa.targetcontrol import QemuTarget
  116. controller = QemuTarget
  117. else:
  118. testtargetloader = TestTargetLoader()
  119. controller = testtargetloader.get_controller_module(target_controller, bbpath)
  120. return controller
  121. def set_kernel_file(self):
  122. postconfig = "QA_GET_MACHINE = \"${MACHINE}\""
  123. machine = get_bb_var('QA_GET_MACHINE', postconfig=postconfig)
  124. self.kernel_file = self.kernel_type + '-' + machine + '.bin'
  125. def set_rootfs_file(self):
  126. image_fstypes = get_bb_var('IMAGE_FSTYPES').split(' ')
  127. # Get a matching value between target's IMAGE_FSTYPES and the image fstypes suppoerted by the target controller.
  128. fstype = self.controller.match_image_fstype(d=None, image_fstypes=image_fstypes)
  129. if fstype:
  130. self.rootfs_file = self.image_name + '.' + fstype
  131. else:
  132. log.error("Could not get a compatible image fstype. Check that IMAGE_FSTYPES and the target controller's supported_image_fstypes fileds have common values.")
  133. sys.exit(1)
  134. def set_manifest_file(self):
  135. self.manifest_file = self.image_name + ".manifest"
  136. def set_extra_download_files(self):
  137. self.extra_download_files = self.get_controller_extra_files()
  138. if not self.extra_download_files:
  139. self.extra_download_files = []
  140. def get_controller_extra_files(self):
  141. controller = self.get_controller()
  142. return controller.get_extra_files()
  143. class BaseRepoProfile(object, metaclass=ABCMeta):
  144. """
  145. This class defines the meta profile for an images repository.
  146. """
  147. def __init__(self, repolink, localdir):
  148. self.localdir = localdir
  149. self.repolink = repolink
  150. # The following abstract methods are the interfaces to the repository profile classes derived from this abstract class.
  151. # This method should check the file named 'file_name' if it is different than the upstream one.
  152. # Should return False if the image is the same as the upstream and True if it differs.
  153. @abstractmethod
  154. def check_old_file(self, file_name):
  155. pass
  156. # This method should fetch file_name and create a symlink to localname if set.
  157. @abstractmethod
  158. def fetch(self, file_name, localname=None):
  159. pass
  160. class PublicAB(BaseRepoProfile):
  161. def __init__(self, repolink, localdir=None):
  162. super(PublicAB, self).__init__(repolink, localdir)
  163. if localdir is None:
  164. self.localdir = os.path.join(os.environ['BUILDDIR'], 'PublicABMirror')
  165. # Not yet implemented. Always returning True.
  166. def check_old_file(self, file_name):
  167. return True
  168. def get_repo_path(self):
  169. path = '/machines/'
  170. postconfig = "QA_GET_MACHINE = \"${MACHINE}\""
  171. machine = get_bb_var('QA_GET_MACHINE', postconfig=postconfig)
  172. if 'qemu' in machine:
  173. path += 'qemu/'
  174. postconfig = "QA_GET_DISTRO = \"${DISTRO}\""
  175. distro = get_bb_var('QA_GET_DISTRO', postconfig=postconfig)
  176. path += distro.replace('poky', machine) + '/'
  177. return path
  178. def fetch(self, file_name, localname=None):
  179. repo_path = self.get_repo_path()
  180. link = self.repolink + repo_path + file_name
  181. self.wget(link, self.localdir, localname)
  182. def wget(self, link, localdir, localname=None, extraargs=None):
  183. wget_cmd = '/usr/bin/env wget -t 2 -T 30 -nv --passive-ftp --no-check-certificate '
  184. if localname:
  185. wget_cmd += ' -O ' + localname + ' '
  186. if extraargs:
  187. wget_cmd += ' ' + extraargs + ' '
  188. wget_cmd += " -P %s '%s'" % (localdir, link)
  189. runCmd(wget_cmd)
  190. class HwAuto():
  191. def __init__(self, image_types, repolink, required_packages, targetprofile, repoprofile, skip_download):
  192. log.info('Initializing..')
  193. self.image_types = image_types
  194. self.repolink = repolink
  195. self.required_packages = required_packages
  196. self.targetprofile = targetprofile
  197. self.repoprofile = repoprofile
  198. self.skip_download = skip_download
  199. self.repo = self.get_repo_profile(self.repolink)
  200. # Get the repository profile; for now we only look inside this module.
  201. def get_repo_profile(self, *args, **kwargs):
  202. repo = getattr(sys.modules[__name__], self.repoprofile)(*args, **kwargs)
  203. log.info("Using repo profile: %s" % repo.__class__.__name__)
  204. return repo
  205. # Get the target profile; for now we only look inside this module.
  206. def get_target_profile(self, *args, **kwargs):
  207. target = getattr(sys.modules[__name__], self.targetprofile)(*args, **kwargs)
  208. log.info("Using target profile: %s" % target.__class__.__name__)
  209. return target
  210. # Run the testimage task on a build while redirecting DEPLOY_DIR_IMAGE to repo.localdir, where the images are downloaded.
  211. def runTestimageBuild(self, image_type):
  212. log.info("Running the runtime tests for %s.." % image_type)
  213. postconfig = "DEPLOY_DIR_IMAGE = \"%s\"" % self.repo.localdir
  214. result = bitbake("%s -c testimage" % image_type, ignore_status=True, postconfig=postconfig)
  215. testimage_results = ftools.read_file(os.path.join(get_bb_var("T", image_type), "log.do_testimage"))
  216. log.info('Runtime tests results for %s:' % image_type)
  217. print(testimage_results)
  218. return result
  219. # Start the procedure!
  220. def run(self):
  221. if self.required_packages:
  222. # Build the required packages for the tests
  223. log.info("Building the required packages: %s ." % ', '.join(map(str, self.required_packages)))
  224. result = bitbake(self.required_packages, ignore_status=True)
  225. if result.status != 0:
  226. log.error("Could not build required packages: %s. Output: %s" % (self.required_packages, result.output))
  227. sys.exit(1)
  228. # Build the package repository meta data.
  229. log.info("Building the package index.")
  230. result = bitbake("package-index", ignore_status=True)
  231. if result.status != 0:
  232. log.error("Could not build 'package-index'. Output: %s" % result.output)
  233. sys.exit(1)
  234. # Create the directory structure for the images to be downloaded
  235. log.info("Creating directory structure %s" % self.repo.localdir)
  236. if not os.path.exists(self.repo.localdir):
  237. os.makedirs(self.repo.localdir)
  238. # For each image type, download the needed files and run the tests.
  239. noissuesfound = True
  240. for image_type in self.image_types:
  241. if self.skip_download:
  242. log.info("Skipping downloading the images..")
  243. else:
  244. target = self.get_target_profile(image_type)
  245. files_dict = target.get_files_dict()
  246. log.info("Downloading files for %s" % image_type)
  247. for f in files_dict:
  248. if self.repo.check_old_file(files_dict[f]):
  249. filepath = os.path.join(self.repo.localdir, files_dict[f])
  250. if os.path.exists(filepath):
  251. os.remove(filepath)
  252. self.repo.fetch(files_dict[f])
  253. result = self.runTestimageBuild(image_type)
  254. if result.status != 0:
  255. noissuesfound = False
  256. if noissuesfound:
  257. log.info('Finished. No issues found.')
  258. else:
  259. log.error('Finished. Some runtime tests have failed. Returning non-0 status code.')
  260. sys.exit(1)
  261. def main():
  262. parser = get_args_parser()
  263. args = parser.parse_args()
  264. hwauto = HwAuto(image_types=args.image_types, repolink=args.repo_link, required_packages=args.required_packages, targetprofile=args.targetprofile, repoprofile=args.repoprofile, skip_download=args.skip_download)
  265. hwauto.run()
  266. if __name__ == "__main__":
  267. try:
  268. ret = main()
  269. except Exception:
  270. ret = 1
  271. import traceback
  272. traceback.print_exc()
  273. sys.exit(ret)