Philipp Schrader | 37fdbb6 | 2021-12-18 00:30:37 -0800 | [diff] [blame] | 1 | """This script mirrors the dependencies from go_deps.bzl as Build-Dependencies. |
| 2 | |
| 3 | We use "go mod download" to manually download each Go dependency. We then tar |
| 4 | up all the dependencies and copy them to the Build-Dependencies server for |
| 5 | hosting. |
| 6 | """ |
| 7 | |
| 8 | import argparse |
| 9 | import hashlib |
| 10 | import json |
| 11 | import os |
| 12 | from pathlib import Path |
| 13 | import subprocess |
| 14 | import sys |
| 15 | import tarfile |
| 16 | from typing import List, Dict |
| 17 | import urllib.request |
| 18 | |
Philipp Schrader | cc016b3 | 2021-12-30 08:59:58 -0800 | [diff] [blame^] | 19 | from bazel_tools.tools.python.runfiles import runfiles |
| 20 | |
| 21 | # Need a fully qualified import here because @bazel_tools interferes. |
| 22 | import org_frc971.tools.go.mirror_lib |
Philipp Schrader | 37fdbb6 | 2021-12-18 00:30:37 -0800 | [diff] [blame] | 23 | |
| 24 | GO_DEPS_WWWW_DIR = "/var/www/html/files/frc971/Build-Dependencies/go_deps" |
| 25 | |
| 26 | def compute_sha256(filepath: str) -> str: |
| 27 | """Computes the SHA256 of a file at the specified location.""" |
| 28 | with open(filepath, "rb") as file: |
| 29 | contents = file.read() |
| 30 | return hashlib.sha256(contents).hexdigest() |
| 31 | |
| 32 | def get_existing_mirrored_repos(ssh_host: str) -> Dict[str, str]: |
| 33 | """Gathers information about the libraries that are currently mirrored.""" |
| 34 | run_result = subprocess.run(["ssh", ssh_host, f"bash -c 'sha256sum {GO_DEPS_WWWW_DIR}/*'"], check=True, stdout=subprocess.PIPE) |
| 35 | |
| 36 | existing_mirrored_repos = {} |
| 37 | for line in run_result.stdout.decode("utf-8").splitlines(): |
| 38 | sha256, fullpath = line.split() |
| 39 | existing_mirrored_repos[Path(fullpath).name] = sha256 |
| 40 | |
| 41 | return existing_mirrored_repos |
| 42 | |
| 43 | def download_repos( |
| 44 | repos: Dict[str, str], |
| 45 | existing_mirrored_repos: Dict[str, str], |
| 46 | tar: tarfile.TarFile) -> Dict[str, str]: |
| 47 | """Downloads the not-yet-mirrored repos into a tarball.""" |
| 48 | cached_info = {} |
| 49 | |
| 50 | for repo in repos: |
| 51 | print(f"Downloading file for {repo['name']}") |
| 52 | importpath = repo["importpath"] |
| 53 | version = repo["version"] |
| 54 | module = f"{importpath}@{version}" |
| 55 | |
| 56 | download_result = subprocess.run( |
| 57 | ["external/go_sdk/bin/go", "mod", "download", "-json", module], |
| 58 | check=True, stdout=subprocess.PIPE) |
| 59 | if download_result.returncode != 0: |
| 60 | print("Failed to download file.") |
| 61 | return 1 |
| 62 | |
| 63 | module_info = json.loads(download_result.stdout.decode("utf-8")) |
| 64 | |
| 65 | name = repo["name"] |
| 66 | zip_path = Path(module_info["Zip"]) |
| 67 | mirrored_name = f"{name}__{zip_path.name}" |
| 68 | if mirrored_name not in existing_mirrored_repos: |
| 69 | # We only add the Go library to the tarball if it's not already |
| 70 | # mirrored. We don't want to overwrite files. |
| 71 | tar.add(zip_path, arcname=mirrored_name) |
| 72 | sha256 = compute_sha256(zip_path) |
| 73 | else: |
| 74 | # Use the already-computed checksum for consistency. |
| 75 | sha256 = existing_mirrored_repos[mirrored_name] |
| 76 | |
| 77 | cached_info[name] = { |
| 78 | "strip_prefix": module, |
| 79 | "filename": mirrored_name, |
| 80 | "sha256": sha256, |
| 81 | "version": version, |
| 82 | "importpath": importpath, |
| 83 | } |
| 84 | |
| 85 | return cached_info |
| 86 | |
| 87 | def copy_to_host_and_unpack(filename: str, ssh_host: str) -> None: |
| 88 | subprocess.run(["scp", filename, f"{ssh_host}:"], check=True) |
| 89 | |
| 90 | # Be careful not to use single quotes in these commands to avoid breaking |
| 91 | # the subprocess.run() invocation below. |
| 92 | command = " && ".join([ |
| 93 | f"tar -C {GO_DEPS_WWWW_DIR} --no-same-owner -xvaf {filename}", |
| 94 | # Change the permissions so other users can read them (and checksum |
| 95 | # them). |
| 96 | f"find {GO_DEPS_WWWW_DIR}/ -type f -exec chmod 644 {{}} +", |
| 97 | ]) |
| 98 | |
| 99 | print("You might be asked for your sudo password shortly.") |
| 100 | subprocess.run(["ssh", "-t", ssh_host, f"sudo -u www-data bash -c '{command}'"], check=True) |
| 101 | |
| 102 | def main(argv): |
| 103 | parser = argparse.ArgumentParser() |
| 104 | parser.add_argument( |
| 105 | "--ssh_host", |
| 106 | type=str, |
| 107 | help=("The SSH host to copy the downloaded Go repositories to. This " |
| 108 | "should be software.971spartans.net where all the " |
| 109 | "Build-Dependencies files live. Only specify this if you have " |
| 110 | "access to the server.")) |
| 111 | parser.add_argument("--go_deps_bzl", type=str, default="go_deps.bzl") |
| 112 | parser.add_argument("--go_mirrors_bzl", type=str, default="tools/go/go_mirrors.bzl") |
| 113 | args = parser.parse_args(argv[1:]) |
| 114 | |
| 115 | os.chdir(os.environ["BUILD_WORKSPACE_DIRECTORY"]) |
| 116 | |
Philipp Schrader | cc016b3 | 2021-12-30 08:59:58 -0800 | [diff] [blame^] | 117 | repos = org_frc971.tools.go.mirror_lib.parse_go_repositories(args.go_deps_bzl) |
Philipp Schrader | 37fdbb6 | 2021-12-18 00:30:37 -0800 | [diff] [blame] | 118 | |
| 119 | if args.ssh_host: |
| 120 | existing_mirrored_repos = get_existing_mirrored_repos(args.ssh_host) |
| 121 | else: |
| 122 | existing_mirrored_repos = {} |
| 123 | |
| 124 | with tarfile.open("go_deps.tar", "w") as tar: |
| 125 | cached_info = download_repos(repos, existing_mirrored_repos, tar) |
| 126 | num_not_already_mirrored = len(tar.getnames()) |
| 127 | |
| 128 | print(f"Found {num_not_already_mirrored}/{len(cached_info)} libraries " |
| 129 | "that need to be mirrored.") |
| 130 | |
| 131 | # Only mirror the deps if we've specified an SSH host and we actually have |
| 132 | # something to mirror. |
| 133 | if args.ssh_host and num_not_already_mirrored: |
| 134 | copy_to_host_and_unpack("go_deps.tar", args.ssh_host) |
| 135 | else: |
| 136 | print("Skipping mirroring because of lack of --ssh_host or there's " |
| 137 | "nothing to actually mirror.") |
| 138 | |
| 139 | with open(args.go_mirrors_bzl, "w") as file: |
| 140 | file.write("# This file is auto-generated. Do not edit.\n") |
| 141 | file.write("GO_MIRROR_INFO = ") |
Philipp Schrader | cc016b3 | 2021-12-30 08:59:58 -0800 | [diff] [blame^] | 142 | # Format as JSON first. It's parsable as Starlark. |
| 143 | json.dump(cached_info, file, indent=4, sort_keys=True) |
Philipp Schrader | 37fdbb6 | 2021-12-18 00:30:37 -0800 | [diff] [blame] | 144 | file.write("\n") |
| 145 | |
| 146 | |
Philipp Schrader | cc016b3 | 2021-12-30 08:59:58 -0800 | [diff] [blame^] | 147 | # Properly format the file now so that the linter doesn't complain. |
| 148 | r = runfiles.Create() |
| 149 | subprocess.run( |
| 150 | [ |
| 151 | r.Rlocation("com_github_bazelbuild_buildtools/buildifier/buildifier_/buildifier"), |
| 152 | args.go_mirrors_bzl, |
| 153 | ], |
| 154 | check=True) |
| 155 | |
| 156 | |
Philipp Schrader | 37fdbb6 | 2021-12-18 00:30:37 -0800 | [diff] [blame] | 157 | if __name__ == "__main__": |
| 158 | sys.exit(main(sys.argv)) |