bitfab 0.78.2 → 0.78.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- checksums.yaml +4 -4
- data/lib/bitfab/cloudReplay.mjs +24170 -0
- data/lib/bitfab/cloud_replay_cli.rb +4 -3
- data/lib/bitfab/version.rb +1 -1
- metadata +2 -2
- data/lib/bitfab/cloudReplay.py +0 -3822
data/lib/bitfab/cloudReplay.py
DELETED
|
@@ -1,3822 +0,0 @@
|
|
|
1
|
-
from __future__ import annotations
|
|
2
|
-
|
|
3
|
-
import argparse
|
|
4
|
-
import base64
|
|
5
|
-
import calendar
|
|
6
|
-
import contextlib
|
|
7
|
-
import functools
|
|
8
|
-
import json
|
|
9
|
-
import os
|
|
10
|
-
import re
|
|
11
|
-
import shlex
|
|
12
|
-
import shutil
|
|
13
|
-
import signal
|
|
14
|
-
import ssl
|
|
15
|
-
import subprocess
|
|
16
|
-
import sys
|
|
17
|
-
import tempfile
|
|
18
|
-
import threading
|
|
19
|
-
import time
|
|
20
|
-
import urllib.error
|
|
21
|
-
import urllib.request
|
|
22
|
-
import uuid
|
|
23
|
-
import zlib
|
|
24
|
-
from pathlib import Path
|
|
25
|
-
from urllib.parse import urlencode
|
|
26
|
-
|
|
27
|
-
WORKFLOW = "bitfab-replay.yml"
|
|
28
|
-
WORKFLOW_NAMES = (WORKFLOW, "bitfab-replay.yaml")
|
|
29
|
-
WORKFLOW_DIRECTORY = ".github/workflows"
|
|
30
|
-
OLD_CONFIG = ".bitfab/cloud.json"
|
|
31
|
-
PREFIX = "bitfab-replay/"
|
|
32
|
-
DEFAULT_SECRET_PREFIX = "BITFAB_CLOUD_"
|
|
33
|
-
API_VERSION = "2026-03-10"
|
|
34
|
-
REPLAY_COMMAND_ENV = "BITFAB_REPLAY_COMMAND"
|
|
35
|
-
SDK_LANGUAGE_ENV = "BITFAB_SDK_LANGUAGE"
|
|
36
|
-
CHECK_COMMAND_ENV = "BITFAB_REPLAY_CHECK"
|
|
37
|
-
EXECUTION_TARGET_ENV = "BITFAB_REPLAY_EXECUTION_TARGET"
|
|
38
|
-
HOSTED_EXECUTION_TARGET = "hosted"
|
|
39
|
-
API_KEY_ENV = "BITFAB_REPLAY_BITFAB_API_KEY"
|
|
40
|
-
PRINT_API_KEY_FLAG = "--print-api-key"
|
|
41
|
-
API_KEY_LINE = "@@bitfab:api-key "
|
|
42
|
-
KEY_INPUT = "key_id"
|
|
43
|
-
KEY_TOKEN_PREFIX = "bfcr_"
|
|
44
|
-
LEFTOVER_KEY_SECRET_PREFIX = "BITFAB_REPLAY_KEY_"
|
|
45
|
-
SECRETS_PER_PAGE = 100
|
|
46
|
-
LEGACY_KEY_SECRET_REFERENCE = re.compile(
|
|
47
|
-
r"^[ \t]*\"?"
|
|
48
|
-
+ API_KEY_ENV
|
|
49
|
-
+ r"\"?[ \t]*:[ \t]*[\"']?\$\{\{\s*secrets\[\s*format\(.*$"
|
|
50
|
-
)
|
|
51
|
-
DEFAULT_SERVICE_URL = "https://bitfab.ai"
|
|
52
|
-
LAUNCH_ID_METADATA_KEY = "bitfab-launch-id"
|
|
53
|
-
AGENT_SESSION_ENV_VARS = (
|
|
54
|
-
"CLAUDE_CODE_SESSION_ID",
|
|
55
|
-
"CODEX_THREAD_ID",
|
|
56
|
-
"AGENT_SESSION_ID",
|
|
57
|
-
)
|
|
58
|
-
SAFE_AGENT_SESSION_ID = re.compile(r"^[A-Za-z0-9_-][A-Za-z0-9._-]*$")
|
|
59
|
-
OIDC_AUDIENCE = "bitfab-cloud-replay"
|
|
60
|
-
ID_TOKEN_PERMISSION = re.compile(
|
|
61
|
-
r"^[ \t]*(\"?id-token\"?[ \t]*:[ \t]*[\"']?write[\"']?|\"?permissions\"?[ \t]*:[ \t]*[\"']?write-all[\"']?)[ \t]*(#.*)?$",
|
|
62
|
-
re.MULTILINE,
|
|
63
|
-
)
|
|
64
|
-
API_KEY_PROBE_SECONDS = 120
|
|
65
|
-
RUN_NAME = "Bitfab replay ${{ inputs.execution_id || github.ref_name }}"
|
|
66
|
-
REQUEST_VERSION = 4
|
|
67
|
-
PLAIN_REQUEST_VERSION = 3
|
|
68
|
-
OLDEST_DISPATCHED_VERSION = 2
|
|
69
|
-
RESULT_LINE = "bitfab-replay-result "
|
|
70
|
-
RESULT_CHUNK = 4000
|
|
71
|
-
OUTPUT_BEGIN = "bitfab-replay-output-begin"
|
|
72
|
-
OUTPUT_END = "bitfab-replay-output-end"
|
|
73
|
-
LOG_TAIL_LINES = 40
|
|
74
|
-
OUTPUT_LIMIT = 16 * 1024 * 1024
|
|
75
|
-
DISK_LIMIT = 1024 * 1024 * 1024
|
|
76
|
-
NEW_FILES_LIMIT = 20 * 1024 * 1024
|
|
77
|
-
POLL_SECONDS = 5
|
|
78
|
-
CLEANABLE_STATES = ("completed", "prepared", "dispatch_unknown", "dispatch_rejected")
|
|
79
|
-
CLOCK_SKEW_SECONDS = 600
|
|
80
|
-
TIMESTAMP = "%Y-%m-%dT%H:%M:%SZ"
|
|
81
|
-
ITEM_ERROR_FIELDS = (
|
|
82
|
-
"error",
|
|
83
|
-
"traceError",
|
|
84
|
-
"trace_error",
|
|
85
|
-
"replayError",
|
|
86
|
-
"replay_error",
|
|
87
|
-
)
|
|
88
|
-
ITEM_ID_FIELDS = ("originalTraceId", "original_trace_id", "traceId", "trace_id")
|
|
89
|
-
ITEM_ERROR_LINES = 20
|
|
90
|
-
ITEM_ERROR_LENGTH = 500
|
|
91
|
-
SUMMARY_ERROR_ITEMS = 100
|
|
92
|
-
EXPERIMENT_FIELDS = {
|
|
93
|
-
"experimentId": ("experimentId", "experiment_id"),
|
|
94
|
-
"experimentUrl": ("experimentUrl", "experiment_url"),
|
|
95
|
-
"testRunId": ("testRunId", "test_run_id"),
|
|
96
|
-
"testRunUrl": ("testRunUrl", "test_run_url"),
|
|
97
|
-
"attempts": ("attempts",),
|
|
98
|
-
}
|
|
99
|
-
UUID = re.compile(r"^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$")
|
|
100
|
-
SHA = re.compile(r"^[0-9a-f]{40}$")
|
|
101
|
-
GITHUB_REMOTE = re.compile(
|
|
102
|
-
r"(?:git@github\.com:|https://github\.com/)([\w.-]+/[\w.-]+?)(?:\.git)?"
|
|
103
|
-
)
|
|
104
|
-
LOG_TIMESTAMP = re.compile(r"^?\d{4}-\d\d-\d\dT[\d:.]+Z ?")
|
|
105
|
-
EXPERIMENT_LINE = re.compile(rb"^\[replay\] Experiment ([0-9a-f-]{36}):")
|
|
106
|
-
PROGRESS_PREFIX = b"@@bitfab:progress "
|
|
107
|
-
PROGRESS_PAYLOAD_FIELDS = (
|
|
108
|
-
"input",
|
|
109
|
-
"result",
|
|
110
|
-
"originalOutput",
|
|
111
|
-
"original_output",
|
|
112
|
-
"selectiveReplay",
|
|
113
|
-
"selective_replay",
|
|
114
|
-
)
|
|
115
|
-
SECRET_REFERENCE = re.compile(
|
|
116
|
-
r"[\"']?([A-Za-z_][A-Za-z0-9_]*)[\"']?[ \t]*:[ \t]*[\"']?\$\{\{\s*secrets(?:\.([A-Za-z_][A-Za-z0-9_]*)|\[\s*[\"']([A-Za-z_][A-Za-z0-9_]*)[\"']\s*\])\s*\}\}"
|
|
117
|
-
)
|
|
118
|
-
ENVIRONMENT_SETTING = re.compile(
|
|
119
|
-
r"^[ \t]*\"?environment\"?[ \t]*:[ \t]*[\"']?([\w.-]+)[\"']?[ \t]*,?[ \t]*$",
|
|
120
|
-
re.MULTILINE,
|
|
121
|
-
)
|
|
122
|
-
PUSH_TRIGGER = re.compile(
|
|
123
|
-
r"^[ \t]*\"?(?:on\"?[ \t]*:.*\bpush\b|push\"?[ \t]*:)", re.MULTILINE
|
|
124
|
-
)
|
|
125
|
-
DISPATCH_INPUTS = ("execution_id", "request", KEY_INPUT)
|
|
126
|
-
PUSH_SUBJECT = "Bitfab replay started on push"
|
|
127
|
-
PUSH_CONDITION = f"github.event_name != 'push' || !startsWith(github.ref_name, '{PREFIX}') || startsWith(github.event.head_commit.message, '{PUSH_SUBJECT}')"
|
|
128
|
-
BRANCH_NAME = re.compile(r"[A-Za-z0-9][A-Za-z0-9._/-]*")
|
|
129
|
-
ENV_NAME = re.compile(r"[A-Za-z_][A-Za-z0-9_]*")
|
|
130
|
-
RESERVED_ENV_PREFIXES = ("GITHUB_", "RUNNER_", "ACTIONS_", "BITFAB_REPLAY_")
|
|
131
|
-
SECRET_ENV_NAME = re.compile(
|
|
132
|
-
r"(?:^|_)(?:KEY|SECRET|TOKEN|PASSWORD|PASSWD|CREDENTIALS?)(?:_|$)", re.IGNORECASE
|
|
133
|
-
)
|
|
134
|
-
ENV_FLAG = "--cloud-env"
|
|
135
|
-
ALLOW_FLAG = "--cloud-allow-file"
|
|
136
|
-
REPEATED_FLAGS = (ENV_FLAG, ALLOW_FLAG)
|
|
137
|
-
URL_PASSWORD = re.compile(r"[A-Za-z][A-Za-z0-9+.-]*://[^/\s:@]*:[^/\s@]+@")
|
|
138
|
-
FOLLOW_FLAGS = (
|
|
139
|
-
"--cloud-status",
|
|
140
|
-
"--cloud-watch",
|
|
141
|
-
"--cloud-cancel",
|
|
142
|
-
"--cloud-cleanup",
|
|
143
|
-
)
|
|
144
|
-
CLOUD_VALUE_FLAGS = (
|
|
145
|
-
*FOLLOW_FLAGS,
|
|
146
|
-
"--cloud-request-id",
|
|
147
|
-
"--cloud-timeout",
|
|
148
|
-
"--cloud-ref",
|
|
149
|
-
)
|
|
150
|
-
CLOUD_SWITCHES = ("--cloud", "--cloud-preview", "--cloud-detach", "--cloud-full-output")
|
|
151
|
-
RENAMED_FLAGS = {
|
|
152
|
-
"--cloud-dry-run": "--cloud-preview",
|
|
153
|
-
"--cloud-check": "--dry-run",
|
|
154
|
-
"--cloud-include": "nothing: new files that git does not ignore are already in the snapshot",
|
|
155
|
-
}
|
|
156
|
-
SEED_FLAGS = ("--seed", "--cases", "--from-trace", "--run")
|
|
157
|
-
PATH_FLAGS = ("--registry", "--params", "--code-change-file")
|
|
158
|
-
CODE_CHANGE_FLAG = "--code-change"
|
|
159
|
-
CODE_CHANGE_BASE_FLAG = "--code-change-base"
|
|
160
|
-
BRANCH_CODE_CHANGES = ("last-branch", "default-branch", "ref")
|
|
161
|
-
GIT_CODE_CHANGES = ("working-tree", *BRANCH_CODE_CHANGES)
|
|
162
|
-
FETCHED_CODE_CHANGES = ("default-branch", "ref")
|
|
163
|
-
CHECKOUT_ONLY_CODE_CHANGES = ("working-tree", "last-branch")
|
|
164
|
-
GIT_TOKEN_ENV = "BITFAB_REPLAY_GIT_TOKEN"
|
|
165
|
-
GIT_TOKEN_VALUE = "${{ github.token }}"
|
|
166
|
-
FETCH_SECONDS = 600
|
|
167
|
-
DESCRIBED_REF = re.compile(r"[^\x00-\x1f\x7f]{1,200}")
|
|
168
|
-
CHECKOUT_DEPTH = 2
|
|
169
|
-
CODE_CHANGE_PATH_ENV = "BITFAB_CODE_CHANGE_PATH"
|
|
170
|
-
CODE_CHANGE_MAX_FILES = 60
|
|
171
|
-
CODE_CHANGE_MAX_FILE_BYTES = 500_000
|
|
172
|
-
CODE_CHANGE_MAX_TOTAL_BYTES = 2_000_000
|
|
173
|
-
BRANCH_WALK_LIMIT = 1000
|
|
174
|
-
CHECK_ARGUMENTS_SECONDS = 300
|
|
175
|
-
CHECK_ARGUMENTS_FLAG = "--check-arguments"
|
|
176
|
-
REPLAY_ARGUMENTS_FLAG = "--replay-arguments"
|
|
177
|
-
ARGUMENTS_CHECKED_ENV = "BITFAB_REPLAY_ARGUMENTS_CHECKED"
|
|
178
|
-
ACTIONS = {
|
|
179
|
-
"checkout": "actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1",
|
|
180
|
-
"node": "actions/setup-node@820762786026740c76f36085b0efc47a31fe5020",
|
|
181
|
-
"pnpm": "pnpm/action-setup@ea17c68df8912ef543352723c149a84f56e3d413",
|
|
182
|
-
"bun": "oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6",
|
|
183
|
-
"python": "actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97",
|
|
184
|
-
"uv": "astral-sh/setup-uv@c18668ad3cf93ea998bef934396af7bb5c839dc7",
|
|
185
|
-
"ruby": "ruby/setup-ruby@14594264cd68ce8a2345dd349bc3d138a4ef85c8",
|
|
186
|
-
"go": "actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e",
|
|
187
|
-
}
|
|
188
|
-
NO_GITHUB = (
|
|
189
|
-
"Cloud replay needs access to GitHub. Any one of these works: "
|
|
190
|
-
"log in with the GitHub CLI (gh auth login); "
|
|
191
|
-
"set GH_TOKEN to a token that can push to the repository and run its Actions; "
|
|
192
|
-
"or push to github.com over https once, so git stores a credential for it"
|
|
193
|
-
)
|
|
194
|
-
HELP = """Cloud replay: run the replay you run locally on GitHub Actions by adding --cloud.
|
|
195
|
-
|
|
196
|
-
bitfab-replay --registry scripts/replay.ts classify --trace-ids UUID --cloud
|
|
197
|
-
|
|
198
|
-
Every replay option works as it does locally, including --dry-run and --fail-on-error,
|
|
199
|
-
and your SDK checks them before anything is uploaded. The runner replays a snapshot of
|
|
200
|
-
your working tree (changed files, plus new files git does not ignore) from the same
|
|
201
|
-
directory, and this command prints the replay's output and exits with its exit code.
|
|
202
|
-
The experiment records your branch, the commit the snapshot was taken on, and the
|
|
203
|
-
snapshot's changed files as its code change, as it would for a local replay.
|
|
204
|
-
Credential-like files that are not on GitHub yet are refused unless you name them with
|
|
205
|
-
--cloud-allow-file. Requires git and Python 3.10+ on macOS or Linux, with a github.com
|
|
206
|
-
origin.
|
|
207
|
-
|
|
208
|
-
The replay's stderr comes back as it printed it. Its stdout result comes back as a
|
|
209
|
-
short summary instead of every item: the experiment ID and URL, how many traces were
|
|
210
|
-
replayed, same, changed, and errored, each errored trace with its error, and the exit
|
|
211
|
-
code. Every item's input and output are saved in the experiment in Bitfab, where the
|
|
212
|
-
Bitfab MCP tools read them, so by default the job log holds no trace data.
|
|
213
|
-
|
|
214
|
-
Options added by --cloud:
|
|
215
|
-
--cloud-preview List what the snapshot would contain and push nothing.
|
|
216
|
-
--cloud-detach Return after dispatch instead of waiting.
|
|
217
|
-
--cloud-full-output Print the replay's whole stdout result, every item included,
|
|
218
|
-
instead of the summary. The result passes through the
|
|
219
|
-
GitHub job log, so it is refused on a public repository,
|
|
220
|
-
and large runs can exceed what the log holds.
|
|
221
|
-
--cloud-timeout MIN Stop the replay after MIN minutes (1..7200).
|
|
222
|
-
--cloud-env NAME=VALUE Set an environment variable for this replay only; repeat it
|
|
223
|
-
for more. NAME alone copies the value from your shell. The
|
|
224
|
-
value is stored in the snapshot commit on GitHub, so this is
|
|
225
|
-
for settings, never secrets: names that look like secrets,
|
|
226
|
-
and names the workflow reads from a secret, are refused.
|
|
227
|
-
--cloud-allow-file PATH
|
|
228
|
-
Upload PATH even though it looks like a credential, such as
|
|
229
|
-
a test certificate; repeat it for more. Refused on a public
|
|
230
|
-
repository, where anyone can read the snapshot branch.
|
|
231
|
-
--cloud-request-id ID Recover a submission whose response was lost.
|
|
232
|
-
--cloud-ref BRANCH Replay BRANCH as it is on GitHub, with no snapshot of your
|
|
233
|
-
working tree, and record the experiment on BRANCH. Meant for
|
|
234
|
-
CI jobs, such as a nightly replay of dev. Runs from a
|
|
235
|
-
checkout of the repository, with GitHub access that can
|
|
236
|
-
read it and run Actions (a job token needs contents: read
|
|
237
|
-
and actions: write, passed as GH_TOKEN), and a workflow on
|
|
238
|
-
BRANCH that declares a request input. With no snapshot,
|
|
239
|
-
--code-change default-branch and ref fetch their base on
|
|
240
|
-
the runner with the run's GitHub token, which the
|
|
241
|
-
workflow passes as BITFAB_REPLAY_GIT_TOKEN and the
|
|
242
|
-
replay never sees; working-tree and last-branch are
|
|
243
|
-
refused, as they are on a dispatched run.
|
|
244
|
-
|
|
245
|
-
A workflow can also dispatch bitfab-replay.yml itself on any branch other than a
|
|
246
|
-
bitfab-replay/ snapshot branch, passing the replay as JSON in the request input:
|
|
247
|
-
|
|
248
|
-
{"args": ["--registry", "scripts/replay.ts", "classify", "--dataset-ids", "UUID"],
|
|
249
|
-
"cwd": "web", "timeoutMinutes": 60, "env": {"LOG_LEVEL": "debug"}}
|
|
250
|
-
|
|
251
|
-
args are the replay options without --cloud. cwd is the directory to replay from,
|
|
252
|
-
relative to the repository root, and defaults to the root. timeoutMinutes and
|
|
253
|
-
fullOutput (true) match --cloud-timeout and --cloud-full-output, and env holds the
|
|
254
|
-
values --cloud-env sets. version and id are optional: version names the request
|
|
255
|
-
format (4 when env is set, otherwise 3; 2 is still accepted), and id is the
|
|
256
|
-
execution UUID, which must match an execution_id input when the workflow has one.
|
|
257
|
-
|
|
258
|
-
The replay runs as the person who started it, so the experiment is recorded as
|
|
259
|
-
yours. Before dispatch, the replay's registry is loaded locally to read its
|
|
260
|
-
client's key, which asks Bitfab for a one-time token passed as the key_id input,
|
|
261
|
-
tied to the repository, branch, and workflow of the run. The runner trades that
|
|
262
|
-
token, together with the GitHub Actions OIDC token of its own run, for a key that
|
|
263
|
-
works only until the replay ends, so only that run can use it; the token alone
|
|
264
|
-
opens nothing. With no key resolved locally, a token Bitfab will not issue or
|
|
265
|
-
trade, or a workflow that declares no key_id input or does not grant
|
|
266
|
-
id-token: write, the run uses the workflow's BITFAB_API_KEY secret instead.
|
|
267
|
-
|
|
268
|
-
The runner's job exits with the replay's exit code, so the Actions run fails when
|
|
269
|
-
the replay does. Traces that errored fail it only under --fail-on-error.
|
|
270
|
-
|
|
271
|
-
Follow a replay by the execution UUID it prints:
|
|
272
|
-
--cloud-watch ID | --cloud-status ID | --cloud-cancel ID | --cloud-cleanup ID
|
|
273
|
-
--cloud-cleanup removes the snapshot branch once the run completed, or when GitHub
|
|
274
|
-
shows no run for it, such as after a dispatch that failed.
|
|
275
|
-
|
|
276
|
-
Set up once:
|
|
277
|
-
--cloud-init [--secret NAME ...] [--environment NAME] [--run COMMAND]
|
|
278
|
-
[--runs-on LABEL] [--secret-prefix PREFIX] [--check COMMAND]
|
|
279
|
-
Writes .github/workflows/bitfab-replay.yml, the only file cloud replay keeps
|
|
280
|
-
in the repository, and lists what is left to do. On an existing workflow it
|
|
281
|
-
adds only the lines a newer SDK needs, such as the push trigger that lets a
|
|
282
|
-
replay run without GitHub access, and lists what it changed.
|
|
283
|
-
--cloud-update [same options] [--remove-old-key-secrets]
|
|
284
|
-
The same command as --cloud-init, for bringing an existing setup up to date.
|
|
285
|
-
It also lists BITFAB_REPLAY_KEY_* secrets an older SDK left in the
|
|
286
|
-
repository, each a copy of someone's Bitfab API key, and with
|
|
287
|
-
--remove-old-key-secrets deletes them.
|
|
288
|
-
--cloud-secrets --env-file FILE [NAME ...] [--environment NAME] [--dry-run]
|
|
289
|
-
Copies local values into the GitHub secrets the workflow reads.
|
|
290
|
-
|
|
291
|
-
GitHub access comes from the GitHub CLI when it is logged in, otherwise from GH_TOKEN
|
|
292
|
-
or GITHUB_TOKEN, otherwise from the github.com credential git already stores. Without
|
|
293
|
-
the GitHub CLI, --cloud-secrets lists the secrets to create by hand and where.
|
|
294
|
-
|
|
295
|
-
Without GitHub access, or with access that cannot read or push to the repository, a
|
|
296
|
-
replay still runs when git can push the snapshot branch and the workflow also starts
|
|
297
|
-
on a push to a bitfab-replay/ branch, as one written or updated by --cloud-init does.
|
|
298
|
-
This command then warns, prints where to watch the run, and returns once the branch
|
|
299
|
-
is pushed, with no updates and exit code 0. The run uses the workflow's BITFAB_API_KEY
|
|
300
|
-
secret, and --cloud-full-output and --cloud-allow-file are refused, since only GitHub
|
|
301
|
-
access can confirm the repository is private. Delete the snapshot branch once the run
|
|
302
|
-
finishes. With access, a replay starts through the GitHub API as before, and its
|
|
303
|
-
snapshot commit asks GitHub not to start any workflow on the push.
|
|
304
|
-
"""
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
class CommandError(RuntimeError):
|
|
308
|
-
def __init__(self, message, http_status=None):
|
|
309
|
-
super().__init__(message)
|
|
310
|
-
self.http_status = http_status
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
class DispatchRejected(ValueError):
|
|
314
|
-
def __init__(self, message, record):
|
|
315
|
-
super().__init__(message)
|
|
316
|
-
self.record = record
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
class GithubUnreachable(ValueError):
|
|
320
|
-
pass
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
class KeepRedirect(urllib.request.HTTPRedirectHandler):
|
|
324
|
-
def redirect_request(self, *args, **kwargs):
|
|
325
|
-
return None
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
def command(args, *, cwd=None, env=None, timeout=60, input=None):
|
|
329
|
-
result = subprocess.run(
|
|
330
|
-
args,
|
|
331
|
-
cwd=cwd,
|
|
332
|
-
env=env,
|
|
333
|
-
input=input,
|
|
334
|
-
text=True,
|
|
335
|
-
check=False,
|
|
336
|
-
capture_output=True,
|
|
337
|
-
timeout=timeout,
|
|
338
|
-
)
|
|
339
|
-
if result.returncode:
|
|
340
|
-
status = re.search(r"\bHTTP (\d{3})\b", result.stderr or "")
|
|
341
|
-
http_status = int(status[1]) if status else None
|
|
342
|
-
raise CommandError(
|
|
343
|
-
f"{args[0]} {args[1]} failed (exit {result.returncode}"
|
|
344
|
-
+ (f", HTTP {http_status}" if http_status else "")
|
|
345
|
-
+ "); check authentication and permissions",
|
|
346
|
-
http_status,
|
|
347
|
-
)
|
|
348
|
-
return result.stdout.strip()
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
def git(root, *args, env=None, input=None):
|
|
352
|
-
return command(["git", "-C", str(root), *args], env=env, input=input)
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
def progress(message):
|
|
356
|
-
print(f"[cloud] {message}", file=sys.stderr, flush=True)
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
def root_directory():
|
|
360
|
-
return Path(command(["git", "rev-parse", "--show-toplevel"])).resolve()
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
def relative_path(value):
|
|
364
|
-
if not isinstance(value, str) or not value or "\\" in value or "\x00" in value:
|
|
365
|
-
raise ValueError("Expected a repository-relative path")
|
|
366
|
-
if Path(value).is_absolute() or ".." in Path(value).parts or value.startswith("-"):
|
|
367
|
-
raise ValueError("Paths must stay inside the repository")
|
|
368
|
-
return value
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
def within(root, value):
|
|
372
|
-
path = (root / relative_path(value)).resolve()
|
|
373
|
-
path.relative_to(root)
|
|
374
|
-
return path
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
def repository_path(root, path):
|
|
378
|
-
try:
|
|
379
|
-
return Path(path).resolve().relative_to(root).as_posix()
|
|
380
|
-
except ValueError as error:
|
|
381
|
-
raise ValueError(f"{path} must be inside the repository") from error
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
def working_directory(root):
|
|
385
|
-
try:
|
|
386
|
-
relative = Path.cwd().resolve().relative_to(root).as_posix()
|
|
387
|
-
except ValueError as error:
|
|
388
|
-
raise ValueError("Run cloud replay from inside the repository") from error
|
|
389
|
-
return relative or "."
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
def repository(root):
|
|
393
|
-
fetch = GITHUB_REMOTE.fullmatch(git(root, "remote", "get-url", "origin"))
|
|
394
|
-
if fetch is None:
|
|
395
|
-
raise ValueError(
|
|
396
|
-
"origin must be a github.com repository without embedded credentials"
|
|
397
|
-
)
|
|
398
|
-
push = GITHUB_REMOTE.fullmatch(git(root, "remote", "get-url", "--push", "origin"))
|
|
399
|
-
if push is None or push[1].lower() != fetch[1].lower():
|
|
400
|
-
raise ValueError("origin fetch and push repositories must match")
|
|
401
|
-
return fetch[1]
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
def find_workflow(root):
|
|
405
|
-
for name in WORKFLOW_NAMES:
|
|
406
|
-
if within(root, f"{WORKFLOW_DIRECTORY}/{name}").is_file():
|
|
407
|
-
return name
|
|
408
|
-
return None
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
def refuse_old_setup(root):
|
|
412
|
-
if within(root, OLD_CONFIG).exists():
|
|
413
|
-
raise ValueError(
|
|
414
|
-
f"This cloud replay setup was made by an older SDK. Delete {OLD_CONFIG} and {WORKFLOW_DIRECTORY}/{WORKFLOW}, then run bitfab-replay --cloud-init"
|
|
415
|
-
)
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
def setup_workflow(root):
|
|
419
|
-
refuse_old_setup(root)
|
|
420
|
-
name = find_workflow(root)
|
|
421
|
-
if name is None:
|
|
422
|
-
raise ValueError(
|
|
423
|
-
f"No {WORKFLOW_DIRECTORY}/{WORKFLOW} yet. Run bitfab-replay --cloud-init, or ask your coding agent for bitfab:setup cloud"
|
|
424
|
-
)
|
|
425
|
-
return name
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
def workflow_secrets(text):
|
|
429
|
-
return {
|
|
430
|
-
name: dotted or bracketed
|
|
431
|
-
for name, dotted, bracketed in SECRET_REFERENCE.findall(text)
|
|
432
|
-
}
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
def secrets_page(repo, environment):
|
|
436
|
-
if environment:
|
|
437
|
-
return f"https://github.com/{repo}/settings/environments"
|
|
438
|
-
return f"https://github.com/{repo}/settings/secrets/actions"
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
ENV_ASSIGNMENT = re.compile(r"[ \t]*(?:export[ \t]+)?([A-Za-z_][A-Za-z0-9_]*)[ \t]*=")
|
|
442
|
-
|
|
443
|
-
ENV_ESCAPES = {"n": "\n", "r": "\r", "t": "\t", '"': '"', "\\": "\\"}
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
def read_environment_value(text, assignment_end, name):
|
|
447
|
-
start = assignment_end
|
|
448
|
-
while start < len(text) and text[start] in " \t":
|
|
449
|
-
start += 1
|
|
450
|
-
if start < len(text) and text[start] in ("'", '"'):
|
|
451
|
-
quote = text[start]
|
|
452
|
-
pieces = []
|
|
453
|
-
position = start + 1
|
|
454
|
-
while position < len(text):
|
|
455
|
-
character = text[position]
|
|
456
|
-
if character == "\\" and quote == '"' and position + 1 < len(text):
|
|
457
|
-
following = text[position + 1]
|
|
458
|
-
pieces.append(ENV_ESCAPES.get(following, character + following))
|
|
459
|
-
position += 2
|
|
460
|
-
continue
|
|
461
|
-
if character == quote:
|
|
462
|
-
return "".join(pieces), position + 1
|
|
463
|
-
pieces.append(character)
|
|
464
|
-
position += 1
|
|
465
|
-
raise ValueError(f"{name} opens a quote that the file never closes")
|
|
466
|
-
end = text.find("\n", assignment_end)
|
|
467
|
-
end = len(text) if end == -1 else end
|
|
468
|
-
raw = text[assignment_end:end]
|
|
469
|
-
comment = re.search(r"\s#", raw)
|
|
470
|
-
return (raw if comment is None else raw[: comment.start()]).strip(), end
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
def parse_environment_file(text):
|
|
474
|
-
values = {}
|
|
475
|
-
position = 0
|
|
476
|
-
while position < len(text):
|
|
477
|
-
end = text.find("\n", position)
|
|
478
|
-
end = len(text) if end == -1 else end
|
|
479
|
-
line = text[position:end]
|
|
480
|
-
match = ENV_ASSIGNMENT.match(line)
|
|
481
|
-
if match is None or line.lstrip().startswith("#"):
|
|
482
|
-
position = end + 1
|
|
483
|
-
continue
|
|
484
|
-
value, consumed = read_environment_value(text, position + match.end(), match[1])
|
|
485
|
-
values[match[1]] = value
|
|
486
|
-
newline = text.find("\n", consumed)
|
|
487
|
-
position = len(text) if newline == -1 else newline + 1
|
|
488
|
-
return values
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
def secret_value(value):
|
|
492
|
-
if "\n" not in value:
|
|
493
|
-
return value
|
|
494
|
-
try:
|
|
495
|
-
parsed = json.loads(value)
|
|
496
|
-
except ValueError:
|
|
497
|
-
return value
|
|
498
|
-
return json.dumps(parsed, separators=(",", ":"))
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
def ensure_environment(repo, environment):
|
|
502
|
-
try:
|
|
503
|
-
api(repo, f"environments/{environment}")
|
|
504
|
-
return "exists"
|
|
505
|
-
except ValueError:
|
|
506
|
-
return "unchecked"
|
|
507
|
-
except RuntimeError as error:
|
|
508
|
-
if getattr(error, "http_status", None) != 404:
|
|
509
|
-
return "unchecked"
|
|
510
|
-
try:
|
|
511
|
-
api(repo, f"environments/{environment}", method="PUT", payload={})
|
|
512
|
-
return "created"
|
|
513
|
-
except RuntimeError:
|
|
514
|
-
return "missing"
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
def configure_secrets(argv):
|
|
518
|
-
parser = argparse.ArgumentParser(
|
|
519
|
-
prog="bitfab-replay --cloud-secrets",
|
|
520
|
-
description="Copy named values from local environment files into the GitHub Actions secrets the cloud replay workflow reads. Values are piped to the GitHub CLI on standard input and never printed, logged, or passed as arguments. Without the GitHub CLI, it lists the secrets to create by hand and where.",
|
|
521
|
-
)
|
|
522
|
-
parser.add_argument(
|
|
523
|
-
"names",
|
|
524
|
-
nargs="*",
|
|
525
|
-
help="Environment variable names to copy; defaults to every secret the workflow maps",
|
|
526
|
-
)
|
|
527
|
-
parser.add_argument(
|
|
528
|
-
"--env-file",
|
|
529
|
-
action="append",
|
|
530
|
-
required=True,
|
|
531
|
-
help="Repository-relative environment file to read; repeatable, earliest definition wins",
|
|
532
|
-
)
|
|
533
|
-
parser.add_argument(
|
|
534
|
-
"--environment",
|
|
535
|
-
help="GitHub Environment to set the secrets in; defaults to the workflow's environment, and is created when it does not exist",
|
|
536
|
-
)
|
|
537
|
-
parser.add_argument(
|
|
538
|
-
"--dry-run",
|
|
539
|
-
action="store_true",
|
|
540
|
-
help="Report which names were found without writing anything to GitHub",
|
|
541
|
-
)
|
|
542
|
-
args = parser.parse_args(argv)
|
|
543
|
-
root = root_directory()
|
|
544
|
-
text = within(root, f"{WORKFLOW_DIRECTORY}/{setup_workflow(root)}").read_text()
|
|
545
|
-
targets = workflow_secrets(text)
|
|
546
|
-
names = args.names or list(targets)
|
|
547
|
-
unknown = [name for name in names if name not in targets]
|
|
548
|
-
if unknown:
|
|
549
|
-
raise ValueError(
|
|
550
|
-
f"The workflow does not read {', '.join(unknown)}. Add each one to the replay step's env as NAME: ${{{{ secrets.{DEFAULT_SECRET_PREFIX}NAME }}}} first"
|
|
551
|
-
)
|
|
552
|
-
configured = ENVIRONMENT_SETTING.search(text)
|
|
553
|
-
environment = args.environment or (configured[1] if configured else None)
|
|
554
|
-
values = {}
|
|
555
|
-
for path in args.env_file:
|
|
556
|
-
for key, value in parse_environment_file(
|
|
557
|
-
within(root, path).read_text()
|
|
558
|
-
).items():
|
|
559
|
-
values.setdefault(key, value)
|
|
560
|
-
repo = repository(root)
|
|
561
|
-
found, missing, empty = [], [], []
|
|
562
|
-
for name in names:
|
|
563
|
-
value = values.get(name, values.get(targets[name]))
|
|
564
|
-
if value is None:
|
|
565
|
-
missing.append(targets[name])
|
|
566
|
-
elif not value:
|
|
567
|
-
empty.append(targets[name])
|
|
568
|
-
else:
|
|
569
|
-
found.append(name)
|
|
570
|
-
result = {
|
|
571
|
-
"repository": repo,
|
|
572
|
-
"environment": environment,
|
|
573
|
-
"dryRun": args.dry_run,
|
|
574
|
-
"set": [],
|
|
575
|
-
"missing": missing,
|
|
576
|
-
"empty": empty,
|
|
577
|
-
}
|
|
578
|
-
if args.dry_run:
|
|
579
|
-
return {**result, "wouldSet": [targets[name] for name in found]}
|
|
580
|
-
if environment:
|
|
581
|
-
result["environmentStatus"] = ensure_environment(repo, environment)
|
|
582
|
-
if found and shutil.which("gh") is None:
|
|
583
|
-
progress(
|
|
584
|
-
"Setting secrets needs the GitHub CLI (https://cli.github.com), which encrypts each value for GitHub; create the ones listed under createByHand instead"
|
|
585
|
-
)
|
|
586
|
-
return {
|
|
587
|
-
**result,
|
|
588
|
-
"createByHand": [targets[name] for name in found],
|
|
589
|
-
"where": secrets_page(repo, environment),
|
|
590
|
-
}
|
|
591
|
-
token = github_access()["token"]
|
|
592
|
-
for name in found:
|
|
593
|
-
command(
|
|
594
|
-
[
|
|
595
|
-
"gh",
|
|
596
|
-
"secret",
|
|
597
|
-
"set",
|
|
598
|
-
targets[name],
|
|
599
|
-
"--repo",
|
|
600
|
-
repo,
|
|
601
|
-
*(["--env", environment] if environment else []),
|
|
602
|
-
],
|
|
603
|
-
input=secret_value(values.get(name, values.get(targets[name]))),
|
|
604
|
-
env={**os.environ, "GH_TOKEN": token},
|
|
605
|
-
)
|
|
606
|
-
result["set"] = [targets[name] for name in found]
|
|
607
|
-
if missing or empty:
|
|
608
|
-
result["where"] = secrets_page(repo, environment)
|
|
609
|
-
return result
|
|
610
|
-
|
|
611
|
-
|
|
612
|
-
@functools.cache
|
|
613
|
-
def github_access():
|
|
614
|
-
if shutil.which("gh") is not None:
|
|
615
|
-
with contextlib.suppress(RuntimeError, OSError, subprocess.SubprocessError):
|
|
616
|
-
token = command(["gh", "auth", "token", "--hostname", "github.com"])
|
|
617
|
-
if token:
|
|
618
|
-
return {"source": "the GitHub CLI", "token": token}
|
|
619
|
-
for name in ("GH_TOKEN", "GITHUB_TOKEN"):
|
|
620
|
-
if os.environ.get(name):
|
|
621
|
-
return {"source": name, "token": os.environ[name]}
|
|
622
|
-
token = stored_git_credential()
|
|
623
|
-
if token:
|
|
624
|
-
return {"source": "the github.com credential git stores", "token": token}
|
|
625
|
-
raise ValueError(NO_GITHUB)
|
|
626
|
-
|
|
627
|
-
|
|
628
|
-
def stored_git_credential():
|
|
629
|
-
try:
|
|
630
|
-
result = subprocess.run(
|
|
631
|
-
["git", "credential", "fill"],
|
|
632
|
-
input="protocol=https\nhost=github.com\n\n",
|
|
633
|
-
text=True,
|
|
634
|
-
capture_output=True,
|
|
635
|
-
check=False,
|
|
636
|
-
timeout=15,
|
|
637
|
-
env={
|
|
638
|
-
**os.environ,
|
|
639
|
-
"GIT_TERMINAL_PROMPT": "0",
|
|
640
|
-
"GCM_INTERACTIVE": "never",
|
|
641
|
-
"GIT_ASKPASS": "",
|
|
642
|
-
"SSH_ASKPASS": "",
|
|
643
|
-
},
|
|
644
|
-
)
|
|
645
|
-
except (OSError, subprocess.SubprocessError):
|
|
646
|
-
return None
|
|
647
|
-
if result.returncode:
|
|
648
|
-
return None
|
|
649
|
-
for line in result.stdout.splitlines():
|
|
650
|
-
if line.startswith("password="):
|
|
651
|
-
return line.removeprefix("password=") or None
|
|
652
|
-
return None
|
|
653
|
-
|
|
654
|
-
|
|
655
|
-
def api(repo, suffix, *, method="GET", payload=None, raw=False):
|
|
656
|
-
path = f"repos/{repo}" + (f"/{suffix}" if suffix else "")
|
|
657
|
-
access = github_access()
|
|
658
|
-
data = None if payload is None else json.dumps(payload)
|
|
659
|
-
request = urllib.request.Request(
|
|
660
|
-
f"https://api.github.com/{path}",
|
|
661
|
-
method=method,
|
|
662
|
-
data=None if data is None else data.encode(),
|
|
663
|
-
headers={
|
|
664
|
-
"Accept": "application/vnd.github+json",
|
|
665
|
-
"Authorization": f"Bearer {access['token']}",
|
|
666
|
-
"X-GitHub-Api-Version": API_VERSION,
|
|
667
|
-
"User-Agent": "bitfab-cloud-replay",
|
|
668
|
-
**({"Content-Type": "application/json"} if data is not None else {}),
|
|
669
|
-
},
|
|
670
|
-
)
|
|
671
|
-
try:
|
|
672
|
-
body = fetch(request, follow_without_credentials=raw)
|
|
673
|
-
except urllib.error.HTTPError as error:
|
|
674
|
-
raise CommandError(
|
|
675
|
-
f"GitHub {method} {path.split('?')[0]} failed (HTTP {error.code}) using {access['source']}",
|
|
676
|
-
error.code,
|
|
677
|
-
) from None
|
|
678
|
-
except (urllib.error.URLError, OSError) as error:
|
|
679
|
-
reason = getattr(error, "reason", error)
|
|
680
|
-
if isinstance(reason, ssl.SSLCertVerificationError):
|
|
681
|
-
raise CommandError(
|
|
682
|
-
"Python cannot verify GitHub's certificate because it has no certificate store. "
|
|
683
|
-
"On a python.org install, run Install Certificates.command from its Applications folder, "
|
|
684
|
-
"or set SSL_CERT_FILE to a certificate bundle"
|
|
685
|
-
) from None
|
|
686
|
-
raise CommandError(f"Could not reach api.github.com: {reason}") from None
|
|
687
|
-
if raw:
|
|
688
|
-
return body.decode(errors="replace").strip()
|
|
689
|
-
return json.loads(body) if body.strip() else None
|
|
690
|
-
|
|
691
|
-
|
|
692
|
-
def fetch(request, *, follow_without_credentials):
|
|
693
|
-
if not follow_without_credentials:
|
|
694
|
-
with urllib.request.urlopen(request, timeout=60) as response:
|
|
695
|
-
return response.read()
|
|
696
|
-
try:
|
|
697
|
-
with urllib.request.build_opener(KeepRedirect).open(
|
|
698
|
-
request, timeout=60
|
|
699
|
-
) as response:
|
|
700
|
-
return response.read()
|
|
701
|
-
except urllib.error.HTTPError as error:
|
|
702
|
-
location = error.headers.get("Location")
|
|
703
|
-
if error.code not in (301, 302, 303, 307, 308) or not location:
|
|
704
|
-
raise
|
|
705
|
-
with urllib.request.urlopen(location, timeout=120) as response:
|
|
706
|
-
return response.read()
|
|
707
|
-
|
|
708
|
-
|
|
709
|
-
def option_name(token):
|
|
710
|
-
return token.split("=", 1)[0]
|
|
711
|
-
|
|
712
|
-
|
|
713
|
-
def split_arguments(argv):
|
|
714
|
-
cloud, switches, replay = {}, set(), []
|
|
715
|
-
index = 0
|
|
716
|
-
while index < len(argv):
|
|
717
|
-
token = argv[index]
|
|
718
|
-
name = option_name(token)
|
|
719
|
-
if name in RENAMED_FLAGS:
|
|
720
|
-
raise ValueError(f"{name} is gone; use {RENAMED_FLAGS[name]}")
|
|
721
|
-
if name in REPEATED_FLAGS:
|
|
722
|
-
if "=" in token:
|
|
723
|
-
value = token.split("=", 1)[1]
|
|
724
|
-
index += 1
|
|
725
|
-
elif index + 1 < len(argv):
|
|
726
|
-
value = argv[index + 1]
|
|
727
|
-
index += 2
|
|
728
|
-
else:
|
|
729
|
-
raise ValueError(
|
|
730
|
-
f"{ENV_FLAG} needs NAME=VALUE or NAME"
|
|
731
|
-
if name == ENV_FLAG
|
|
732
|
-
else f"{name} needs a path"
|
|
733
|
-
)
|
|
734
|
-
cloud.setdefault(name, []).append(value)
|
|
735
|
-
elif name in CLOUD_VALUE_FLAGS:
|
|
736
|
-
if "=" in token:
|
|
737
|
-
value = token.split("=", 1)[1]
|
|
738
|
-
index += 1
|
|
739
|
-
elif index + 1 < len(argv):
|
|
740
|
-
value = argv[index + 1]
|
|
741
|
-
index += 2
|
|
742
|
-
else:
|
|
743
|
-
raise ValueError(f"{name} needs a value")
|
|
744
|
-
if name in cloud:
|
|
745
|
-
raise ValueError(f"{name} was given twice")
|
|
746
|
-
cloud[name] = value
|
|
747
|
-
elif token in CLOUD_SWITCHES:
|
|
748
|
-
switches.add(token)
|
|
749
|
-
index += 1
|
|
750
|
-
elif name in SEED_FLAGS:
|
|
751
|
-
raise ValueError(f"{name} seeds traces; run it locally, without --cloud")
|
|
752
|
-
else:
|
|
753
|
-
replay.append(token)
|
|
754
|
-
index += 1
|
|
755
|
-
return cloud, switches, replay
|
|
756
|
-
|
|
757
|
-
|
|
758
|
-
def parse(argv):
|
|
759
|
-
cloud, switches, replay = split_arguments(argv)
|
|
760
|
-
following = [flag for flag in FOLLOW_FLAGS if flag in cloud]
|
|
761
|
-
if following:
|
|
762
|
-
if len(following) != 1 or len(cloud) != 1 or switches - {"--cloud"} or replay:
|
|
763
|
-
raise ValueError("Cloud follow-up commands take only their execution UUID")
|
|
764
|
-
operation = following[0].removeprefix("--cloud-")
|
|
765
|
-
execution_id = cloud[following[0]]
|
|
766
|
-
else:
|
|
767
|
-
if not replay:
|
|
768
|
-
raise ValueError(
|
|
769
|
-
"Add --cloud to the replay command you run locally, such as bitfab-replay --registry scripts/replay.ts classify --trace-ids UUID --cloud"
|
|
770
|
-
)
|
|
771
|
-
timeout = cloud.get("--cloud-timeout")
|
|
772
|
-
if timeout is not None and not (
|
|
773
|
-
timeout.isdigit() and 1 <= int(timeout) <= 7200
|
|
774
|
-
):
|
|
775
|
-
raise ValueError("--cloud-timeout must be 1..7200 minutes")
|
|
776
|
-
branch = cloud.get("--cloud-ref")
|
|
777
|
-
if branch is not None and (
|
|
778
|
-
not BRANCH_NAME.fullmatch(branch)
|
|
779
|
-
or branch.startswith(PREFIX)
|
|
780
|
-
or ".." in branch
|
|
781
|
-
or branch.endswith((".", "/", ".lock"))
|
|
782
|
-
):
|
|
783
|
-
raise ValueError(
|
|
784
|
-
f"--cloud-ref takes a branch name such as dev, other than a {PREFIX} snapshot branch"
|
|
785
|
-
)
|
|
786
|
-
if ENV_FLAG in cloud:
|
|
787
|
-
cloud[ENV_FLAG] = replay_environment(cloud[ENV_FLAG])
|
|
788
|
-
if ALLOW_FLAG in cloud and "--cloud-ref" in cloud:
|
|
789
|
-
raise ValueError(
|
|
790
|
-
f"{ALLOW_FLAG} lets a file into the snapshot of your working tree, and --cloud-ref replays the branch on GitHub with no snapshot"
|
|
791
|
-
)
|
|
792
|
-
operation = "submit"
|
|
793
|
-
execution_id = cloud.get("--cloud-request-id") or str(uuid.uuid4())
|
|
794
|
-
if not UUID.fullmatch(execution_id):
|
|
795
|
-
raise ValueError("Execution ID must be a UUID")
|
|
796
|
-
return {
|
|
797
|
-
"operation": operation,
|
|
798
|
-
"id": execution_id,
|
|
799
|
-
"cloud": cloud,
|
|
800
|
-
"switches": switches,
|
|
801
|
-
"replay": replay,
|
|
802
|
-
}
|
|
803
|
-
|
|
804
|
-
|
|
805
|
-
def validate_arguments(args):
|
|
806
|
-
if not isinstance(args, list) or not all(isinstance(value, str) for value in args):
|
|
807
|
-
raise ValueError("Replay arguments must be a list of strings")
|
|
808
|
-
for value in args:
|
|
809
|
-
if "\x00" in value or "\n" in value:
|
|
810
|
-
raise ValueError("Replay options must be single-line values")
|
|
811
|
-
if value.startswith("--cloud"):
|
|
812
|
-
raise ValueError("The runner replays locally and never dispatches again")
|
|
813
|
-
if sum(len(value) for value in args) > 16000:
|
|
814
|
-
raise ValueError("Replay options exceed 16000 characters")
|
|
815
|
-
|
|
816
|
-
|
|
817
|
-
def replay_environment(assignments):
|
|
818
|
-
values = {}
|
|
819
|
-
for assignment in assignments:
|
|
820
|
-
name, separator, value = assignment.partition("=")
|
|
821
|
-
if not separator:
|
|
822
|
-
if name not in os.environ:
|
|
823
|
-
raise ValueError(
|
|
824
|
-
f"{ENV_FLAG} {name} copies {name} from your shell, and it is not set there; pass {ENV_FLAG} {name}=VALUE instead"
|
|
825
|
-
)
|
|
826
|
-
value = os.environ[name]
|
|
827
|
-
if name in values:
|
|
828
|
-
raise ValueError(f"{ENV_FLAG} sets {name} twice")
|
|
829
|
-
values[name] = value
|
|
830
|
-
validate_environment(values)
|
|
831
|
-
return values
|
|
832
|
-
|
|
833
|
-
|
|
834
|
-
def validate_environment(values):
|
|
835
|
-
if not isinstance(values, dict) or not all(
|
|
836
|
-
isinstance(name, str) and isinstance(value, str)
|
|
837
|
-
for name, value in values.items()
|
|
838
|
-
):
|
|
839
|
-
raise ValueError("Replay environment must map names to string values")
|
|
840
|
-
for name, value in values.items():
|
|
841
|
-
if not ENV_NAME.fullmatch(name):
|
|
842
|
-
raise ValueError(
|
|
843
|
-
f"{name!r} is not an environment variable name; use letters, digits, and underscores"
|
|
844
|
-
)
|
|
845
|
-
if name.upper().startswith(RESERVED_ENV_PREFIXES) or name.upper() == "CI":
|
|
846
|
-
raise ValueError(
|
|
847
|
-
f"{name} belongs to GitHub Actions or the cloud runner and cannot be set per replay"
|
|
848
|
-
)
|
|
849
|
-
if SECRET_ENV_NAME.search(name):
|
|
850
|
-
raise ValueError(
|
|
851
|
-
f"{name} looks like a secret, and {ENV_FLAG} values are stored in the snapshot commit on GitHub. Map it in the workflow's replay step env from a GitHub secret instead, then set it with bitfab-replay --cloud-secrets"
|
|
852
|
-
)
|
|
853
|
-
if "\x00" in value or "\n" in value or "\r" in value:
|
|
854
|
-
raise ValueError(f"{name} must be a single-line value")
|
|
855
|
-
if URL_PASSWORD.search(value):
|
|
856
|
-
raise ValueError(
|
|
857
|
-
f"{name} holds a URL with a password, and {ENV_FLAG} values are stored in the snapshot commit on GitHub. Map it in the workflow's replay step env from a GitHub secret instead, then set it with bitfab-replay --cloud-secrets"
|
|
858
|
-
)
|
|
859
|
-
if sum(len(name) + len(value) for name, value in values.items()) > 16000:
|
|
860
|
-
raise ValueError("Replay environment exceeds 16000 characters")
|
|
861
|
-
|
|
862
|
-
|
|
863
|
-
def workflow_environment_conflicts(root, values):
|
|
864
|
-
path = running_workflow(root)
|
|
865
|
-
mapped = workflow_secrets(path.read_text()) if path.is_file() else {}
|
|
866
|
-
conflicts = sorted(name for name in values if name in mapped)
|
|
867
|
-
if conflicts:
|
|
868
|
-
raise ValueError(
|
|
869
|
-
f"The workflow already reads {', '.join(conflicts)} from a GitHub secret, so a replay cannot set it; update the secret with bitfab-replay --cloud-secrets"
|
|
870
|
-
)
|
|
871
|
-
|
|
872
|
-
|
|
873
|
-
def dry_run(args):
|
|
874
|
-
return "--dry-run" in args
|
|
875
|
-
|
|
876
|
-
|
|
877
|
-
def replay_arguments(argv):
|
|
878
|
-
try:
|
|
879
|
-
parsed = parse(argv)
|
|
880
|
-
except ValueError:
|
|
881
|
-
return None
|
|
882
|
-
return parsed["replay"] if parsed["operation"] == "submit" else None
|
|
883
|
-
|
|
884
|
-
|
|
885
|
-
def check_arguments(replay):
|
|
886
|
-
if os.environ.get(ARGUMENTS_CHECKED_ENV) == "1":
|
|
887
|
-
return
|
|
888
|
-
try:
|
|
889
|
-
result = subprocess.run(
|
|
890
|
-
[*replay_command(), CHECK_ARGUMENTS_FLAG, *replay],
|
|
891
|
-
text=True,
|
|
892
|
-
capture_output=True,
|
|
893
|
-
stdin=subprocess.DEVNULL,
|
|
894
|
-
check=False,
|
|
895
|
-
timeout=CHECK_ARGUMENTS_SECONDS,
|
|
896
|
-
)
|
|
897
|
-
except subprocess.TimeoutExpired:
|
|
898
|
-
raise ValueError(
|
|
899
|
-
f"The replay command took more than {CHECK_ARGUMENTS_SECONDS} seconds to check these options, so nothing was uploaded; make sure it reaches the Bitfab replay entry point without waiting on input or a slow setup step"
|
|
900
|
-
) from None
|
|
901
|
-
if result.returncode:
|
|
902
|
-
message = (result.stderr or result.stdout).strip()
|
|
903
|
-
raise ValueError(
|
|
904
|
-
message
|
|
905
|
-
or f"The replay command refused these options (exit {result.returncode})"
|
|
906
|
-
)
|
|
907
|
-
|
|
908
|
-
|
|
909
|
-
def replay_flag_value(replay, flag):
|
|
910
|
-
for index, token in enumerate(replay):
|
|
911
|
-
name, separator, value = token.partition("=")
|
|
912
|
-
if name != flag:
|
|
913
|
-
continue
|
|
914
|
-
if separator:
|
|
915
|
-
return value
|
|
916
|
-
if index + 1 < len(replay):
|
|
917
|
-
return replay[index + 1]
|
|
918
|
-
return None
|
|
919
|
-
|
|
920
|
-
|
|
921
|
-
def launch_metadata_args(execution_id):
|
|
922
|
-
return ["--metadata", f"{LAUNCH_ID_METADATA_KEY}={execution_id}"]
|
|
923
|
-
|
|
924
|
-
|
|
925
|
-
def agent_session_id(replay):
|
|
926
|
-
explicit = (replay_flag_value(replay, "--agent-session-id") or "").strip()
|
|
927
|
-
if explicit:
|
|
928
|
-
return explicit
|
|
929
|
-
for name in AGENT_SESSION_ENV_VARS:
|
|
930
|
-
value = os.environ.get(name, "").strip()
|
|
931
|
-
if value and len(value) <= 255:
|
|
932
|
-
return value
|
|
933
|
-
return None
|
|
934
|
-
|
|
935
|
-
|
|
936
|
-
def record_agent_session_launch(parsed):
|
|
937
|
-
session_id = agent_session_id(parsed["replay"])
|
|
938
|
-
if session_id is None or not SAFE_AGENT_SESSION_ID.fullmatch(session_id):
|
|
939
|
-
return
|
|
940
|
-
try:
|
|
941
|
-
directory = Path.home() / ".bitfab" / "agent-sessions" / session_id
|
|
942
|
-
directory.mkdir(parents=True, exist_ok=True)
|
|
943
|
-
service_url = (
|
|
944
|
-
os.environ.get("BITFAB_SERVICE_URL", "").strip() or DEFAULT_SERVICE_URL
|
|
945
|
-
)
|
|
946
|
-
resumed = replay_flag_value(parsed["replay"], "--resume")
|
|
947
|
-
line = json.dumps(
|
|
948
|
-
{
|
|
949
|
-
"launchId": None if resumed else parsed["id"],
|
|
950
|
-
"experimentId": resumed,
|
|
951
|
-
"name": replay_flag_value(parsed["replay"], "--name"),
|
|
952
|
-
"serviceUrl": service_url.rstrip("/"),
|
|
953
|
-
"startedAt": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
|
|
954
|
-
}
|
|
955
|
-
)
|
|
956
|
-
with open(directory / "experiments.jsonl", "a", encoding="utf-8") as handle:
|
|
957
|
-
handle.write(line + "\n")
|
|
958
|
-
except Exception:
|
|
959
|
-
return
|
|
960
|
-
|
|
961
|
-
|
|
962
|
-
def replay_request(root, parsed):
|
|
963
|
-
cwd = Path.cwd().resolve()
|
|
964
|
-
args, files = [], []
|
|
965
|
-
|
|
966
|
-
def snapshot_path(value):
|
|
967
|
-
path = cwd / value
|
|
968
|
-
files.append(repository_path(root, path))
|
|
969
|
-
return (
|
|
970
|
-
os.path.relpath(path.resolve(), cwd) if Path(value).is_absolute() else value
|
|
971
|
-
)
|
|
972
|
-
|
|
973
|
-
replay = parsed["replay"]
|
|
974
|
-
index = 0
|
|
975
|
-
while index < len(replay):
|
|
976
|
-
token = replay[index]
|
|
977
|
-
name, separator, value = token.partition("=")
|
|
978
|
-
if name in PATH_FLAGS and separator:
|
|
979
|
-
args.append(f"{name}={snapshot_path(value)}")
|
|
980
|
-
elif name in PATH_FLAGS and index + 1 < len(replay):
|
|
981
|
-
args += [token, snapshot_path(replay[index + 1])]
|
|
982
|
-
index += 1
|
|
983
|
-
else:
|
|
984
|
-
args.append(token)
|
|
985
|
-
index += 1
|
|
986
|
-
if replay_flag_value(replay, "--resume") is None:
|
|
987
|
-
args += launch_metadata_args(parsed["id"])
|
|
988
|
-
validate_arguments(args)
|
|
989
|
-
request = {
|
|
990
|
-
"version": REQUEST_VERSION
|
|
991
|
-
if parsed["cloud"].get(ENV_FLAG)
|
|
992
|
-
else PLAIN_REQUEST_VERSION,
|
|
993
|
-
"id": parsed["id"],
|
|
994
|
-
"cwd": working_directory(root),
|
|
995
|
-
"args": args,
|
|
996
|
-
}
|
|
997
|
-
if "--cloud-timeout" in parsed["cloud"]:
|
|
998
|
-
request["timeoutMinutes"] = int(parsed["cloud"]["--cloud-timeout"])
|
|
999
|
-
if "--cloud-full-output" in parsed["switches"]:
|
|
1000
|
-
request["fullOutput"] = True
|
|
1001
|
-
if parsed["cloud"].get(ENV_FLAG):
|
|
1002
|
-
request["env"] = parsed["cloud"][ENV_FLAG]
|
|
1003
|
-
return request, files
|
|
1004
|
-
|
|
1005
|
-
|
|
1006
|
-
def current_branch(root):
|
|
1007
|
-
try:
|
|
1008
|
-
return git(root, "symbolic-ref", "--short", "-q", "HEAD") or None
|
|
1009
|
-
except CommandError:
|
|
1010
|
-
return None
|
|
1011
|
-
|
|
1012
|
-
|
|
1013
|
-
def quiet_git(root, *args):
|
|
1014
|
-
try:
|
|
1015
|
-
return git(root, *args)
|
|
1016
|
-
except CommandError:
|
|
1017
|
-
return ""
|
|
1018
|
-
|
|
1019
|
-
|
|
1020
|
-
def default_branch(root):
|
|
1021
|
-
origin_head = quiet_git(root, "rev-parse", "--abbrev-ref", "origin/HEAD")
|
|
1022
|
-
candidates = [
|
|
1023
|
-
origin_head if origin_head and origin_head != "origin/HEAD" else None,
|
|
1024
|
-
"origin/main",
|
|
1025
|
-
"origin/master",
|
|
1026
|
-
"main",
|
|
1027
|
-
"master",
|
|
1028
|
-
]
|
|
1029
|
-
return next(
|
|
1030
|
-
(
|
|
1031
|
-
ref
|
|
1032
|
-
for ref in dict.fromkeys(filter(None, candidates))
|
|
1033
|
-
if quiet_git(root, "rev-parse", "--verify", "-q", f"{ref}^{{commit}}")
|
|
1034
|
-
),
|
|
1035
|
-
None,
|
|
1036
|
-
)
|
|
1037
|
-
|
|
1038
|
-
|
|
1039
|
-
def current_branch_refs(root):
|
|
1040
|
-
branch = current_branch(root)
|
|
1041
|
-
if not branch:
|
|
1042
|
-
return set()
|
|
1043
|
-
return {f"refs/heads/{branch}"} | {
|
|
1044
|
-
f"refs/remotes/{remote}/{branch}"
|
|
1045
|
-
for remote in quiet_git(root, "remote").split()
|
|
1046
|
-
}
|
|
1047
|
-
|
|
1048
|
-
|
|
1049
|
-
def own_branch_refs(root):
|
|
1050
|
-
upstream = quiet_git(root, "rev-parse", "--symbolic-full-name", "@{upstream}")
|
|
1051
|
-
own = current_branch_refs(root)
|
|
1052
|
-
if upstream:
|
|
1053
|
-
own.add(upstream)
|
|
1054
|
-
return own
|
|
1055
|
-
|
|
1056
|
-
|
|
1057
|
-
def on_default_branch(root, default):
|
|
1058
|
-
full_name = quiet_git(root, "rev-parse", "--symbolic-full-name", default)
|
|
1059
|
-
return bool(full_name) and full_name in current_branch_refs(root)
|
|
1060
|
-
|
|
1061
|
-
|
|
1062
|
-
def branch_tips(root):
|
|
1063
|
-
own = own_branch_refs(root)
|
|
1064
|
-
listing = quiet_git(
|
|
1065
|
-
root,
|
|
1066
|
-
"for-each-ref",
|
|
1067
|
-
"--format=%(objectname) %(refname)",
|
|
1068
|
-
"refs/heads",
|
|
1069
|
-
"refs/remotes",
|
|
1070
|
-
)
|
|
1071
|
-
tips = {}
|
|
1072
|
-
for line in listing.splitlines():
|
|
1073
|
-
sha, _, ref = line.partition(" ")
|
|
1074
|
-
if ref and ref not in own and not ref.endswith("/HEAD"):
|
|
1075
|
-
tips.setdefault(
|
|
1076
|
-
sha, ref.removeprefix("refs/heads/").removeprefix("refs/remotes/")
|
|
1077
|
-
)
|
|
1078
|
-
return tips
|
|
1079
|
-
|
|
1080
|
-
|
|
1081
|
-
def branch_point(root):
|
|
1082
|
-
head = quiet_git(root, "rev-parse", "HEAD")
|
|
1083
|
-
if not head:
|
|
1084
|
-
return None
|
|
1085
|
-
default = default_branch(root)
|
|
1086
|
-
if default and on_default_branch(root, default):
|
|
1087
|
-
return None
|
|
1088
|
-
default_base = quiet_git(root, "merge-base", "HEAD", default) if default else ""
|
|
1089
|
-
walk = ["rev-list", "--first-parent", f"--max-count={BRANCH_WALK_LIMIT}", "HEAD"]
|
|
1090
|
-
if default_base:
|
|
1091
|
-
walk.append(f"^{default_base}")
|
|
1092
|
-
tips = branch_tips(root)
|
|
1093
|
-
for sha in quiet_git(root, *walk).split()[1:]:
|
|
1094
|
-
if sha in tips:
|
|
1095
|
-
return {"sha": sha, "ref": tips[sha]}
|
|
1096
|
-
if default_base and default_base != head:
|
|
1097
|
-
return {"sha": default_base, "ref": default}
|
|
1098
|
-
return None
|
|
1099
|
-
|
|
1100
|
-
|
|
1101
|
-
def default_branch_point(root):
|
|
1102
|
-
default = default_branch(root)
|
|
1103
|
-
sha = quiet_git(root, "merge-base", "HEAD", default) if default else ""
|
|
1104
|
-
return {"sha": sha, "ref": default} if sha else None
|
|
1105
|
-
|
|
1106
|
-
|
|
1107
|
-
def chosen_base_point(root, chosen):
|
|
1108
|
-
if not chosen or chosen.startswith("-"):
|
|
1109
|
-
return None
|
|
1110
|
-
for ref in (chosen, f"origin/{chosen}"):
|
|
1111
|
-
if quiet_git(root, "rev-parse", "--verify", "-q", f"{ref}^{{commit}}"):
|
|
1112
|
-
sha = quiet_git(root, "merge-base", "HEAD", ref)
|
|
1113
|
-
return {"sha": sha, "ref": chosen} if sha else None
|
|
1114
|
-
raise ValueError(
|
|
1115
|
-
f"{CODE_CHANGE_BASE_FLAG} {chosen} names no branch or commit in this repository; pass a branch name or a commit SHA, and fetch it first if it only exists on the remote"
|
|
1116
|
-
)
|
|
1117
|
-
|
|
1118
|
-
|
|
1119
|
-
def refuse_git_code_change(replay, where):
|
|
1120
|
-
kind = flag_value(replay, CODE_CHANGE_FLAG)
|
|
1121
|
-
if kind in CHECKOUT_ONLY_CODE_CHANGES:
|
|
1122
|
-
raise ValueError(
|
|
1123
|
-
f"{where} as it is on GitHub, with no snapshot of a checkout, so --code-change {kind} has nothing to compare against there; pass --code-change default-branch, --code-change ref with {CODE_CHANGE_BASE_FLAG}, --code-change skip, or --code-change manual with --code-change-file, or start it with bitfab-replay --cloud and no --cloud-ref, which resolves {kind} from your checkout before upload"
|
|
1124
|
-
)
|
|
1125
|
-
if kind == "ref" and not BRANCH_NAME.fullmatch(
|
|
1126
|
-
flag_value(replay, CODE_CHANGE_BASE_FLAG) or ""
|
|
1127
|
-
):
|
|
1128
|
-
raise ValueError(
|
|
1129
|
-
f"{where} as it is on GitHub, so --code-change ref needs {CODE_CHANGE_BASE_FLAG} naming a branch or commit SHA on GitHub to fetch there"
|
|
1130
|
-
)
|
|
1131
|
-
|
|
1132
|
-
|
|
1133
|
-
def code_change_base(root, replay):
|
|
1134
|
-
kind = flag_value(replay, CODE_CHANGE_FLAG)
|
|
1135
|
-
if kind == "ref":
|
|
1136
|
-
return chosen_base_point(root, flag_value(replay, CODE_CHANGE_BASE_FLAG))
|
|
1137
|
-
if kind == "last-branch":
|
|
1138
|
-
return branch_point(root)
|
|
1139
|
-
if kind == "default-branch":
|
|
1140
|
-
return default_branch_point(root)
|
|
1141
|
-
return None
|
|
1142
|
-
|
|
1143
|
-
|
|
1144
|
-
def replay_artifact(path):
|
|
1145
|
-
return path == ".bitfab" or path.startswith(".bitfab/")
|
|
1146
|
-
|
|
1147
|
-
|
|
1148
|
-
def sensitive(path):
|
|
1149
|
-
parts = Path(path).parts
|
|
1150
|
-
name = Path(path).name.lower()
|
|
1151
|
-
return (
|
|
1152
|
-
any(part in (".git", ".ssh", ".aws") for part in parts)
|
|
1153
|
-
or name == ".env"
|
|
1154
|
-
or (
|
|
1155
|
-
name.startswith(".env.")
|
|
1156
|
-
and name not in (".env.example", ".env.sample", ".env.template")
|
|
1157
|
-
)
|
|
1158
|
-
or name in (".npmrc", ".pypirc", ".netrc", "id_rsa", "id_ed25519")
|
|
1159
|
-
or name.endswith((".pem", ".key", ".p12", ".pfx", ".local.json"))
|
|
1160
|
-
or name
|
|
1161
|
-
in (
|
|
1162
|
-
"credentials",
|
|
1163
|
-
"credentials.json",
|
|
1164
|
-
"secrets.json",
|
|
1165
|
-
"secrets.yml",
|
|
1166
|
-
"secrets.yaml",
|
|
1167
|
-
)
|
|
1168
|
-
)
|
|
1169
|
-
|
|
1170
|
-
|
|
1171
|
-
def snapshot_subject(execution_id, on_push):
|
|
1172
|
-
if on_push:
|
|
1173
|
-
return f"{PUSH_SUBJECT} {execution_id}"
|
|
1174
|
-
return f"Bitfab replay {execution_id} [skip actions]"
|
|
1175
|
-
|
|
1176
|
-
|
|
1177
|
-
def snapshot(
|
|
1178
|
-
root, workflow, files, request, *, preview=False, allowed=(), on_push=False
|
|
1179
|
-
):
|
|
1180
|
-
if git(root, "ls-files", "-u"):
|
|
1181
|
-
raise ValueError("Resolve merge conflicts before snapshotting")
|
|
1182
|
-
head = git(root, "rev-parse", "HEAD")
|
|
1183
|
-
with tempfile.TemporaryDirectory(prefix="bitfab-cloud-index-") as directory:
|
|
1184
|
-
env = {**os.environ, "GIT_INDEX_FILE": str(Path(directory) / "index")}
|
|
1185
|
-
git(root, "read-tree", head, env=env)
|
|
1186
|
-
git(root, "add", "-A", "--", ".", env=env)
|
|
1187
|
-
entries = git(root, "ls-files", "--stage", "-z", env=env).split("\x00")
|
|
1188
|
-
tracked = set()
|
|
1189
|
-
for entry in filter(None, entries):
|
|
1190
|
-
metadata, path = entry.split("\t", 1)
|
|
1191
|
-
tracked.add(path)
|
|
1192
|
-
if metadata.startswith("160000"):
|
|
1193
|
-
raise ValueError(
|
|
1194
|
-
f"{path} is a submodule or nested repository, which cloud snapshots do not support"
|
|
1195
|
-
)
|
|
1196
|
-
ignored = [
|
|
1197
|
-
path
|
|
1198
|
-
for path in [f"{WORKFLOW_DIRECTORY}/{workflow}", *files]
|
|
1199
|
-
if path not in tracked
|
|
1200
|
-
]
|
|
1201
|
-
if ignored:
|
|
1202
|
-
raise ValueError(
|
|
1203
|
-
"Git ignores "
|
|
1204
|
-
+ ", ".join(ignored)
|
|
1205
|
-
+ ", so the snapshot cannot include it; stop ignoring it or move it"
|
|
1206
|
-
)
|
|
1207
|
-
tree = git(root, "write-tree", env=env)
|
|
1208
|
-
changes = [
|
|
1209
|
-
line.split("\t", 1)
|
|
1210
|
-
for line in git(
|
|
1211
|
-
root, "diff", "--name-status", "--no-renames", head, tree
|
|
1212
|
-
).splitlines()
|
|
1213
|
-
]
|
|
1214
|
-
new_files = sorted(path for status, path in changes if status == "A")
|
|
1215
|
-
changed_files = sorted(path for status, path in changes if status != "A")
|
|
1216
|
-
unpushed = git(
|
|
1217
|
-
root,
|
|
1218
|
-
"log",
|
|
1219
|
-
"--format=",
|
|
1220
|
-
"--name-only",
|
|
1221
|
-
"--no-renames",
|
|
1222
|
-
"--diff-filter=AM",
|
|
1223
|
-
head,
|
|
1224
|
-
"--not",
|
|
1225
|
-
"--remotes",
|
|
1226
|
-
).splitlines()
|
|
1227
|
-
uploaded = ({*new_files, *changed_files} & tracked) | set(unpushed)
|
|
1228
|
-
for path in sorted(uploaded - set(allowed)):
|
|
1229
|
-
if sensitive(path):
|
|
1230
|
-
raise ValueError(
|
|
1231
|
-
f"Refusing to upload {path}, which looks like a credential and is not on GitHub yet; add it to .gitignore and take it out of any commit you have not pushed, or pass {ALLOW_FLAG} {path} if it is safe to upload. If it is already on GitHub, run git fetch so this check can see it"
|
|
1232
|
-
)
|
|
1233
|
-
sizes = {path: (root / path).lstat().st_size for path in new_files}
|
|
1234
|
-
size = sum(sizes.values())
|
|
1235
|
-
if size > NEW_FILES_LIMIT:
|
|
1236
|
-
largest = sorted(new_files, key=lambda path: -sizes[path])
|
|
1237
|
-
raise ValueError(
|
|
1238
|
-
f"New files add {size // (1024 * 1024)} MiB to the snapshot, more than {NEW_FILES_LIMIT // (1024 * 1024)} MiB; add large outputs to .gitignore, such as "
|
|
1239
|
-
+ ", ".join(largest[:5])
|
|
1240
|
-
)
|
|
1241
|
-
summary = {
|
|
1242
|
-
"baseSha": head,
|
|
1243
|
-
"changedFiles": changed_files,
|
|
1244
|
-
"newFiles": new_files,
|
|
1245
|
-
}
|
|
1246
|
-
if preview:
|
|
1247
|
-
return summary
|
|
1248
|
-
branch_base = str((request.get("codeChangeBase") or {}).get("sha", ""))
|
|
1249
|
-
extra_parent = (
|
|
1250
|
-
["-p", branch_base]
|
|
1251
|
-
if SHA.fullmatch(branch_base) and branch_base != head
|
|
1252
|
-
else []
|
|
1253
|
-
)
|
|
1254
|
-
sha = git(
|
|
1255
|
-
root,
|
|
1256
|
-
"commit-tree",
|
|
1257
|
-
tree,
|
|
1258
|
-
"-p",
|
|
1259
|
-
head,
|
|
1260
|
-
*extra_parent,
|
|
1261
|
-
input=f"{snapshot_subject(request['id'], on_push)}\n\n{json.dumps(request)}\n",
|
|
1262
|
-
)
|
|
1263
|
-
return {**summary, "sha": sha}
|
|
1264
|
-
|
|
1265
|
-
|
|
1266
|
-
def state_directory(root):
|
|
1267
|
-
path = Path(git(root, "rev-parse", "--absolute-git-dir")) / "bitfab-cloud"
|
|
1268
|
-
path.mkdir(mode=0o700, exist_ok=True)
|
|
1269
|
-
return path
|
|
1270
|
-
|
|
1271
|
-
|
|
1272
|
-
def save(path, record):
|
|
1273
|
-
with tempfile.NamedTemporaryFile(mode="w", dir=path.parent, delete=False) as file:
|
|
1274
|
-
json.dump(record, file)
|
|
1275
|
-
file.write("\n")
|
|
1276
|
-
name = file.name
|
|
1277
|
-
os.replace(name, path)
|
|
1278
|
-
|
|
1279
|
-
|
|
1280
|
-
@contextlib.contextmanager
|
|
1281
|
-
def execution_lock(directory, execution_id):
|
|
1282
|
-
import fcntl
|
|
1283
|
-
|
|
1284
|
-
with (directory / f"{execution_id}.lock").open("a") as lock:
|
|
1285
|
-
try:
|
|
1286
|
-
fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
|
1287
|
-
except BlockingIOError as error:
|
|
1288
|
-
raise ValueError(
|
|
1289
|
-
"Another command is operating on this cloud execution"
|
|
1290
|
-
) from error
|
|
1291
|
-
yield
|
|
1292
|
-
|
|
1293
|
-
|
|
1294
|
-
def find_run(record):
|
|
1295
|
-
if record.get("snapshot") is False:
|
|
1296
|
-
return find_branch_run(record)
|
|
1297
|
-
event = "push" if record.get("startedOnPush") else "workflow_dispatch"
|
|
1298
|
-
query = urlencode({"event": event, "branch": record["branch"], "per_page": 100})
|
|
1299
|
-
runs = api(
|
|
1300
|
-
record["repository"], f"actions/workflows/{record['workflow']}/runs?{query}"
|
|
1301
|
-
)
|
|
1302
|
-
matches = [
|
|
1303
|
-
run
|
|
1304
|
-
for run in runs["workflow_runs"]
|
|
1305
|
-
if run["head_sha"] == record["sha"] and run["head_branch"] == record["branch"]
|
|
1306
|
-
]
|
|
1307
|
-
if len(matches) > 1:
|
|
1308
|
-
raise ValueError(
|
|
1309
|
-
"Multiple matching GitHub runs; inspect Actions before cleanup"
|
|
1310
|
-
)
|
|
1311
|
-
return matches[0] if matches else None
|
|
1312
|
-
|
|
1313
|
-
|
|
1314
|
-
def find_branch_run(record):
|
|
1315
|
-
dispatched = calendar.timegm(time.strptime(record["dispatchedAt"], TIMESTAMP))
|
|
1316
|
-
query = urlencode(
|
|
1317
|
-
{
|
|
1318
|
-
"event": "workflow_dispatch",
|
|
1319
|
-
"branch": record["branch"],
|
|
1320
|
-
"created": ">=" + timestamp(dispatched - CLOCK_SKEW_SECONDS),
|
|
1321
|
-
"per_page": 100,
|
|
1322
|
-
}
|
|
1323
|
-
)
|
|
1324
|
-
runs = api(
|
|
1325
|
-
record["repository"], f"actions/workflows/{record['workflow']}/runs?{query}"
|
|
1326
|
-
)
|
|
1327
|
-
on_branch = [
|
|
1328
|
-
run for run in runs["workflow_runs"] if run["head_branch"] == record["branch"]
|
|
1329
|
-
]
|
|
1330
|
-
named = [run for run in on_branch if record["id"] in run.get("display_title", "")]
|
|
1331
|
-
matches = named or [
|
|
1332
|
-
run for run in on_branch if run.get("created_at", "") >= record["dispatchedAt"]
|
|
1333
|
-
]
|
|
1334
|
-
if len(matches) > 1:
|
|
1335
|
-
raise ValueError(
|
|
1336
|
-
f"Several runs were dispatched on {record['branch']} at about the same time, so this execution cannot tell which is its own; find it in the Actions tab"
|
|
1337
|
-
)
|
|
1338
|
-
return matches[0] if matches else None
|
|
1339
|
-
|
|
1340
|
-
|
|
1341
|
-
def timestamp(seconds):
|
|
1342
|
-
return time.strftime(TIMESTAMP, time.gmtime(seconds))
|
|
1343
|
-
|
|
1344
|
-
|
|
1345
|
-
def status(record, *, fetch_result=True):
|
|
1346
|
-
if record["state"] in ("prepared", "dispatch_rejected"):
|
|
1347
|
-
return record
|
|
1348
|
-
run = (
|
|
1349
|
-
api(record["repository"], f"actions/runs/{record['runId']}")
|
|
1350
|
-
if record.get("runId")
|
|
1351
|
-
else find_run(record)
|
|
1352
|
-
)
|
|
1353
|
-
if run is None:
|
|
1354
|
-
record["state"] = "dispatch_unknown"
|
|
1355
|
-
return record
|
|
1356
|
-
if record.get("snapshot") is False and run["head_branch"] == record["branch"]:
|
|
1357
|
-
record["sha"] = run["head_sha"]
|
|
1358
|
-
if run["head_sha"] != record["sha"] or run["head_branch"] != record["branch"]:
|
|
1359
|
-
raise ValueError("GitHub run does not match the recorded execution")
|
|
1360
|
-
record.update(
|
|
1361
|
-
runId=run["id"],
|
|
1362
|
-
url=run["html_url"],
|
|
1363
|
-
state=run["status"],
|
|
1364
|
-
conclusion=run.get("conclusion"),
|
|
1365
|
-
)
|
|
1366
|
-
if fetch_result and record["state"] == "completed" and "exitCode" not in record:
|
|
1367
|
-
outcome(record)
|
|
1368
|
-
return record
|
|
1369
|
-
|
|
1370
|
-
|
|
1371
|
-
def replay_job(record):
|
|
1372
|
-
jobs = api(
|
|
1373
|
-
record["repository"], f"actions/runs/{record['runId']}/jobs?per_page=100"
|
|
1374
|
-
)
|
|
1375
|
-
jobs = (jobs or {}).get("jobs", [])
|
|
1376
|
-
named = [job for job in jobs if job.get("name") == "replay"]
|
|
1377
|
-
return (named or jobs or [None])[0]
|
|
1378
|
-
|
|
1379
|
-
|
|
1380
|
-
def job_log(record):
|
|
1381
|
-
job = replay_job(record)
|
|
1382
|
-
if job is None:
|
|
1383
|
-
return []
|
|
1384
|
-
for attempt in range(6):
|
|
1385
|
-
try:
|
|
1386
|
-
text = api(record["repository"], f"actions/jobs/{job['id']}/logs", raw=True)
|
|
1387
|
-
return [LOG_TIMESTAMP.sub("", line) for line in text.splitlines()]
|
|
1388
|
-
except RuntimeError:
|
|
1389
|
-
if attempt == 5:
|
|
1390
|
-
raise
|
|
1391
|
-
time.sleep(POLL_SECONDS)
|
|
1392
|
-
return []
|
|
1393
|
-
|
|
1394
|
-
|
|
1395
|
-
def read_result(lines):
|
|
1396
|
-
chunks = [
|
|
1397
|
-
line[len(RESULT_LINE) :] for line in lines if line.startswith(RESULT_LINE)
|
|
1398
|
-
]
|
|
1399
|
-
if not chunks:
|
|
1400
|
-
return None
|
|
1401
|
-
try:
|
|
1402
|
-
return json.loads(
|
|
1403
|
-
zlib.decompress(base64.b64decode("".join(chunks), validate=True))
|
|
1404
|
-
)
|
|
1405
|
-
except ValueError as error:
|
|
1406
|
-
raise ValueError("The runner left an unreadable replay result") from error
|
|
1407
|
-
|
|
1408
|
-
|
|
1409
|
-
def replay_output(lines):
|
|
1410
|
-
if OUTPUT_BEGIN not in lines:
|
|
1411
|
-
return None
|
|
1412
|
-
start = lines.index(OUTPUT_BEGIN) + 1
|
|
1413
|
-
end = lines.index(OUTPUT_END, start) if OUTPUT_END in lines[start:] else len(lines)
|
|
1414
|
-
return lines[start:end]
|
|
1415
|
-
|
|
1416
|
-
|
|
1417
|
-
def outcome(record):
|
|
1418
|
-
lines = job_log(record)
|
|
1419
|
-
result = read_result(lines)
|
|
1420
|
-
if result is None:
|
|
1421
|
-
record["exitCode"] = 1
|
|
1422
|
-
return {"record": record, "lines": lines, "result": None}
|
|
1423
|
-
if (
|
|
1424
|
-
result.get("executionId") != record["id"]
|
|
1425
|
-
or result.get("commitSha") != record["sha"]
|
|
1426
|
-
):
|
|
1427
|
-
raise ValueError("Replay result does not match this execution")
|
|
1428
|
-
record["exitCode"] = result["exitCode"]
|
|
1429
|
-
parsed = last_json(result.get("stdout", "")) or {}
|
|
1430
|
-
test_run = result.get("testRunId") or experiment_fields(parsed).get("testRunId")
|
|
1431
|
-
if isinstance(test_run, str) and UUID.fullmatch(test_run):
|
|
1432
|
-
record["testRunId"] = test_run
|
|
1433
|
-
if result.get("stoppedEarly"):
|
|
1434
|
-
record["stoppedEarly"] = result["stoppedEarly"]
|
|
1435
|
-
return {"record": record, "lines": lines, "result": result}
|
|
1436
|
-
|
|
1437
|
-
|
|
1438
|
-
def print_outcome(found):
|
|
1439
|
-
record, lines, result = found["record"], found["lines"], found["result"]
|
|
1440
|
-
if result is None:
|
|
1441
|
-
errors = [
|
|
1442
|
-
index for index, line in enumerate(lines) if line.startswith("##[error]")
|
|
1443
|
-
]
|
|
1444
|
-
shown = lines[: errors[0] + 1] if errors else lines
|
|
1445
|
-
tail = [line for line in shown if line.strip()][-LOG_TAIL_LINES:]
|
|
1446
|
-
for line in tail:
|
|
1447
|
-
print(line, file=sys.stderr)
|
|
1448
|
-
progress(
|
|
1449
|
-
f"The run stopped before the replay finished ({record.get('conclusion')}); the end of its log is above. Full log: {record.get('url')}"
|
|
1450
|
-
)
|
|
1451
|
-
return 1
|
|
1452
|
-
for line in replay_output(lines) or []:
|
|
1453
|
-
print(line, file=sys.stderr)
|
|
1454
|
-
sys.stderr.flush()
|
|
1455
|
-
if result.get("stdoutOmittedBytes"):
|
|
1456
|
-
progress(
|
|
1457
|
-
f"The replay also printed {result['stdoutOmittedBytes'] // (1024 * 1024)} MiB to stdout before its result, such as a library's logging; only the end was kept"
|
|
1458
|
-
)
|
|
1459
|
-
print(result.get("stdout", ""), end="", flush=True)
|
|
1460
|
-
summary = last_json(result.get("stdout", "")) or {}
|
|
1461
|
-
if summary.get("cloudSummary") is True:
|
|
1462
|
-
progress(
|
|
1463
|
-
"Printed a summary of the result; every item's input and output are in the experiment"
|
|
1464
|
-
+ (
|
|
1465
|
-
f" at {summary['experimentUrl']}"
|
|
1466
|
-
if summary.get("experimentUrl")
|
|
1467
|
-
else ""
|
|
1468
|
-
)
|
|
1469
|
-
+ "; the Bitfab MCP tools read them. Add --cloud-full-output to print every item here instead"
|
|
1470
|
-
)
|
|
1471
|
-
if record.get("stoppedEarly"):
|
|
1472
|
-
progress(
|
|
1473
|
-
f"Replay stopped early: {record['stoppedEarly']}. Traces that finished are saved"
|
|
1474
|
-
+ (
|
|
1475
|
-
f" in experiment {record['testRunId']}"
|
|
1476
|
-
if record.get("testRunId")
|
|
1477
|
-
else ""
|
|
1478
|
-
)
|
|
1479
|
-
)
|
|
1480
|
-
return result["exitCode"] or 1
|
|
1481
|
-
return result["exitCode"]
|
|
1482
|
-
|
|
1483
|
-
|
|
1484
|
-
def cleanup(root, record):
|
|
1485
|
-
remove_key(record)
|
|
1486
|
-
if record.get("cleaned"):
|
|
1487
|
-
return
|
|
1488
|
-
if record.get("snapshot") is False:
|
|
1489
|
-
record["cleaned"] = True
|
|
1490
|
-
return
|
|
1491
|
-
if record.get("state") not in CLEANABLE_STATES:
|
|
1492
|
-
raise ValueError(
|
|
1493
|
-
"Cleanup requires a confirmed completed GitHub run; cancel and wait first"
|
|
1494
|
-
)
|
|
1495
|
-
if record["branch"] != PREFIX + record["id"] or not SHA.fullmatch(record["sha"]):
|
|
1496
|
-
raise ValueError("Refusing cleanup of an unowned branch")
|
|
1497
|
-
ref = "refs/heads/" + record["branch"]
|
|
1498
|
-
remote = git(root, "ls-remote", "--heads", "origin", ref)
|
|
1499
|
-
if remote:
|
|
1500
|
-
if remote.split()[0] != record["sha"]:
|
|
1501
|
-
raise ValueError(
|
|
1502
|
-
"Snapshot branch moved; refusing to delete someone else's changes"
|
|
1503
|
-
)
|
|
1504
|
-
git(
|
|
1505
|
-
root,
|
|
1506
|
-
"push",
|
|
1507
|
-
f"--force-with-lease={ref}:{record['sha']}",
|
|
1508
|
-
"origin",
|
|
1509
|
-
f":{ref}",
|
|
1510
|
-
)
|
|
1511
|
-
record["cleaned"] = True
|
|
1512
|
-
|
|
1513
|
-
|
|
1514
|
-
def http_status(error):
|
|
1515
|
-
status = getattr(error, "http_status", None)
|
|
1516
|
-
return f" (HTTP {status})" if status else ""
|
|
1517
|
-
|
|
1518
|
-
|
|
1519
|
-
def preflight(repo, workflow, *, pushes=True, full_output=False, allows_files=False):
|
|
1520
|
-
try:
|
|
1521
|
-
access = github_access()
|
|
1522
|
-
except ValueError as error:
|
|
1523
|
-
raise GithubUnreachable(str(error)) from error
|
|
1524
|
-
try:
|
|
1525
|
-
details = api(repo, "")
|
|
1526
|
-
except RuntimeError as error:
|
|
1527
|
-
refused = getattr(error, "http_status", None) in (401, 403, 404)
|
|
1528
|
-
raise (GithubUnreachable if refused else ValueError)(
|
|
1529
|
-
f"GitHub access from {access['source']} cannot read {repo}{http_status(error)}; use an account or token with write access to it"
|
|
1530
|
-
) from error
|
|
1531
|
-
if pushes and (details or {}).get("permissions", {}).get("push") is False:
|
|
1532
|
-
raise GithubUnreachable(
|
|
1533
|
-
f"GitHub access from {access['source']} cannot push to {repo}; use an account or token with write access to it"
|
|
1534
|
-
)
|
|
1535
|
-
if full_output and (details or {}).get("private") is False:
|
|
1536
|
-
raise ValueError(
|
|
1537
|
-
f"--cloud-full-output writes every trace's input and output into the Actions job log, and anyone can read the logs of {repo} because it is public; leave it off and read the items in the experiment with the Bitfab MCP tools"
|
|
1538
|
-
)
|
|
1539
|
-
if allows_files and (details or {}).get("private") is False:
|
|
1540
|
-
raise ValueError(
|
|
1541
|
-
f"{ALLOW_FLAG} uploads a credential-like file to a snapshot branch, and anyone can read the branches of {repo} because it is public"
|
|
1542
|
-
)
|
|
1543
|
-
path = f"{WORKFLOW_DIRECTORY}/{workflow}"
|
|
1544
|
-
try:
|
|
1545
|
-
registered = api(repo, f"actions/workflows/{workflow}")
|
|
1546
|
-
except RuntimeError as error:
|
|
1547
|
-
raise ValueError(
|
|
1548
|
-
f"GitHub Actions has not registered {path}{http_status(error)}; merging it to the default branch once registers it, and after that each replay runs the copy in its own snapshot"
|
|
1549
|
-
) from error
|
|
1550
|
-
if registered.get("state") != "active":
|
|
1551
|
-
raise ValueError(
|
|
1552
|
-
f"{path} is {registered.get('state')}; enable it in the repository's Actions tab"
|
|
1553
|
-
)
|
|
1554
|
-
|
|
1555
|
-
|
|
1556
|
-
def describe_snapshot(source):
|
|
1557
|
-
changed, new = len(source["changedFiles"]), len(source["newFiles"])
|
|
1558
|
-
progress(
|
|
1559
|
-
f"Snapshot of {source['baseSha'][:12]} with {changed} changed and {new} new files"
|
|
1560
|
-
+ (
|
|
1561
|
-
f" ({', '.join(source['newFiles'][:5])}{', ...' if new > 5 else ''})"
|
|
1562
|
-
if new
|
|
1563
|
-
else ""
|
|
1564
|
-
)
|
|
1565
|
-
)
|
|
1566
|
-
|
|
1567
|
-
|
|
1568
|
-
def allowed_files(root, parsed):
|
|
1569
|
-
cwd = Path.cwd().resolve()
|
|
1570
|
-
return [
|
|
1571
|
-
repository_path(root, cwd / value)
|
|
1572
|
-
for value in parsed["cloud"].get(ALLOW_FLAG, [])
|
|
1573
|
-
]
|
|
1574
|
-
|
|
1575
|
-
|
|
1576
|
-
def submit(root, repo, workflow, parsed, path):
|
|
1577
|
-
execution_id = parsed["id"]
|
|
1578
|
-
request, files = replay_request(root, parsed)
|
|
1579
|
-
branch = current_branch(root)
|
|
1580
|
-
if branch:
|
|
1581
|
-
request["branch"] = branch
|
|
1582
|
-
base = code_change_base(root, parsed["replay"])
|
|
1583
|
-
if base:
|
|
1584
|
-
request["codeChangeBase"] = base
|
|
1585
|
-
check_arguments(parsed["replay"])
|
|
1586
|
-
allowed = allowed_files(root, parsed)
|
|
1587
|
-
if "--cloud-preview" in parsed["switches"]:
|
|
1588
|
-
return {
|
|
1589
|
-
"preview": True,
|
|
1590
|
-
"repository": repo,
|
|
1591
|
-
**snapshot(root, workflow, files, request, preview=True, allowed=allowed),
|
|
1592
|
-
}
|
|
1593
|
-
if path.exists():
|
|
1594
|
-
record = json.loads(path.read_text())
|
|
1595
|
-
if record["request"] != request or record["repository"].lower() != repo.lower():
|
|
1596
|
-
raise ValueError("Execution ID already belongs to a different request")
|
|
1597
|
-
if record.get("startedOnPush") and record["state"] != "prepared":
|
|
1598
|
-
try:
|
|
1599
|
-
github_access()
|
|
1600
|
-
except ValueError as error:
|
|
1601
|
-
record["unfollowed"] = str(error)
|
|
1602
|
-
return record
|
|
1603
|
-
status(record, fetch_result=False)
|
|
1604
|
-
if record["state"] == "prepared":
|
|
1605
|
-
raise ValueError(
|
|
1606
|
-
"Submission stopped before dispatch. Use --cloud-cleanup, then submit a new execution UUID"
|
|
1607
|
-
)
|
|
1608
|
-
refuse_rejected(record)
|
|
1609
|
-
return record
|
|
1610
|
-
unfollowed = None
|
|
1611
|
-
try:
|
|
1612
|
-
preflight(
|
|
1613
|
-
repo,
|
|
1614
|
-
workflow,
|
|
1615
|
-
full_output=request.get("fullOutput") is True,
|
|
1616
|
-
allows_files=bool(allowed),
|
|
1617
|
-
)
|
|
1618
|
-
except GithubUnreachable as error:
|
|
1619
|
-
unfollowed = str(error)
|
|
1620
|
-
refuse_unfollowed(root, repo, workflow, request, allowed, unfollowed)
|
|
1621
|
-
if dry_run(request["args"]):
|
|
1622
|
-
progress(
|
|
1623
|
-
"--dry-run dispatches a GitHub run that checks secrets and resolves the traces without replaying; it receives the workflow's secrets"
|
|
1624
|
-
)
|
|
1625
|
-
source = snapshot(
|
|
1626
|
-
root, workflow, files, request, allowed=allowed, on_push=bool(unfollowed)
|
|
1627
|
-
)
|
|
1628
|
-
describe_snapshot(source)
|
|
1629
|
-
record = {
|
|
1630
|
-
"id": execution_id,
|
|
1631
|
-
"repository": repo,
|
|
1632
|
-
"workflow": workflow,
|
|
1633
|
-
"branch": PREFIX + execution_id,
|
|
1634
|
-
"request": request,
|
|
1635
|
-
"state": "prepared",
|
|
1636
|
-
**({"startedOnPush": True} if unfollowed else {}),
|
|
1637
|
-
**source,
|
|
1638
|
-
}
|
|
1639
|
-
save(path, record)
|
|
1640
|
-
progress(f"Execution {execution_id}; resume with --cloud-watch {execution_id}")
|
|
1641
|
-
ref = "refs/heads/" + record["branch"]
|
|
1642
|
-
try:
|
|
1643
|
-
git(
|
|
1644
|
-
root,
|
|
1645
|
-
"push",
|
|
1646
|
-
f"--force-with-lease={ref}:",
|
|
1647
|
-
"origin",
|
|
1648
|
-
f"{record['sha']}:{ref}",
|
|
1649
|
-
)
|
|
1650
|
-
except RuntimeError as error:
|
|
1651
|
-
raise ValueError(
|
|
1652
|
-
f"Pushing the snapshot branch {record['branch']} to origin failed; check that git can push to {repo}"
|
|
1653
|
-
) from error
|
|
1654
|
-
record["state"] = "dispatch_unknown"
|
|
1655
|
-
save(path, record)
|
|
1656
|
-
if unfollowed:
|
|
1657
|
-
record["unfollowed"] = unfollowed
|
|
1658
|
-
return record
|
|
1659
|
-
text = within(root, f"{WORKFLOW_DIRECTORY}/{workflow}").read_text()
|
|
1660
|
-
declared = declared_inputs(text)
|
|
1661
|
-
key_inputs = issue_key_token(root, record, text)
|
|
1662
|
-
save(path, record)
|
|
1663
|
-
return dispatch(
|
|
1664
|
-
record,
|
|
1665
|
-
{"execution_id": execution_id, "request": "-", **key_inputs},
|
|
1666
|
-
declared,
|
|
1667
|
-
)
|
|
1668
|
-
|
|
1669
|
-
|
|
1670
|
-
def push_trigger(lines):
|
|
1671
|
-
for index, line in enumerate(lines):
|
|
1672
|
-
if re.fullmatch(r'"?on"?[ \t]*:[ \t]*(#.*)?', line):
|
|
1673
|
-
end = block_end(lines, index, 0)
|
|
1674
|
-
step = child_indent(lines, index, end, " ")
|
|
1675
|
-
row = next(
|
|
1676
|
-
(
|
|
1677
|
-
row
|
|
1678
|
-
for row in range(index + 1, end)
|
|
1679
|
-
if re.fullmatch(rf'{step}"?push"?[ \t]*:.*', lines[row])
|
|
1680
|
-
),
|
|
1681
|
-
None,
|
|
1682
|
-
)
|
|
1683
|
-
if row is None:
|
|
1684
|
-
return None
|
|
1685
|
-
return lines[row : block_end(lines, row, len(step))]
|
|
1686
|
-
if re.match(r'"?on"?[ \t]*:', line):
|
|
1687
|
-
return [line] if re.search(r"\bpush\b", line) else None
|
|
1688
|
-
return None
|
|
1689
|
-
|
|
1690
|
-
|
|
1691
|
-
def starts_on_push(text):
|
|
1692
|
-
trigger = push_trigger(text.splitlines()) or []
|
|
1693
|
-
return any(PREFIX in line for line in trigger) and not any(
|
|
1694
|
-
"branches-ignore" in line for line in trigger
|
|
1695
|
-
)
|
|
1696
|
-
|
|
1697
|
-
|
|
1698
|
-
def refuse_unfollowed(root, repo, workflow, request, allowed, reason):
|
|
1699
|
-
path = f"{WORKFLOW_DIRECTORY}/{workflow}"
|
|
1700
|
-
if not starts_on_push(within(root, path).read_text()):
|
|
1701
|
-
raise ValueError(
|
|
1702
|
-
f"{reason}. Without it a replay can still run, with no updates here, once {path} also starts on a push to a {PREFIX} branch: run bitfab-replay --cloud-update and commit the workflow it updates"
|
|
1703
|
-
)
|
|
1704
|
-
if request.get("fullOutput") is True:
|
|
1705
|
-
raise ValueError(
|
|
1706
|
-
f"--cloud-full-output writes every trace's input and output into the Actions job log, so it needs GitHub access that confirms {repo} is private: {reason}"
|
|
1707
|
-
)
|
|
1708
|
-
if allowed:
|
|
1709
|
-
raise ValueError(
|
|
1710
|
-
f"{ALLOW_FLAG} uploads a credential-like file to a snapshot branch, so it needs GitHub access that confirms {repo} is private: {reason}"
|
|
1711
|
-
)
|
|
1712
|
-
|
|
1713
|
-
|
|
1714
|
-
def report_unfollowed(record, reason):
|
|
1715
|
-
progress(
|
|
1716
|
-
f"Warning: the replay started on GitHub, but this command gets no updates on it: {reason}"
|
|
1717
|
-
)
|
|
1718
|
-
progress(
|
|
1719
|
-
f"It runs with the workflow's BITFAB_API_KEY secret, since replaying as you needs GitHub access. Watch it at https://github.com/{record['repository']}/actions/workflows/{record['workflow']}; its experiment appears in Bitfab when it finishes"
|
|
1720
|
-
)
|
|
1721
|
-
progress(
|
|
1722
|
-
f"Once it finishes, delete its snapshot branch with git push origin --delete {record['branch']}, or with --cloud-cleanup {record['id']} from a machine with GitHub access"
|
|
1723
|
-
)
|
|
1724
|
-
|
|
1725
|
-
|
|
1726
|
-
def local_client(root, request):
|
|
1727
|
-
try:
|
|
1728
|
-
output = command(
|
|
1729
|
-
[*replay_command(), *request["args"], PRINT_API_KEY_FLAG],
|
|
1730
|
-
cwd=within(root, request["cwd"]),
|
|
1731
|
-
timeout=API_KEY_PROBE_SECONDS,
|
|
1732
|
-
input="",
|
|
1733
|
-
)
|
|
1734
|
-
except (ValueError, RuntimeError, OSError, subprocess.SubprocessError):
|
|
1735
|
-
return None
|
|
1736
|
-
for line in reversed(output.splitlines()):
|
|
1737
|
-
if not line.startswith(API_KEY_LINE):
|
|
1738
|
-
continue
|
|
1739
|
-
try:
|
|
1740
|
-
reported = json.loads(line.removeprefix(API_KEY_LINE))
|
|
1741
|
-
except ValueError:
|
|
1742
|
-
return None
|
|
1743
|
-
if not isinstance(reported, dict):
|
|
1744
|
-
return None
|
|
1745
|
-
key = reported.get("apiKey")
|
|
1746
|
-
if not isinstance(key, str) or not key.strip():
|
|
1747
|
-
return None
|
|
1748
|
-
url = reported.get("serviceUrl")
|
|
1749
|
-
if not isinstance(url, str) or not url.strip():
|
|
1750
|
-
url = DEFAULT_SERVICE_URL
|
|
1751
|
-
return {"apiKey": key, "serviceUrl": url.rstrip("/")}
|
|
1752
|
-
return None
|
|
1753
|
-
|
|
1754
|
-
|
|
1755
|
-
def bitfab_api(client, path, *, method="POST", payload=None):
|
|
1756
|
-
data = None if payload is None else json.dumps(payload).encode()
|
|
1757
|
-
request = urllib.request.Request(
|
|
1758
|
-
f"{client['serviceUrl']}/api/sdk/{path}",
|
|
1759
|
-
method=method,
|
|
1760
|
-
data=data,
|
|
1761
|
-
headers={
|
|
1762
|
-
**(
|
|
1763
|
-
{"Authorization": f"Bearer {client['apiKey']}"}
|
|
1764
|
-
if client.get("apiKey")
|
|
1765
|
-
else {}
|
|
1766
|
-
),
|
|
1767
|
-
"User-Agent": "bitfab-cloud-replay",
|
|
1768
|
-
**({"Content-Type": "application/json"} if data is not None else {}),
|
|
1769
|
-
},
|
|
1770
|
-
)
|
|
1771
|
-
try:
|
|
1772
|
-
with urllib.request.urlopen(request, timeout=60) as response:
|
|
1773
|
-
body = response.read()
|
|
1774
|
-
except urllib.error.HTTPError as error:
|
|
1775
|
-
try:
|
|
1776
|
-
reason = json.loads(error.read()).get("error")
|
|
1777
|
-
except (ValueError, AttributeError, OSError):
|
|
1778
|
-
reason = None
|
|
1779
|
-
raise CommandError(
|
|
1780
|
-
f"Bitfab {method} {path} failed (HTTP {error.code})"
|
|
1781
|
-
+ (f": {reason}" if reason else ""),
|
|
1782
|
-
error.code,
|
|
1783
|
-
) from None
|
|
1784
|
-
except (urllib.error.URLError, OSError) as error:
|
|
1785
|
-
raise CommandError(
|
|
1786
|
-
f"Could not reach {client['serviceUrl']}: {getattr(error, 'reason', error)}"
|
|
1787
|
-
) from None
|
|
1788
|
-
return json.loads(body) if body.strip() else {}
|
|
1789
|
-
|
|
1790
|
-
|
|
1791
|
-
def grants_id_token(text):
|
|
1792
|
-
return ID_TOKEN_PERMISSION.search(text) is not None
|
|
1793
|
-
|
|
1794
|
-
|
|
1795
|
-
def issue_key_token(root, record, text):
|
|
1796
|
-
shared = "so the run uses the workflow's BITFAB_API_KEY secret"
|
|
1797
|
-
if KEY_INPUT not in declared_inputs(text):
|
|
1798
|
-
progress(
|
|
1799
|
-
f"The workflow takes no {KEY_INPUT} input, {shared}. To replay as yourself, run bitfab-replay --cloud-update, which adds the {KEY_INPUT} input to the workflow"
|
|
1800
|
-
)
|
|
1801
|
-
return {}
|
|
1802
|
-
if not grants_id_token(text):
|
|
1803
|
-
progress(
|
|
1804
|
-
f"The workflow does not grant id-token: write, so its run cannot prove to Bitfab which run it is, {shared}. To replay as yourself, run bitfab-replay --cloud-update, which adds it"
|
|
1805
|
-
)
|
|
1806
|
-
return {}
|
|
1807
|
-
client = local_client(root, record["request"])
|
|
1808
|
-
if client is None:
|
|
1809
|
-
progress(
|
|
1810
|
-
f"The replay's Bitfab client resolved no API key on this machine, {shared}"
|
|
1811
|
-
)
|
|
1812
|
-
return {}
|
|
1813
|
-
try:
|
|
1814
|
-
issued = bitfab_api(
|
|
1815
|
-
client,
|
|
1816
|
-
"replay/cloudKey",
|
|
1817
|
-
payload={
|
|
1818
|
-
"executionId": record["id"],
|
|
1819
|
-
"repository": record["repository"],
|
|
1820
|
-
"ref": "refs/heads/" + record["branch"],
|
|
1821
|
-
"workflow": record["workflow"],
|
|
1822
|
-
},
|
|
1823
|
-
)
|
|
1824
|
-
except CommandError as error:
|
|
1825
|
-
progress(f"{error}, {shared}")
|
|
1826
|
-
return {}
|
|
1827
|
-
token = issued.get("token")
|
|
1828
|
-
if not isinstance(token, str) or not token.startswith(KEY_TOKEN_PREFIX):
|
|
1829
|
-
progress(f"Bitfab issued no replay token, {shared}")
|
|
1830
|
-
return {}
|
|
1831
|
-
progress(
|
|
1832
|
-
f"Replaying as you: the run gets a one-time token that only {record['workflow']} running on {record['branch']} in {record['repository']} can use"
|
|
1833
|
-
)
|
|
1834
|
-
return {KEY_INPUT: token}
|
|
1835
|
-
|
|
1836
|
-
|
|
1837
|
-
def remove_key(record):
|
|
1838
|
-
secret = record.get("keySecret")
|
|
1839
|
-
if not secret or secret.get("removed"):
|
|
1840
|
-
return
|
|
1841
|
-
try:
|
|
1842
|
-
command(
|
|
1843
|
-
[
|
|
1844
|
-
"gh",
|
|
1845
|
-
"secret",
|
|
1846
|
-
"delete",
|
|
1847
|
-
secret["name"],
|
|
1848
|
-
"--repo",
|
|
1849
|
-
record["repository"],
|
|
1850
|
-
*(["--env", secret["environment"]] if secret["environment"] else []),
|
|
1851
|
-
],
|
|
1852
|
-
env={**os.environ, "GH_TOKEN": github_access()["token"]},
|
|
1853
|
-
)
|
|
1854
|
-
except (ValueError, RuntimeError, OSError, subprocess.SubprocessError) as error:
|
|
1855
|
-
if getattr(error, "http_status", None) != 404:
|
|
1856
|
-
progress(
|
|
1857
|
-
f"Could not delete the GitHub secret {secret['name']}; delete it at {secrets_page(record['repository'], secret['environment'])}"
|
|
1858
|
-
)
|
|
1859
|
-
return
|
|
1860
|
-
secret["removed"] = True
|
|
1861
|
-
|
|
1862
|
-
|
|
1863
|
-
def declared_inputs(text):
|
|
1864
|
-
return {
|
|
1865
|
-
name
|
|
1866
|
-
for name in DISPATCH_INPUTS
|
|
1867
|
-
if re.search(rf"^[ \t]*\"?{name}\"?[ \t]*:", text, re.MULTILINE)
|
|
1868
|
-
}
|
|
1869
|
-
|
|
1870
|
-
|
|
1871
|
-
def dispatch(record, inputs, declared, *, run_details=False):
|
|
1872
|
-
payload = {"ref": record["branch"]}
|
|
1873
|
-
sent = {name: value for name, value in inputs.items() if name in declared}
|
|
1874
|
-
if sent:
|
|
1875
|
-
payload["inputs"] = sent
|
|
1876
|
-
path = f"actions/workflows/{record['workflow']}/dispatches"
|
|
1877
|
-
try:
|
|
1878
|
-
try:
|
|
1879
|
-
response = api(
|
|
1880
|
-
record["repository"],
|
|
1881
|
-
path,
|
|
1882
|
-
method="POST",
|
|
1883
|
-
payload={**payload, "return_run_details": True}
|
|
1884
|
-
if run_details
|
|
1885
|
-
else payload,
|
|
1886
|
-
)
|
|
1887
|
-
except RuntimeError as error:
|
|
1888
|
-
if not run_details or getattr(error, "http_status", None) != 422:
|
|
1889
|
-
raise
|
|
1890
|
-
response = api(record["repository"], path, method="POST", payload=payload)
|
|
1891
|
-
except RuntimeError as error:
|
|
1892
|
-
code = getattr(error, "http_status", None)
|
|
1893
|
-
problem = f"Dispatching {record['workflow']} on {record['branch']} failed{http_status(error)}"
|
|
1894
|
-
if code is not None and 400 <= code < 500 and code != 429:
|
|
1895
|
-
record["state"] = "dispatch_rejected"
|
|
1896
|
-
raise DispatchRejected(
|
|
1897
|
-
f"{problem}, so no run started"
|
|
1898
|
-
+ (
|
|
1899
|
-
""
|
|
1900
|
-
if record.get("snapshot") is False
|
|
1901
|
-
else " and the snapshot branch was removed"
|
|
1902
|
-
)
|
|
1903
|
-
+ ". The GitHub account needs write access to Actions, and the registered workflow must accept workflow_dispatch",
|
|
1904
|
-
record,
|
|
1905
|
-
) from error
|
|
1906
|
-
raise ValueError(
|
|
1907
|
-
f"{problem}, and GitHub may still have started it. Follow it with --cloud-watch {record['id']}, or once --cloud-status {record['id']} shows no run, remove it with --cloud-cleanup {record['id']}"
|
|
1908
|
-
) from error
|
|
1909
|
-
if isinstance(response, dict) and response.get("workflow_run_id"):
|
|
1910
|
-
record["runId"] = response["workflow_run_id"]
|
|
1911
|
-
record["url"] = response.get("html_url")
|
|
1912
|
-
record["state"] = "queued"
|
|
1913
|
-
return record
|
|
1914
|
-
|
|
1915
|
-
|
|
1916
|
-
def branch_head(repo, branch):
|
|
1917
|
-
try:
|
|
1918
|
-
found = api(repo, f"git/ref/heads/{branch}")
|
|
1919
|
-
except RuntimeError as error:
|
|
1920
|
-
if getattr(error, "http_status", None) == 404:
|
|
1921
|
-
raise ValueError(f"{repo} has no branch {branch}") from error
|
|
1922
|
-
raise
|
|
1923
|
-
sha = ((found or {}).get("object") or {}).get("sha", "")
|
|
1924
|
-
if not SHA.fullmatch(sha):
|
|
1925
|
-
raise ValueError(f"GitHub gave no commit for branch {branch}")
|
|
1926
|
-
return sha
|
|
1927
|
-
|
|
1928
|
-
|
|
1929
|
-
def branch_workflow(repo, workflow, sha):
|
|
1930
|
-
path = f"{WORKFLOW_DIRECTORY}/{workflow}"
|
|
1931
|
-
try:
|
|
1932
|
-
found = api(repo, f"contents/{path}?ref={sha}")
|
|
1933
|
-
except RuntimeError as error:
|
|
1934
|
-
raise ValueError(
|
|
1935
|
-
f"Could not read {path} at {sha[:12]}{http_status(error)}; the branch needs the workflow"
|
|
1936
|
-
) from error
|
|
1937
|
-
return base64.b64decode((found or {}).get("content", "")).decode(errors="replace")
|
|
1938
|
-
|
|
1939
|
-
|
|
1940
|
-
def submit_as_is(root, repo, workflow, parsed, path):
|
|
1941
|
-
execution_id = parsed["id"]
|
|
1942
|
-
branch = parsed["cloud"]["--cloud-ref"]
|
|
1943
|
-
request, _ = replay_request(root, parsed)
|
|
1944
|
-
check_arguments(parsed["replay"])
|
|
1945
|
-
refuse_git_code_change(parsed["replay"], f"--cloud-ref replays {branch}")
|
|
1946
|
-
sha = branch_head(repo, branch)
|
|
1947
|
-
if "--cloud-preview" in parsed["switches"]:
|
|
1948
|
-
return {
|
|
1949
|
-
"preview": True,
|
|
1950
|
-
"repository": repo,
|
|
1951
|
-
"branch": branch,
|
|
1952
|
-
"sha": sha,
|
|
1953
|
-
"request": request,
|
|
1954
|
-
}
|
|
1955
|
-
if path.exists():
|
|
1956
|
-
record = json.loads(path.read_text())
|
|
1957
|
-
if (
|
|
1958
|
-
record["request"] != request
|
|
1959
|
-
or record["repository"].lower() != repo.lower()
|
|
1960
|
-
or record["branch"] != branch
|
|
1961
|
-
):
|
|
1962
|
-
raise ValueError("Execution ID already belongs to a different request")
|
|
1963
|
-
status(record, fetch_result=False)
|
|
1964
|
-
refuse_rejected(record)
|
|
1965
|
-
return record
|
|
1966
|
-
preflight(
|
|
1967
|
-
repo, workflow, pushes=False, full_output=request.get("fullOutput") is True
|
|
1968
|
-
)
|
|
1969
|
-
text = branch_workflow(repo, workflow, sha)
|
|
1970
|
-
declared = declared_inputs(text)
|
|
1971
|
-
if "request" not in declared:
|
|
1972
|
-
raise ValueError(
|
|
1973
|
-
f"{WORKFLOW_DIRECTORY}/{workflow} on {branch} declares no request input, so it cannot take a replay; add request (type: string, required: false) under on.workflow_dispatch.inputs and land it on {branch}"
|
|
1974
|
-
)
|
|
1975
|
-
record = {
|
|
1976
|
-
"id": execution_id,
|
|
1977
|
-
"repository": repo,
|
|
1978
|
-
"workflow": workflow,
|
|
1979
|
-
"branch": branch,
|
|
1980
|
-
"snapshot": False,
|
|
1981
|
-
"request": request,
|
|
1982
|
-
"state": "dispatch_unknown",
|
|
1983
|
-
"sha": sha,
|
|
1984
|
-
"dispatchedAt": timestamp(time.time() - 5),
|
|
1985
|
-
}
|
|
1986
|
-
save(path, record)
|
|
1987
|
-
progress(
|
|
1988
|
-
f"Replaying {branch} at {sha[:12]} as it is on GitHub, without local changes. Execution {execution_id}; resume with --cloud-watch {execution_id}"
|
|
1989
|
-
)
|
|
1990
|
-
key_inputs = issue_key_token(root, record, text)
|
|
1991
|
-
save(path, record)
|
|
1992
|
-
return dispatch(
|
|
1993
|
-
record,
|
|
1994
|
-
{"execution_id": execution_id, "request": json.dumps(request), **key_inputs},
|
|
1995
|
-
declared,
|
|
1996
|
-
run_details=True,
|
|
1997
|
-
)
|
|
1998
|
-
|
|
1999
|
-
|
|
2000
|
-
def report_steps(record, shown):
|
|
2001
|
-
job = replay_job(record)
|
|
2002
|
-
for step in (job or {}).get("steps", []):
|
|
2003
|
-
if step.get("status") not in ("in_progress", "completed"):
|
|
2004
|
-
continue
|
|
2005
|
-
if "--cloud-execute" in (step.get("name") or ""):
|
|
2006
|
-
remove_key(record)
|
|
2007
|
-
if step.get("name") not in shown:
|
|
2008
|
-
shown.add(step.get("name"))
|
|
2009
|
-
progress(step.get("name"))
|
|
2010
|
-
|
|
2011
|
-
|
|
2012
|
-
def refuse_rejected(record):
|
|
2013
|
-
if record["state"] == "dispatch_rejected":
|
|
2014
|
-
raise ValueError(
|
|
2015
|
-
"GitHub refused this execution's dispatch, so no run exists; submit the replay again without --cloud-request-id"
|
|
2016
|
-
)
|
|
2017
|
-
|
|
2018
|
-
|
|
2019
|
-
def wait(record, path):
|
|
2020
|
-
started = time.monotonic()
|
|
2021
|
-
announced, steps = None, set()
|
|
2022
|
-
while record["state"] != "completed":
|
|
2023
|
-
status(record, fetch_result=False)
|
|
2024
|
-
save(path, record)
|
|
2025
|
-
refuse_rejected(record)
|
|
2026
|
-
if record["state"] != announced and record.get("url"):
|
|
2027
|
-
announced = record["state"]
|
|
2028
|
-
progress(f"{announced.replace('_', ' ').capitalize()}: {record['url']}")
|
|
2029
|
-
if record["state"] == "in_progress":
|
|
2030
|
-
report_steps(record, steps)
|
|
2031
|
-
if (
|
|
2032
|
-
record["state"] == "dispatch_unknown"
|
|
2033
|
-
and time.monotonic() - started >= 10 * 60
|
|
2034
|
-
):
|
|
2035
|
-
raise ValueError(
|
|
2036
|
-
f"GitHub has shown no run for this dispatch after 10 minutes. Check Actions, then resume with --cloud-watch {record['id']} or remove the snapshot branch with --cloud-cleanup {record['id']}"
|
|
2037
|
-
)
|
|
2038
|
-
if record["state"] != "completed":
|
|
2039
|
-
time.sleep(POLL_SECONDS)
|
|
2040
|
-
|
|
2041
|
-
|
|
2042
|
-
def run_cli(argv):
|
|
2043
|
-
parsed = parse(argv)
|
|
2044
|
-
operation, execution_id = parsed["operation"], parsed["id"]
|
|
2045
|
-
if os.name != "posix" or sys.version_info < (3, 10):
|
|
2046
|
-
raise ValueError("Cloud replay currently requires macOS/Linux and Python 3.10+")
|
|
2047
|
-
root = root_directory()
|
|
2048
|
-
workflow = setup_workflow(root) if operation == "submit" else None
|
|
2049
|
-
repo = repository(root)
|
|
2050
|
-
directory = state_directory(root)
|
|
2051
|
-
path = directory / f"{execution_id}.json"
|
|
2052
|
-
with execution_lock(directory, execution_id):
|
|
2053
|
-
if operation == "submit":
|
|
2054
|
-
submitter = submit_as_is if "--cloud-ref" in parsed["cloud"] else submit
|
|
2055
|
-
try:
|
|
2056
|
-
record = submitter(root, repo, workflow, parsed, path)
|
|
2057
|
-
except DispatchRejected as error:
|
|
2058
|
-
cleanup(root, error.record)
|
|
2059
|
-
save(path, error.record)
|
|
2060
|
-
raise
|
|
2061
|
-
if record.get("preview"):
|
|
2062
|
-
return record, None
|
|
2063
|
-
if record["state"] != "prepared":
|
|
2064
|
-
record_agent_session_launch(parsed)
|
|
2065
|
-
reason = record.pop("unfollowed", None)
|
|
2066
|
-
if reason:
|
|
2067
|
-
report_unfollowed(record, reason)
|
|
2068
|
-
save(path, record)
|
|
2069
|
-
return record, None
|
|
2070
|
-
else:
|
|
2071
|
-
if not path.exists():
|
|
2072
|
-
raise ValueError(
|
|
2073
|
-
"No local execution record for this UUID in this worktree"
|
|
2074
|
-
)
|
|
2075
|
-
record = json.loads(path.read_text())
|
|
2076
|
-
if record["repository"].lower() != repo.lower():
|
|
2077
|
-
raise ValueError("origin no longer matches the execution repository")
|
|
2078
|
-
status(record, fetch_result=operation == "status")
|
|
2079
|
-
if operation == "cancel" and record["state"] != "completed":
|
|
2080
|
-
if not record.get("runId"):
|
|
2081
|
-
raise ValueError(
|
|
2082
|
-
"Run not yet found; inspect Actions and retry status before cancelling"
|
|
2083
|
-
)
|
|
2084
|
-
api(repo, f"actions/runs/{record['runId']}/cancel", method="POST")
|
|
2085
|
-
record["state"] = "cancel_requested"
|
|
2086
|
-
save(path, record)
|
|
2087
|
-
attached = operation == "watch" or (
|
|
2088
|
-
operation == "submit" and "--cloud-detach" not in parsed["switches"]
|
|
2089
|
-
)
|
|
2090
|
-
found = None
|
|
2091
|
-
if attached and record["state"] != "prepared":
|
|
2092
|
-
wait(record, path)
|
|
2093
|
-
found = outcome(record)
|
|
2094
|
-
if record["state"] == "completed" or (
|
|
2095
|
-
operation == "cleanup" and record["state"] in CLEANABLE_STATES
|
|
2096
|
-
):
|
|
2097
|
-
cleanup(root, record)
|
|
2098
|
-
elif operation == "cleanup":
|
|
2099
|
-
raise ValueError(
|
|
2100
|
-
f"The GitHub run is {record['state'].replace('_', ' ')}; cancel it with --cloud-cancel {record['id']} and clean up once it completes. No branch was deleted"
|
|
2101
|
-
)
|
|
2102
|
-
save(path, record)
|
|
2103
|
-
return record, found
|
|
2104
|
-
|
|
2105
|
-
|
|
2106
|
-
def replay_command():
|
|
2107
|
-
try:
|
|
2108
|
-
value = json.loads(os.environ.get(REPLAY_COMMAND_ENV, ""))
|
|
2109
|
-
except ValueError:
|
|
2110
|
-
value = None
|
|
2111
|
-
if (
|
|
2112
|
-
not isinstance(value, list)
|
|
2113
|
-
or not value
|
|
2114
|
-
or not all(isinstance(part, str) and part for part in value)
|
|
2115
|
-
):
|
|
2116
|
-
raise ValueError(
|
|
2117
|
-
"Start the replay step with the SDK's bitfab-replay command and --cloud-execute, so the runner knows how to start the replay"
|
|
2118
|
-
)
|
|
2119
|
-
return value
|
|
2120
|
-
|
|
2121
|
-
|
|
2122
|
-
def snapshot_request(root, commit):
|
|
2123
|
-
message = git(root, "log", "-1", "--format=%B", commit)
|
|
2124
|
-
_, _, body = message.partition("\n\n")
|
|
2125
|
-
try:
|
|
2126
|
-
request = json.loads(body)
|
|
2127
|
-
except ValueError:
|
|
2128
|
-
request = None
|
|
2129
|
-
if not isinstance(request, dict) or request.get("version") not in (
|
|
2130
|
-
PLAIN_REQUEST_VERSION,
|
|
2131
|
-
REQUEST_VERSION,
|
|
2132
|
-
):
|
|
2133
|
-
version = request.get("version", 0) if isinstance(request, dict) else 0
|
|
2134
|
-
newer = isinstance(version, int) and version > REQUEST_VERSION
|
|
2135
|
-
raise ValueError(
|
|
2136
|
-
"This replay was submitted by a "
|
|
2137
|
-
+ ("newer" if newer else "different")
|
|
2138
|
-
+ " SDK than the one the snapshot installs; match the SDK you run locally to the one in the lockfile"
|
|
2139
|
-
)
|
|
2140
|
-
if os.environ.get("GITHUB_REF_NAME") != PREFIX + str(request.get("id")):
|
|
2141
|
-
raise ValueError(
|
|
2142
|
-
"The runner replays only the snapshot branch its request names; start replays with bitfab-replay --cloud"
|
|
2143
|
-
)
|
|
2144
|
-
validate_arguments(request["args"])
|
|
2145
|
-
if "env" in request:
|
|
2146
|
-
validate_environment(request["env"])
|
|
2147
|
-
return request
|
|
2148
|
-
|
|
2149
|
-
|
|
2150
|
-
def dispatch_event():
|
|
2151
|
-
path = os.environ.get("GITHUB_EVENT_PATH")
|
|
2152
|
-
if not path or not Path(path).is_file():
|
|
2153
|
-
return {}
|
|
2154
|
-
event = json.loads(Path(path).read_text())
|
|
2155
|
-
return event if isinstance(event, dict) else {}
|
|
2156
|
-
|
|
2157
|
-
|
|
2158
|
-
def dispatched_inputs():
|
|
2159
|
-
inputs = dispatch_event().get("inputs")
|
|
2160
|
-
return inputs if isinstance(inputs, dict) else {}
|
|
2161
|
-
|
|
2162
|
-
|
|
2163
|
-
def event_default_branch():
|
|
2164
|
-
repository = dispatch_event().get("repository")
|
|
2165
|
-
branch = repository.get("default_branch") if isinstance(repository, dict) else None
|
|
2166
|
-
if not isinstance(branch, str) or not BRANCH_NAME.fullmatch(branch):
|
|
2167
|
-
raise ValueError(
|
|
2168
|
-
"The run's event names no default branch, so --code-change default-branch has nothing to compare against; pass --code-change ref with --code-change-base"
|
|
2169
|
-
)
|
|
2170
|
-
return branch
|
|
2171
|
-
|
|
2172
|
-
|
|
2173
|
-
def decode_request(text):
|
|
2174
|
-
try:
|
|
2175
|
-
return json.loads(text)
|
|
2176
|
-
except ValueError:
|
|
2177
|
-
pass
|
|
2178
|
-
try:
|
|
2179
|
-
return json.loads(base64.b64decode(text, validate=True))
|
|
2180
|
-
except ValueError as error:
|
|
2181
|
-
raise ValueError(
|
|
2182
|
-
"The request input is neither JSON nor base64-encoded JSON"
|
|
2183
|
-
) from error
|
|
2184
|
-
|
|
2185
|
-
|
|
2186
|
-
def dispatched_request():
|
|
2187
|
-
branch = os.environ.get("GITHUB_REF_NAME", "")
|
|
2188
|
-
inputs = dispatched_inputs()
|
|
2189
|
-
text = str(inputs.get("request") or "").strip()
|
|
2190
|
-
if text in ("", "-"):
|
|
2191
|
-
raise ValueError(
|
|
2192
|
-
f"A replay of {branch} takes its request from the workflow_dispatch request input, and this run has none; start replays with bitfab-replay --cloud, or --cloud --cloud-ref {branch} to replay the branch as it is"
|
|
2193
|
-
)
|
|
2194
|
-
request = decode_request(text)
|
|
2195
|
-
if not isinstance(request, dict):
|
|
2196
|
-
raise ValueError("The request input must be a JSON object")
|
|
2197
|
-
version = request.get("version", REQUEST_VERSION)
|
|
2198
|
-
if not isinstance(version, int) or version < OLDEST_DISPATCHED_VERSION:
|
|
2199
|
-
raise ValueError(
|
|
2200
|
-
f"Request version {version!r} is not supported; send version {REQUEST_VERSION}, or leave version out"
|
|
2201
|
-
)
|
|
2202
|
-
if version > REQUEST_VERSION:
|
|
2203
|
-
raise ValueError(
|
|
2204
|
-
f"This replay was submitted by a newer SDK than the one {branch} installs; the request is version {version} and this SDK reads up to {REQUEST_VERSION}"
|
|
2205
|
-
)
|
|
2206
|
-
execution_id = request.get("id") or inputs.get("execution_id") or str(uuid.uuid4())
|
|
2207
|
-
if not isinstance(execution_id, str) or not UUID.fullmatch(execution_id):
|
|
2208
|
-
raise ValueError("The request id must be a UUID")
|
|
2209
|
-
if inputs.get("execution_id") and inputs["execution_id"] != execution_id:
|
|
2210
|
-
raise ValueError("The request id does not match the execution_id input")
|
|
2211
|
-
args = request.get("args")
|
|
2212
|
-
validate_arguments(args)
|
|
2213
|
-
refuse_git_code_change(args, f"A dispatched replay runs {branch}")
|
|
2214
|
-
if request.get("check") is True and "--dry-run" not in args:
|
|
2215
|
-
args = [*args, "--dry-run"]
|
|
2216
|
-
normalized = {
|
|
2217
|
-
"version": REQUEST_VERSION,
|
|
2218
|
-
"id": execution_id,
|
|
2219
|
-
"cwd": request.get("cwd") or ".",
|
|
2220
|
-
"args": args,
|
|
2221
|
-
}
|
|
2222
|
-
timeout = request.get("timeoutMinutes")
|
|
2223
|
-
if timeout is not None:
|
|
2224
|
-
if not isinstance(timeout, int) or not 1 <= timeout <= 7200:
|
|
2225
|
-
raise ValueError("timeoutMinutes must be 1..7200")
|
|
2226
|
-
normalized["timeoutMinutes"] = timeout
|
|
2227
|
-
if request.get("fullOutput") is True:
|
|
2228
|
-
normalized["fullOutput"] = True
|
|
2229
|
-
if request.get("env"):
|
|
2230
|
-
validate_environment(request["env"])
|
|
2231
|
-
normalized["env"] = request["env"]
|
|
2232
|
-
return normalized
|
|
2233
|
-
|
|
2234
|
-
|
|
2235
|
-
def runner_request(root, commit):
|
|
2236
|
-
if os.environ.get("GITHUB_REF_NAME", "").startswith(PREFIX):
|
|
2237
|
-
return snapshot_request(root, commit)
|
|
2238
|
-
return dispatched_request()
|
|
2239
|
-
|
|
2240
|
-
|
|
2241
|
-
def check_out_snapshot_base(root, commit, branch):
|
|
2242
|
-
try:
|
|
2243
|
-
base = git(root, "rev-parse", "--verify", "-q", f"{commit}^")
|
|
2244
|
-
except CommandError:
|
|
2245
|
-
print(
|
|
2246
|
-
"This checkout does not include the commit the snapshot was taken on, so the experiment records no code change and the snapshot commit instead of your branch; set fetch-depth: 2 on the workflow's checkout step, or run bitfab-replay --cloud-update",
|
|
2247
|
-
flush=True,
|
|
2248
|
-
)
|
|
2249
|
-
return None
|
|
2250
|
-
if isinstance(branch, str) and BRANCH_NAME.fullmatch(branch):
|
|
2251
|
-
try:
|
|
2252
|
-
git(root, "update-ref", f"refs/heads/{branch}", base)
|
|
2253
|
-
git(root, "symbolic-ref", "HEAD", f"refs/heads/{branch}")
|
|
2254
|
-
return base
|
|
2255
|
-
except CommandError:
|
|
2256
|
-
pass
|
|
2257
|
-
git(root, "reset", "-q", "--soft", base)
|
|
2258
|
-
return base
|
|
2259
|
-
|
|
2260
|
-
|
|
2261
|
-
def flag_value(args, flag):
|
|
2262
|
-
for index, value in enumerate(args):
|
|
2263
|
-
if value.startswith(f"{flag}="):
|
|
2264
|
-
return value.partition("=")[2]
|
|
2265
|
-
if value == flag and index + 1 < len(args):
|
|
2266
|
-
return args[index + 1]
|
|
2267
|
-
return None
|
|
2268
|
-
|
|
2269
|
-
|
|
2270
|
-
def replay_name(args):
|
|
2271
|
-
return flag_value(args, "--name")
|
|
2272
|
-
|
|
2273
|
-
|
|
2274
|
-
def git_blob(root, ref, path):
|
|
2275
|
-
try:
|
|
2276
|
-
size = int(git(root, "cat-file", "-s", f"{ref}:{path}"))
|
|
2277
|
-
except (CommandError, ValueError):
|
|
2278
|
-
return None
|
|
2279
|
-
if size > CODE_CHANGE_MAX_FILE_BYTES:
|
|
2280
|
-
return None
|
|
2281
|
-
result = subprocess.run(
|
|
2282
|
-
["git", "-C", str(root), "show", f"{ref}:{path}"],
|
|
2283
|
-
capture_output=True,
|
|
2284
|
-
check=False,
|
|
2285
|
-
)
|
|
2286
|
-
if result.returncode or b"\x00" in result.stdout[:8000]:
|
|
2287
|
-
return None
|
|
2288
|
-
return result.stdout.decode("utf-8", "replace").replace("\r\n", "\n")
|
|
2289
|
-
|
|
2290
|
-
|
|
2291
|
-
def changed_paths(root, base, commit):
|
|
2292
|
-
raw = git(
|
|
2293
|
-
root,
|
|
2294
|
-
"diff",
|
|
2295
|
-
"--name-status",
|
|
2296
|
-
"--find-renames",
|
|
2297
|
-
"-z",
|
|
2298
|
-
base,
|
|
2299
|
-
commit,
|
|
2300
|
-
"--",
|
|
2301
|
-
":!.bitfab",
|
|
2302
|
-
)
|
|
2303
|
-
parts = [part for part in raw.split("\x00") if part]
|
|
2304
|
-
index = 0
|
|
2305
|
-
while index + 1 < len(parts):
|
|
2306
|
-
status, before_path = parts[index][0], parts[index + 1]
|
|
2307
|
-
index += 2
|
|
2308
|
-
path = before_path
|
|
2309
|
-
if status in "RC" and index < len(parts):
|
|
2310
|
-
path = parts[index]
|
|
2311
|
-
index += 1
|
|
2312
|
-
yield status, before_path, path
|
|
2313
|
-
|
|
2314
|
-
|
|
2315
|
-
def snapshot_code_change(
|
|
2316
|
-
root, base, commit, name, against="uncommitted (vs HEAD)", subject_ref=None
|
|
2317
|
-
):
|
|
2318
|
-
files, total = [], 0
|
|
2319
|
-
for status, before_path, path in changed_paths(root, base, commit):
|
|
2320
|
-
if len(files) >= CODE_CHANGE_MAX_FILES:
|
|
2321
|
-
break
|
|
2322
|
-
before = "" if status == "A" else git_blob(root, base, before_path)
|
|
2323
|
-
after = "" if status == "D" else git_blob(root, commit, path)
|
|
2324
|
-
if before is None or after is None or before == after:
|
|
2325
|
-
continue
|
|
2326
|
-
size = len(before.encode()) + len(after.encode())
|
|
2327
|
-
if total + size > CODE_CHANGE_MAX_TOTAL_BYTES:
|
|
2328
|
-
continue
|
|
2329
|
-
total += size
|
|
2330
|
-
files.append({"path": path, "before": before, "after": after})
|
|
2331
|
-
if not files:
|
|
2332
|
-
return None
|
|
2333
|
-
head = (name or "").strip() or git(
|
|
2334
|
-
root, "log", "-1", "--format=%s", subject_ref or base
|
|
2335
|
-
)
|
|
2336
|
-
word = "file" if len(files) == 1 else "files"
|
|
2337
|
-
return {
|
|
2338
|
-
"description": f"{head or 'Working-tree change'} ({len(files)} {word} changed {against})",
|
|
2339
|
-
"files": files,
|
|
2340
|
-
}
|
|
2341
|
-
|
|
2342
|
-
|
|
2343
|
-
def branch_code_change(root, base, commit, request):
|
|
2344
|
-
code_change_base = request.get("codeChangeBase")
|
|
2345
|
-
if not isinstance(code_change_base, dict):
|
|
2346
|
-
return None
|
|
2347
|
-
sha, ref = code_change_base.get("sha"), code_change_base.get("ref")
|
|
2348
|
-
if not (
|
|
2349
|
-
isinstance(sha, str)
|
|
2350
|
-
and SHA.fullmatch(sha)
|
|
2351
|
-
and isinstance(ref, str)
|
|
2352
|
-
and DESCRIBED_REF.fullmatch(ref)
|
|
2353
|
-
and (
|
|
2354
|
-
sha == base
|
|
2355
|
-
or quiet_git(root, "rev-parse", "--verify", "-q", f"{commit}^2") == sha
|
|
2356
|
-
)
|
|
2357
|
-
):
|
|
2358
|
-
return None
|
|
2359
|
-
return snapshot_code_change(
|
|
2360
|
-
root, sha, commit, replay_name(request["args"]), f"vs {ref}", base
|
|
2361
|
-
)
|
|
2362
|
-
|
|
2363
|
-
|
|
2364
|
-
def runner_code_change(root, base, commit, request):
|
|
2365
|
-
kind = flag_value(request["args"], CODE_CHANGE_FLAG)
|
|
2366
|
-
if kind == "working-tree":
|
|
2367
|
-
change = snapshot_code_change(root, base, commit, replay_name(request["args"]))
|
|
2368
|
-
elif kind in BRANCH_CODE_CHANGES:
|
|
2369
|
-
change = branch_code_change(root, base, commit, request)
|
|
2370
|
-
else:
|
|
2371
|
-
return None
|
|
2372
|
-
return change or {"files": []}
|
|
2373
|
-
|
|
2374
|
-
|
|
2375
|
-
def git_token_environment(token):
|
|
2376
|
-
environment = {**os.environ, "GIT_TERMINAL_PROMPT": "0"}
|
|
2377
|
-
if not token:
|
|
2378
|
-
return environment
|
|
2379
|
-
basic = base64.b64encode(f"x-access-token:{token}".encode()).decode()
|
|
2380
|
-
return {
|
|
2381
|
-
**environment,
|
|
2382
|
-
"GIT_CONFIG_COUNT": "1",
|
|
2383
|
-
"GIT_CONFIG_KEY_0": "http.https://github.com/.extraheader",
|
|
2384
|
-
"GIT_CONFIG_VALUE_0": f"AUTHORIZATION: basic {basic}",
|
|
2385
|
-
}
|
|
2386
|
-
|
|
2387
|
-
|
|
2388
|
-
def fetched_base(root, ref, token):
|
|
2389
|
-
shallow = quiet_git(root, "rev-parse", "--is-shallow-repository") == "true"
|
|
2390
|
-
try:
|
|
2391
|
-
command(
|
|
2392
|
-
[
|
|
2393
|
-
"git",
|
|
2394
|
-
"-C",
|
|
2395
|
-
str(root),
|
|
2396
|
-
"fetch",
|
|
2397
|
-
"-q",
|
|
2398
|
-
"--no-tags",
|
|
2399
|
-
*(["--unshallow"] if shallow else []),
|
|
2400
|
-
"origin",
|
|
2401
|
-
ref,
|
|
2402
|
-
],
|
|
2403
|
-
env=git_token_environment(token),
|
|
2404
|
-
timeout=FETCH_SECONDS,
|
|
2405
|
-
)
|
|
2406
|
-
except (CommandError, subprocess.TimeoutExpired) as error:
|
|
2407
|
-
hint = (
|
|
2408
|
-
"check that it exists on GitHub"
|
|
2409
|
-
if token
|
|
2410
|
-
else f"the workflow passes no {GIT_TOKEN_ENV} to fetch it with, so run bitfab-replay --cloud-update and commit the workflow it updates"
|
|
2411
|
-
)
|
|
2412
|
-
raise ValueError(
|
|
2413
|
-
f"Could not fetch {ref} from origin to compare against ({error}); {hint}, or pass --code-change skip"
|
|
2414
|
-
) from None
|
|
2415
|
-
base = quiet_git(root, "merge-base", "HEAD", "FETCH_HEAD")
|
|
2416
|
-
if not base:
|
|
2417
|
-
raise ValueError(
|
|
2418
|
-
f"This branch shares no history with {ref}, so there is nothing to compare against"
|
|
2419
|
-
)
|
|
2420
|
-
return base
|
|
2421
|
-
|
|
2422
|
-
|
|
2423
|
-
def dispatched_code_change(root, commit, request, token):
|
|
2424
|
-
args = request["args"]
|
|
2425
|
-
kind = flag_value(args, CODE_CHANGE_FLAG)
|
|
2426
|
-
if kind not in FETCHED_CODE_CHANGES:
|
|
2427
|
-
return None
|
|
2428
|
-
ref = (
|
|
2429
|
-
flag_value(args, CODE_CHANGE_BASE_FLAG)
|
|
2430
|
-
if kind == "ref"
|
|
2431
|
-
else event_default_branch()
|
|
2432
|
-
)
|
|
2433
|
-
print(f"Fetching {ref} to record the code change against it", flush=True)
|
|
2434
|
-
base = fetched_base(root, ref, token)
|
|
2435
|
-
change = snapshot_code_change(
|
|
2436
|
-
root, base, commit, replay_name(args), f"vs {ref}", commit
|
|
2437
|
-
)
|
|
2438
|
-
return change or {"files": []}
|
|
2439
|
-
|
|
2440
|
-
|
|
2441
|
-
def write_code_change(change):
|
|
2442
|
-
handle, path = tempfile.mkstemp(
|
|
2443
|
-
prefix="bitfab-code-change-",
|
|
2444
|
-
suffix=".json",
|
|
2445
|
-
dir=os.environ.get("RUNNER_TEMP") or None,
|
|
2446
|
-
)
|
|
2447
|
-
with os.fdopen(handle, "w") as out:
|
|
2448
|
-
json.dump(change, out)
|
|
2449
|
-
return path
|
|
2450
|
-
|
|
2451
|
-
|
|
2452
|
-
def execute():
|
|
2453
|
-
if os.environ.get("GITHUB_RUN_ATTEMPT") != "1":
|
|
2454
|
-
raise ValueError("Submit a new replay instead of rerunning an Actions job")
|
|
2455
|
-
git_token = os.environ.pop(GIT_TOKEN_ENV, None)
|
|
2456
|
-
root = root_directory()
|
|
2457
|
-
commit = os.environ["GITHUB_SHA"]
|
|
2458
|
-
if git(root, "rev-parse", "HEAD") != commit:
|
|
2459
|
-
raise ValueError("Runner checkout does not match the dispatched commit")
|
|
2460
|
-
request = runner_request(root, commit)
|
|
2461
|
-
snapshot = os.environ.get("GITHUB_REF_NAME", "").startswith(PREFIX)
|
|
2462
|
-
base = (
|
|
2463
|
-
check_out_snapshot_base(root, commit, request.get("branch"))
|
|
2464
|
-
if snapshot
|
|
2465
|
-
else None
|
|
2466
|
-
)
|
|
2467
|
-
directory = within(root, request["cwd"])
|
|
2468
|
-
check_secrets(root)
|
|
2469
|
-
environment = request.get("env") or {}
|
|
2470
|
-
if environment:
|
|
2471
|
-
workflow_environment_conflicts(root, environment)
|
|
2472
|
-
print(f"Setting {', '.join(sorted(environment))} from the request", flush=True)
|
|
2473
|
-
if snapshot:
|
|
2474
|
-
change = (
|
|
2475
|
-
None if base is None else runner_code_change(root, base, commit, request)
|
|
2476
|
-
)
|
|
2477
|
-
else:
|
|
2478
|
-
change = dispatched_code_change(root, commit, request, git_token)
|
|
2479
|
-
run_environment = dict(environment)
|
|
2480
|
-
if change is not None:
|
|
2481
|
-
run_environment[CODE_CHANGE_PATH_ENV] = write_code_change(change)
|
|
2482
|
-
args = [*replay_command(), *request["args"]]
|
|
2483
|
-
if dry_run(request["args"]):
|
|
2484
|
-
run_check_command(directory, environment)
|
|
2485
|
-
experiment = {}
|
|
2486
|
-
starter = starter_key(root, request)
|
|
2487
|
-
previous = signal.signal(signal.SIGTERM, raise_interrupt)
|
|
2488
|
-
print(OUTPUT_BEGIN, flush=True)
|
|
2489
|
-
try:
|
|
2490
|
-
code, stdout, omitted, stopped = run_command(
|
|
2491
|
-
directory,
|
|
2492
|
-
args,
|
|
2493
|
-
request.get("timeoutMinutes"),
|
|
2494
|
-
experiment,
|
|
2495
|
-
summarize=request.get("fullOutput") is not True,
|
|
2496
|
-
environment=run_environment,
|
|
2497
|
-
)
|
|
2498
|
-
finally:
|
|
2499
|
-
print(OUTPUT_END, flush=True)
|
|
2500
|
-
signal.signal(signal.SIGTERM, previous)
|
|
2501
|
-
revoke_starter_key(starter)
|
|
2502
|
-
result = {
|
|
2503
|
-
"executionId": request["id"],
|
|
2504
|
-
"commitSha": commit,
|
|
2505
|
-
"exitCode": code,
|
|
2506
|
-
"stdout": stdout,
|
|
2507
|
-
}
|
|
2508
|
-
if omitted:
|
|
2509
|
-
result["stdoutOmittedBytes"] = omitted
|
|
2510
|
-
if stopped:
|
|
2511
|
-
result["stoppedEarly"] = stopped
|
|
2512
|
-
if UUID.fullmatch(experiment.get("id", "")):
|
|
2513
|
-
result["testRunId"] = experiment["id"]
|
|
2514
|
-
write_result(result)
|
|
2515
|
-
return result
|
|
2516
|
-
|
|
2517
|
-
|
|
2518
|
-
def runner_warning(message):
|
|
2519
|
-
print(f"::warning title=Bitfab replay::{message}", flush=True)
|
|
2520
|
-
|
|
2521
|
-
|
|
2522
|
-
def warn_if_workflow_outdated():
|
|
2523
|
-
problems = []
|
|
2524
|
-
if API_KEY_ENV in os.environ:
|
|
2525
|
-
problems.append(
|
|
2526
|
-
f"still sets {API_KEY_ENV} from a secret named by the run's inputs, which makes GitHub give this run every secret in the repository"
|
|
2527
|
-
)
|
|
2528
|
-
if not os.environ.get("ACTIONS_ID_TOKEN_REQUEST_URL"):
|
|
2529
|
-
problems.append(
|
|
2530
|
-
"does not grant id-token: write, so replays use the workflow's BITFAB_API_KEY secret instead of running as the person who started them"
|
|
2531
|
-
)
|
|
2532
|
-
if problems:
|
|
2533
|
-
runner_warning(
|
|
2534
|
-
f"This workflow {' and '.join(problems)}. Run bitfab-replay --cloud-update and commit the workflow it updates"
|
|
2535
|
-
)
|
|
2536
|
-
|
|
2537
|
-
|
|
2538
|
-
def starter_key(root, request):
|
|
2539
|
-
warn_if_workflow_outdated()
|
|
2540
|
-
if os.environ.get(API_KEY_ENV, "").strip():
|
|
2541
|
-
print(
|
|
2542
|
-
"Replaying with the Bitfab API key of the person who started this run",
|
|
2543
|
-
flush=True,
|
|
2544
|
-
)
|
|
2545
|
-
return None
|
|
2546
|
-
token = str(dispatched_inputs().get(KEY_INPUT) or "").strip()
|
|
2547
|
-
if not token.startswith(KEY_TOKEN_PREFIX):
|
|
2548
|
-
return None
|
|
2549
|
-
shared = "so this run uses the workflow's BITFAB_API_KEY secret"
|
|
2550
|
-
runner = local_client(root, request)
|
|
2551
|
-
if runner is None:
|
|
2552
|
-
runner_warning(
|
|
2553
|
-
f"The replay's Bitfab client resolved no API key on the runner, {shared}"
|
|
2554
|
-
)
|
|
2555
|
-
return None
|
|
2556
|
-
try:
|
|
2557
|
-
identity = github_run_identity()
|
|
2558
|
-
except CommandError as error:
|
|
2559
|
-
runner_warning(f"{error}, {shared}")
|
|
2560
|
-
return None
|
|
2561
|
-
timeout = request.get("timeoutMinutes")
|
|
2562
|
-
try:
|
|
2563
|
-
redeemed = bitfab_api(
|
|
2564
|
-
{"serviceUrl": runner["serviceUrl"]},
|
|
2565
|
-
"replay/cloudKey/redeem",
|
|
2566
|
-
payload={
|
|
2567
|
-
"token": token,
|
|
2568
|
-
"oidcToken": identity,
|
|
2569
|
-
**({"minutes": timeout} if timeout else {}),
|
|
2570
|
-
},
|
|
2571
|
-
)
|
|
2572
|
-
except CommandError as error:
|
|
2573
|
-
runner_warning(f"{error}, {shared}")
|
|
2574
|
-
return None
|
|
2575
|
-
key = redeemed.get("apiKey")
|
|
2576
|
-
if not isinstance(key, str) or not key.strip():
|
|
2577
|
-
runner_warning(f"Bitfab returned no key for the replay token, {shared}")
|
|
2578
|
-
return None
|
|
2579
|
-
print(f"::add-mask::{key}", flush=True)
|
|
2580
|
-
os.environ[API_KEY_ENV] = key
|
|
2581
|
-
print(
|
|
2582
|
-
"Replaying as the person who started this run, with a key that is turned off when the replay ends",
|
|
2583
|
-
flush=True,
|
|
2584
|
-
)
|
|
2585
|
-
return {"apiKey": key, "serviceUrl": runner["serviceUrl"]}
|
|
2586
|
-
|
|
2587
|
-
|
|
2588
|
-
def github_run_identity():
|
|
2589
|
-
url = os.environ.get("ACTIONS_ID_TOKEN_REQUEST_URL")
|
|
2590
|
-
bearer = os.environ.get("ACTIONS_ID_TOKEN_REQUEST_TOKEN")
|
|
2591
|
-
if not url or not bearer:
|
|
2592
|
-
raise CommandError(
|
|
2593
|
-
"The workflow does not grant id-token: write, so this run cannot prove to Bitfab which run it is; run bitfab-replay --cloud-update to add it"
|
|
2594
|
-
)
|
|
2595
|
-
separator = "&" if "?" in url else "?"
|
|
2596
|
-
request = urllib.request.Request(
|
|
2597
|
-
f"{url}{separator}{urlencode({'audience': OIDC_AUDIENCE})}",
|
|
2598
|
-
headers={
|
|
2599
|
-
"Authorization": f"Bearer {bearer}",
|
|
2600
|
-
"User-Agent": "bitfab-cloud-replay",
|
|
2601
|
-
},
|
|
2602
|
-
)
|
|
2603
|
-
try:
|
|
2604
|
-
with urllib.request.urlopen(request, timeout=30) as response:
|
|
2605
|
-
value = json.loads(response.read()).get("value")
|
|
2606
|
-
except (urllib.error.URLError, OSError, ValueError, AttributeError) as error:
|
|
2607
|
-
raise CommandError(
|
|
2608
|
-
f"GitHub did not issue this run's OIDC token: {getattr(error, 'reason', error)}"
|
|
2609
|
-
) from None
|
|
2610
|
-
if not isinstance(value, str) or not value:
|
|
2611
|
-
raise CommandError("GitHub returned no OIDC token for this run")
|
|
2612
|
-
return value
|
|
2613
|
-
|
|
2614
|
-
|
|
2615
|
-
def revoke_starter_key(starter):
|
|
2616
|
-
if starter is None:
|
|
2617
|
-
return
|
|
2618
|
-
try:
|
|
2619
|
-
bitfab_api(starter, "replay/cloudKey", method="DELETE")
|
|
2620
|
-
except CommandError as error:
|
|
2621
|
-
runner_warning(
|
|
2622
|
-
f"Could not turn off this replay's key ({error}); it expires on its own 30 minutes after the replay's timeout"
|
|
2623
|
-
)
|
|
2624
|
-
|
|
2625
|
-
|
|
2626
|
-
def running_workflow(root):
|
|
2627
|
-
reference = os.environ.get("GITHUB_WORKFLOW_REF", "")
|
|
2628
|
-
match = re.search(r"(\.github/workflows/[^@]+)@", reference)
|
|
2629
|
-
if match:
|
|
2630
|
-
return within(root, match[1])
|
|
2631
|
-
return within(root, f"{WORKFLOW_DIRECTORY}/{find_workflow(root) or WORKFLOW}")
|
|
2632
|
-
|
|
2633
|
-
|
|
2634
|
-
def check_secrets(root):
|
|
2635
|
-
path = running_workflow(root)
|
|
2636
|
-
targets = workflow_secrets(path.read_text()) if path.is_file() else {}
|
|
2637
|
-
empty = [name for name in targets if os.environ.get(name) == ""]
|
|
2638
|
-
if empty:
|
|
2639
|
-
raise ValueError(
|
|
2640
|
-
"These replay environment variables are empty on the runner: "
|
|
2641
|
-
+ ", ".join(f"{name} (secret {targets[name]})" for name in empty)
|
|
2642
|
-
+ ". GitHub passes a secret that does not exist as an empty string. Create each one under Settings, Secrets and variables, Actions, in the repository or in the job's Environment"
|
|
2643
|
-
)
|
|
2644
|
-
for name in targets:
|
|
2645
|
-
if any(
|
|
2646
|
-
0 < len(line.strip()) < 4
|
|
2647
|
-
for line in os.environ.get(name, "").splitlines()[1:]
|
|
2648
|
-
):
|
|
2649
|
-
print(
|
|
2650
|
-
f"::warning title=Bitfab replay::{name} has a line of three characters or fewer, such as a lone brace in multi-line JSON, and GitHub masks that text everywhere in this log. Store it on one line; bitfab-replay --cloud-secrets does this for JSON",
|
|
2651
|
-
flush=True,
|
|
2652
|
-
)
|
|
2653
|
-
|
|
2654
|
-
|
|
2655
|
-
def run_check_command(directory, environment=None):
|
|
2656
|
-
check = os.environ.get(CHECK_COMMAND_ENV, "").strip()
|
|
2657
|
-
if not check:
|
|
2658
|
-
return
|
|
2659
|
-
print(f"Running {CHECK_COMMAND_ENV}: {check}", flush=True)
|
|
2660
|
-
code = subprocess.run(
|
|
2661
|
-
shlex.split(check),
|
|
2662
|
-
cwd=directory,
|
|
2663
|
-
env={**os.environ, **(environment or {})},
|
|
2664
|
-
stdin=subprocess.DEVNULL,
|
|
2665
|
-
check=False,
|
|
2666
|
-
).returncode
|
|
2667
|
-
if code:
|
|
2668
|
-
raise ValueError(f"{CHECK_COMMAND_ENV} exited {code}; its output is above")
|
|
2669
|
-
|
|
2670
|
-
|
|
2671
|
-
def item_errors(items):
|
|
2672
|
-
errors = []
|
|
2673
|
-
for item in items:
|
|
2674
|
-
if not item_errored(item):
|
|
2675
|
-
continue
|
|
2676
|
-
error = next(
|
|
2677
|
-
item[field] for field in ITEM_ERROR_FIELDS if item.get(field) is not None
|
|
2678
|
-
)
|
|
2679
|
-
if isinstance(error, dict):
|
|
2680
|
-
error = error.get("message") or json.dumps(error)
|
|
2681
|
-
trace = next(
|
|
2682
|
-
(
|
|
2683
|
-
item[field]
|
|
2684
|
-
for field in ITEM_ID_FIELDS
|
|
2685
|
-
if isinstance(item.get(field), str)
|
|
2686
|
-
),
|
|
2687
|
-
"unknown trace",
|
|
2688
|
-
)
|
|
2689
|
-
text = " ".join(str(error).split())
|
|
2690
|
-
if len(text) > ITEM_ERROR_LENGTH:
|
|
2691
|
-
text = text[:ITEM_ERROR_LENGTH] + "..."
|
|
2692
|
-
errored = {"originalTraceId": trace, "error": text}
|
|
2693
|
-
if isinstance(item.get("attempt"), int):
|
|
2694
|
-
errored["attempt"] = item["attempt"]
|
|
2695
|
-
errors.append(errored)
|
|
2696
|
-
return errors
|
|
2697
|
-
|
|
2698
|
-
|
|
2699
|
-
def item_field(item, camel, snake):
|
|
2700
|
-
return item[camel] if camel in item else item.get(snake)
|
|
2701
|
-
|
|
2702
|
-
|
|
2703
|
-
def canonical(value):
|
|
2704
|
-
return json.dumps(value, separators=(",", ":"))
|
|
2705
|
-
|
|
2706
|
-
|
|
2707
|
-
def experiment_fields(parsed):
|
|
2708
|
-
fields = {}
|
|
2709
|
-
for name, spellings in EXPERIMENT_FIELDS.items():
|
|
2710
|
-
value = next(
|
|
2711
|
-
(parsed[key] for key in spellings if parsed.get(key) is not None), None
|
|
2712
|
-
)
|
|
2713
|
-
if value is not None:
|
|
2714
|
-
fields[name] = value
|
|
2715
|
-
return fields
|
|
2716
|
-
|
|
2717
|
-
|
|
2718
|
-
def replay_summary(parsed):
|
|
2719
|
-
items = [item for item in parsed["items"] if isinstance(item, dict)]
|
|
2720
|
-
replayed = [item for item in items if not carried_over(item)]
|
|
2721
|
-
errors = item_errors(replayed)
|
|
2722
|
-
counts = {
|
|
2723
|
-
"replayed": len(replayed),
|
|
2724
|
-
"carriedOver": len(items) - len(replayed),
|
|
2725
|
-
"same": 0,
|
|
2726
|
-
"changed": 0,
|
|
2727
|
-
"matchedExpected": 0,
|
|
2728
|
-
"missedExpected": 0,
|
|
2729
|
-
"errored": len(errors),
|
|
2730
|
-
}
|
|
2731
|
-
for item in replayed:
|
|
2732
|
-
if item_errored(item):
|
|
2733
|
-
continue
|
|
2734
|
-
equal = canonical(item.get("result")) == canonical(
|
|
2735
|
-
item_field(item, "originalOutput", "original_output")
|
|
2736
|
-
)
|
|
2737
|
-
if item_field(item, "ingestionType", "ingestion_type") == "seeded":
|
|
2738
|
-
counts["matchedExpected" if equal else "missedExpected"] += 1
|
|
2739
|
-
else:
|
|
2740
|
-
counts["same" if equal else "changed"] += 1
|
|
2741
|
-
summary = {
|
|
2742
|
-
"cloudSummary": True,
|
|
2743
|
-
**experiment_fields(parsed),
|
|
2744
|
-
"counts": counts,
|
|
2745
|
-
"erroredItems": errors[:SUMMARY_ERROR_ITEMS],
|
|
2746
|
-
}
|
|
2747
|
-
if len(errors) > SUMMARY_ERROR_ITEMS:
|
|
2748
|
-
summary["erroredItemsOmitted"] = len(errors) - SUMMARY_ERROR_ITEMS
|
|
2749
|
-
return summary
|
|
2750
|
-
|
|
2751
|
-
|
|
2752
|
-
def result_summary(stdout):
|
|
2753
|
-
parsed = last_json(stdout) or {}
|
|
2754
|
-
if parsed.get("cloudSummary") is True:
|
|
2755
|
-
return parsed
|
|
2756
|
-
if isinstance(parsed.get("items"), list):
|
|
2757
|
-
return replay_summary(parsed)
|
|
2758
|
-
return None
|
|
2759
|
-
|
|
2760
|
-
|
|
2761
|
-
def item_errored(item):
|
|
2762
|
-
return isinstance(item, dict) and any(
|
|
2763
|
-
item.get(field) is not None for field in ITEM_ERROR_FIELDS
|
|
2764
|
-
)
|
|
2765
|
-
|
|
2766
|
-
|
|
2767
|
-
def carried_over(item):
|
|
2768
|
-
return isinstance(item, dict) and (
|
|
2769
|
-
item.get("carriedOver") is True or item.get("carried_over") is True
|
|
2770
|
-
)
|
|
2771
|
-
|
|
2772
|
-
|
|
2773
|
-
def raise_interrupt(signum, frame):
|
|
2774
|
-
raise KeyboardInterrupt
|
|
2775
|
-
|
|
2776
|
-
|
|
2777
|
-
def without_item_payload(line):
|
|
2778
|
-
try:
|
|
2779
|
-
event = json.loads(line[len(PROGRESS_PREFIX) :])
|
|
2780
|
-
except ValueError:
|
|
2781
|
-
return line
|
|
2782
|
-
item = event.get("item") if isinstance(event, dict) else None
|
|
2783
|
-
if not isinstance(item, dict):
|
|
2784
|
-
return line
|
|
2785
|
-
event["item"] = {
|
|
2786
|
-
key: value for key, value in item.items() if key not in PROGRESS_PAYLOAD_FIELDS
|
|
2787
|
-
}
|
|
2788
|
-
return PROGRESS_PREFIX + json.dumps(event).encode() + b"\n"
|
|
2789
|
-
|
|
2790
|
-
|
|
2791
|
-
def forward_stderr(stream, experiment, summarize):
|
|
2792
|
-
for line in iter(stream.readline, b""):
|
|
2793
|
-
if summarize and line.startswith(PROGRESS_PREFIX):
|
|
2794
|
-
line = without_item_payload(line)
|
|
2795
|
-
sys.stdout.write(line.decode(errors="replace"))
|
|
2796
|
-
sys.stdout.flush()
|
|
2797
|
-
if "id" not in experiment:
|
|
2798
|
-
match = EXPERIMENT_LINE.match(line)
|
|
2799
|
-
if match:
|
|
2800
|
-
experiment["id"] = match[1].decode()
|
|
2801
|
-
|
|
2802
|
-
|
|
2803
|
-
def trailing_json(text):
|
|
2804
|
-
decoder = json.JSONDecoder()
|
|
2805
|
-
for offset in [0, *[i + 1 for i, value in enumerate(text) if value == "\n"]]:
|
|
2806
|
-
if text.startswith("{", offset):
|
|
2807
|
-
try:
|
|
2808
|
-
value, end = decoder.raw_decode(text, offset)
|
|
2809
|
-
except json.JSONDecodeError:
|
|
2810
|
-
continue
|
|
2811
|
-
if not text[end:].strip() and isinstance(value, dict):
|
|
2812
|
-
return offset, value
|
|
2813
|
-
return None, None
|
|
2814
|
-
|
|
2815
|
-
|
|
2816
|
-
def last_json(text):
|
|
2817
|
-
return trailing_json(text)[1]
|
|
2818
|
-
|
|
2819
|
-
|
|
2820
|
-
def relayed_stdout(output, code, summarize):
|
|
2821
|
-
if summarize:
|
|
2822
|
-
output.seek(0)
|
|
2823
|
-
parsed = last_json(output.read().decode(errors="replace"))
|
|
2824
|
-
if isinstance(parsed, dict) and isinstance(parsed.get("items"), list):
|
|
2825
|
-
return json.dumps({**replay_summary(parsed), "exitCode": code}) + "\n", 0
|
|
2826
|
-
return carried_stdout(output)
|
|
2827
|
-
|
|
2828
|
-
|
|
2829
|
-
def carried_stdout(output):
|
|
2830
|
-
start = max(0, os.fstat(output.fileno()).st_size - OUTPUT_LIMIT)
|
|
2831
|
-
output.seek(start)
|
|
2832
|
-
text = output.read().decode(errors="replace")
|
|
2833
|
-
if not start:
|
|
2834
|
-
return text, 0
|
|
2835
|
-
offset = trailing_json(text)[0] or 0
|
|
2836
|
-
return text[offset:], start + len(text[:offset].encode())
|
|
2837
|
-
|
|
2838
|
-
|
|
2839
|
-
def write_result(result):
|
|
2840
|
-
encoded = base64.b64encode(zlib.compress(json.dumps(result).encode())).decode()
|
|
2841
|
-
for start in range(0, len(encoded), RESULT_CHUNK):
|
|
2842
|
-
print(RESULT_LINE + encoded[start : start + RESULT_CHUNK])
|
|
2843
|
-
sys.stdout.flush()
|
|
2844
|
-
summary = os.environ.get("GITHUB_STEP_SUMMARY")
|
|
2845
|
-
if summary:
|
|
2846
|
-
with Path(summary).open("a") as file:
|
|
2847
|
-
file.write(summary_markdown(result))
|
|
2848
|
-
|
|
2849
|
-
|
|
2850
|
-
def annotate(result):
|
|
2851
|
-
if result.get("stoppedEarly"):
|
|
2852
|
-
message = f"Replay stopped early: {result['stoppedEarly']}"
|
|
2853
|
-
elif result["exitCode"]:
|
|
2854
|
-
message = f"Replay exited {result['exitCode']}, so this job exits with it too"
|
|
2855
|
-
else:
|
|
2856
|
-
return
|
|
2857
|
-
print(f"::warning title=Bitfab replay::{message}", flush=True)
|
|
2858
|
-
|
|
2859
|
-
|
|
2860
|
-
def runner_exit_code(result):
|
|
2861
|
-
if result.get("stoppedEarly"):
|
|
2862
|
-
return result["exitCode"] or 1
|
|
2863
|
-
return result["exitCode"]
|
|
2864
|
-
|
|
2865
|
-
|
|
2866
|
-
def summary_markdown(result):
|
|
2867
|
-
summary = result_summary(result["stdout"]) or {}
|
|
2868
|
-
counts = summary.get("counts", {})
|
|
2869
|
-
test_run = result.get("testRunId") or summary.get("testRunId")
|
|
2870
|
-
errors = summary.get("erroredItems", [])
|
|
2871
|
-
lines = [f"Commit: `{result['commitSha']}`", f"Exit code: {result['exitCode']}"]
|
|
2872
|
-
if test_run:
|
|
2873
|
-
lines.insert(0, f"Test run: `{test_run}`")
|
|
2874
|
-
if result.get("stoppedEarly"):
|
|
2875
|
-
lines.append(f"Stopped early: {result['stoppedEarly']}")
|
|
2876
|
-
elif counts.get("replayed") or counts.get("carriedOver"):
|
|
2877
|
-
lines.append(
|
|
2878
|
-
f"Replayed: {counts['replayed']}, same: {counts['same']}, changed: {counts['changed']}, errored: {counts['errored']}"
|
|
2879
|
-
)
|
|
2880
|
-
text = "### Bitfab replay\n\n" + "\n\n".join(lines) + "\n"
|
|
2881
|
-
if errors:
|
|
2882
|
-
shown = [
|
|
2883
|
-
f"trace {error['originalTraceId']}: {error['error']}"
|
|
2884
|
-
for error in errors[:ITEM_ERROR_LINES]
|
|
2885
|
-
]
|
|
2886
|
-
if counts.get("errored", 0) > len(shown):
|
|
2887
|
-
shown.append(f"and {counts['errored'] - len(shown)} more errored items")
|
|
2888
|
-
text += "\n#### Errored items\n\n" + "".join(
|
|
2889
|
-
f"- `{line.replace('`', chr(39))}`\n" for line in shown
|
|
2890
|
-
)
|
|
2891
|
-
return text
|
|
2892
|
-
|
|
2893
|
-
|
|
2894
|
-
def run_command(
|
|
2895
|
-
directory, args, timeout, experiment, *, summarize=True, environment=None
|
|
2896
|
-
):
|
|
2897
|
-
stopped = None
|
|
2898
|
-
with tempfile.TemporaryFile() as output:
|
|
2899
|
-
with subprocess.Popen(
|
|
2900
|
-
args,
|
|
2901
|
-
cwd=directory,
|
|
2902
|
-
env={
|
|
2903
|
-
**os.environ,
|
|
2904
|
-
**(environment or {}),
|
|
2905
|
-
EXECUTION_TARGET_ENV: HOSTED_EXECUTION_TARGET,
|
|
2906
|
-
},
|
|
2907
|
-
stdout=output,
|
|
2908
|
-
stderr=subprocess.PIPE,
|
|
2909
|
-
stdin=subprocess.DEVNULL,
|
|
2910
|
-
start_new_session=True,
|
|
2911
|
-
) as child:
|
|
2912
|
-
reader = threading.Thread(
|
|
2913
|
-
target=forward_stderr,
|
|
2914
|
-
args=(child.stderr, experiment, summarize),
|
|
2915
|
-
daemon=True,
|
|
2916
|
-
)
|
|
2917
|
-
reader.start()
|
|
2918
|
-
try:
|
|
2919
|
-
deadline = None if timeout is None else time.monotonic() + timeout * 60
|
|
2920
|
-
parent = os.getppid()
|
|
2921
|
-
checked = time.monotonic()
|
|
2922
|
-
while child.poll() is None:
|
|
2923
|
-
if os.fstat(output.fileno()).st_size > DISK_LIMIT:
|
|
2924
|
-
raise ValueError("Replay printed more than 1 GiB to stdout")
|
|
2925
|
-
if deadline is not None and time.monotonic() >= deadline:
|
|
2926
|
-
stopped = f"it reached the {timeout}-minute --cloud-timeout"
|
|
2927
|
-
stop(child)
|
|
2928
|
-
break
|
|
2929
|
-
if time.monotonic() - checked >= 1:
|
|
2930
|
-
checked = time.monotonic()
|
|
2931
|
-
if os.getppid() != parent:
|
|
2932
|
-
raise KeyboardInterrupt
|
|
2933
|
-
time.sleep(0.1)
|
|
2934
|
-
except KeyboardInterrupt:
|
|
2935
|
-
stopped = "the GitHub run was cancelled"
|
|
2936
|
-
stop(child)
|
|
2937
|
-
except BaseException:
|
|
2938
|
-
stop(child)
|
|
2939
|
-
raise
|
|
2940
|
-
finally:
|
|
2941
|
-
with contextlib.suppress(ProcessLookupError, PermissionError):
|
|
2942
|
-
os.killpg(child.pid, signal.SIGKILL)
|
|
2943
|
-
reader.join(timeout=5)
|
|
2944
|
-
code = child.returncode if child.returncode >= 0 else 1
|
|
2945
|
-
text, omitted = relayed_stdout(output, code, summarize)
|
|
2946
|
-
return code, text, omitted, stopped
|
|
2947
|
-
|
|
2948
|
-
|
|
2949
|
-
def stop(child):
|
|
2950
|
-
with contextlib.suppress(ProcessLookupError):
|
|
2951
|
-
os.killpg(child.pid, signal.SIGTERM)
|
|
2952
|
-
with contextlib.suppress(subprocess.TimeoutExpired):
|
|
2953
|
-
child.wait(timeout=30)
|
|
2954
|
-
with contextlib.suppress(ProcessLookupError):
|
|
2955
|
-
os.killpg(child.pid, signal.SIGKILL)
|
|
2956
|
-
child.wait()
|
|
2957
|
-
|
|
2958
|
-
|
|
2959
|
-
PNPM_FOR_LOCKFILE = {"9": "10", "6": "8", "5": "7"}
|
|
2960
|
-
DEFAULT_PNPM = "10"
|
|
2961
|
-
RUBY_VERSION_FILES = [".ruby-version", ".tool-versions"]
|
|
2962
|
-
PLAIN_SCALAR = re.compile(r"[A-Za-z0-9_./][A-Za-z0-9_ ./@*+=,()-]*")
|
|
2963
|
-
YAML_WORDS = {"true", "false", "yes", "no", "on", "off", "null", "~", "y", "n"}
|
|
2964
|
-
|
|
2965
|
-
|
|
2966
|
-
def yaml_scalar(value):
|
|
2967
|
-
if isinstance(value, (dict, list)):
|
|
2968
|
-
return "{}" if isinstance(value, dict) else "[]"
|
|
2969
|
-
if isinstance(value, bool):
|
|
2970
|
-
return "true" if value else "false"
|
|
2971
|
-
if isinstance(value, int):
|
|
2972
|
-
return str(value)
|
|
2973
|
-
text = str(value)
|
|
2974
|
-
if (
|
|
2975
|
-
PLAIN_SCALAR.fullmatch(text)
|
|
2976
|
-
and text == text.strip()
|
|
2977
|
-
and text.lower() not in YAML_WORDS
|
|
2978
|
-
and not re.fullmatch(r"[\d._+-]+", text)
|
|
2979
|
-
):
|
|
2980
|
-
return text
|
|
2981
|
-
return json.dumps(text)
|
|
2982
|
-
|
|
2983
|
-
|
|
2984
|
-
def yaml_key(key):
|
|
2985
|
-
return "on" if key == "on" else yaml_scalar(str(key))
|
|
2986
|
-
|
|
2987
|
-
|
|
2988
|
-
def yaml_lines(value, indent=0):
|
|
2989
|
-
pad = " " * indent
|
|
2990
|
-
lines = []
|
|
2991
|
-
if isinstance(value, dict):
|
|
2992
|
-
for key, item in value.items():
|
|
2993
|
-
if isinstance(item, (dict, list)) and item:
|
|
2994
|
-
lines.append(f"{pad}{yaml_key(key)}:")
|
|
2995
|
-
lines += yaml_lines(item, indent + 1)
|
|
2996
|
-
else:
|
|
2997
|
-
lines.append(f"{pad}{yaml_key(key)}: {yaml_scalar(item)}")
|
|
2998
|
-
else:
|
|
2999
|
-
for item in value:
|
|
3000
|
-
if isinstance(item, dict) and item:
|
|
3001
|
-
nested = yaml_lines(item, indent + 1)
|
|
3002
|
-
lines.append(f"{pad}- {nested[0].lstrip()}")
|
|
3003
|
-
lines += nested[1:]
|
|
3004
|
-
else:
|
|
3005
|
-
lines.append(f"{pad}- {yaml_scalar(item)}")
|
|
3006
|
-
return lines
|
|
3007
|
-
|
|
3008
|
-
|
|
3009
|
-
def to_yaml(document):
|
|
3010
|
-
return "\n".join(yaml_lines(document)) + "\n"
|
|
3011
|
-
|
|
3012
|
-
|
|
3013
|
-
def find_upward(root, start, names):
|
|
3014
|
-
directory = start
|
|
3015
|
-
while True:
|
|
3016
|
-
for name in names:
|
|
3017
|
-
if (directory / name).is_file():
|
|
3018
|
-
return directory, name
|
|
3019
|
-
if directory == root:
|
|
3020
|
-
return None, None
|
|
3021
|
-
directory = directory.parent
|
|
3022
|
-
|
|
3023
|
-
|
|
3024
|
-
def step_directory(root, directory):
|
|
3025
|
-
relative = directory.relative_to(root).as_posix()
|
|
3026
|
-
return {} if relative in ("", ".") else {"working-directory": relative}
|
|
3027
|
-
|
|
3028
|
-
|
|
3029
|
-
def detect_language(root, start):
|
|
3030
|
-
markers = {
|
|
3031
|
-
"package.json": "typescript",
|
|
3032
|
-
"pyproject.toml": "python",
|
|
3033
|
-
"requirements.txt": "python",
|
|
3034
|
-
"Gemfile": "ruby",
|
|
3035
|
-
"go.mod": "go",
|
|
3036
|
-
}
|
|
3037
|
-
_, found = find_upward(root, start, list(markers))
|
|
3038
|
-
if found is None:
|
|
3039
|
-
raise ValueError(
|
|
3040
|
-
"Could not tell which Bitfab SDK this project uses; run --cloud-init through your SDK's bitfab-replay command"
|
|
3041
|
-
)
|
|
3042
|
-
return markers[found]
|
|
3043
|
-
|
|
3044
|
-
|
|
3045
|
-
def version_input(root, start, key, names, default):
|
|
3046
|
-
directory, name = find_upward(root, start, names)
|
|
3047
|
-
if name is None:
|
|
3048
|
-
return {f"{key}-version": default}
|
|
3049
|
-
return {f"{key}-version-file": (directory / name).relative_to(root).as_posix()}
|
|
3050
|
-
|
|
3051
|
-
|
|
3052
|
-
def typescript_project(root, start):
|
|
3053
|
-
directory, lockfile = find_upward(
|
|
3054
|
-
root,
|
|
3055
|
-
start,
|
|
3056
|
-
["pnpm-lock.yaml", "bun.lock", "bun.lockb", "yarn.lock", "package-lock.json"],
|
|
3057
|
-
)
|
|
3058
|
-
manager = {
|
|
3059
|
-
"pnpm-lock.yaml": "pnpm",
|
|
3060
|
-
"bun.lock": "bun",
|
|
3061
|
-
"bun.lockb": "bun",
|
|
3062
|
-
"yarn.lock": "yarn",
|
|
3063
|
-
}.get(lockfile, "npm")
|
|
3064
|
-
install = {
|
|
3065
|
-
"pnpm": "pnpm install --frozen-lockfile",
|
|
3066
|
-
"bun": "bun install --frozen-lockfile",
|
|
3067
|
-
"yarn": "yarn install --frozen-lockfile",
|
|
3068
|
-
"npm": "npm ci" if lockfile else "npm install",
|
|
3069
|
-
}[manager]
|
|
3070
|
-
steps = []
|
|
3071
|
-
if manager == "pnpm":
|
|
3072
|
-
steps.append(pnpm_setup(root, directory, lockfile))
|
|
3073
|
-
if manager == "bun":
|
|
3074
|
-
steps.append({"uses": ACTIONS["bun"]})
|
|
3075
|
-
cache = {}
|
|
3076
|
-
if manager in ("pnpm", "yarn", "npm") and lockfile:
|
|
3077
|
-
cache["cache"] = manager
|
|
3078
|
-
if directory != root:
|
|
3079
|
-
cache["cache-dependency-path"] = (
|
|
3080
|
-
(directory / lockfile).relative_to(root).as_posix()
|
|
3081
|
-
)
|
|
3082
|
-
steps += [
|
|
3083
|
-
{
|
|
3084
|
-
"uses": ACTIONS["node"],
|
|
3085
|
-
"with": {
|
|
3086
|
-
**version_input(
|
|
3087
|
-
root, start, "node", [".nvmrc", ".node-version"], "lts/*"
|
|
3088
|
-
),
|
|
3089
|
-
**cache,
|
|
3090
|
-
},
|
|
3091
|
-
},
|
|
3092
|
-
{**step_directory(root, directory or start), "run": install},
|
|
3093
|
-
]
|
|
3094
|
-
run = {
|
|
3095
|
-
"pnpm": "pnpm exec bitfab-replay",
|
|
3096
|
-
"bun": "bunx bitfab-replay",
|
|
3097
|
-
"yarn": "yarn bitfab-replay",
|
|
3098
|
-
"npm": "npx --no-install bitfab-replay",
|
|
3099
|
-
}[manager]
|
|
3100
|
-
return steps, run
|
|
3101
|
-
|
|
3102
|
-
|
|
3103
|
-
def pnpm_setup(root, directory, lockfile):
|
|
3104
|
-
package = directory / "package.json"
|
|
3105
|
-
try:
|
|
3106
|
-
declared = json.loads(package.read_text()).get("packageManager", "")
|
|
3107
|
-
except (OSError, ValueError, AttributeError):
|
|
3108
|
-
declared = ""
|
|
3109
|
-
if isinstance(declared, str) and declared.startswith("pnpm@"):
|
|
3110
|
-
if directory == root:
|
|
3111
|
-
return {"uses": ACTIONS["pnpm"]}
|
|
3112
|
-
return {
|
|
3113
|
-
"uses": ACTIONS["pnpm"],
|
|
3114
|
-
"with": {"package_json_file": package.relative_to(root).as_posix()},
|
|
3115
|
-
}
|
|
3116
|
-
found = re.search(
|
|
3117
|
-
r"^lockfileVersion:\s*['\"]?(\d+)",
|
|
3118
|
-
(directory / lockfile).read_text(errors="replace"),
|
|
3119
|
-
re.MULTILINE,
|
|
3120
|
-
)
|
|
3121
|
-
version = PNPM_FOR_LOCKFILE.get(found[1] if found else "", DEFAULT_PNPM)
|
|
3122
|
-
return {"uses": ACTIONS["pnpm"], "with": {"version": version}}
|
|
3123
|
-
|
|
3124
|
-
|
|
3125
|
-
def python_project(root, start):
|
|
3126
|
-
directory, lockfile = find_upward(
|
|
3127
|
-
root, start, ["uv.lock", "poetry.lock", "requirements.txt", "pyproject.toml"]
|
|
3128
|
-
)
|
|
3129
|
-
location = step_directory(root, directory or start)
|
|
3130
|
-
python = {
|
|
3131
|
-
"uses": ACTIONS["python"],
|
|
3132
|
-
"with": version_input(root, start, "python", [".python-version"], "3.12"),
|
|
3133
|
-
}
|
|
3134
|
-
if lockfile == "uv.lock":
|
|
3135
|
-
return [
|
|
3136
|
-
{"uses": ACTIONS["uv"]},
|
|
3137
|
-
{**location, "run": "uv sync --frozen"},
|
|
3138
|
-
], "uv run bitfab-replay"
|
|
3139
|
-
if lockfile == "poetry.lock":
|
|
3140
|
-
return [
|
|
3141
|
-
python,
|
|
3142
|
-
{
|
|
3143
|
-
**location,
|
|
3144
|
-
"run": "pipx install poetry && poetry install --no-interaction",
|
|
3145
|
-
},
|
|
3146
|
-
], "poetry run bitfab-replay"
|
|
3147
|
-
install = (
|
|
3148
|
-
"pip install -r requirements.txt"
|
|
3149
|
-
if lockfile == "requirements.txt"
|
|
3150
|
-
else "pip install ."
|
|
3151
|
-
)
|
|
3152
|
-
return [python, {**location, "run": install}], "bitfab-replay"
|
|
3153
|
-
|
|
3154
|
-
|
|
3155
|
-
def ruby_project(root, start):
|
|
3156
|
-
directory, _ = find_upward(root, start, ["Gemfile"])
|
|
3157
|
-
directory = directory or start
|
|
3158
|
-
found, name = find_upward(root, directory, RUBY_VERSION_FILES)
|
|
3159
|
-
version = (
|
|
3160
|
-
{}
|
|
3161
|
-
if found == directory
|
|
3162
|
-
else {"ruby-version": (name and ruby_version(found / name)) or "ruby"}
|
|
3163
|
-
)
|
|
3164
|
-
return [
|
|
3165
|
-
{
|
|
3166
|
-
"uses": ACTIONS["ruby"],
|
|
3167
|
-
"with": {
|
|
3168
|
-
**version,
|
|
3169
|
-
"bundler-cache": True,
|
|
3170
|
-
**step_directory(root, directory),
|
|
3171
|
-
},
|
|
3172
|
-
}
|
|
3173
|
-
], "bundle exec bitfab-replay"
|
|
3174
|
-
|
|
3175
|
-
|
|
3176
|
-
def ruby_version(path):
|
|
3177
|
-
text = path.read_text(errors="replace")
|
|
3178
|
-
if path.name == ".tool-versions":
|
|
3179
|
-
found = re.search(r"^ruby\s+(\S+)", text, re.MULTILINE)
|
|
3180
|
-
return found[1] if found else None
|
|
3181
|
-
return text.strip() or None
|
|
3182
|
-
|
|
3183
|
-
|
|
3184
|
-
def go_project(root, start):
|
|
3185
|
-
directory, name = find_upward(root, start, ["go.mod"])
|
|
3186
|
-
version = (
|
|
3187
|
-
{"go-version-file": (directory / name).relative_to(root).as_posix()}
|
|
3188
|
-
if name
|
|
3189
|
-
else {"go-version": "stable"}
|
|
3190
|
-
)
|
|
3191
|
-
return [{"uses": ACTIONS["go"], "with": version}], go_registry_command(root, start)
|
|
3192
|
-
|
|
3193
|
-
|
|
3194
|
-
def go_registry_command(root, start):
|
|
3195
|
-
programs = set()
|
|
3196
|
-
for directory, folders, names in os.walk(root):
|
|
3197
|
-
folders[:] = [
|
|
3198
|
-
folder
|
|
3199
|
-
for folder in folders
|
|
3200
|
-
if not folder.startswith(".")
|
|
3201
|
-
and folder not in ("node_modules", "vendor", "testdata")
|
|
3202
|
-
]
|
|
3203
|
-
for name in names:
|
|
3204
|
-
if not name.endswith(".go") or name.endswith("_test.go"):
|
|
3205
|
-
continue
|
|
3206
|
-
text = (Path(directory) / name).read_text(errors="replace")
|
|
3207
|
-
if "RunCloudReplayCLI(" in text and re.search(
|
|
3208
|
-
r"^package main\b", text, re.MULTILINE
|
|
3209
|
-
):
|
|
3210
|
-
programs.add(Path(directory))
|
|
3211
|
-
if len(programs) != 1:
|
|
3212
|
-
return None
|
|
3213
|
-
relative = os.path.relpath(programs.pop(), start)
|
|
3214
|
-
return f"go run {relative if relative.startswith('..') else './' + relative}"
|
|
3215
|
-
|
|
3216
|
-
|
|
3217
|
-
PROJECTS = {
|
|
3218
|
-
"typescript": typescript_project,
|
|
3219
|
-
"python": python_project,
|
|
3220
|
-
"ruby": ruby_project,
|
|
3221
|
-
"go": go_project,
|
|
3222
|
-
}
|
|
3223
|
-
|
|
3224
|
-
|
|
3225
|
-
def push_triggers(root, workflow):
|
|
3226
|
-
found = []
|
|
3227
|
-
directory = root / WORKFLOW_DIRECTORY
|
|
3228
|
-
for path in sorted(directory.glob("*.y*ml")) if directory.is_dir() else []:
|
|
3229
|
-
text = path.read_text(errors="replace")
|
|
3230
|
-
if path.name != workflow and PUSH_TRIGGER.search(text) and PREFIX not in text:
|
|
3231
|
-
found.append(path.relative_to(root).as_posix())
|
|
3232
|
-
for path in (root / "vercel.json", Path.cwd() / "vercel.json"):
|
|
3233
|
-
relative = path.resolve().relative_to(root).as_posix()
|
|
3234
|
-
if (
|
|
3235
|
-
path.is_file()
|
|
3236
|
-
and PREFIX not in path.read_text(errors="replace")
|
|
3237
|
-
and relative not in found
|
|
3238
|
-
):
|
|
3239
|
-
found.append(relative)
|
|
3240
|
-
return found
|
|
3241
|
-
|
|
3242
|
-
|
|
3243
|
-
def workflow_document(steps, run, directory, env, *, runs_on, environment):
|
|
3244
|
-
job = {"if": PUSH_CONDITION, "runs-on": runs_on}
|
|
3245
|
-
if environment:
|
|
3246
|
-
job["environment"] = environment
|
|
3247
|
-
job["steps"] = [
|
|
3248
|
-
{
|
|
3249
|
-
"uses": ACTIONS["checkout"],
|
|
3250
|
-
"with": {"persist-credentials": False, "fetch-depth": CHECKOUT_DEPTH},
|
|
3251
|
-
},
|
|
3252
|
-
*steps,
|
|
3253
|
-
{
|
|
3254
|
-
**({} if directory == "." else {"working-directory": directory}),
|
|
3255
|
-
"run": f"{run} --cloud-execute",
|
|
3256
|
-
"env": {**env, GIT_TOKEN_ENV: GIT_TOKEN_VALUE},
|
|
3257
|
-
},
|
|
3258
|
-
]
|
|
3259
|
-
return {
|
|
3260
|
-
"name": "Bitfab replay",
|
|
3261
|
-
"run-name": RUN_NAME,
|
|
3262
|
-
"on": {
|
|
3263
|
-
"workflow_dispatch": {
|
|
3264
|
-
"inputs": {
|
|
3265
|
-
"execution_id": {"type": "string", "required": False},
|
|
3266
|
-
"request": {"type": "string", "required": False},
|
|
3267
|
-
KEY_INPUT: {"type": "string", "required": False},
|
|
3268
|
-
}
|
|
3269
|
-
},
|
|
3270
|
-
"push": {"branches": [PREFIX + "**"]},
|
|
3271
|
-
},
|
|
3272
|
-
"permissions": {"contents": "read", "id-token": "write"},
|
|
3273
|
-
"jobs": {"replay": job},
|
|
3274
|
-
}
|
|
3275
|
-
|
|
3276
|
-
|
|
3277
|
-
def indentation(line):
|
|
3278
|
-
return len(line) - len(line.lstrip(" \t"))
|
|
3279
|
-
|
|
3280
|
-
|
|
3281
|
-
def block_end(lines, start, indent):
|
|
3282
|
-
end = start + 1
|
|
3283
|
-
while end < len(lines) and (
|
|
3284
|
-
not lines[end].strip()
|
|
3285
|
-
or lines[end].lstrip().startswith("#")
|
|
3286
|
-
or indentation(lines[end]) > indent
|
|
3287
|
-
):
|
|
3288
|
-
end += 1
|
|
3289
|
-
while end > start + 1 and (
|
|
3290
|
-
not lines[end - 1].strip()
|
|
3291
|
-
or (
|
|
3292
|
-
lines[end - 1].lstrip().startswith("#")
|
|
3293
|
-
and indentation(lines[end - 1]) <= indent
|
|
3294
|
-
)
|
|
3295
|
-
):
|
|
3296
|
-
end -= 1
|
|
3297
|
-
return end
|
|
3298
|
-
|
|
3299
|
-
|
|
3300
|
-
def add_input(lines, name):
|
|
3301
|
-
for index, line in enumerate(lines):
|
|
3302
|
-
if not re.fullmatch(r'[ \t]*"?request"?[ \t]*:[ \t]*', line):
|
|
3303
|
-
continue
|
|
3304
|
-
indent = indentation(line)
|
|
3305
|
-
child = " " * (
|
|
3306
|
-
indentation(lines[index + 1])
|
|
3307
|
-
if block_end(lines, index, indent) > index + 1
|
|
3308
|
-
else indent + 2
|
|
3309
|
-
)
|
|
3310
|
-
end = block_end(lines, index, indent - 1)
|
|
3311
|
-
lines[end:end] = [
|
|
3312
|
-
f"{line[:indent]}{name}:",
|
|
3313
|
-
f"{child}type: string",
|
|
3314
|
-
f"{child}required: false",
|
|
3315
|
-
]
|
|
3316
|
-
return True
|
|
3317
|
-
return False
|
|
3318
|
-
|
|
3319
|
-
|
|
3320
|
-
def add_run_name(lines):
|
|
3321
|
-
named = next(
|
|
3322
|
-
(
|
|
3323
|
-
index
|
|
3324
|
-
for index, line in enumerate(lines)
|
|
3325
|
-
if re.match(r'"?name"?[ \t]*:', line)
|
|
3326
|
-
),
|
|
3327
|
-
-1,
|
|
3328
|
-
)
|
|
3329
|
-
lines.insert(named + 1, f"run-name: {json.dumps(RUN_NAME)}")
|
|
3330
|
-
|
|
3331
|
-
|
|
3332
|
-
def without_yaml_comment(line):
|
|
3333
|
-
return re.sub(r"(^|\s)#.*", "", line)
|
|
3334
|
-
|
|
3335
|
-
|
|
3336
|
-
def remove_legacy_key_env(lines):
|
|
3337
|
-
kept = [line for line in lines if not LEGACY_KEY_SECRET_REFERENCE.match(line)]
|
|
3338
|
-
if len(kept) == len(lines):
|
|
3339
|
-
return False
|
|
3340
|
-
lines[:] = kept
|
|
3341
|
-
return True
|
|
3342
|
-
|
|
3343
|
-
|
|
3344
|
-
def raise_checkout_depth(lines, start, end):
|
|
3345
|
-
for at in range(start, end):
|
|
3346
|
-
if not re.match(r'[ \t]*"?fetch-depth"?[ \t]*:', lines[at]):
|
|
3347
|
-
continue
|
|
3348
|
-
depth = re.match(
|
|
3349
|
-
r'([ \t]*"?fetch-depth"?[ \t]*:[ \t]*)["\']?(\d+)["\']?(.*)',
|
|
3350
|
-
lines[at],
|
|
3351
|
-
)
|
|
3352
|
-
if depth is None or int(depth[2]) == 0 or int(depth[2]) >= CHECKOUT_DEPTH:
|
|
3353
|
-
return False
|
|
3354
|
-
lines[at] = f"{depth[1]}{CHECKOUT_DEPTH}{depth[3]}"
|
|
3355
|
-
return True
|
|
3356
|
-
return None
|
|
3357
|
-
|
|
3358
|
-
|
|
3359
|
-
def add_checkout_depth(lines):
|
|
3360
|
-
for index, line in enumerate(lines):
|
|
3361
|
-
match = re.match(
|
|
3362
|
-
r'([ \t]*)(- +)?"?uses"?[ \t]*:[ \t]*"?[\w.-]+/checkout@',
|
|
3363
|
-
without_yaml_comment(line),
|
|
3364
|
-
)
|
|
3365
|
-
if not match:
|
|
3366
|
-
continue
|
|
3367
|
-
key = len(match[1]) + len(match[2] or "")
|
|
3368
|
-
start = index
|
|
3369
|
-
while start > 0 and not re.match(r"[ \t]*- ", lines[start]):
|
|
3370
|
-
start -= 1
|
|
3371
|
-
end = block_end(lines, start, key - 1)
|
|
3372
|
-
raised = raise_checkout_depth(lines, start, end)
|
|
3373
|
-
if raised is not None:
|
|
3374
|
-
return "updated" if raised else "unchanged"
|
|
3375
|
-
entry = f"fetch-depth: {CHECKOUT_DEPTH}"
|
|
3376
|
-
for at in range(start, end):
|
|
3377
|
-
with_key = re.fullmatch(
|
|
3378
|
-
r"[ \t]*(- +)?with[ \t]*:(.*)", without_yaml_comment(lines[at])
|
|
3379
|
-
)
|
|
3380
|
-
if not with_key:
|
|
3381
|
-
continue
|
|
3382
|
-
if len(lines[at]) - len(lines[at].lstrip(" \t-")) != key:
|
|
3383
|
-
continue
|
|
3384
|
-
if with_key[2].strip():
|
|
3385
|
-
return "by hand"
|
|
3386
|
-
entries = block_end(lines, at, key)
|
|
3387
|
-
child = indentation(lines[at + 1]) if entries > at + 1 else key + 2
|
|
3388
|
-
lines.insert(entries, " " * child + entry)
|
|
3389
|
-
return "updated"
|
|
3390
|
-
lines[end:end] = [" " * key + "with:", " " * (key + 2) + entry]
|
|
3391
|
-
return "updated"
|
|
3392
|
-
return "unchanged"
|
|
3393
|
-
|
|
3394
|
-
|
|
3395
|
-
def has_git_token_env(lines):
|
|
3396
|
-
return any(
|
|
3397
|
-
re.match(rf'[ \t]*(- +)?"?{GIT_TOKEN_ENV}"?[ \t]*:', without_yaml_comment(line))
|
|
3398
|
-
for line in lines
|
|
3399
|
-
)
|
|
3400
|
-
|
|
3401
|
-
|
|
3402
|
-
def add_git_token_env(lines):
|
|
3403
|
-
execute = next(
|
|
3404
|
-
(
|
|
3405
|
-
index
|
|
3406
|
-
for index in range(len(lines) - 1, -1, -1)
|
|
3407
|
-
if "--cloud-execute" in without_yaml_comment(lines[index])
|
|
3408
|
-
),
|
|
3409
|
-
None,
|
|
3410
|
-
)
|
|
3411
|
-
if execute is None:
|
|
3412
|
-
return False
|
|
3413
|
-
start = execute
|
|
3414
|
-
while start > 0 and not re.match(r"[ \t]*- ", lines[start]):
|
|
3415
|
-
start -= 1
|
|
3416
|
-
key = len(lines[start]) - len(lines[start].lstrip(" \t-"))
|
|
3417
|
-
end = block_end(lines, start, key - 1)
|
|
3418
|
-
entry = f"{GIT_TOKEN_ENV}: {json.dumps(GIT_TOKEN_VALUE)}"
|
|
3419
|
-
for at in range(start, end):
|
|
3420
|
-
env_key = re.fullmatch(
|
|
3421
|
-
r"[ \t]*(- +)?\"?env\"?[ \t]*:(.*)", without_yaml_comment(lines[at])
|
|
3422
|
-
)
|
|
3423
|
-
if not env_key or len(lines[at]) - len(lines[at].lstrip(" \t-")) != key:
|
|
3424
|
-
continue
|
|
3425
|
-
if env_key[2].strip():
|
|
3426
|
-
return False
|
|
3427
|
-
entries = block_end(lines, at, key)
|
|
3428
|
-
child = indentation(lines[at + 1]) if entries > at + 1 else key + 2
|
|
3429
|
-
lines.insert(entries, " " * child + entry)
|
|
3430
|
-
return True
|
|
3431
|
-
lines[end:end] = [" " * key + "env:", " " * (key + 2) + entry]
|
|
3432
|
-
return True
|
|
3433
|
-
|
|
3434
|
-
|
|
3435
|
-
def add_id_token_permission(lines):
|
|
3436
|
-
for index, line in enumerate(lines):
|
|
3437
|
-
if not re.fullmatch(r'"?permissions"?[ \t]*:[ \t]*(#.*)?', line):
|
|
3438
|
-
continue
|
|
3439
|
-
end = block_end(lines, index, 0)
|
|
3440
|
-
lines.insert(end, f"{child_indent(lines, index, end, ' ')}id-token: write")
|
|
3441
|
-
return True
|
|
3442
|
-
return False
|
|
3443
|
-
|
|
3444
|
-
|
|
3445
|
-
def holds_yaml(line):
|
|
3446
|
-
return bool(line.strip()) and not line.lstrip().startswith("#")
|
|
3447
|
-
|
|
3448
|
-
|
|
3449
|
-
def child_indent(lines, index, end, fallback):
|
|
3450
|
-
return next(
|
|
3451
|
-
(
|
|
3452
|
-
lines[row][: indentation(lines[row])]
|
|
3453
|
-
for row in range(index + 1, end)
|
|
3454
|
-
if holds_yaml(lines[row])
|
|
3455
|
-
),
|
|
3456
|
-
fallback,
|
|
3457
|
-
)
|
|
3458
|
-
|
|
3459
|
-
|
|
3460
|
-
def add_push_trigger(lines):
|
|
3461
|
-
for index, line in enumerate(lines):
|
|
3462
|
-
if not re.fullmatch(r'"?on"?[ \t]*:[ \t]*(#.*)?', line):
|
|
3463
|
-
continue
|
|
3464
|
-
end = block_end(lines, index, 0)
|
|
3465
|
-
step = child_indent(lines, index, end, " ")
|
|
3466
|
-
lines[end:end] = [
|
|
3467
|
-
f"{step}push:",
|
|
3468
|
-
f"{step * 2}branches:",
|
|
3469
|
-
f"{step * 3}- {PREFIX}**",
|
|
3470
|
-
]
|
|
3471
|
-
return True
|
|
3472
|
-
return False
|
|
3473
|
-
|
|
3474
|
-
|
|
3475
|
-
def add_push_condition(lines):
|
|
3476
|
-
jobs = next(
|
|
3477
|
-
(
|
|
3478
|
-
index
|
|
3479
|
-
for index, line in enumerate(lines)
|
|
3480
|
-
if re.fullmatch(r'"?jobs"?[ \t]*:[ \t]*(#.*)?', line)
|
|
3481
|
-
),
|
|
3482
|
-
None,
|
|
3483
|
-
)
|
|
3484
|
-
if jobs is None:
|
|
3485
|
-
return False
|
|
3486
|
-
end = block_end(lines, jobs, 0)
|
|
3487
|
-
job = next((row for row in range(jobs + 1, end) if holds_yaml(lines[row])), None)
|
|
3488
|
-
if job is None or not lines[job].rstrip().endswith(":"):
|
|
3489
|
-
return False
|
|
3490
|
-
job_end = block_end(lines, job, indentation(lines[job]))
|
|
3491
|
-
step = child_indent(lines, job, job_end, " " * (indentation(lines[job]) + 2))
|
|
3492
|
-
if any(
|
|
3493
|
-
re.fullmatch(rf'{step}"?if"?[ \t]*:.*', lines[row])
|
|
3494
|
-
for row in range(job + 1, job_end)
|
|
3495
|
-
):
|
|
3496
|
-
return False
|
|
3497
|
-
lines.insert(job + 1, f"{step}if: {json.dumps(PUSH_CONDITION)}")
|
|
3498
|
-
return True
|
|
3499
|
-
|
|
3500
|
-
|
|
3501
|
-
def secret_scope(environment):
|
|
3502
|
-
return f"environments/{environment}/" if environment else "actions/"
|
|
3503
|
-
|
|
3504
|
-
|
|
3505
|
-
def secret_names(repo, environment):
|
|
3506
|
-
names, page = [], 1
|
|
3507
|
-
while True:
|
|
3508
|
-
listed = (
|
|
3509
|
-
api(
|
|
3510
|
-
repo,
|
|
3511
|
-
f"{secret_scope(environment)}secrets?per_page={SECRETS_PER_PAGE}&page={page}",
|
|
3512
|
-
)
|
|
3513
|
-
or {}
|
|
3514
|
-
)
|
|
3515
|
-
batch = [secret["name"] for secret in listed.get("secrets", [])]
|
|
3516
|
-
names.extend(batch)
|
|
3517
|
-
if len(batch) < SECRETS_PER_PAGE:
|
|
3518
|
-
return names
|
|
3519
|
-
page += 1
|
|
3520
|
-
|
|
3521
|
-
|
|
3522
|
-
def leftover_key_secrets(repo, environment):
|
|
3523
|
-
return [
|
|
3524
|
-
{"name": name, "environment": scope}
|
|
3525
|
-
for scope in dict.fromkeys([None, environment])
|
|
3526
|
-
for name in secret_names(repo, scope)
|
|
3527
|
-
if name.startswith(LEFTOVER_KEY_SECRET_PREFIX)
|
|
3528
|
-
]
|
|
3529
|
-
|
|
3530
|
-
|
|
3531
|
-
def delete_secret(repo, secret):
|
|
3532
|
-
try:
|
|
3533
|
-
api(
|
|
3534
|
-
repo,
|
|
3535
|
-
f"{secret_scope(secret['environment'])}secrets/{secret['name']}",
|
|
3536
|
-
method="DELETE",
|
|
3537
|
-
)
|
|
3538
|
-
except CommandError as error:
|
|
3539
|
-
if error.http_status != 404:
|
|
3540
|
-
return False
|
|
3541
|
-
return True
|
|
3542
|
-
|
|
3543
|
-
|
|
3544
|
-
def leftover_key_secret_report(root, text, remove):
|
|
3545
|
-
try:
|
|
3546
|
-
repo = repository(root)
|
|
3547
|
-
except ValueError:
|
|
3548
|
-
return {}, []
|
|
3549
|
-
configured = ENVIRONMENT_SETTING.search(text)
|
|
3550
|
-
environment = configured[1] if configured else None
|
|
3551
|
-
pages = " and ".join(
|
|
3552
|
-
dict.fromkeys(secrets_page(repo, scope) for scope in (None, environment))
|
|
3553
|
-
)
|
|
3554
|
-
try:
|
|
3555
|
-
found = leftover_key_secrets(repo, environment)
|
|
3556
|
-
except (ValueError, RuntimeError):
|
|
3557
|
-
return {}, [
|
|
3558
|
-
f"Could not list the repository's secrets to look for {LEFTOVER_KEY_SECRET_PREFIX}* secrets an older SDK left behind, each a copy of someone's Bitfab API key; delete any at {pages}"
|
|
3559
|
-
]
|
|
3560
|
-
if not found:
|
|
3561
|
-
return {}, []
|
|
3562
|
-
if not remove:
|
|
3563
|
-
return {"oldKeySecrets": [secret["name"] for secret in found]}, [
|
|
3564
|
-
f"Delete {len(found)} {LEFTOVER_KEY_SECRET_PREFIX}* secret{'s' if len(found) != 1 else ''} an older SDK left behind when a replay could not remove {'them' if len(found) != 1 else 'it'}. Each holds a copy of the Bitfab API key of the person who started that replay, and nothing reads them now. Run bitfab-replay --cloud-update --remove-old-key-secrets, or delete them at {pages}"
|
|
3565
|
-
]
|
|
3566
|
-
removed = [secret for secret in found if delete_secret(repo, secret)]
|
|
3567
|
-
failed = [secret["name"] for secret in found if secret not in removed]
|
|
3568
|
-
report = {"removedOldKeySecrets": [secret["name"] for secret in removed]}
|
|
3569
|
-
if not failed:
|
|
3570
|
-
return report, []
|
|
3571
|
-
return {**report, "oldKeySecrets": failed}, [
|
|
3572
|
-
f"Could not delete {', '.join(failed)}, which needs permission to manage the repository's Actions secrets; delete them at {pages}"
|
|
3573
|
-
]
|
|
3574
|
-
|
|
3575
|
-
|
|
3576
|
-
def update_workflow(root, path, *, remove_old_key_secrets=False):
|
|
3577
|
-
target = within(root, path)
|
|
3578
|
-
text = target.read_text()
|
|
3579
|
-
lines = text.split("\n")
|
|
3580
|
-
updated, by_hand = [], []
|
|
3581
|
-
declared = declared_inputs(text)
|
|
3582
|
-
for name in ("execution_id", KEY_INPUT):
|
|
3583
|
-
if name in declared:
|
|
3584
|
-
continue
|
|
3585
|
-
if add_input(lines, name):
|
|
3586
|
-
updated.append(f"Added the {name} input")
|
|
3587
|
-
else:
|
|
3588
|
-
by_hand.append(
|
|
3589
|
-
f"{name} (type: string, required: false) under on.workflow_dispatch.inputs"
|
|
3590
|
-
)
|
|
3591
|
-
if not starts_on_push(text):
|
|
3592
|
-
if push_trigger(lines) is None and add_push_trigger(lines):
|
|
3593
|
-
updated.append(
|
|
3594
|
-
f"Started the workflow on a push to a {PREFIX} branch too, so a replay runs without GitHub access, with no updates on it"
|
|
3595
|
-
)
|
|
3596
|
-
else:
|
|
3597
|
-
by_hand.append(f"{PREFIX}** in on.push.branches")
|
|
3598
|
-
if push_trigger(lines) is not None and PUSH_SUBJECT not in text:
|
|
3599
|
-
if add_push_condition(lines):
|
|
3600
|
-
updated.append(
|
|
3601
|
-
"Skipped the push run of a replay started through the GitHub API, so each replay runs once"
|
|
3602
|
-
)
|
|
3603
|
-
else:
|
|
3604
|
-
by_hand.append(f"if: {json.dumps(PUSH_CONDITION)} on the replay job")
|
|
3605
|
-
if not re.search(r'^"?run-name"?[ \t]*:', text, re.MULTILINE):
|
|
3606
|
-
add_run_name(lines)
|
|
3607
|
-
updated.append("Named each run after its execution")
|
|
3608
|
-
if not grants_id_token(text):
|
|
3609
|
-
if add_id_token_permission(lines):
|
|
3610
|
-
updated.append(
|
|
3611
|
-
"Granted id-token: write, so a run can prove to Bitfab which run it is and get the key of the person who started it"
|
|
3612
|
-
)
|
|
3613
|
-
else:
|
|
3614
|
-
by_hand.append(
|
|
3615
|
-
"id-token: write under the workflow's top-level permissions block"
|
|
3616
|
-
)
|
|
3617
|
-
if remove_legacy_key_env(lines):
|
|
3618
|
-
updated.append(
|
|
3619
|
-
f"Removed the {API_KEY_ENV} line, which read a secret by a name built from the run's inputs and so gave the runner every secret in the repository; the runner now gets the key from Bitfab"
|
|
3620
|
-
)
|
|
3621
|
-
if not has_git_token_env(lines):
|
|
3622
|
-
if add_git_token_env(lines):
|
|
3623
|
-
updated.append(
|
|
3624
|
-
f"Passed the run's GitHub token to the replay step as {GIT_TOKEN_ENV}, so a --cloud-ref or dispatched replay can fetch the branch it compares against for --code-change default-branch or ref; the replay itself never sees it"
|
|
3625
|
-
)
|
|
3626
|
-
else:
|
|
3627
|
-
by_hand.append(
|
|
3628
|
-
f"{GIT_TOKEN_ENV}: {json.dumps(GIT_TOKEN_VALUE)} in the env of the step that runs --cloud-execute"
|
|
3629
|
-
)
|
|
3630
|
-
depth = add_checkout_depth(lines)
|
|
3631
|
-
if depth == "updated":
|
|
3632
|
-
updated.append(
|
|
3633
|
-
"Checked out the commit each snapshot is taken on, so experiments record the code change"
|
|
3634
|
-
)
|
|
3635
|
-
elif depth == "by hand":
|
|
3636
|
-
by_hand.append(f"fetch-depth: {CHECKOUT_DEPTH} in the checkout step's with")
|
|
3637
|
-
if updated:
|
|
3638
|
-
target.write_text("\n".join(lines))
|
|
3639
|
-
steps = []
|
|
3640
|
-
if updated:
|
|
3641
|
-
steps.append(
|
|
3642
|
-
f"Commit {path}. A --cloud replay runs the workflow in its own snapshot, so the next one uses it; --cloud-ref replays need it on the branch they replay"
|
|
3643
|
-
)
|
|
3644
|
-
if by_hand:
|
|
3645
|
-
steps.append(
|
|
3646
|
-
"Cloud replay could not place these lines, so add them by hand: "
|
|
3647
|
-
+ "; ".join(by_hand)
|
|
3648
|
-
)
|
|
3649
|
-
if not steps:
|
|
3650
|
-
steps.append(
|
|
3651
|
-
"Already set up. Edit the workflow directly to change its install steps, secrets, runner, or Environment"
|
|
3652
|
-
)
|
|
3653
|
-
leftovers, leftover_steps = leftover_key_secret_report(
|
|
3654
|
-
root, text, remove_old_key_secrets
|
|
3655
|
-
)
|
|
3656
|
-
return {
|
|
3657
|
-
"files": [path] if updated else [],
|
|
3658
|
-
"workflow": path,
|
|
3659
|
-
"updated": updated,
|
|
3660
|
-
**leftovers,
|
|
3661
|
-
"next": [*steps, *leftover_steps],
|
|
3662
|
-
}
|
|
3663
|
-
|
|
3664
|
-
|
|
3665
|
-
def initialize(argv, name="--cloud-init"):
|
|
3666
|
-
parser = argparse.ArgumentParser(
|
|
3667
|
-
prog=f"bitfab-replay {name}",
|
|
3668
|
-
description="Write .github/workflows/bitfab-replay.yml, the only file cloud replay keeps in the repository, and list what is left to do. It detects the runtime, package manager, install command, and replay command from the directory you run it in. On an existing workflow it only adds what a newer SDK needs (the execution_id and key_id inputs, the push trigger and the condition that skips a duplicate push run, the run name, the id-token: write permission, and the BITFAB_REPLAY_GIT_TOKEN line that lets a --cloud-ref or dispatched replay fetch the branch it compares against), removes the BITFAB_REPLAY_BITFAB_API_KEY line older SDKs wrote, lists what it changed, and lists the BITFAB_REPLAY_KEY_* secrets older SDKs left in the repository; edit it directly for anything else.",
|
|
3669
|
-
)
|
|
3670
|
-
parser.add_argument(
|
|
3671
|
-
"--secret",
|
|
3672
|
-
action="append",
|
|
3673
|
-
default=[],
|
|
3674
|
-
metavar="NAME",
|
|
3675
|
-
help="Environment variable the replay reads from a GitHub secret, such as OPENAI_API_KEY; repeatable. BITFAB_API_KEY is always included",
|
|
3676
|
-
)
|
|
3677
|
-
parser.add_argument(
|
|
3678
|
-
"--secret-prefix",
|
|
3679
|
-
default=DEFAULT_SECRET_PREFIX,
|
|
3680
|
-
help=f"Prefix of the GitHub secret each value is read from (default {DEFAULT_SECRET_PREFIX}, so OPENAI_API_KEY reads {DEFAULT_SECRET_PREFIX}OPENAI_API_KEY); pass an empty string to reuse secrets under their own names",
|
|
3681
|
-
)
|
|
3682
|
-
parser.add_argument(
|
|
3683
|
-
"--environment",
|
|
3684
|
-
help="GitHub Environment that holds the secrets, such as bitfab-replay; add required reviewers to it so no run gets credentials until someone approves",
|
|
3685
|
-
)
|
|
3686
|
-
parser.add_argument(
|
|
3687
|
-
"--run",
|
|
3688
|
-
help='Command that starts the SDK\'s bitfab-replay on the runner, such as "pnpm exec bitfab-replay"; detected for every SDK, including the Go program that calls RunCloudReplayCLI',
|
|
3689
|
-
)
|
|
3690
|
-
parser.add_argument("--runs-on", default="ubuntu-24.04", help="Runner label")
|
|
3691
|
-
parser.add_argument(
|
|
3692
|
-
"--remove-old-key-secrets",
|
|
3693
|
-
action="store_true",
|
|
3694
|
-
help=f"On an existing workflow, also delete the {LEFTOVER_KEY_SECRET_PREFIX}* GitHub secrets an older SDK left behind, each a copy of the Bitfab API key of the person who started a replay",
|
|
3695
|
-
)
|
|
3696
|
-
parser.add_argument(
|
|
3697
|
-
"--check",
|
|
3698
|
-
help='Command the runner also runs on a --cloud --dry-run, such as "node scripts/checkBucket.js"',
|
|
3699
|
-
)
|
|
3700
|
-
args = parser.parse_args(argv)
|
|
3701
|
-
root = root_directory()
|
|
3702
|
-
refuse_old_setup(root)
|
|
3703
|
-
existing = find_workflow(root)
|
|
3704
|
-
if existing is not None:
|
|
3705
|
-
return update_workflow(
|
|
3706
|
-
root,
|
|
3707
|
-
f"{WORKFLOW_DIRECTORY}/{existing}",
|
|
3708
|
-
remove_old_key_secrets=args.remove_old_key_secrets,
|
|
3709
|
-
)
|
|
3710
|
-
prefix = args.secret_prefix
|
|
3711
|
-
if prefix and not re.fullmatch(r"[A-Z][A-Z0-9_]*_", prefix):
|
|
3712
|
-
raise ValueError(
|
|
3713
|
-
"--secret-prefix must be uppercase and end with an underscore, such as BITFAB_CLOUD_"
|
|
3714
|
-
)
|
|
3715
|
-
names = list(dict.fromkeys(["BITFAB_API_KEY", *args.secret]))
|
|
3716
|
-
if not all(re.fullmatch(r"[A-Z_][A-Z0-9_]*", name) for name in names):
|
|
3717
|
-
raise ValueError("Secret names must be uppercase environment variable names")
|
|
3718
|
-
start = Path.cwd().resolve()
|
|
3719
|
-
directory = working_directory(root)
|
|
3720
|
-
language = os.environ.get(SDK_LANGUAGE_ENV) or detect_language(root, start)
|
|
3721
|
-
steps, run = PROJECTS[language](root, start)
|
|
3722
|
-
run = args.run or run
|
|
3723
|
-
if not run:
|
|
3724
|
-
raise ValueError(
|
|
3725
|
-
'Pass --run with the command that starts your registry program on the runner, such as --run "go run ./cmd/registry"'
|
|
3726
|
-
)
|
|
3727
|
-
env = {name: "${{ secrets." + prefix + name + " }}" for name in names}
|
|
3728
|
-
if args.check:
|
|
3729
|
-
env[CHECK_COMMAND_ENV] = args.check
|
|
3730
|
-
path = f"{WORKFLOW_DIRECTORY}/{WORKFLOW}"
|
|
3731
|
-
target = within(root, path)
|
|
3732
|
-
target.parent.mkdir(parents=True, exist_ok=True)
|
|
3733
|
-
with target.open("x") as file:
|
|
3734
|
-
file.write(
|
|
3735
|
-
to_yaml(
|
|
3736
|
-
workflow_document(
|
|
3737
|
-
steps,
|
|
3738
|
-
run,
|
|
3739
|
-
directory,
|
|
3740
|
-
env,
|
|
3741
|
-
runs_on=args.runs_on,
|
|
3742
|
-
environment=args.environment,
|
|
3743
|
-
)
|
|
3744
|
-
)
|
|
3745
|
-
)
|
|
3746
|
-
secrets = sorted(prefix + name for name in names)
|
|
3747
|
-
triggers = push_triggers(root, WORKFLOW)
|
|
3748
|
-
try:
|
|
3749
|
-
where = secrets_page(repository(root), args.environment)
|
|
3750
|
-
except (ValueError, RuntimeError):
|
|
3751
|
-
where = "the repository's Settings, Secrets and variables, Actions"
|
|
3752
|
-
return {
|
|
3753
|
-
"files": [path],
|
|
3754
|
-
"detected": {
|
|
3755
|
-
"language": language,
|
|
3756
|
-
"install": [step.get("run") or step["uses"] for step in steps],
|
|
3757
|
-
"replay": f"{run} --cloud-execute",
|
|
3758
|
-
},
|
|
3759
|
-
"secrets": secrets,
|
|
3760
|
-
"reviewPushTriggers": triggers,
|
|
3761
|
-
"next": [
|
|
3762
|
-
"Compare the install steps with your CI and add anything detection missed, such as a build or code-generation step",
|
|
3763
|
-
f"Create the secrets {', '.join(secrets)} at {where}, or copy them from a local file with bitfab-replay --cloud-secrets --env-file .env",
|
|
3764
|
-
*(
|
|
3765
|
-
[
|
|
3766
|
-
f"Keep bitfab-replay/** branches from triggering {', '.join(triggers)}"
|
|
3767
|
-
]
|
|
3768
|
-
if triggers
|
|
3769
|
-
else []
|
|
3770
|
-
),
|
|
3771
|
-
f"Commit {path} and merge it to the default branch once, so GitHub registers it",
|
|
3772
|
-
"Add --cloud --dry-run to your replay command to check the runner, then replay with --cloud",
|
|
3773
|
-
],
|
|
3774
|
-
}
|
|
3775
|
-
|
|
3776
|
-
|
|
3777
|
-
def print_json(value):
|
|
3778
|
-
print(json.dumps(value, indent=2), flush=True)
|
|
3779
|
-
|
|
3780
|
-
|
|
3781
|
-
def main():
|
|
3782
|
-
argv = sys.argv[1:]
|
|
3783
|
-
try:
|
|
3784
|
-
if argv[:1] in (["--cloud-init"], ["--cloud-update"]):
|
|
3785
|
-
print_json(initialize(argv[1:], argv[0]))
|
|
3786
|
-
return 0
|
|
3787
|
-
if argv[:1] == ["--cloud-secrets"]:
|
|
3788
|
-
print_json(configure_secrets(argv[1:]))
|
|
3789
|
-
return 0
|
|
3790
|
-
if argv[:1] == [REPLAY_ARGUMENTS_FLAG]:
|
|
3791
|
-
print_json(replay_arguments(argv[1:]))
|
|
3792
|
-
return 0
|
|
3793
|
-
if argv == ["--cloud-execute"]:
|
|
3794
|
-
result = execute()
|
|
3795
|
-
annotate(result)
|
|
3796
|
-
return runner_exit_code(result)
|
|
3797
|
-
if "-h" in argv or "--help" in argv:
|
|
3798
|
-
print(HELP, end="")
|
|
3799
|
-
return 0
|
|
3800
|
-
record, found = run_cli(argv)
|
|
3801
|
-
if found is not None:
|
|
3802
|
-
return print_outcome(found)
|
|
3803
|
-
print_json(record)
|
|
3804
|
-
return record.get("exitCode", 0) if record.get("state") == "completed" else 0
|
|
3805
|
-
except KeyboardInterrupt:
|
|
3806
|
-
progress(
|
|
3807
|
-
"Detached. A GitHub run that already started continues; follow it with --cloud-watch and the printed execution UUID, or stop it with --cloud-cancel and remove its snapshot branch with --cloud-cleanup once it completes"
|
|
3808
|
-
)
|
|
3809
|
-
return 130
|
|
3810
|
-
except (
|
|
3811
|
-
ValueError,
|
|
3812
|
-
RuntimeError,
|
|
3813
|
-
OSError,
|
|
3814
|
-
subprocess.SubprocessError,
|
|
3815
|
-
KeyError,
|
|
3816
|
-
) as error:
|
|
3817
|
-
print(f"Cloud replay: {error}", file=sys.stderr)
|
|
3818
|
-
return 1
|
|
3819
|
-
|
|
3820
|
-
|
|
3821
|
-
if __name__ == "__main__":
|
|
3822
|
-
raise SystemExit(main())
|