blob: 52d611f8417dd36f452b8b4b487e0b49d13f180a [file] [log] [blame]
Philipp Schrader37fdbb62021-12-18 00:30:37 -08001"""This script mirrors the dependencies from go_deps.bzl as Build-Dependencies.
2
3We use "go mod download" to manually download each Go dependency. We then tar
4up all the dependencies and copy them to the Build-Dependencies server for
5hosting.
6"""
7
8import argparse
9import hashlib
10import json
11import os
12from pathlib import Path
13import subprocess
14import sys
15import tarfile
16from typing import List, Dict
Philipp Schradercc016b32021-12-30 08:59:58 -080017
18# Need a fully qualified import here because @bazel_tools interferes.
19import org_frc971.tools.go.mirror_lib
Philipp Schrader37fdbb62021-12-18 00:30:37 -080020
21GO_DEPS_WWWW_DIR = "/var/www/html/files/frc971/Build-Dependencies/go_deps"
22
Ravago Jones5127ccc2022-07-31 16:32:45 -070023
Philipp Schrader37fdbb62021-12-18 00:30:37 -080024def compute_sha256(filepath: str) -> str:
25 """Computes the SHA256 of a file at the specified location."""
26 with open(filepath, "rb") as file:
27 contents = file.read()
28 return hashlib.sha256(contents).hexdigest()
29
Ravago Jones5127ccc2022-07-31 16:32:45 -070030
Philipp Schrader37fdbb62021-12-18 00:30:37 -080031def get_existing_mirrored_repos(ssh_host: str) -> Dict[str, str]:
32 """Gathers information about the libraries that are currently mirrored."""
Ravago Jones5127ccc2022-07-31 16:32:45 -070033 run_result = subprocess.run(
34 ["ssh", ssh_host, f"bash -c 'sha256sum {GO_DEPS_WWWW_DIR}/*'"],
35 check=True,
36 stdout=subprocess.PIPE)
Philipp Schrader37fdbb62021-12-18 00:30:37 -080037
38 existing_mirrored_repos = {}
39 for line in run_result.stdout.decode("utf-8").splitlines():
40 sha256, fullpath = line.split()
41 existing_mirrored_repos[Path(fullpath).name] = sha256
42
43 return existing_mirrored_repos
44
Ravago Jones5127ccc2022-07-31 16:32:45 -070045
46def download_repos(repos: Dict[str, str], existing_mirrored_repos: Dict[str,
47 str],
48 tar: tarfile.TarFile) -> Dict[str, str]:
Philipp Schrader37fdbb62021-12-18 00:30:37 -080049 """Downloads the not-yet-mirrored repos into a tarball."""
50 cached_info = {}
51
52 for repo in repos:
53 print(f"Downloading file for {repo['name']}")
54 importpath = repo["importpath"]
55 version = repo["version"]
56 module = f"{importpath}@{version}"
57
58 download_result = subprocess.run(
59 ["external/go_sdk/bin/go", "mod", "download", "-json", module],
Ravago Jones5127ccc2022-07-31 16:32:45 -070060 check=True,
61 stdout=subprocess.PIPE)
Philipp Schrader37fdbb62021-12-18 00:30:37 -080062 if download_result.returncode != 0:
63 print("Failed to download file.")
64 return 1
65
66 module_info = json.loads(download_result.stdout.decode("utf-8"))
67
68 name = repo["name"]
69 zip_path = Path(module_info["Zip"])
70 mirrored_name = f"{name}__{zip_path.name}"
71 if mirrored_name not in existing_mirrored_repos:
72 # We only add the Go library to the tarball if it's not already
73 # mirrored. We don't want to overwrite files.
74 tar.add(zip_path, arcname=mirrored_name)
75 sha256 = compute_sha256(zip_path)
76 else:
77 # Use the already-computed checksum for consistency.
78 sha256 = existing_mirrored_repos[mirrored_name]
79
80 cached_info[name] = {
81 "strip_prefix": module,
82 "filename": mirrored_name,
83 "sha256": sha256,
84 "version": version,
85 "importpath": importpath,
86 }
87
88 return cached_info
89
Ravago Jones5127ccc2022-07-31 16:32:45 -070090
Philipp Schrader37fdbb62021-12-18 00:30:37 -080091def copy_to_host_and_unpack(filename: str, ssh_host: str) -> None:
92 subprocess.run(["scp", filename, f"{ssh_host}:"], check=True)
93
94 # Be careful not to use single quotes in these commands to avoid breaking
95 # the subprocess.run() invocation below.
96 command = " && ".join([
97 f"tar -C {GO_DEPS_WWWW_DIR} --no-same-owner -xvaf {filename}",
98 # Change the permissions so other users can read them (and checksum
99 # them).
100 f"find {GO_DEPS_WWWW_DIR}/ -type f -exec chmod 644 {{}} +",
101 ])
102
103 print("You might be asked for your sudo password shortly.")
Ravago Jones5127ccc2022-07-31 16:32:45 -0700104 subprocess.run(
105 ["ssh", "-t", ssh_host, f"sudo -u www-data bash -c '{command}'"],
106 check=True)
107
Philipp Schrader37fdbb62021-12-18 00:30:37 -0800108
109def main(argv):
110 parser = argparse.ArgumentParser()
Philipp Schraderd96d4cb2022-02-06 15:37:29 -0800111 group = parser.add_mutually_exclusive_group()
112 group.add_argument(
113 "--prune",
114 action="store_true",
115 help=("When set, makes the tool prune go_mirrors_bzl to match the "
116 "repositories specified in go_deps_bzl. Incompatible with "
117 "--ssh_host."))
118 group.add_argument(
Philipp Schrader37fdbb62021-12-18 00:30:37 -0800119 "--ssh_host",
120 type=str,
121 help=("The SSH host to copy the downloaded Go repositories to. This "
122 "should be software.971spartans.net where all the "
123 "Build-Dependencies files live. Only specify this if you have "
124 "access to the server."))
125 parser.add_argument("--go_deps_bzl", type=str, default="go_deps.bzl")
Ravago Jones5127ccc2022-07-31 16:32:45 -0700126 parser.add_argument("--go_mirrors_bzl",
127 type=str,
128 default="tools/go/go_mirrors.bzl")
Philipp Schrader37fdbb62021-12-18 00:30:37 -0800129 args = parser.parse_args(argv[1:])
130
131 os.chdir(os.environ["BUILD_WORKSPACE_DIRECTORY"])
132
Ravago Jones5127ccc2022-07-31 16:32:45 -0700133 repos = org_frc971.tools.go.mirror_lib.parse_go_repositories(
134 args.go_deps_bzl)
Philipp Schrader37fdbb62021-12-18 00:30:37 -0800135
136 if args.ssh_host:
137 existing_mirrored_repos = get_existing_mirrored_repos(args.ssh_host)
138 else:
139 existing_mirrored_repos = {}
140
Philipp Schraderd96d4cb2022-02-06 15:37:29 -0800141 exit_code = 0
Philipp Schrader37fdbb62021-12-18 00:30:37 -0800142
Philipp Schraderd96d4cb2022-02-06 15:37:29 -0800143 if args.prune:
144 # Delete all mirror info that is not needed anymore.
Ravago Jones5127ccc2022-07-31 16:32:45 -0700145 existing_cache_info = org_frc971.tools.go.mirror_lib.parse_go_mirror_info(
146 args.go_mirrors_bzl)
Philipp Schraderd96d4cb2022-02-06 15:37:29 -0800147 cached_info = {}
148 for repo in repos:
149 try:
150 cached_info[repo["name"]] = existing_cache_info[repo["name"]]
151 except KeyError:
152 print(f"{repo['name']} needs to be mirrored still.")
153 exit_code = 1
Philipp Schrader37fdbb62021-12-18 00:30:37 -0800154 else:
Philipp Schraderd96d4cb2022-02-06 15:37:29 -0800155 # Download all the repositories that need to be mirrored.
156 with tarfile.open("go_deps.tar", "w") as tar:
157 cached_info = download_repos(repos, existing_mirrored_repos, tar)
158 num_not_already_mirrored = len(tar.getnames())
Philipp Schrader37fdbb62021-12-18 00:30:37 -0800159
Philipp Schraderd96d4cb2022-02-06 15:37:29 -0800160 print(f"Found {num_not_already_mirrored}/{len(cached_info)} libraries "
161 "that need to be mirrored.")
Philipp Schrader37fdbb62021-12-18 00:30:37 -0800162
Philipp Schraderd96d4cb2022-02-06 15:37:29 -0800163 # Only mirror the deps if we've specified an SSH host and we actually have
164 # something to mirror.
165 if args.ssh_host and num_not_already_mirrored:
166 copy_to_host_and_unpack("go_deps.tar", args.ssh_host)
167 else:
Ravago Jones5127ccc2022-07-31 16:32:45 -0700168 print(
169 "Skipping mirroring because of lack of --ssh_host or there's "
170 "nothing to actually mirror.")
Philipp Schrader37fdbb62021-12-18 00:30:37 -0800171
Ravago Jones5127ccc2022-07-31 16:32:45 -0700172 org_frc971.tools.go.mirror_lib.write_go_mirror_info(
173 args.go_mirrors_bzl, cached_info)
Philipp Schraderd96d4cb2022-02-06 15:37:29 -0800174
175 return exit_code
Philipp Schradercc016b32021-12-30 08:59:58 -0800176
177
Philipp Schrader37fdbb62021-12-18 00:30:37 -0800178if __name__ == "__main__":
179 sys.exit(main(sys.argv))