versions_fetcher.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339
  1. import logging
  2. import os
  3. import ap_git
  4. import json
  5. import jsonschema
  6. from pathlib import Path
  7. from threading import Lock
  8. from utils import TaskRunner
  9. from .vehicles_manager import VehiclesManager as vehm
  10. class VersionInfo:
  11. """
  12. Class to wrap version info properties.
  13. """
  14. def __init__(self,
  15. remote: str,
  16. commit_ref: str,
  17. release_type: str,
  18. version_number: str,
  19. ap_build_artifacts_url) -> None:
  20. self.remote = remote
  21. self.commit_ref = commit_ref
  22. self.release_type = release_type
  23. self.version_number = version_number
  24. self.ap_build_artifacts_url = ap_build_artifacts_url
  25. class RemoteInfo:
  26. """
  27. Class to wrap remote info properties.
  28. """
  29. def __init__(self,
  30. name: str,
  31. url: str) -> None:
  32. self.name = name
  33. self.url = url
  34. def to_dict(self):
  35. return {
  36. 'name': self.name,
  37. 'url': self.url,
  38. }
  39. class VersionsFetcher:
  40. """
  41. Class to fetch the version-to-build metadata from remotes.json
  42. and provide methods to view the same
  43. """
  44. __singleton = None
  45. def __init__(self, remotes_json_path: str,
  46. ap_repo: ap_git.GitRepo):
  47. """
  48. Initializes the VersionsFetcher instance
  49. with a given remotes.json path.
  50. Parameters:
  51. remotes_json_path (str): Path to the remotes.json file.
  52. ap_repo (GitRepo): ArduPilot local git repository. This local
  53. repository is shared between the VersionsFetcher
  54. and the APSourceMetadataFetcher.
  55. Raises:
  56. RuntimeError: If an instance of this class already exists,
  57. enforcing a singleton pattern.
  58. """
  59. if vehm.get_singleton() is None:
  60. raise RuntimeError("VehiclesManager should be initialised first")
  61. # Enforce singleton pattern by raising an error if
  62. # an instance already exists.
  63. if VersionsFetcher.__singleton:
  64. raise RuntimeError("VersionsFetcher must be a singleton.")
  65. self.logger = logging.getLogger(__name__)
  66. self.__remotes_json_path = remotes_json_path
  67. self.__ensure_remotes_json()
  68. self.__access_lock_versions_metadata = Lock()
  69. self.__versions_metadata = []
  70. tasks = (
  71. (self.fetch_ap_releases, 1200),
  72. (self.fetch_whitelisted_tags, 1200),
  73. )
  74. self.__task__runner = TaskRunner(tasks=tasks)
  75. self.repo = ap_repo
  76. VersionsFetcher.__singleton = self
  77. def start(self) -> None:
  78. """
  79. Start auto-fetch jobs.
  80. """
  81. self.logger.info(
  82. "Starting VersionsFetcher background auto-fetch jobs."
  83. )
  84. self.__task__runner.start()
  85. def get_all_remotes_info(self) -> list[RemoteInfo]:
  86. """
  87. Return the list of RemoteInfo objects constructed from the
  88. information in the remotes.json file
  89. Returns:
  90. list: RemoteInfo objects for all remotes mentioned in remotes.json
  91. """
  92. return [
  93. RemoteInfo(
  94. name=remote.get('name', None),
  95. url=remote.get('url', None)
  96. )
  97. for remote in self.__get_versions_metadata()
  98. ]
  99. def get_remote_info(self, remote_name: str) -> RemoteInfo:
  100. """
  101. Return the RemoteInfo for the given remote name, None otherwise.
  102. Returns:
  103. RemoteInfo: The remote information object.
  104. """
  105. return next(
  106. (
  107. remote for remote in self.get_all_remotes_info()
  108. if remote.name == remote_name
  109. ),
  110. None
  111. )
  112. def get_versions_for_vehicle(self, vehicle_name: str) -> list[VersionInfo]:
  113. """
  114. Return the list of dictionaries containing the info about the
  115. versions listed to be built for a particular vehicle.
  116. Parameters:
  117. vehicle_name (str): the vehicle to fetch versions list for
  118. Returns:
  119. list: VersionInfo objects for all versions allowed to be
  120. built for the said vehicle.
  121. """
  122. if vehicle_name is None:
  123. raise ValueError("Vehicle is a required parameter.")
  124. all_vehicles = vehm.get_singleton().get_all_vehicle_names_sorted()
  125. if vehicle_name not in all_vehicles:
  126. raise ValueError(f"Invalid vehicle name '{vehicle_name}'.")
  127. versions_list = []
  128. for remote in self.__get_versions_metadata():
  129. for vehicle in remote['vehicles']:
  130. if vehicle['name'] != vehicle_name:
  131. continue
  132. for release in vehicle['releases']:
  133. versions_list.append(VersionInfo(
  134. remote=remote.get('name', None),
  135. commit_ref=release.get('commit_reference', None),
  136. release_type=release.get('release_type', None),
  137. version_number=release.get('version_number', None),
  138. ap_build_artifacts_url=release.get(
  139. 'ap_build_artifacts_url',
  140. None
  141. )
  142. ))
  143. return versions_list
  144. def is_version_listed(self, vehicle_name: str, remote: str,
  145. commit_ref: str) -> bool:
  146. """
  147. Check if a version with given properties mentioned in remotes.json
  148. Parameters:
  149. vehicle_name (str): Name of the vehicle for which version is listed
  150. remote (str): remote under which the version is listed
  151. commit_ref(str): commit reference for the version
  152. Returns:
  153. bool: True if the said version is mentioned in remotes.json,
  154. False otherwise
  155. """
  156. if vehicle_name is None:
  157. raise ValueError("vehicle_name is a required parameter.")
  158. if remote is None:
  159. raise ValueError("Remote is a required parameter.")
  160. if commit_ref is None:
  161. raise ValueError("Commit reference is a required parameter.")
  162. return (remote, commit_ref) in [
  163. (version_info.remote, version_info.commit_ref)
  164. for version_info in
  165. self.get_versions_for_vehicle(vehicle_name=vehicle_name)
  166. ]
  167. def get_version_info(self, vehicle_name: str, remote: str,
  168. commit_ref: str) -> VersionInfo:
  169. """
  170. Find first version matching the given properties in remotes.json
  171. Parameters:
  172. vehicle_name (str): Name of the vehicle for which version is listed
  173. remote (str): remote under which the version is listed
  174. commit_ref(str): commit reference for the version
  175. Returns:
  176. VersionInfo: Object for the version matching the properties,
  177. None if not found
  178. """
  179. return next(
  180. (
  181. version
  182. for version in self.get_versions_for_vehicle(
  183. vehicle_name=vehicle_name
  184. )
  185. if version.remote == remote and
  186. version.commit_ref == commit_ref
  187. ),
  188. None
  189. )
  190. def reload_remotes_json(self) -> None:
  191. """
  192. Read remotes.json, validate its structure against the schema
  193. and cache it in memory
  194. """
  195. # load file containing vehicles listed to be built for each
  196. # remote along with the branches/tags/commits on which the
  197. # firmware can be built
  198. remotes_json_schema_path = os.path.join(
  199. os.path.dirname(__file__),
  200. 'remotes.schema.json'
  201. )
  202. with open(self.__remotes_json_path, 'r') as f, \
  203. open(remotes_json_schema_path, 'r') as s:
  204. f_content = f.read()
  205. # Early return if file is empty
  206. if not f_content:
  207. return
  208. versions_metadata = json.loads(f_content)
  209. schema = json.loads(s.read())
  210. # validate schema
  211. jsonschema.validate(instance=versions_metadata, schema=schema)
  212. self.__set_versions_metadata(versions_metadata=versions_metadata)
  213. # update git repo with latest remotes list
  214. self.__sync_remotes_with_ap_repo()
  215. def __ensure_remotes_json(self) -> None:
  216. """
  217. Ensures remotes.json exists and is a valid JSON file.
  218. """
  219. p = Path(self.__remotes_json_path)
  220. if not p.exists():
  221. # Ensure parent directory exists
  222. Path.mkdir(p.parent, parents=True, exist_ok=True)
  223. # write empty json list
  224. with open(p, 'w') as f:
  225. f.write('[]')
  226. def __set_versions_metadata(self, versions_metadata: list) -> None:
  227. """
  228. Set versions metadata property with the one passed as parameter
  229. This requires to acquire the access lock to avoid overwriting the
  230. object while it is being read
  231. """
  232. if versions_metadata is None:
  233. raise ValueError("versions_metadata is a required parameter. "
  234. "Cannot be None.")
  235. with self.__access_lock_versions_metadata:
  236. self.__versions_metadata = versions_metadata
  237. def __get_versions_metadata(self) -> list:
  238. """
  239. Read versions metadata property
  240. This requires to acquire the access lock to avoid reading the list
  241. while it is being modified
  242. Returns:
  243. list: the versions metadata list
  244. """
  245. with self.__access_lock_versions_metadata:
  246. return self.__versions_metadata
  247. def __sync_remotes_with_ap_repo(self):
  248. """
  249. Update the remotes in ArduPilot local repository with the latest
  250. remotes list.
  251. """
  252. remotes = tuple(
  253. (remote.name, remote.url)
  254. for remote in self.get_all_remotes_info()
  255. )
  256. self.repo.remote_add_bulk(remotes=remotes, force=True)
  257. def fetch_ap_releases(self) -> None:
  258. """
  259. Execute the fetch_releases.py script to update remotes.json
  260. with Ardupilot's official releases
  261. """
  262. from scripts import fetch_releases
  263. fetch_releases.run(
  264. base_dir=os.path.join(
  265. os.path.dirname(self.__remotes_json_path),
  266. '..',
  267. ),
  268. remote_name="ardupilot",
  269. )
  270. self.reload_remotes_json()
  271. return
  272. def fetch_whitelisted_tags(self) -> None:
  273. """
  274. Execute the fetch_whitelisted_tags.py script to update
  275. remotes.json with tags from whitelisted repos
  276. """
  277. from scripts import fetch_whitelisted_tags
  278. fetch_whitelisted_tags.run(
  279. base_dir=os.path.join(
  280. os.path.dirname(self.__remotes_json_path),
  281. '..',
  282. )
  283. )
  284. self.reload_remotes_json()
  285. return
  286. @staticmethod
  287. def get_singleton():
  288. return VersionsFetcher.__singleton