| 1 |
#!/usr/bin/env python3 |
| 2 |
# Copyright (c) Meta Platforms, Inc. and affiliates. |
| 3 |
# |
| 4 |
# This source code is licensed under the MIT license found in the |
| 5 |
# LICENSE file in the root directory of this source tree. |
| 6 |
|
| 7 |
import errno |
| 8 |
import hashlib |
| 9 |
import os |
| 10 |
import re |
| 11 |
import shutil |
| 12 |
import stat |
| 13 |
import subprocess |
| 14 |
import sys |
| 15 |
import tarfile |
| 16 |
import time |
| 17 |
import zipfile |
| 18 |
from datetime import datetime |
| 19 |
from typing import Dict, NamedTuple |
| 20 |
from urllib.parse import urlparse |
| 21 |
from urllib.request import Request, urlopen |
| 22 |
|
| 23 |
from .copytree import prefetch_dir_if_eden |
| 24 |
from .envfuncs import Env |
| 25 |
from .errors import TransientFailure |
| 26 |
from .platform import is_windows |
| 27 |
from .runcmd import run_cmd |
| 28 |
|
| 29 |
|
| 30 |
def file_name_is_cmake_file(file_name): |
| 31 |
file_name = file_name.lower() |
| 32 |
base = os.path.basename(file_name) |
| 33 |
return ( |
| 34 |
base.endswith(".cmake") |
| 35 |
or base.endswith(".cmake.in") |
| 36 |
or base == "cmakelists.txt" |
| 37 |
) |
| 38 |
|
| 39 |
|
| 40 |
class ChangeStatus(object): |
| 41 |
"""Indicates the nature of changes that happened while updating |
| 42 |
the source directory. There are two broad uses: |
| 43 |
* When extracting archives for third party software we want to |
| 44 |
know that we did something (eg: we either extracted code or |
| 45 |
we didn't do anything) |
| 46 |
* For 1st party code where we use shipit to transform the code, |
| 47 |
we want to know if we changed anything so that we can perform |
| 48 |
a build, but we generally want to be a little more nuanced |
| 49 |
and be able to distinguish between just changing a source file |
| 50 |
and whether we might need to reconfigure the build system. |
| 51 |
""" |
| 52 |
|
| 53 |
def __init__(self, all_changed: bool = False) -> None: |
| 54 |
"""Construct a ChangeStatus object. The default is to create |
| 55 |
a status that indicates no changes, but passing all_changed=True |
| 56 |
will create one that indicates that everything changed""" |
| 57 |
if all_changed: |
| 58 |
self.source_files = 1 |
| 59 |
self.make_files = 1 |
| 60 |
else: |
| 61 |
self.source_files = 0 |
| 62 |
self.make_files = 0 |
| 63 |
|
| 64 |
def record_change(self, file_name) -> None: |
| 65 |
"""Used by the shipit fetcher to record changes as it updates |
| 66 |
files in the destination. If the file name might be one used |
| 67 |
in the cmake build system that we use for 1st party code, then |
| 68 |
record that as a "make file" change. We could broaden this |
| 69 |
to match any file used by various build systems, but it is |
| 70 |
only really useful for our internal cmake stuff at this time. |
| 71 |
If the file isn't a build file and is under the `fbcode_builder` |
| 72 |
dir then we don't class that as an interesting change that we |
| 73 |
might need to rebuild, so we ignore it. |
| 74 |
Otherwise we record the file as a source file change.""" |
| 75 |
|
| 76 |
file_name = file_name.lower() |
| 77 |
if file_name_is_cmake_file(file_name): |
| 78 |
self.make_files += 1 |
| 79 |
elif "/fbcode_builder/cmake" in file_name: |
| 80 |
self.source_files += 1 |
| 81 |
elif "/fbcode_builder/" not in file_name: |
| 82 |
self.source_files += 1 |
| 83 |
|
| 84 |
def sources_changed(self) -> bool: |
| 85 |
"""Returns true if any source files were changed during |
| 86 |
an update operation. This will typically be used to decide |
| 87 |
that the build system to be run on the source dir in an |
| 88 |
incremental mode""" |
| 89 |
return self.source_files > 0 |
| 90 |
|
| 91 |
def build_changed(self) -> bool: |
| 92 |
"""Returns true if any build files were changed during |
| 93 |
an update operation. This will typically be used to decidfe |
| 94 |
that the build system should be reconfigured and re-run |
| 95 |
as a full build""" |
| 96 |
return self.make_files > 0 |
| 97 |
|
| 98 |
|
| 99 |
class Fetcher(object): |
| 100 |
"""The Fetcher is responsible for fetching and extracting the |
| 101 |
sources for project. The Fetcher instance defines where the |
| 102 |
extracted data resides and reports this to the consumer via |
| 103 |
its `get_src_dir` method.""" |
| 104 |
|
| 105 |
def update(self) -> ChangeStatus: |
| 106 |
"""Brings the src dir up to date, ideally minimizing |
| 107 |
changes so that a subsequent build doesn't over-build. |
| 108 |
Returns a ChangeStatus object that helps the caller to |
| 109 |
understand the nature of the changes required during |
| 110 |
the update.""" |
| 111 |
return ChangeStatus() |
| 112 |
|
| 113 |
def clean(self) -> None: |
| 114 |
"""Reverts any changes that might have been made to |
| 115 |
the src dir""" |
| 116 |
pass |
| 117 |
|
| 118 |
def hash(self) -> None: |
| 119 |
"""Returns a hash that identifies the version of the code in the |
| 120 |
working copy. For a git repo this is commit hash for the working |
| 121 |
copy. For other Fetchers this should relate to the version of |
| 122 |
the code in the src dir. The intent is that if a manifest |
| 123 |
changes the version/rev of a project that the hash be different. |
| 124 |
Importantly, this should be computable without actually fetching |
| 125 |
the code, as we want this to factor into a hash used to download |
| 126 |
a pre-built version of the code, without having to first download |
| 127 |
and extract its sources (eg: boost on windows is pretty painful). |
| 128 |
""" |
| 129 |
pass |
| 130 |
|
| 131 |
def get_src_dir(self) -> None: |
| 132 |
"""Returns the source directory that the project was |
| 133 |
extracted into""" |
| 134 |
pass |
| 135 |
|
| 136 |
|
| 137 |
class LocalDirFetcher(object): |
| 138 |
"""This class exists to override the normal fetching behavior, and |
| 139 |
use an explicit user-specified directory for the project sources. |
| 140 |
|
| 141 |
This fetcher cannot update or track changes. It always reports that the |
| 142 |
project has changed, forcing it to always be built.""" |
| 143 |
|
| 144 |
def __init__(self, path) -> None: |
| 145 |
self.path = os.path.realpath(path) |
| 146 |
|
| 147 |
def update(self) -> ChangeStatus: |
| 148 |
return ChangeStatus(all_changed=True) |
| 149 |
|
| 150 |
def hash(self) -> str: |
| 151 |
return "0" * 40 |
| 152 |
|
| 153 |
def get_src_dir(self): |
| 154 |
return self.path |
| 155 |
|
| 156 |
|
| 157 |
class SystemPackageFetcher(object): |
| 158 |
def __init__(self, build_options, packages) -> None: |
| 159 |
self.manager = build_options.host_type.get_package_manager() |
| 160 |
self.packages = packages.get(self.manager) |
| 161 |
self.host_type = build_options.host_type |
| 162 |
if self.packages: |
| 163 |
self.installed = None |
| 164 |
else: |
| 165 |
self.installed = False |
| 166 |
|
| 167 |
def packages_are_installed(self): |
| 168 |
if self.installed is not None: |
| 169 |
return self.installed |
| 170 |
|
| 171 |
cmd = None |
| 172 |
if self.manager == "rpm": |
| 173 |
cmd = ["rpm", "-q"] + sorted(self.packages) |
| 174 |
elif self.manager == "deb": |
| 175 |
cmd = ["dpkg", "-s"] + sorted(self.packages) |
| 176 |
elif self.manager == "homebrew": |
| 177 |
cmd = ["brew", "ls", "--versions"] + sorted(self.packages) |
| 178 |
|
| 179 |
if cmd: |
| 180 |
proc = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE) |
| 181 |
if proc.returncode == 0: |
| 182 |
# captured as binary as we will hash this later |
| 183 |
self.installed = proc.stdout |
| 184 |
else: |
| 185 |
# Need all packages to be present to consider us installed |
| 186 |
self.installed = False |
| 187 |
|
| 188 |
else: |
| 189 |
self.installed = False |
| 190 |
|
| 191 |
return bool(self.installed) |
| 192 |
|
| 193 |
def update(self) -> ChangeStatus: |
| 194 |
assert self.installed |
| 195 |
return ChangeStatus(all_changed=False) |
| 196 |
|
| 197 |
def hash(self) -> str: |
| 198 |
if self.packages_are_installed(): |
| 199 |
return hashlib.sha256(self.installed).hexdigest() |
| 200 |
else: |
| 201 |
return "0" * 40 |
| 202 |
|
| 203 |
def get_src_dir(self) -> None: |
| 204 |
return None |
| 205 |
|
| 206 |
|
| 207 |
class PreinstalledNopFetcher(SystemPackageFetcher): |
| 208 |
def __init__(self) -> None: |
| 209 |
self.installed = True |
| 210 |
|
| 211 |
|
| 212 |
class GitFetcher(Fetcher): |
| 213 |
DEFAULT_DEPTH = 1 |
| 214 |
|
| 215 |
def __init__(self, build_options, manifest, repo_url, rev, depth) -> None: |
| 216 |
# Extract the host/path portions of the URL and generate a flattened |
| 217 |
# directory name. eg: |
| 218 |
# github.com/facebook/folly.git -> github.com-facebook-folly.git |
| 219 |
url = urlparse(repo_url) |
| 220 |
directory = "%s%s" % (url.netloc, url.path) |
| 221 |
for s in ["/", "\\", ":"]: |
| 222 |
directory = directory.replace(s, "-") |
| 223 |
|
| 224 |
# Place it in a repos dir in the scratch space |
| 225 |
repos_dir = os.path.join(build_options.scratch_dir, "repos") |
| 226 |
if not os.path.exists(repos_dir): |
| 227 |
os.makedirs(repos_dir) |
| 228 |
self.repo_dir = os.path.join(repos_dir, directory) |
| 229 |
|
| 230 |
if not rev and build_options.project_hashes: |
| 231 |
hash_file = os.path.join( |
| 232 |
build_options.project_hashes, |
| 233 |
re.sub("\\.git$", "-rev.txt", url.path[1:]), |
| 234 |
) |
| 235 |
if os.path.exists(hash_file): |
| 236 |
with open(hash_file, "r") as f: |
| 237 |
data = f.read() |
| 238 |
m = re.match("Subproject commit ([a-fA-F0-9]{40})", data) |
| 239 |
if not m: |
| 240 |
raise Exception("Failed to parse rev from %s" % hash_file) |
| 241 |
rev = m.group(1) |
| 242 |
print("Using pinned rev %s for %s" % (rev, repo_url)) |
| 243 |
|
| 244 |
self.rev = rev or "main" |
| 245 |
self.origin_repo = repo_url |
| 246 |
self.manifest = manifest |
| 247 |
self.depth = depth if depth else GitFetcher.DEFAULT_DEPTH |
| 248 |
|
| 249 |
def _update(self) -> ChangeStatus: |
| 250 |
current_hash = ( |
| 251 |
subprocess.check_output(["git", "rev-parse", "HEAD"], cwd=self.repo_dir) |
| 252 |
.strip() |
| 253 |
.decode("utf-8") |
| 254 |
) |
| 255 |
target_hash = ( |
| 256 |
subprocess.check_output(["git", "rev-parse", self.rev], cwd=self.repo_dir) |
| 257 |
.strip() |
| 258 |
.decode("utf-8") |
| 259 |
) |
| 260 |
if target_hash == current_hash: |
| 261 |
# It's up to date, so there are no changes. This doesn't detect eg: |
| 262 |
# if origin/main moved and rev='main', but that's ok for our purposes; |
| 263 |
# we should be using explicit hashes or eg: a stable branch for the cases |
| 264 |
# that we care about, and it isn't unreasonable to require that the user |
| 265 |
# explicitly perform a clean build if those have moved. For the most |
| 266 |
# part we prefer that folks build using a release tarball from github |
| 267 |
# rather than use the git protocol, as it is generally a bit quicker |
| 268 |
# to fetch and easier to hash and verify tarball downloads. |
| 269 |
return ChangeStatus() |
| 270 |
|
| 271 |
print("Updating %s -> %s" % (self.repo_dir, self.rev)) |
| 272 |
run_cmd(["git", "fetch", "origin", self.rev], cwd=self.repo_dir) |
| 273 |
run_cmd(["git", "checkout", self.rev], cwd=self.repo_dir) |
| 274 |
run_cmd(["git", "submodule", "update", "--init"], cwd=self.repo_dir) |
| 275 |
|
| 276 |
return ChangeStatus(True) |
| 277 |
|
| 278 |
def update(self) -> ChangeStatus: |
| 279 |
if os.path.exists(self.repo_dir): |
| 280 |
return self._update() |
| 281 |
self._clone() |
| 282 |
return ChangeStatus(True) |
| 283 |
|
| 284 |
def _clone(self) -> None: |
| 285 |
print("Cloning %s..." % self.origin_repo) |
| 286 |
# The basename/dirname stuff allows us to dance around issues where |
| 287 |
# eg: this python process is native win32, but the git.exe is cygwin |
| 288 |
# or msys and doesn't like the absolute windows path that we'd otherwise |
| 289 |
# pass to it. Careful use of cwd helps avoid headaches with cygpath. |
| 290 |
run_cmd( |
| 291 |
[ |
| 292 |
"git", |
| 293 |
"clone", |
| 294 |
"--depth=" + str(self.depth), |
| 295 |
"--", |
| 296 |
self.origin_repo, |
| 297 |
os.path.basename(self.repo_dir), |
| 298 |
], |
| 299 |
cwd=os.path.dirname(self.repo_dir), |
| 300 |
) |
| 301 |
self._update() |
| 302 |
|
| 303 |
def clean(self) -> None: |
| 304 |
if os.path.exists(self.repo_dir): |
| 305 |
run_cmd(["git", "clean", "-fxd"], cwd=self.repo_dir) |
| 306 |
|
| 307 |
def hash(self): |
| 308 |
return self.rev |
| 309 |
|
| 310 |
def get_src_dir(self): |
| 311 |
return self.repo_dir |
| 312 |
|
| 313 |
|
| 314 |
def does_file_need_update(src_name, src_st, dest_name): |
| 315 |
try: |
| 316 |
target_st = os.lstat(dest_name) |
| 317 |
except OSError as exc: |
| 318 |
if exc.errno != errno.ENOENT: |
| 319 |
raise |
| 320 |
return True |
| 321 |
|
| 322 |
if src_st.st_size != target_st.st_size: |
| 323 |
return True |
| 324 |
|
| 325 |
if stat.S_IFMT(src_st.st_mode) != stat.S_IFMT(target_st.st_mode): |
| 326 |
return True |
| 327 |
if stat.S_ISLNK(src_st.st_mode): |
| 328 |
return os.readlink(src_name) != os.readlink(dest_name) |
| 329 |
if not stat.S_ISREG(src_st.st_mode): |
| 330 |
return True |
| 331 |
|
| 332 |
# They might have the same content; compare. |
| 333 |
with open(src_name, "rb") as sf, open(dest_name, "rb") as df: |
| 334 |
chunk_size = 8192 |
| 335 |
while True: |
| 336 |
src_data = sf.read(chunk_size) |
| 337 |
dest_data = df.read(chunk_size) |
| 338 |
if src_data != dest_data: |
| 339 |
return True |
| 340 |
if len(src_data) < chunk_size: |
| 341 |
# EOF |
| 342 |
break |
| 343 |
return False |
| 344 |
|
| 345 |
|
| 346 |
def copy_if_different(src_name, dest_name) -> bool: |
| 347 |
"""Copy src_name -> dest_name, but only touch dest_name |
| 348 |
if src_name is different from dest_name, making this a |
| 349 |
more build system friendly way to copy.""" |
| 350 |
src_st = os.lstat(src_name) |
| 351 |
if not does_file_need_update(src_name, src_st, dest_name): |
| 352 |
return False |
| 353 |
|
| 354 |
dest_parent = os.path.dirname(dest_name) |
| 355 |
if not os.path.exists(dest_parent): |
| 356 |
os.makedirs(dest_parent) |
| 357 |
if stat.S_ISLNK(src_st.st_mode): |
| 358 |
try: |
| 359 |
os.unlink(dest_name) |
| 360 |
except OSError as exc: |
| 361 |
if exc.errno != errno.ENOENT: |
| 362 |
raise |
| 363 |
target = os.readlink(src_name) |
| 364 |
print("Symlinking %s -> %s" % (dest_name, target)) |
| 365 |
os.symlink(target, dest_name) |
| 366 |
else: |
| 367 |
print("Copying %s -> %s" % (src_name, dest_name)) |
| 368 |
shutil.copy2(src_name, dest_name) |
| 369 |
|
| 370 |
return True |
| 371 |
|
| 372 |
|
| 373 |
def list_files_under_dir_newer_than_timestamp(dir_to_scan, ts): |
| 374 |
for root, _dirs, files in os.walk(dir_to_scan): |
| 375 |
for src_file in files: |
| 376 |
full_name = os.path.join(root, src_file) |
| 377 |
st = os.lstat(full_name) |
| 378 |
if st.st_mtime > ts: |
| 379 |
yield full_name |
| 380 |
|
| 381 |
|
| 382 |
class ShipitPathMap(object): |
| 383 |
def __init__(self) -> None: |
| 384 |
self.roots = [] |
| 385 |
self.mapping = [] |
| 386 |
self.exclusion = [] |
| 387 |
|
| 388 |
def add_mapping(self, fbsource_dir, target_dir) -> None: |
| 389 |
"""Add a posix path or pattern. We cannot normpath the input |
| 390 |
here because that would change the paths from posix to windows |
| 391 |
form and break the logic throughout this class.""" |
| 392 |
self.roots.append(fbsource_dir) |
| 393 |
self.mapping.append((fbsource_dir, target_dir)) |
| 394 |
|
| 395 |
def add_exclusion(self, pattern) -> None: |
| 396 |
self.exclusion.append(re.compile(pattern)) |
| 397 |
|
| 398 |
def _minimize_roots(self) -> None: |
| 399 |
"""compute the de-duplicated set of roots within fbsource. |
| 400 |
We take the shortest common directory prefix to make this |
| 401 |
determination""" |
| 402 |
self.roots.sort(key=len) |
| 403 |
minimized = [] |
| 404 |
|
| 405 |
for r in self.roots: |
| 406 |
add_this_entry = True |
| 407 |
for existing in minimized: |
| 408 |
if r.startswith(existing + "/"): |
| 409 |
add_this_entry = False |
| 410 |
break |
| 411 |
if add_this_entry: |
| 412 |
minimized.append(r) |
| 413 |
|
| 414 |
self.roots = minimized |
| 415 |
|
| 416 |
def _sort_mapping(self) -> None: |
| 417 |
self.mapping.sort(reverse=True, key=lambda x: len(x[0])) |
| 418 |
|
| 419 |
def _map_name(self, norm_name, dest_root): |
| 420 |
if norm_name.endswith(".pyc") or norm_name.endswith(".swp"): |
| 421 |
# Ignore some incidental garbage while iterating |
| 422 |
return None |
| 423 |
|
| 424 |
for excl in self.exclusion: |
| 425 |
if excl.match(norm_name): |
| 426 |
return None |
| 427 |
|
| 428 |
for src_name, dest_name in self.mapping: |
| 429 |
if norm_name == src_name or norm_name.startswith(src_name + "/"): |
| 430 |
rel_name = os.path.relpath(norm_name, src_name) |
| 431 |
# We can have "." as a component of some paths, depending |
| 432 |
# on the contents of the shipit transformation section. |
| 433 |
# normpath doesn't always remove `.` as the final component |
| 434 |
# of the path, which be problematic when we later mkdir |
| 435 |
# the dirname of the path that we return. Take care to avoid |
| 436 |
# returning a path with a `.` in it. |
| 437 |
rel_name = os.path.normpath(rel_name) |
| 438 |
if dest_name == ".": |
| 439 |
return os.path.normpath(os.path.join(dest_root, rel_name)) |
| 440 |
dest_name = os.path.normpath(dest_name) |
| 441 |
return os.path.normpath(os.path.join(dest_root, dest_name, rel_name)) |
| 442 |
|
| 443 |
raise Exception("%s did not match any rules" % norm_name) |
| 444 |
|
| 445 |
def mirror(self, fbsource_root, dest_root) -> ChangeStatus: |
| 446 |
self._minimize_roots() |
| 447 |
self._sort_mapping() |
| 448 |
|
| 449 |
change_status = ChangeStatus() |
| 450 |
|
| 451 |
# Record the full set of files that should be in the tree |
| 452 |
full_file_list = set() |
| 453 |
|
| 454 |
if sys.platform == "win32": |
| 455 |
# Let's not assume st_dev has a consistent value on Windows. |
| 456 |
def st_dev(path): |
| 457 |
return 1 |
| 458 |
|
| 459 |
else: |
| 460 |
|
| 461 |
def st_dev(path): |
| 462 |
return os.lstat(path).st_dev |
| 463 |
|
| 464 |
for fbsource_subdir in self.roots: |
| 465 |
dir_to_mirror = os.path.join(fbsource_root, fbsource_subdir) |
| 466 |
root_dev = st_dev(dir_to_mirror) |
| 467 |
prefetch_dir_if_eden(dir_to_mirror) |
| 468 |
if not os.path.exists(dir_to_mirror): |
| 469 |
raise Exception( |
| 470 |
"%s doesn't exist; check your sparse profile!" % dir_to_mirror |
| 471 |
) |
| 472 |
|
| 473 |
for root, dirs, files in os.walk(dir_to_mirror): |
| 474 |
dirs[:] = [d for d in dirs if root_dev == st_dev(os.path.join(root, d))] |
| 475 |
|
| 476 |
for src_file in files: |
| 477 |
full_name = os.path.join(root, src_file) |
| 478 |
rel_name = os.path.relpath(full_name, fbsource_root) |
| 479 |
norm_name = rel_name.replace("\\", "/") |
| 480 |
|
| 481 |
target_name = self._map_name(norm_name, dest_root) |
| 482 |
if target_name: |
| 483 |
full_file_list.add(target_name) |
| 484 |
if copy_if_different(full_name, target_name): |
| 485 |
change_status.record_change(target_name) |
| 486 |
|
| 487 |
# Compare the list of previously shipped files; if a file is |
| 488 |
# in the old list but not the new list then it has been |
| 489 |
# removed from the source and should be removed from the |
| 490 |
# destination. |
| 491 |
# Why don't we simply create this list by walking dest_root? |
| 492 |
# Some builds currently have to be in-source builds and |
| 493 |
# may legitimately need to keep some state in the source tree :-/ |
| 494 |
installed_name = os.path.join(dest_root, ".shipit_shipped") |
| 495 |
if os.path.exists(installed_name): |
| 496 |
with open(installed_name, "rb") as f: |
| 497 |
for name in f.read().decode("utf-8").splitlines(): |
| 498 |
name = name.strip() |
| 499 |
if name not in full_file_list: |
| 500 |
print("Remove %s" % name) |
| 501 |
os.unlink(name) |
| 502 |
change_status.record_change(name) |
| 503 |
|
| 504 |
with open(installed_name, "wb") as f: |
| 505 |
for name in sorted(list(full_file_list)): |
| 506 |
f.write(("%s\n" % name).encode("utf-8")) |
| 507 |
|
| 508 |
return change_status |
| 509 |
|
| 510 |
|
| 511 |
class FbsourceRepoData(NamedTuple): |
| 512 |
hash: str |
| 513 |
date: str |
| 514 |
|
| 515 |
|
| 516 |
FBSOURCE_REPO_DATA: Dict[str, FbsourceRepoData] = {} |
| 517 |
|
| 518 |
|
| 519 |
def get_fbsource_repo_data(build_options) -> FbsourceRepoData: |
| 520 |
"""Returns the commit metadata for the fbsource repo. |
| 521 |
Since we may have multiple first party projects to |
| 522 |
hash, and because we don't mutate the repo, we cache |
| 523 |
this hash in a global.""" |
| 524 |
cached_data = FBSOURCE_REPO_DATA.get(build_options.fbsource_dir) |
| 525 |
if cached_data: |
| 526 |
return cached_data |
| 527 |
|
| 528 |
if "GETDEPS_HG_REPO_DATA" in os.environ: |
| 529 |
log_data = os.environ["GETDEPS_HG_REPO_DATA"] |
| 530 |
else: |
| 531 |
cmd = ["hg", "log", "-r.", "-T{node}\n{date|hgdate}"] |
| 532 |
env = Env() |
| 533 |
env.set("HGPLAIN", "1") |
| 534 |
log_data = subprocess.check_output( |
| 535 |
cmd, cwd=build_options.fbsource_dir, env=dict(env.items()) |
| 536 |
).decode("ascii") |
| 537 |
|
| 538 |
(hash, datestr) = log_data.split("\n") |
| 539 |
|
| 540 |
# datestr is like "seconds fractionalseconds" |
| 541 |
# We want "20200324.113140" |
| 542 |
(unixtime, _fractional) = datestr.split(" ") |
| 543 |
date = datetime.fromtimestamp(int(unixtime)).strftime("%Y%m%d.%H%M%S") |
| 544 |
cached_data = FbsourceRepoData(hash=hash, date=date) |
| 545 |
|
| 546 |
FBSOURCE_REPO_DATA[build_options.fbsource_dir] = cached_data |
| 547 |
|
| 548 |
return cached_data |
| 549 |
|
| 550 |
|
| 551 |
class SimpleShipitTransformerFetcher(Fetcher): |
| 552 |
def __init__(self, build_options, manifest, ctx) -> None: |
| 553 |
self.build_options = build_options |
| 554 |
self.manifest = manifest |
| 555 |
self.repo_dir = os.path.join(build_options.scratch_dir, "shipit", manifest.name) |
| 556 |
self.ctx = ctx |
| 557 |
|
| 558 |
def clean(self) -> None: |
| 559 |
if os.path.exists(self.repo_dir): |
| 560 |
shutil.rmtree(self.repo_dir) |
| 561 |
|
| 562 |
def update(self) -> ChangeStatus: |
| 563 |
mapping = ShipitPathMap() |
| 564 |
for src, dest in self.manifest.get_section_as_ordered_pairs( |
| 565 |
"shipit.pathmap", self.ctx |
| 566 |
): |
| 567 |
mapping.add_mapping(src, dest) |
| 568 |
if self.manifest.shipit_fbcode_builder: |
| 569 |
mapping.add_mapping( |
| 570 |
"fbcode/opensource/fbcode_builder", "build/fbcode_builder" |
| 571 |
) |
| 572 |
for pattern in self.manifest.get_section_as_args("shipit.strip", self.ctx): |
| 573 |
mapping.add_exclusion(pattern) |
| 574 |
|
| 575 |
return mapping.mirror(self.build_options.fbsource_dir, self.repo_dir) |
| 576 |
|
| 577 |
# pyre-fixme[15]: `hash` overrides method defined in `Fetcher` inconsistently. |
| 578 |
def hash(self) -> str: |
| 579 |
# We return a fixed non-hash string for in-fbsource builds. |
| 580 |
# We're relying on the `update` logic to correctly invalidate |
| 581 |
# the build in the case that files have changed. |
| 582 |
return "fbsource" |
| 583 |
|
| 584 |
def get_src_dir(self): |
| 585 |
return self.repo_dir |
| 586 |
|
| 587 |
|
| 588 |
class ShipitTransformerFetcher(Fetcher): |
| 589 |
SHIPIT = "/var/www/scripts/opensource/shipit/run_shipit.php" |
| 590 |
|
| 591 |
def __init__(self, build_options, project_name) -> None: |
| 592 |
self.build_options = build_options |
| 593 |
self.project_name = project_name |
| 594 |
self.repo_dir = os.path.join(build_options.scratch_dir, "shipit", project_name) |
| 595 |
|
| 596 |
def update(self) -> ChangeStatus: |
| 597 |
if os.path.exists(self.repo_dir): |
| 598 |
return ChangeStatus() |
| 599 |
self.run_shipit() |
| 600 |
return ChangeStatus(True) |
| 601 |
|
| 602 |
def clean(self) -> None: |
| 603 |
if os.path.exists(self.repo_dir): |
| 604 |
shutil.rmtree(self.repo_dir) |
| 605 |
|
| 606 |
@classmethod |
| 607 |
def available(cls): |
| 608 |
return os.path.exists(cls.SHIPIT) |
| 609 |
|
| 610 |
def run_shipit(self) -> None: |
| 611 |
tmp_path = self.repo_dir + ".new" |
| 612 |
try: |
| 613 |
if os.path.exists(tmp_path): |
| 614 |
shutil.rmtree(tmp_path) |
| 615 |
|
| 616 |
# Run shipit |
| 617 |
run_cmd( |
| 618 |
[ |
| 619 |
"php", |
| 620 |
ShipitTransformerFetcher.SHIPIT, |
| 621 |
"--project=" + self.project_name, |
| 622 |
"--create-new-repo", |
| 623 |
"--source-repo-dir=" + self.build_options.fbsource_dir, |
| 624 |
"--source-branch=.", |
| 625 |
"--skip-source-init", |
| 626 |
"--skip-source-pull", |
| 627 |
"--skip-source-clean", |
| 628 |
"--skip-push", |
| 629 |
"--skip-reset", |
| 630 |
"--destination-use-anonymous-https", |
| 631 |
"--create-new-repo-output-path=" + tmp_path, |
| 632 |
] |
| 633 |
) |
| 634 |
|
| 635 |
# Remove the .git directory from the repository it generated. |
| 636 |
# There is no need to commit this. |
| 637 |
repo_git_dir = os.path.join(tmp_path, ".git") |
| 638 |
shutil.rmtree(repo_git_dir) |
| 639 |
os.rename(tmp_path, self.repo_dir) |
| 640 |
except Exception: |
| 641 |
# Clean up after a failed extraction |
| 642 |
if os.path.exists(tmp_path): |
| 643 |
shutil.rmtree(tmp_path) |
| 644 |
self.clean() |
| 645 |
raise |
| 646 |
|
| 647 |
# pyre-fixme[15]: `hash` overrides method defined in `Fetcher` inconsistently. |
| 648 |
def hash(self) -> str: |
| 649 |
# We return a fixed non-hash string for in-fbsource builds. |
| 650 |
return "fbsource" |
| 651 |
|
| 652 |
def get_src_dir(self): |
| 653 |
return self.repo_dir |
| 654 |
|
| 655 |
|
| 656 |
def download_url_to_file_with_progress(url: str, file_name) -> None: |
| 657 |
print("Download with %s -> %s ..." % (url, file_name)) |
| 658 |
|
| 659 |
class Progress(object): |
| 660 |
last_report = 0 |
| 661 |
|
| 662 |
def write_update(self, total, amount): |
| 663 |
if total == -1: |
| 664 |
total = "(Unknown)" |
| 665 |
|
| 666 |
if sys.stdout.isatty(): |
| 667 |
sys.stdout.write("\r downloading %s of %s " % (amount, total)) |
| 668 |
else: |
| 669 |
# When logging to CI logs, avoid spamming the logs and print |
| 670 |
# status every few seconds |
| 671 |
now = time.time() |
| 672 |
if now - self.last_report > 5: |
| 673 |
sys.stdout.write(".. %s of %s " % (amount, total)) |
| 674 |
self.last_report = now |
| 675 |
sys.stdout.flush() |
| 676 |
|
| 677 |
def progress_pycurl(self, total, amount, _uploadtotal, _uploadamount): |
| 678 |
self.write_update(total, amount) |
| 679 |
|
| 680 |
progress = Progress() |
| 681 |
start = time.time() |
| 682 |
try: |
| 683 |
if os.environ.get("GETDEPS_USE_WGET") is not None: |
| 684 |
subprocess.run( |
| 685 |
[ |
| 686 |
"wget", |
| 687 |
"-O", |
| 688 |
file_name, |
| 689 |
url, |
| 690 |
] |
| 691 |
) |
| 692 |
|
| 693 |
headers = None |
| 694 |
|
| 695 |
elif os.environ.get("GETDEPS_USE_LIBCURL") is not None: |
| 696 |
import pycurl |
| 697 |
|
| 698 |
with open(file_name, "wb") as f: |
| 699 |
c = pycurl.Curl() |
| 700 |
c.setopt(pycurl.URL, url) |
| 701 |
c.setopt(pycurl.WRITEDATA, f) |
| 702 |
# display progress |
| 703 |
c.setopt(pycurl.NOPROGRESS, False) |
| 704 |
c.setopt(pycurl.XFERINFOFUNCTION, progress.progress_pycurl) |
| 705 |
c.perform() |
| 706 |
c.close() |
| 707 |
headers = None |
| 708 |
else: |
| 709 |
req_header = {"Accept": "application/*"} |
| 710 |
res = urlopen(Request(url, None, req_header)) |
| 711 |
chunk_size = 8192 # urlretrieve uses this value |
| 712 |
headers = res.headers |
| 713 |
content_length = res.headers.get("Content-Length") |
| 714 |
total = int(content_length.strip()) if content_length else -1 |
| 715 |
amount = 0 |
| 716 |
with open(file_name, "wb") as f: |
| 717 |
chunk = res.read(chunk_size) |
| 718 |
while chunk: |
| 719 |
f.write(chunk) |
| 720 |
amount += len(chunk) |
| 721 |
progress.write_update(total, amount) |
| 722 |
chunk = res.read(chunk_size) |
| 723 |
except (OSError, IOError) as exc: # noqa: B014 |
| 724 |
raise TransientFailure( |
| 725 |
"Failed to download %s to %s: %s" % (url, file_name, str(exc)) |
| 726 |
) |
| 727 |
|
| 728 |
end = time.time() |
| 729 |
sys.stdout.write(" [Complete in %f seconds]\n" % (end - start)) |
| 730 |
sys.stdout.flush() |
| 731 |
if headers is not None: |
| 732 |
print(f"{headers}") |
| 733 |
|
| 734 |
|
| 735 |
class ArchiveFetcher(Fetcher): |
| 736 |
def __init__(self, build_options, manifest, url, sha256) -> None: |
| 737 |
self.manifest = manifest |
| 738 |
self.url = url |
| 739 |
self.sha256 = sha256 |
| 740 |
self.build_options = build_options |
| 741 |
|
| 742 |
url = urlparse(self.url) |
| 743 |
basename = "%s-%s" % (manifest.name, os.path.basename(url.path)) |
| 744 |
self.file_name = os.path.join(build_options.scratch_dir, "downloads", basename) |
| 745 |
self.src_dir = os.path.join(build_options.scratch_dir, "extracted", basename) |
| 746 |
self.hash_file = self.src_dir + ".hash" |
| 747 |
|
| 748 |
def _verify_hash(self) -> None: |
| 749 |
h = hashlib.sha256() |
| 750 |
with open(self.file_name, "rb") as f: |
| 751 |
while True: |
| 752 |
block = f.read(8192) |
| 753 |
if not block: |
| 754 |
break |
| 755 |
h.update(block) |
| 756 |
digest = h.hexdigest() |
| 757 |
if digest != self.sha256: |
| 758 |
os.unlink(self.file_name) |
| 759 |
raise Exception( |
| 760 |
"%s: expected sha256 %s but got %s" % (self.url, self.sha256, digest) |
| 761 |
) |
| 762 |
|
| 763 |
def _download_dir(self): |
| 764 |
"""returns the download dir, creating it if it doesn't already exist""" |
| 765 |
download_dir = os.path.dirname(self.file_name) |
| 766 |
if not os.path.exists(download_dir): |
| 767 |
os.makedirs(download_dir) |
| 768 |
return download_dir |
| 769 |
|
| 770 |
def _download(self) -> None: |
| 771 |
self._download_dir() |
| 772 |
download_url_to_file_with_progress(self.url, self.file_name) |
| 773 |
self._verify_hash() |
| 774 |
|
| 775 |
def clean(self) -> None: |
| 776 |
if os.path.exists(self.src_dir): |
| 777 |
shutil.rmtree(self.src_dir) |
| 778 |
|
| 779 |
def update(self) -> ChangeStatus: |
| 780 |
try: |
| 781 |
with open(self.hash_file, "r") as f: |
| 782 |
saved_hash = f.read().strip() |
| 783 |
if saved_hash == self.sha256 and os.path.exists(self.src_dir): |
| 784 |
# Everything is up to date |
| 785 |
return ChangeStatus() |
| 786 |
print( |
| 787 |
"saved hash %s doesn't match expected hash %s, re-validating" |
| 788 |
% (saved_hash, self.sha256) |
| 789 |
) |
| 790 |
os.unlink(self.hash_file) |
| 791 |
except EnvironmentError: |
| 792 |
pass |
| 793 |
|
| 794 |
# If we got here we know the contents of src_dir are either missing |
| 795 |
# or wrong, so blow away whatever happened to be there first. |
| 796 |
if os.path.exists(self.src_dir): |
| 797 |
shutil.rmtree(self.src_dir) |
| 798 |
|
| 799 |
# If we already have a file here, make sure it looks legit before |
| 800 |
# proceeding: any errors and we just remove it and re-download |
| 801 |
if os.path.exists(self.file_name): |
| 802 |
try: |
| 803 |
self._verify_hash() |
| 804 |
except Exception: |
| 805 |
if os.path.exists(self.file_name): |
| 806 |
os.unlink(self.file_name) |
| 807 |
|
| 808 |
if not os.path.exists(self.file_name): |
| 809 |
self._download() |
| 810 |
|
| 811 |
if tarfile.is_tarfile(self.file_name): |
| 812 |
opener = tarfile.open |
| 813 |
elif zipfile.is_zipfile(self.file_name): |
| 814 |
opener = zipfile.ZipFile |
| 815 |
else: |
| 816 |
raise Exception("don't know how to extract %s" % self.file_name) |
| 817 |
os.makedirs(self.src_dir) |
| 818 |
print("Extract %s -> %s" % (self.file_name, self.src_dir)) |
| 819 |
t = opener(self.file_name) |
| 820 |
if is_windows(): |
| 821 |
# Ensure that we don't fall over when dealing with long paths |
| 822 |
# on windows |
| 823 |
src = r"\\?\%s" % os.path.normpath(self.src_dir) |
| 824 |
else: |
| 825 |
src = self.src_dir |
| 826 |
# The `str` here is necessary to ensure that we don't pass a unicode |
| 827 |
# object down to tarfile.extractall on python2. When extracting |
| 828 |
# the boost tarball it makes some assumptions and tries to convert |
| 829 |
# a non-ascii path to ascii and throws. |
| 830 |
src = str(src) |
| 831 |
t.extractall(src) |
| 832 |
|
| 833 |
with open(self.hash_file, "w") as f: |
| 834 |
f.write(self.sha256) |
| 835 |
|
| 836 |
return ChangeStatus(True) |
| 837 |
|
| 838 |
def hash(self): |
| 839 |
return self.sha256 |
| 840 |
|
| 841 |
def get_src_dir(self): |
| 842 |
return self.src_dir |
| 843 |
|
| 844 |
|
| 845 |
def homebrew_package_prefix(package): |
| 846 |
cmd = ["brew", "--prefix", package] |
| 847 |
try: |
| 848 |
proc = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE) |
| 849 |
except FileNotFoundError: |
| 850 |
return |
| 851 |
|
| 852 |
if proc.returncode == 0: |
| 853 |
return proc.stdout.decode("utf-8").rstrip() |