core.py 12 KB

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