IDFApp.py 19 KB

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