IDFApp.py 17 KB

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