IDFApp.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461
  1. # Copyright 2015-2017 Espressif Systems (Shanghai) PTE LTD
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http:#www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. """ IDF Test Applications """
  15. import subprocess
  16. import hashlib
  17. import json
  18. import os
  19. import sys
  20. from tiny_test_fw import App
  21. from . import CIAssignExampleTest
  22. try:
  23. import gitlab_api
  24. except ImportError:
  25. gitlab_api = None
  26. def parse_flash_settings(path):
  27. file_name = os.path.basename(path)
  28. if file_name == "flasher_args.json":
  29. # CMake version using build metadata file
  30. with open(path, "r") as f:
  31. args = json.load(f)
  32. flash_files = [(offs, binary) for (offs, binary) in args["flash_files"].items() if offs != ""]
  33. flash_settings = args["flash_settings"]
  34. app_name = os.path.splitext(args["app"]["file"])[0]
  35. else:
  36. # GNU Make version uses download.config arguments file
  37. with open(path, "r") as f:
  38. args = f.readlines()[-1].split(" ")
  39. flash_files = []
  40. flash_settings = {}
  41. for idx in range(0, len(args), 2): # process arguments in pairs
  42. if args[idx].startswith("--"):
  43. # strip the -- from the command line argument
  44. flash_settings[args[idx][2:]] = args[idx + 1]
  45. else:
  46. # offs, filename
  47. flash_files.append((args[idx], args[idx + 1]))
  48. # we can only guess app name in download.config.
  49. for p in flash_files:
  50. if not os.path.dirname(p[1]) and "partition" not in p[1]:
  51. # app bin usually in the same dir with download.config and it's not partition table
  52. app_name = os.path.splitext(p[1])[0]
  53. break
  54. else:
  55. app_name = None
  56. return flash_files, flash_settings, app_name
  57. class Artifacts(object):
  58. def __init__(self, dest_root_path, artifact_index_file, app_path, config_name, target):
  59. assert gitlab_api
  60. # at least one of app_path or config_name is not None. otherwise we can't match artifact
  61. assert app_path or config_name
  62. assert os.path.exists(artifact_index_file)
  63. self.gitlab_inst = gitlab_api.Gitlab(os.getenv("CI_PROJECT_ID"))
  64. self.dest_root_path = dest_root_path
  65. with open(artifact_index_file, "r") as f:
  66. artifact_index = json.load(f)
  67. self.artifact_info = self._find_artifact(artifact_index, app_path, config_name, target)
  68. @staticmethod
  69. def _find_artifact(artifact_index, app_path, config_name, target):
  70. for artifact_info in artifact_index:
  71. match_result = True
  72. if app_path:
  73. match_result = app_path in artifact_info["app_dir"]
  74. if config_name:
  75. match_result = match_result and config_name == artifact_info["config"]
  76. if target:
  77. match_result = match_result and target == artifact_info["target"]
  78. if match_result:
  79. ret = artifact_info
  80. break
  81. else:
  82. ret = None
  83. return ret
  84. def download_artifacts(self):
  85. if self.artifact_info:
  86. base_path = os.path.join(self.artifact_info["work_dir"], self.artifact_info["build_dir"])
  87. job_id = self.artifact_info["ci_job_id"]
  88. # 1. download flash args file
  89. if self.artifact_info["build_system"] == "cmake":
  90. flash_arg_file = os.path.join(base_path, "flasher_args.json")
  91. else:
  92. flash_arg_file = os.path.join(base_path, "download.config")
  93. self.gitlab_inst.download_artifact(job_id, [flash_arg_file], self.dest_root_path)
  94. # 2. download all binary files
  95. flash_files, flash_settings, app_name = parse_flash_settings(os.path.join(self.dest_root_path,
  96. flash_arg_file))
  97. artifact_files = [os.path.join(base_path, p[1]) for p in flash_files]
  98. artifact_files.append(os.path.join(base_path, app_name + ".elf"))
  99. self.gitlab_inst.download_artifact(job_id, artifact_files, self.dest_root_path)
  100. # 3. download sdkconfig file
  101. self.gitlab_inst.download_artifact(job_id, [os.path.join(os.path.dirname(base_path), "sdkconfig")],
  102. self.dest_root_path)
  103. else:
  104. base_path = None
  105. return base_path
  106. def download_artifact_files(self, file_names):
  107. if self.artifact_info:
  108. base_path = os.path.join(self.artifact_info["work_dir"], self.artifact_info["build_dir"])
  109. job_id = self.artifact_info["ci_job_id"]
  110. # download all binary files
  111. artifact_files = [os.path.join(base_path, fn) for fn in file_names]
  112. self.gitlab_inst.download_artifact(job_id, artifact_files, self.dest_root_path)
  113. # download sdkconfig file
  114. self.gitlab_inst.download_artifact(job_id, [os.path.join(os.path.dirname(base_path), "sdkconfig")],
  115. self.dest_root_path)
  116. else:
  117. base_path = None
  118. return base_path
  119. class IDFApp(App.BaseApp):
  120. """
  121. Implements common esp-idf application behavior.
  122. idf applications should inherent from this class and overwrite method get_binary_path.
  123. """
  124. IDF_DOWNLOAD_CONFIG_FILE = "download.config"
  125. IDF_FLASH_ARGS_FILE = "flasher_args.json"
  126. def __init__(self, app_path, config_name=None, target=None):
  127. super(IDFApp, self).__init__(app_path)
  128. self.config_name = config_name
  129. self.target = target
  130. self.idf_path = self.get_sdk_path()
  131. self.binary_path = self.get_binary_path(app_path, config_name, target)
  132. self.elf_file = self._get_elf_file_path(self.binary_path)
  133. self._elf_file_sha256 = None
  134. assert os.path.exists(self.binary_path)
  135. if self.IDF_DOWNLOAD_CONFIG_FILE not in os.listdir(self.binary_path):
  136. if self.IDF_FLASH_ARGS_FILE not in os.listdir(self.binary_path):
  137. msg = ("Neither {} nor {} exists. "
  138. "Try to run 'make print_flash_cmd | tail -n 1 > {}/{}' "
  139. "or 'idf.py build' "
  140. "for resolving the issue."
  141. "").format(self.IDF_DOWNLOAD_CONFIG_FILE, self.IDF_FLASH_ARGS_FILE,
  142. self.binary_path, self.IDF_DOWNLOAD_CONFIG_FILE)
  143. raise AssertionError(msg)
  144. self.flash_files, self.flash_settings = self._parse_flash_download_config()
  145. self.partition_table = self._parse_partition_table()
  146. @classmethod
  147. def get_sdk_path(cls):
  148. # type: () -> str
  149. idf_path = os.getenv("IDF_PATH")
  150. assert idf_path
  151. assert os.path.exists(idf_path)
  152. return idf_path
  153. def _get_sdkconfig_paths(self):
  154. """
  155. returns list of possible paths where sdkconfig could be found
  156. Note: could be overwritten by a derived class to provide other locations or order
  157. """
  158. return [os.path.join(self.binary_path, "sdkconfig"), os.path.join(self.binary_path, "..", "sdkconfig")]
  159. def get_sdkconfig(self):
  160. """
  161. reads sdkconfig and returns a dictionary with all configuredvariables
  162. :raise: AssertionError: if sdkconfig file does not exist in defined paths
  163. """
  164. d = {}
  165. sdkconfig_file = None
  166. for i in self._get_sdkconfig_paths():
  167. if os.path.exists(i):
  168. sdkconfig_file = i
  169. break
  170. assert sdkconfig_file is not None
  171. with open(sdkconfig_file) as f:
  172. for line in f:
  173. configs = line.split('=')
  174. if len(configs) == 2:
  175. d[configs[0]] = configs[1].rstrip()
  176. return d
  177. def get_binary_path(self, app_path, config_name=None, target=None):
  178. # type: (str, str, str) -> str
  179. """
  180. get binary path according to input app_path.
  181. subclass must overwrite this method.
  182. :param app_path: path of application
  183. :param config_name: name of the application build config. Will match any config if None
  184. :param target: target name. Will match for target if None
  185. :return: abs app binary path
  186. """
  187. pass
  188. @staticmethod
  189. def _get_elf_file_path(binary_path):
  190. ret = ""
  191. file_names = os.listdir(binary_path)
  192. for fn in file_names:
  193. if os.path.splitext(fn)[1] == ".elf":
  194. ret = os.path.join(binary_path, fn)
  195. return ret
  196. def _parse_flash_download_config(self):
  197. """
  198. Parse flash download config from build metadata files
  199. Sets self.flash_files, self.flash_settings
  200. (Called from constructor)
  201. Returns (flash_files, flash_settings)
  202. """
  203. if self.IDF_FLASH_ARGS_FILE in os.listdir(self.binary_path):
  204. # CMake version using build metadata file
  205. path = os.path.join(self.binary_path, self.IDF_FLASH_ARGS_FILE)
  206. else:
  207. # GNU Make version uses download.config arguments file
  208. path = os.path.join(self.binary_path, self.IDF_DOWNLOAD_CONFIG_FILE)
  209. flash_files, flash_settings, app_name = parse_flash_settings(path)
  210. # The build metadata file does not currently have details, which files should be encrypted and which not.
  211. # Assume that all files should be encrypted if flash encryption is enabled in development mode.
  212. sdkconfig_dict = self.get_sdkconfig()
  213. flash_settings["encrypt"] = "CONFIG_SECURE_FLASH_ENCRYPTION_MODE_DEVELOPMENT" in sdkconfig_dict
  214. # make file offsets into integers, make paths absolute
  215. flash_files = [(int(offs, 0), os.path.join(self.binary_path, file_path.strip())) for (offs, file_path) in flash_files]
  216. return flash_files, flash_settings
  217. def _parse_partition_table(self):
  218. """
  219. Parse partition table contents based on app binaries
  220. Returns partition_table data
  221. (Called from constructor)
  222. """
  223. partition_tool = os.path.join(self.idf_path,
  224. "components",
  225. "partition_table",
  226. "gen_esp32part.py")
  227. assert os.path.exists(partition_tool)
  228. errors = []
  229. # self.flash_files is sorted based on offset in order to have a consistent result with different versions of
  230. # Python
  231. for (_, path) in sorted(self.flash_files, key=lambda elem: elem[0]):
  232. if 'partition' in os.path.split(path)[1]:
  233. partition_file = os.path.join(self.binary_path, path)
  234. process = subprocess.Popen([sys.executable, partition_tool, partition_file],
  235. stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  236. (raw_data, raw_error) = process.communicate()
  237. if isinstance(raw_error, bytes):
  238. raw_error = raw_error.decode()
  239. if 'Traceback' in raw_error:
  240. # Some exception occured. It is possible that we've tried the wrong binary file.
  241. errors.append((path, raw_error))
  242. continue
  243. if isinstance(raw_data, bytes):
  244. raw_data = raw_data.decode()
  245. break
  246. else:
  247. traceback_msg = os.linesep.join(['{} {}:{}{}'.format(partition_tool,
  248. p,
  249. os.linesep,
  250. msg) for p, msg in errors])
  251. raise ValueError("No partition table found for IDF binary path: {}{}{}".format(self.binary_path,
  252. os.linesep,
  253. traceback_msg))
  254. partition_table = dict()
  255. for line in raw_data.splitlines():
  256. if line[0] != "#":
  257. try:
  258. _name, _type, _subtype, _offset, _size, _flags = line.split(",")
  259. if _size[-1] == "K":
  260. _size = int(_size[:-1]) * 1024
  261. elif _size[-1] == "M":
  262. _size = int(_size[:-1]) * 1024 * 1024
  263. else:
  264. _size = int(_size)
  265. _offset = int(_offset, 0)
  266. except ValueError:
  267. continue
  268. partition_table[_name] = {
  269. "type": _type,
  270. "subtype": _subtype,
  271. "offset": _offset,
  272. "size": _size,
  273. "flags": _flags
  274. }
  275. return partition_table
  276. def get_elf_sha256(self):
  277. if self._elf_file_sha256:
  278. return self._elf_file_sha256
  279. sha256 = hashlib.sha256()
  280. with open(self.elf_file, 'rb') as f:
  281. sha256.update(f.read())
  282. self._elf_file_sha256 = sha256.hexdigest()
  283. return self._elf_file_sha256
  284. class Example(IDFApp):
  285. def _get_sdkconfig_paths(self):
  286. """
  287. overrides the parent method to provide exact path of sdkconfig for example tests
  288. """
  289. return [os.path.join(self.binary_path, "..", "sdkconfig")]
  290. def _try_get_binary_from_local_fs(self, app_path, config_name=None, target=None, local_build_dir="build_examples"):
  291. # build folder of example path
  292. path = os.path.join(self.idf_path, app_path, "build")
  293. if os.path.exists(path):
  294. return path
  295. if not config_name:
  296. config_name = "default"
  297. if not target:
  298. target = "esp32"
  299. # Search for CI build folders.
  300. # Path format: $IDF_PATH/build_examples/app_path_with_underscores/config/target
  301. # (see tools/ci/build_examples_cmake.sh)
  302. # For example: $IDF_PATH/build_examples/examples_get-started_blink/default/esp32
  303. app_path_underscored = app_path.replace(os.path.sep, "_")
  304. example_path = os.path.join(self.idf_path, local_build_dir)
  305. for dirpath in os.listdir(example_path):
  306. if os.path.basename(dirpath) == app_path_underscored:
  307. path = os.path.join(example_path, dirpath, config_name, target, "build")
  308. if os.path.exists(path):
  309. return path
  310. else:
  311. return None
  312. def get_binary_path(self, app_path, config_name=None, target=None):
  313. path = self._try_get_binary_from_local_fs(app_path, config_name, target)
  314. if path:
  315. return path
  316. else:
  317. artifacts = Artifacts(self.idf_path,
  318. CIAssignExampleTest.get_artifact_index_file(case_group=CIAssignExampleTest.ExampleGroup),
  319. app_path, config_name, target)
  320. path = artifacts.download_artifacts()
  321. if path:
  322. return os.path.join(self.idf_path, path)
  323. else:
  324. raise OSError("Failed to find example binary")
  325. class UT(IDFApp):
  326. def get_binary_path(self, app_path, config_name=None, target=None):
  327. if not config_name:
  328. config_name = "default"
  329. path = os.path.join(self.idf_path, app_path)
  330. default_build_path = os.path.join(path, "build")
  331. if os.path.exists(default_build_path):
  332. return default_build_path
  333. # first try to get from build folder of unit-test-app
  334. path = os.path.join(self.idf_path, "tools", "unit-test-app", "build")
  335. if os.path.exists(path):
  336. # found, use bin in build path
  337. return path
  338. # ``make ut-build-all-configs`` or ``make ut-build-CONFIG`` will copy binary to output folder
  339. path = os.path.join(self.idf_path, "tools", "unit-test-app", "output", target, config_name)
  340. if os.path.exists(path):
  341. return path
  342. raise OSError("Failed to get unit-test-app binary path")
  343. class TestApp(Example):
  344. def get_binary_path(self, app_path, config_name=None, target=None):
  345. path = self._try_get_binary_from_local_fs(app_path, config_name, target, local_build_dir="build_test_apps")
  346. if path:
  347. return path
  348. else:
  349. artifacts = Artifacts(self.idf_path,
  350. CIAssignExampleTest.get_artifact_index_file(case_group=CIAssignExampleTest.TestAppsGroup),
  351. app_path, config_name, target)
  352. path = artifacts.download_artifacts()
  353. if path:
  354. return os.path.join(self.idf_path, path)
  355. else:
  356. raise OSError("Failed to find example binary")
  357. class LoadableElfTestApp(TestApp):
  358. def __init__(self, app_path, app_files, config_name=None, target=None):
  359. # add arg `app_files` for loadable elf test_app.
  360. # Such examples only build elf files, so it doesn't generate flasher_args.json.
  361. # So we can't get app files from config file. Test case should pass it to application.
  362. super(IDFApp, self).__init__(app_path)
  363. self.app_files = app_files
  364. self.config_name = config_name
  365. self.target = target
  366. self.idf_path = self.get_sdk_path()
  367. self.binary_path = self.get_binary_path(app_path, config_name, target)
  368. self.elf_file = self._get_elf_file_path(self.binary_path)
  369. assert os.path.exists(self.binary_path)
  370. def get_binary_path(self, app_path, config_name=None, target=None):
  371. path = self._try_get_binary_from_local_fs(app_path, config_name, target, local_build_dir="build_test_apps")
  372. if path:
  373. return path
  374. else:
  375. artifacts = Artifacts(self.idf_path,
  376. CIAssignExampleTest.get_artifact_index_file(case_group=CIAssignExampleTest.TestAppsGroup),
  377. app_path, config_name, target)
  378. path = artifacts.download_artifact_files(self.app_files)
  379. if path:
  380. return os.path.join(self.idf_path, path)
  381. else:
  382. raise OSError("Failed to find the loadable ELF file")
  383. class SSC(IDFApp):
  384. def get_binary_path(self, app_path, config_name=None, target=None):
  385. # TODO: to implement SSC get binary path
  386. return app_path
  387. class AT(IDFApp):
  388. def get_binary_path(self, app_path, config_name=None, target=None):
  389. # TODO: to implement AT get binary path
  390. return app_path