core.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452
  1. import logging
  2. import time
  3. import os
  4. import fnmatch
  5. import ap_git
  6. import json
  7. import jsonschema
  8. from pathlib import Path
  9. from . import exceptions as ex
  10. from threading import Lock
  11. from utils import TaskRunner
  12. logger = logging.getLogger(__name__)
  13. class APSourceMetadataFetcher:
  14. """
  15. Class to fetch metadata like available boards, features etc.
  16. from the AP source code
  17. """
  18. __singleton = None
  19. def __init__(self, ap_repo: ap_git.GitRepo) -> None:
  20. """
  21. Initializes the APSourceMetadataFetcher instance
  22. with a given repository path.
  23. Parameters:
  24. ap_repo (GitRepo): ArduPilot local git repository containing
  25. the metadata generation scripts.
  26. Raises:
  27. TooManyInstancesError: If an instance of this class already exists,
  28. enforcing a singleton pattern.
  29. """
  30. # Enforce singleton pattern by raising an error if
  31. # an instance already exists.
  32. if APSourceMetadataFetcher.__singleton:
  33. raise ex.TooManyInstancesError()
  34. self.repo = ap_repo
  35. APSourceMetadataFetcher.__singleton = self
  36. def get_boards_at_commit(self, remote: str,
  37. commit_ref: str) -> tuple:
  38. """
  39. Retrieves a list of boards available for building at a
  40. specified commit and returns the list and the default board.
  41. Parameters:
  42. remote (str): The name of the remote repository.
  43. commit_ref (str): The commit reference to check out.
  44. Returns:
  45. tuple: A tuple containing:
  46. - boards (list): A list of boards available at the
  47. specified commit.
  48. - default_board (str): The first board in the sorted list,
  49. designated as the default.
  50. """
  51. tstart = time.time()
  52. import importlib.util
  53. with self.repo.get_checkout_lock():
  54. self.repo.checkout_remote_commit_ref(
  55. remote=remote,
  56. commit_ref=commit_ref,
  57. force=True,
  58. hard_reset=True,
  59. clean_working_tree=True
  60. )
  61. spec = importlib.util.spec_from_file_location(
  62. name="board_list.py",
  63. location=os.path.join(
  64. self.repo.get_local_path(),
  65. 'Tools', 'scripts',
  66. 'board_list.py')
  67. )
  68. mod = importlib.util.module_from_spec(spec)
  69. spec.loader.exec_module(mod)
  70. all_boards = mod.AUTOBUILD_BOARDS
  71. exclude_patterns = ['fmuv*', 'SITL*']
  72. boards = []
  73. for b in all_boards:
  74. excluded = False
  75. for p in exclude_patterns:
  76. if fnmatch.fnmatch(b.lower(), p.lower()):
  77. excluded = True
  78. break
  79. if not excluded:
  80. boards.append(b)
  81. logger.debug(
  82. f"Took {(time.time() - tstart)} seconds to get boards"
  83. )
  84. boards.sort()
  85. default_board = boards[0]
  86. return (boards, default_board)
  87. def get_build_options_at_commit(self, remote: str,
  88. commit_ref: str) -> list:
  89. """
  90. Retrieves a list of build options available at a specified commit.
  91. Parameters:
  92. remote (str): The name of the remote repository.
  93. commit_ref (str): The commit reference to check out.
  94. Returns:
  95. list: A list of build options available at the specified commit.
  96. """
  97. tstart = time.time()
  98. import importlib.util
  99. with self.repo.get_checkout_lock():
  100. self.repo.checkout_remote_commit_ref(
  101. remote=remote,
  102. commit_ref=commit_ref,
  103. force=True,
  104. hard_reset=True,
  105. clean_working_tree=True
  106. )
  107. spec = importlib.util.spec_from_file_location(
  108. name="build_options.py",
  109. location=os.path.join(
  110. self.repo.get_local_path(),
  111. 'Tools',
  112. 'scripts',
  113. 'build_options.py'
  114. )
  115. )
  116. mod = importlib.util.module_from_spec(spec)
  117. spec.loader.exec_module(mod)
  118. build_options = mod.BUILD_OPTIONS
  119. logger.debug(
  120. f"Took {(time.time() - tstart)} seconds to get build options"
  121. )
  122. return build_options
  123. @staticmethod
  124. def get_singleton():
  125. return APSourceMetadataFetcher.__singleton
  126. class VersionInfo:
  127. """
  128. Class to wrap version info properties inside a single object
  129. """
  130. def __init__(self,
  131. remote: str,
  132. commit_ref: str,
  133. release_type: str,
  134. version_number: str,
  135. ap_build_artifacts_url) -> None:
  136. self.remote = remote
  137. self.commit_ref = commit_ref
  138. self.release_type = release_type
  139. self.version_number = version_number
  140. self.ap_build_artifacts_url = ap_build_artifacts_url
  141. class RemoteInfo:
  142. """
  143. Class to wrap remote info properties inside a single object
  144. """
  145. def __init__(self,
  146. name: str,
  147. url: str) -> None:
  148. self.name = name
  149. self.url = url
  150. class VersionsFetcher:
  151. """
  152. Class to fetch the version-to-build metadata from remotes.json
  153. and provide methods to view the same
  154. """
  155. __singleton = None
  156. def __init__(self, remotes_json_path: str,
  157. ap_repo: ap_git.GitRepo):
  158. """
  159. Initializes the VersionsFetcher instance
  160. with a given remotes.json path.
  161. Parameters:
  162. remotes_json_path (str): Path to the remotes.json file.
  163. ap_repo (GitRepo): ArduPilot local git repository. This local
  164. repository is shared between the VersionsFetcher
  165. and the APSourceMetadataFetcher.
  166. Raises:
  167. TooManyInstancesError: If an instance of this class already exists,
  168. enforcing a singleton pattern.
  169. """
  170. # Enforce singleton pattern by raising an error if
  171. # an instance already exists.
  172. if VersionsFetcher.__singleton:
  173. raise ex.TooManyInstancesError()
  174. self.__remotes_json_path = remotes_json_path
  175. self.__ensure_remotes_json()
  176. self.__access_lock_versions_metadata = Lock()
  177. self.__versions_metadata = []
  178. tasks = (
  179. (self.fetch_ap_releases, 1200),
  180. (self.fetch_whitelisted_tags, 1200),
  181. )
  182. self.__task__runner = TaskRunner(tasks=tasks)
  183. self.repo = ap_repo
  184. VersionsFetcher.__singleton = self
  185. def start(self) -> None:
  186. """
  187. Start auto-fetch jobs.
  188. """
  189. logger.info("Starting VersionsFetcher background auto-fetch jobs.")
  190. self.__task__runner.start()
  191. def get_all_remotes_info(self) -> list[RemoteInfo]:
  192. """
  193. Return the list of RemoteInfo objects constructed from the
  194. information in the remotes.json file
  195. Returns:
  196. list: RemoteInfo objects for all remotes mentioned in remotes.json
  197. """
  198. return [
  199. RemoteInfo(
  200. name=remote.get('name', None),
  201. url=remote.get('url', None)
  202. )
  203. for remote in self.__get_versions_metadata()
  204. ]
  205. def get_versions_for_vehicle(self, vehicle_name: str) -> list[VersionInfo]:
  206. """
  207. Return the list of dictionaries containing the info about the
  208. versions listed to be built for a particular vehicle.
  209. Parameters:
  210. vehicle_name (str): the vehicle to fetch versions list for
  211. Returns:
  212. list: VersionInfo objects for all versions allowed to be
  213. built for the said vehicle.
  214. """
  215. if vehicle_name is None:
  216. raise ValueError("Vehicle is a required parameter.")
  217. versions_list = []
  218. for remote in self.__get_versions_metadata():
  219. for vehicle in remote['vehicles']:
  220. if vehicle['name'] != vehicle_name:
  221. continue
  222. for release in vehicle['releases']:
  223. versions_list.append(VersionInfo(
  224. remote=remote.get('name', None),
  225. commit_ref=release.get('commit_reference', None),
  226. release_type=release.get('release_type', None),
  227. version_number=release.get('version_number', None),
  228. ap_build_artifacts_url=release.get(
  229. 'ap_build_artifacts_url',
  230. None
  231. )
  232. ))
  233. return versions_list
  234. def get_all_vehicles_sorted_uniq(self) -> list[str]:
  235. """
  236. Return a sorted list of all vehicles listed in remotes.json structure
  237. Returns:
  238. list: Vehicles listed in remotes.json
  239. """
  240. vehicles_set = set()
  241. for remote in self.__get_versions_metadata():
  242. for vehicle in remote['vehicles']:
  243. vehicles_set.add(vehicle['name'])
  244. return sorted(list(vehicles_set))
  245. def is_version_listed(self, vehicle: str, remote: str,
  246. commit_ref: str) -> bool:
  247. """
  248. Check if a version with given properties mentioned in remotes.json
  249. Parameters:
  250. vehicle (str): vehicle for which version is listed
  251. remote (str): remote under which the version is listed
  252. commit_ref(str): commit reference for the version
  253. Returns:
  254. bool: True if the said version is mentioned in remotes.json,
  255. False otherwise
  256. """
  257. if vehicle is None:
  258. raise ValueError("Vehicle is a required parameter.")
  259. if remote is None:
  260. raise ValueError("Remote is a required parameter.")
  261. if commit_ref is None:
  262. raise ValueError("Commit reference is a required parameter.")
  263. return (remote, commit_ref) in [
  264. (version_info.remote, version_info.commit_ref)
  265. for version_info in
  266. self.get_versions_for_vehicle(vehicle_name=vehicle)
  267. ]
  268. def get_version_info(self, vehicle: str, remote: str,
  269. commit_ref: str) -> VersionInfo:
  270. """
  271. Find first version matching the given properties in remotes.json
  272. Parameters:
  273. vehicle (str): vehicle for which version is listed
  274. remote (str): remote under which the version is listed
  275. commit_ref(str): commit reference for the version
  276. Returns:
  277. VersionInfo: Object for the version matching the properties,
  278. None if not found
  279. """
  280. return next(
  281. (
  282. version
  283. for version in self.get_versions_for_vehicle(
  284. vehicle_name=vehicle
  285. )
  286. if version.remote == remote and
  287. version.commit_ref == commit_ref
  288. ),
  289. None
  290. )
  291. def reload_remotes_json(self) -> None:
  292. """
  293. Read remotes.json, validate its structure against the schema
  294. and cache it in memory
  295. """
  296. # load file containing vehicles listed to be built for each
  297. # remote along with the branches/tags/commits on which the
  298. # firmware can be built
  299. remotes_json_schema_path = os.path.join(
  300. os.path.dirname(__file__),
  301. 'remotes.schema.json'
  302. )
  303. with open(self.__remotes_json_path, 'r') as f, \
  304. open(remotes_json_schema_path, 'r') as s:
  305. f_content = f.read()
  306. # Early return if file is empty
  307. if not f_content:
  308. return
  309. versions_metadata = json.loads(f_content)
  310. schema = json.loads(s.read())
  311. # validate schema
  312. jsonschema.validate(instance=versions_metadata, schema=schema)
  313. self.__set_versions_metadata(versions_metadata=versions_metadata)
  314. # update git repo with latest remotes list
  315. self.__sync_remotes_with_ap_repo()
  316. def __ensure_remotes_json(self) -> None:
  317. """
  318. Ensures remotes.json exists and is a valid JSON file.
  319. """
  320. p = Path(self.__remotes_json_path)
  321. if not p.exists():
  322. # Ensure parent directory exists
  323. Path.mkdir(p.parent, parents=True, exist_ok=True)
  324. # write empty json list
  325. with open(p, 'w') as f:
  326. f.write('[]')
  327. def __set_versions_metadata(self, versions_metadata: list) -> None:
  328. """
  329. Set versions metadata property with the one passed as parameter
  330. This requires to acquire the access lock to avoid overwriting the
  331. object while it is being read
  332. """
  333. if versions_metadata is None:
  334. raise ValueError("versions_metadata is a required parameter. "
  335. "Cannot be None.")
  336. with self.__access_lock_versions_metadata:
  337. self.__versions_metadata = versions_metadata
  338. def __get_versions_metadata(self) -> list:
  339. """
  340. Read versions metadata property
  341. This requires to acquire the access lock to avoid reading the list
  342. while it is being modified
  343. Returns:
  344. list: the versions metadata list
  345. """
  346. with self.__access_lock_versions_metadata:
  347. return self.__versions_metadata
  348. def __sync_remotes_with_ap_repo(self):
  349. """
  350. Update the remotes in ArduPilot local repository with the latest
  351. remotes list.
  352. """
  353. remotes = tuple(
  354. (remote.name, remote.url)
  355. for remote in self.get_all_remotes_info()
  356. )
  357. self.repo.remote_add_bulk(remotes=remotes, force=True)
  358. def fetch_ap_releases(self) -> None:
  359. """
  360. Execute the fetch_releases.py script to update remotes.json
  361. with Ardupilot's official releases
  362. """
  363. from scripts import fetch_releases
  364. fetch_releases.run(
  365. base_dir=os.path.join(
  366. os.path.dirname(self.__remotes_json_path),
  367. '..',
  368. ),
  369. remote_name="ardupilot",
  370. )
  371. self.reload_remotes_json()
  372. return
  373. def fetch_whitelisted_tags(self) -> None:
  374. """
  375. Execute the fetch_whitelisted_tags.py script to update
  376. remotes.json with tags from whitelisted repos
  377. """
  378. from scripts import fetch_whitelisted_tags
  379. fetch_whitelisted_tags.run(
  380. base_dir=os.path.join(
  381. os.path.dirname(self.__remotes_json_path),
  382. '..',
  383. )
  384. )
  385. self.reload_remotes_json()
  386. return
  387. @staticmethod
  388. def get_singleton():
  389. return VersionsFetcher.__singleton