Debian Codegraph @

src/buildstream_plugins/sources/cargo.py

raw
1 #
2 # Licensed under the Apache License, Version 2.0 (the "License");
3 # you may not use this file except in compliance with the License.
4 # You may obtain a copy of the License at
5 #
6 # http://www.apache.org/licenses/LICENSE-2.0
7 #
8 # Unless required by applicable law or agreed to in writing, software
9 # distributed under the License is distributed on an "AS IS" BASIS,
10 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 # See the License for the specific language governing permissions and
12 # limitations under the License.
13 #
14 # Authors:
15 # Tristan Van Berkom <[email protected]>
16
17 #
18 # This plugin was originally developped in the https://gitlab.com/BuildStream/bst-plugins-experimental/
19 # repository and was copied from a60426126e5bec2d630fcd889a9f5af13af00ea6
20 #
21
22 """
23 cargo - Automatically stage crate dependencies
24 ==============================================
25 A convenience Source element for vendoring rust project dependencies.
26
27 Placing this source in the source list, after a source which stages a
28 Cargo.lock file, will allow this source to read the Cargo.lock file and
29 obtain the crates automatically into %{vendordir}.
30
31 Set the `ref` field to an empty list like so: `ref: []`, and then run
32 `bst source track path_to_bst_file.bst`.
33
34 **Usage:**
35
36 .. code:: yaml
37
38 # Specify the cargo source kind
39 kind: cargo
40
41 # Url of the crates repository to download from (default: https://static.crates.io/crates)
42 url: https://static.crates.io/crates
43
44 # Internal source reference, this is a list of dictionaries
45 # which store the crate names and versions.
46 #
47 # This will be automatically updated with `bst source track`
48 ref:
49 - name: packagename
50 version: 1.2.1
51 - name: packagename
52 version: 1.3.0
53
54 # Specify a directory for the vendored crates (defaults to ./crates)
55 vendor-dir: crates
56
57 # Optionally specify the name of the lock file to use (defaults to Cargo.lock)
58 cargo-lock: Cargo.lock
59
60
61 See `built-in functionality doumentation
62 <https://docs.buildstream.build/master/buildstream.source.html#core-source-builtins>`_ for
63 details on common configuration options for sources.
64
65
66 Reporting `SourceInfo <https://docs.buildstream.build/master/buildstream.source.html#buildstream.source.SourceInfo>`_
67 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
68 The cargo source reports the URL of the archive crates as the *url* for each crate.
69
70 Further, the cargo source reports the `SourceInfoMedium.REMOTE_FILE
71 <https://docs.buildstream.build/master/buildstream.source.html#buildstream.source.SourceInfoMedium.REMOTE_FILE>`_
72 *medium* and the `SourceVersionType.SHA256
73 <https://docs.buildstream.build/master/buildstream.source.html#buildstream.source.SourceVersionType.SHA256>`_
74 *version_type*, for which it reports the checksum of the archive as the *version*.
75
76 The versions extracted from the Cargo.lock at tracking time are used to report the *guess_version*.
77
78 Additional source info can be specified using the `provenance` field for each referenced crate as per
79 `built-in source provenance documentation
80 <https://docs.buildstream.build/master/buildstream.source.html#built-in-functionality>`_.
81 """
82
83 import json
84 import os.path
85 import tarfile
86
87 # We prefer tomli that was put into standard library as tomllib
88 # starting from 3.11
89 try:
90 import tomllib # type: ignore
91 except ImportError:
92 import tomli as tomllib # type: ignore
93
94 from buildstream import Source, SourceFetcher, SourceError
95 from buildstream import utils
96
97 from ._utils import download_file
98
99 #
100 # Soft import of buildstream symbols only available in newer versions
101 #
102 # The BST_MIN_VERSION will provide a better user experience.
103 #
104 try:
105 from buildstream import SourceInfoMedium, SourceVersionType
106 except ImportError:
107 pass
108
109
110 # This automatically goes into .cargo/config
111 #
112 _default_vendor_config_template = (
113 "[source.crates-io]\n"
114 + 'registry = "{vendorurl}"\n'
115 + 'replace-with = "vendored-sources"\n'
116 + "[source.vendored-sources]\n"
117 + 'directory = "{vendordir}"\n'
118 )
119
120
121 # Crate()
122 #
123 # Use a SourceFetcher class to be the per crate helper
124 #
125 # Args:
126 # cargo (Cargo): The main Source implementation
127 # name (str): The name of the crate to depend on
128 # version (str): The version of the crate to depend on
129 # sha (str|None): The sha256 checksum of the downloaded crate
130 #
131 class Crate(SourceFetcher):
132 def __init__(self, cargo, name, version, sha=None, provenance=None):
133 super().__init__()
134
135 self.cargo = cargo
136 self.name = name
137 self.version = str(version)
138 self.sha = sha
139 self.provenance = provenance
140 self.mark_download_url(cargo.url)
141
142 ########################################################
143 # SourceFetcher API method implementations #
144 ########################################################
145
146 def fetch(self, alias_override=None, **kwargs):
147
148 # Just a defensive check, it is impossible for the
149 # file to be already cached because Source.fetch() will
150 # not be called if the source is already cached.
151 #
152 if os.path.isfile(self._get_mirror_file()):
153 return # pragma: nocover
154
155 # Download the crate
156 crate_url, auth_scheme = self._get_url(alias_override)
157 with self.cargo.timed_activity("Downloading: {}".format(crate_url), silent_nested=True):
158 sha256 = self._download(crate_url, auth_scheme)
159 if self.sha is not None and sha256 != self.sha:
160 raise SourceError(
161 "File downloaded from {} has sha256sum '{}', not '{}'!".format(crate_url, sha256, self.sha)
162 )
163
164 def get_source_info(self):
165 url, _ = self._get_url()
166 return self.cargo.create_source_info(
167 url,
168 SourceInfoMedium.REMOTE_FILE,
169 SourceVersionType.SHA256,
170 self.sha,
171 version_guess=self.version,
172 provenance_node=self.provenance,
173 )
174
175 ########################################################
176 # Helper APIs for the Cargo Source to use #
177 ########################################################
178
179 # stage()
180 #
181 # A delegate method to do the work for a single crate
182 # in Source.stage().
183 #
184 # Args:
185 # (directory): The vendor subdirectory to stage to
186 #
187 def stage(self, directory):
188 try:
189 mirror_file = self._get_mirror_file()
190 with tarfile.open(mirror_file) as tar:
191 members = tar.getmembers()
192 if hasattr(tarfile, "tar_filter"):
193 # Python 3.12+ (and older versions with backports)
194 tar.extractall(path=directory, filter="tar")
195 else:
196 for member in members:
197 self._assert_tarinfo_safe(member, directory)
198 tar.extractall(path=directory, members=members)
199
200 if members:
201 dirname = members[0].name.split("/")[0]
202 package_dir = os.path.join(directory, dirname)
203 checksum_file = os.path.join(package_dir, ".cargo-checksum.json")
204 with open(checksum_file, "w", encoding="utf-8") as f:
205 checksum_data = {"package": self.sha, "files": {}}
206 json.dump(checksum_data, f)
207
208 except (tarfile.TarError, OSError) as e:
209 raise SourceError("{}: Error staging source: {}".format(self, e)) from e
210
211 # is_cached()
212 #
213 # Get whether we have a local cached version of the source
214 #
215 # Returns:
216 # (bool): Whether we are cached or not
217 #
218 def is_cached(self):
219 return os.path.isfile(self._get_mirror_file())
220
221 # is_resolved()
222 #
223 # Get whether the current crate is resolved
224 #
225 # Returns:
226 # (bool): Whether we have a sha or not
227 #
228 def is_resolved(self):
229 return self.sha is not None
230
231 ########################################################
232 # Private helpers #
233 ########################################################
234
235 # Assert that a tarfile is safe to extract; specifically, make
236 # sure that we don't do anything outside of the target
237 # directory (this is possible, if, say, someone engineered a
238 # tarfile to contain paths that start with ..).
239 def _assert_tarinfo_safe(self, member: tarfile.TarInfo, target_dir: str):
240 final_path = os.path.abspath(os.path.join(target_dir, member.path))
241 if not final_path.startswith(target_dir):
242 raise SourceError(
243 "{}: Tarfile attempts to extract outside the staging area: "
244 "{} -> {}".format(self, member.path, final_path)
245 )
246
247 if member.islnk():
248 linked_path = os.path.abspath(os.path.join(target_dir, member.linkname))
249 if not linked_path.startswith(target_dir):
250 raise SourceError(
251 "{}: Tarfile attempts to hardlink outside the staging area: "
252 "{} -> {}".format(self, member.path, final_path)
253 )
254
255 # Don't need to worry about symlinks because they're just
256 # files here and won't be able to do much harm once we are
257 # in a sandbox.
258
259 # _download()
260 #
261 # Downloads the crate from the url and caches it.
262 #
263 # Args:
264 # url (str): The url to download from
265 #
266 # Returns:
267 # (str): The sha256 checksum of the downloaded crate
268 #
269 def _download(self, url, auth_scheme):
270 # We do not use etag in case what we have in cache is
271 # not matching ref in order to be able to recover from
272 # corrupted download.
273 if self.sha:
274 etag = self._get_etag(self.sha)
275 else:
276 etag = None
277
278 with self.cargo.tempdir() as td:
279 local_file, etag, error = download_file(url, etag, td, auth_scheme)
280
281 if error:
282 raise SourceError("{}: Error mirroring {}: {}".format(self, url, error), temporary=True)
283
284 # Make sure url-specific mirror dir exists.
285 os.makedirs(self._get_mirror_dir(), exist_ok=True)
286
287 # Store by sha256sum
288 sha256 = utils.sha256sum(local_file)
289 # Even if the file already exists, move the new file over.
290 # In case the old file was corrupted somehow.
291 os.rename(local_file, self._get_mirror_file(sha256))
292
293 if etag:
294 self._store_etag(sha256, etag)
295 return sha256
296
297 # _get_url()
298 #
299 # Fetches the URL to download this crate from
300 #
301 # Args:
302 # alias (str|None): The URL alias to apply, if any
303 #
304 # Returns:
305 # (str): The URL for this crate
306 #
307 def _get_url(self, alias=None):
308 path = "{name}/{name}-{version}.crate".format(name=self.name, version=self.version)
309 extra_data = {}
310 if utils.get_bst_version() >= (2, 2):
311 translated_url = self.cargo.translate_url(
312 self.cargo.url, suffix=path, alias_override=alias, extra_data=extra_data
313 )
314 else:
315 translated_url = self.cargo.translate_url(self.cargo.url, alias_override=alias) + path
316
317 return translated_url, extra_data.get("http-auth")
318
319 # _get_etag()
320 #
321 # Fetches the locally stored ETag information for this
322 # crate's download.
323 #
324 # Args:
325 # sha (str): The sha256 checksum of the downloaded crate
326 #
327 # Returns:
328 # (str|None): The ETag to use for requests, or None if nothing is
329 # locally downloaded
330 #
331 def _get_etag(self, sha):
332 etagfilename = os.path.join(self._get_mirror_dir(), "{}.etag".format(sha))
333 if os.path.exists(etagfilename):
334 with open(etagfilename, "r", encoding="utf-8") as etagfile:
335 return etagfile.read()
336
337 return None
338
339 # _store_etag()
340 #
341 # Stores the locally cached ETag information for this crate.
342 #
343 # Args:
344 # sha (str): The sha256 checksum of the downloaded crate
345 # etag (str): The ETag to use for requests of this crate
346 #
347 def _store_etag(self, sha, etag):
348 etagfilename = os.path.join(self._get_mirror_dir(), "{}.etag".format(sha))
349 with utils.save_file_atomic(etagfilename) as etagfile:
350 etagfile.write(etag)
351
352 # _get_mirror_dir()
353 #
354 # Gets the local mirror directory for this upstream cargo repository
355 #
356 def _get_mirror_dir(self):
357 return os.path.join(
358 self.cargo.get_mirror_directory(),
359 utils.url_directory_name(self.cargo.url),
360 self.name,
361 self.version,
362 )
363
364 # _get_mirror_file()
365 #
366 # Gets the local mirror filename for this crate
367 #
368 # Args:
369 # sha (str|None): The sha256 checksum of the downloaded crate
370 #
371 def _get_mirror_file(self, sha=None):
372 return os.path.join(self._get_mirror_dir(), sha or self.sha)
373
374
375 class CargoSource(Source):
376 BST_MIN_VERSION = "2.5"
377
378 # We need the Cargo.lock file to construct our ref at track time
379 BST_REQUIRES_PREVIOUS_SOURCES_TRACK = True
380
381 BST_CUSTOM_SOURCE_PROVENANCE = True
382
383 ########################################################
384 # Plugin/Source API method implementations #
385 ########################################################
386 def configure(self, node):
387 # The url before any aliasing
388 #
389 self.original_url = node.get_str("url", "https://static.crates.io/crates")
390 self.cargo_lock = node.get_str("cargo-lock", "Cargo.lock")
391 self.vendor_dir = node.get_str("vendor-dir", "crates")
392 self.provenance = {}
393
394 # Because source provenance info lives in the ref it would be
395 # removed upon source track, create a backup here so it is
396 # available to be added back in when setting the ref
397 ref = node.get_sequence("ref", None)
398 if ref is not None:
399 for crate in ref:
400 if "provenance" in crate:
401 crate_name = crate.get_str("name")
402 provenance = crate.get_mapping("provenance")
403 self.provenance[crate_name] = provenance.strip_node_info()
404
405 # If the specified URL is just an alias, require the alias to resolve
406 # to a URL with a trailing slash. Otherwise, append a trailing slash if
407 # it's missing, for backward compatibility.
408 self.url = self.original_url
409 if not self.url.endswith(":") and not self.url.endswith("/"):
410 self.url += "/"
411
412 node.validate_keys(Source.COMMON_CONFIG_KEYS + ["url", "ref", "cargo-lock", "vendor-dir"])
413
414 # Needs to be marked here so that `track` can translate it later.
415 self.mark_download_url(self.url)
416
417 self.load_ref(node)
418
419 def preflight(self):
420 return
421
422 def get_unique_key(self):
423 return [self.original_url, self.cargo_lock, self.vendor_dir, self.ref]
424
425 def is_resolved(self):
426 return (self.ref is not None) and all(crate.is_resolved() for crate in self.crates)
427
428 def is_cached(self):
429 return all(crate.is_cached() for crate in self.crates)
430
431 def load_ref(self, node):
432 ref = node.get_sequence("ref", None)
433 self._recompute_crates(ref)
434
435 def get_ref(self):
436 return self.ref
437
438 def set_ref(self, ref, node):
439 def add_provenance(crate):
440 if crate["name"] in self.provenance:
441 crate["provenance"] = self.provenance[crate["name"]]
442 return crate
443
444 # add provenance back in
445 ref = list(map(add_provenance, ref))
446
447 node["ref"] = ref
448 self._recompute_crates(node.get_sequence("ref"))
449
450 def track(self, *, previous_sources_dir):
451 new_ref = []
452 lockfile = os.path.join(previous_sources_dir, self.cargo_lock)
453
454 try:
455 with open(lockfile, "rb") as f:
456 try:
457 lock = tomllib.load(f)
458 except tomllib.TOMLDecodeError as e:
459 raise SourceError(
460 "Malformed Cargo.lock file at: {}".format(self.cargo_lock),
461 detail="{}".format(e),
462 ) from e
463 except FileNotFoundError as e:
464 raise SourceError(
465 "Failed to find Cargo.lock file at: {}".format(self.cargo_lock),
466 detail="The cargo plugin expects to find a Cargo.lock file in\n"
467 + "the sources staged before it in the source list, but none was found.",
468 ) from e
469
470 # FIXME: Better validation would be good here, so we can raise more
471 # useful error messages in the case of a malformed Cargo.lock file.
472 #
473 for package in lock["package"]:
474 if "source" not in package:
475 continue
476 new_ref += [{"name": package["name"], "version": str(package["version"]), "sha": package.get("checksum")}]
477
478 # Make sure the order we set it at track time is deterministic
479 new_ref = sorted(new_ref, key=lambda c: (c["name"], c["version"]))
480
481 # Download the crates and get their shas
482 for crate_obj in new_ref:
483 if crate_obj["sha"] is not None:
484 continue
485
486 crate = Crate(self, crate_obj["name"], crate_obj["version"])
487
488 crate_url, auth_scheme = crate._get_url()
489 with self.timed_activity("Downloading: {}".format(crate_url), silent_nested=True):
490 crate_obj["sha"] = crate._download(crate_url, auth_scheme)
491
492 return new_ref
493
494 def stage(self, directory):
495
496 # Stage the crates into the vendor directory
497 vendor_dir = os.path.join(directory, self.vendor_dir)
498 for crate in self.crates:
499 crate.stage(vendor_dir)
500
501 # Stage our vendor config
502 vendor_config = _default_vendor_config_template.format(
503 vendorurl=self.translate_url(self.url), vendordir=self.vendor_dir
504 )
505 conf_dir = os.path.join(directory, ".cargo")
506 conf_file = os.path.join(conf_dir, "config")
507 os.makedirs(conf_dir, exist_ok=True)
508 with open(conf_file, "w", encoding="utf-8") as f:
509 f.write(vendor_config)
510
511 def get_source_fetchers(self):
512 return self.crates
513
514 ########################################################
515 # Private helpers #
516 ########################################################
517
518 def _recompute_crates(self, ref):
519 self.crates = self._parse_crates(ref)
520 if not self.crates:
521 self.ref = None
522 else:
523 self.ref = [{"name": crate.name, "version": crate.version, "sha": crate.sha} for crate in self.crates]
524
525 # _parse_crates():
526 #
527 # Generates a list of crates based on the passed ref
528 #
529 # Args:
530 # (list|None) refs: The list of name/version dictionaries
531 #
532 # Returns:
533 # (list): A list of Crate objects
534 #
535 def _parse_crates(self, refs):
536
537 # Return an empty list for no ref
538 if refs is None:
539 return []
540
541 return [
542 Crate(
543 self,
544 crate.get_str("name"),
545 crate.get_str("version"),
546 sha=crate.get_str("sha", None),
547 provenance=crate.get_mapping("provenance", None),
548 )
549 for crate in refs
550 ]
551
552
553 def setup():
554 return CargoSource