IDFApp.py 16 KB

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