test-remote-image 14 KB

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