caisson-tools 0.1.0__py3-none-any.whl
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.
- caisson_tools/__init__.py +1 -0
- caisson_tools/_revision.txt +1 -0
- caisson_tools/agentctl-commands.json +1 -0
- caisson_tools/allowlist_syntax.py +44 -0
- caisson_tools/browser.py +36 -0
- caisson_tools/common.py +174 -0
- caisson_tools/context.py +36 -0
- caisson_tools/environment.py +92 -0
- caisson_tools/management.py +113 -0
- caisson_tools/manifest.py +41 -0
- caisson_tools/ops.py +839 -0
- caisson_tools/podman.py +325 -0
- caisson_tools/remote.py +158 -0
- caisson_tools/secrets.py +100 -0
- caisson_tools/serve.py +160 -0
- caisson_tools/terminal.py +194 -0
- caisson_tools/transport.py +370 -0
- caisson_tools/user.py +789 -0
- caisson_tools/version.py +37 -0
- caisson_tools-0.1.0.dist-info/METADATA +69 -0
- caisson_tools-0.1.0.dist-info/RECORD +25 -0
- caisson_tools-0.1.0.dist-info/WHEEL +4 -0
- caisson_tools-0.1.0.dist-info/entry_points.txt +3 -0
- caisson_tools-0.1.0.dist-info/licenses/LICENSE +202 -0
- caisson_tools-0.1.0.dist-info/licenses/NOTICE +6 -0
caisson_tools/ops.py
ADDED
|
@@ -0,0 +1,839 @@
|
|
|
1
|
+
"""Trusted-operator wrappers. No cloud calls happen at import or REPL startup."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import hashlib
|
|
6
|
+
import json
|
|
7
|
+
import os
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
import re
|
|
10
|
+
import shlex
|
|
11
|
+
import shutil
|
|
12
|
+
import sys
|
|
13
|
+
import tempfile
|
|
14
|
+
|
|
15
|
+
import click
|
|
16
|
+
|
|
17
|
+
from .common import LocalPath, UXGroup, console, private_directory, repl, run, run_cli, write_json
|
|
18
|
+
from .environment import workspace_document as validate_workspace_config
|
|
19
|
+
from .manifest import load_manifest
|
|
20
|
+
from .secrets import SecretDocument, edit_secret, publish_secret
|
|
21
|
+
from .version import add_version_commands
|
|
22
|
+
|
|
23
|
+
LOGS = (
|
|
24
|
+
'resource.type="gce_instance" AND jsonPayload._SYSTEMD_UNIT='
|
|
25
|
+
'("mgmtd.service" OR "mgmt-sync.service" OR "mgmtd-retry.service" '
|
|
26
|
+
'OR "google-startup-scripts.service")'
|
|
27
|
+
)
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def environment(state):
|
|
31
|
+
root = Path(state["checkout"]).resolve()
|
|
32
|
+
helper = root / "infra/tools/deploy-env.sh"
|
|
33
|
+
if not helper.is_file():
|
|
34
|
+
raise click.ClickException(
|
|
35
|
+
"Run from the repository root, or use: caisson-ops --checkout /path/to/caisson doctor"
|
|
36
|
+
)
|
|
37
|
+
if not re.fullmatch(r"[a-z][a-z0-9-]{4,61}[a-z0-9]", os.environ.get("PROJECT_ID", "")):
|
|
38
|
+
raise click.ClickException(
|
|
39
|
+
"Export PROJECT_ID to the explicit GCP project ID, "
|
|
40
|
+
"then restart caisson-ops (for example: export PROJECT_ID=your-project)"
|
|
41
|
+
)
|
|
42
|
+
# The existing Bash helper is the single source of deployment defaults.
|
|
43
|
+
keys = ["PROJECT_ID", "REGION", "MGMT_HOST", "STATE_BUCKET", "IMAGE", "TAG"]
|
|
44
|
+
script = 'set -e; source "$1"; printf "%s\\0" ' + " ".join(f'"${{{key}}}"' for key in keys)
|
|
45
|
+
values = run(["bash", "-c", script, "caisson-ops", helper], capture=True, cwd=root)
|
|
46
|
+
env = dict(zip(keys, values.rstrip("\0").split("\0"), strict=True))
|
|
47
|
+
env["root"] = root
|
|
48
|
+
if state.get("ops_context", {}).get("account"):
|
|
49
|
+
env["account"] = state["ops_context"]["account"]
|
|
50
|
+
state["ops_context"] = env
|
|
51
|
+
if not state.get("in_repl"):
|
|
52
|
+
console.print(f"Target: {env['PROJECT_ID']} / {env['REGION']}")
|
|
53
|
+
return env
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def cloud(env, *args, capture=False, input=None):
|
|
57
|
+
return run(
|
|
58
|
+
["gcloud", f"--project={env['PROJECT_ID']}", *args],
|
|
59
|
+
capture=capture,
|
|
60
|
+
input=input,
|
|
61
|
+
cwd=env["root"],
|
|
62
|
+
)
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def tofu(env, *args, capture=False):
|
|
66
|
+
return run(
|
|
67
|
+
["tofu", f"-chdir={env['root'] / 'infra/opentofu'}", *args],
|
|
68
|
+
capture=capture,
|
|
69
|
+
cwd=env["root"],
|
|
70
|
+
)
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def outputs(env):
|
|
74
|
+
try:
|
|
75
|
+
result = json.loads(tofu(env, "output", "-json", capture=True))
|
|
76
|
+
data = {key: value["value"] for key, value in result.items()}
|
|
77
|
+
except (ValueError, KeyError, AttributeError, TypeError) as exc:
|
|
78
|
+
raise click.ClickException(
|
|
79
|
+
"Could not read OpenTofu outputs. Verify the initialized backend and "
|
|
80
|
+
"run tofu -chdir=infra/opentofu output -json."
|
|
81
|
+
) from exc
|
|
82
|
+
settings = data.get("mgmtd_settings", "")
|
|
83
|
+
project = re.search(r"^\s+project:\s+(\S+)\s*$", settings, re.MULTILINE)
|
|
84
|
+
if not project or project[1] != env["PROJECT_ID"] or data.get("region") != env["REGION"]:
|
|
85
|
+
raise click.ClickException("OpenTofu state project/region does not match PROJECT_ID/REGION")
|
|
86
|
+
return data
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def account(env):
|
|
90
|
+
env.pop("account", None)
|
|
91
|
+
value = cloud(
|
|
92
|
+
env, "auth", "list", "--filter=status:ACTIVE", "--format=value(account)", capture=True
|
|
93
|
+
).strip()
|
|
94
|
+
if not value:
|
|
95
|
+
raise click.ClickException("No active GCP account; run gcloud auth login")
|
|
96
|
+
env["account"] = value
|
|
97
|
+
return value
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def show_identity(env):
|
|
101
|
+
identity = account(env)
|
|
102
|
+
console.print(f"Project: {env['PROJECT_ID']} | Region: {env['REGION']} | Account: {identity}")
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def approve(env, action):
|
|
106
|
+
show_identity(env)
|
|
107
|
+
click.confirm(action, abort=True)
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def deploy_dir(env):
|
|
111
|
+
return private_directory(env["root"] / "deploy")
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def release_path(env, kind="image"):
|
|
115
|
+
# Avoid accidentally pushing a record from another project in the same checkout.
|
|
116
|
+
return deploy_dir(env) / f"{kind}-{env['PROJECT_ID']}.json"
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def read_release(env):
|
|
120
|
+
try:
|
|
121
|
+
record = json.loads(release_path(env).read_text())
|
|
122
|
+
except FileNotFoundError as exc:
|
|
123
|
+
raise click.ClickException("No build record; run caisson-ops image build first") from exc
|
|
124
|
+
except ValueError as exc:
|
|
125
|
+
raise click.ClickException("Invalid build record; run caisson-ops image build again") from exc
|
|
126
|
+
if not isinstance(record, dict):
|
|
127
|
+
raise click.ClickException("Invalid build record; run caisson-ops image build again")
|
|
128
|
+
if record.get("project") != env["PROJECT_ID"] or record.get("image") != env["IMAGE"]:
|
|
129
|
+
raise click.ClickException("Build record belongs to another project/image")
|
|
130
|
+
return record
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
def write_release(env, record, kind="image"):
|
|
134
|
+
write_json(release_path(env, kind), record)
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
def sha256(path):
|
|
138
|
+
with Path(path).open("rb") as stream:
|
|
139
|
+
return hashlib.file_digest(stream, "sha256").hexdigest()
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
@click.group(
|
|
143
|
+
cls=UXGroup,
|
|
144
|
+
invoke_without_command=True,
|
|
145
|
+
epilog="""Setup:
|
|
146
|
+
|
|
147
|
+
export PROJECT_ID=your-project
|
|
148
|
+
|
|
149
|
+
caisson-ops init
|
|
150
|
+
|
|
151
|
+
caisson-ops doctor
|
|
152
|
+
|
|
153
|
+
Optional REGION, MGMT_HOST, STATE_BUCKET, IMAGE and TAG use infra/tools/deploy-env.sh defaults.
|
|
154
|
+
Cloud operations use existing gcloud login; OpenTofu requires ADC.""",
|
|
155
|
+
)
|
|
156
|
+
@click.option(
|
|
157
|
+
"--checkout",
|
|
158
|
+
type=LocalPath(file_okay=False, path_type=Path),
|
|
159
|
+
help="Source checkout (default: current directory).",
|
|
160
|
+
)
|
|
161
|
+
@click.pass_context
|
|
162
|
+
def cli(ctx, checkout):
|
|
163
|
+
"""Operator tools. Requires explicit PROJECT_ID and trusted local credentials."""
|
|
164
|
+
state = ctx.ensure_object(dict)
|
|
165
|
+
state["checkout"] = checkout or state.get("checkout", Path.cwd())
|
|
166
|
+
if ctx.invoked_subcommand is None:
|
|
167
|
+
if sys.stdin.isatty() and sys.stdout.isatty():
|
|
168
|
+
state["in_repl"] = True
|
|
169
|
+
try:
|
|
170
|
+
env = environment(state)
|
|
171
|
+
account(env)
|
|
172
|
+
console.print(
|
|
173
|
+
f"Operator target: {env['PROJECT_ID']} / {env['REGION']}. "
|
|
174
|
+
"Run init if this checkout needs backend setup, "
|
|
175
|
+
"doctor to check login and dependencies, then help for tasks."
|
|
176
|
+
)
|
|
177
|
+
except (click.ClickException, click.exceptions.Exit) as exc:
|
|
178
|
+
console.print(f"Setup needed: {exc}.")
|
|
179
|
+
repl(cli, state, "caisson-ops")
|
|
180
|
+
|
|
181
|
+
|
|
182
|
+
@cli.command()
|
|
183
|
+
@click.pass_obj
|
|
184
|
+
def init(state):
|
|
185
|
+
"""Initialize this checkout's OpenTofu backend without applying changes.
|
|
186
|
+
|
|
187
|
+
Safe to rerun against the same backend. Uses STATE_BUCKET and prefix caisson.
|
|
188
|
+
Does not migrate state or force backend reconfiguration; backend changes fail
|
|
189
|
+
for manual review instead.
|
|
190
|
+
"""
|
|
191
|
+
env = environment(state)
|
|
192
|
+
click.echo(f"State backend: gs://{env['STATE_BUCKET']}/caisson")
|
|
193
|
+
try:
|
|
194
|
+
tofu(
|
|
195
|
+
env,
|
|
196
|
+
"init",
|
|
197
|
+
"-input=false",
|
|
198
|
+
f"-backend-config=bucket={env['STATE_BUCKET']}",
|
|
199
|
+
"-backend-config=prefix=caisson",
|
|
200
|
+
)
|
|
201
|
+
except click.exceptions.Exit:
|
|
202
|
+
click.echo(
|
|
203
|
+
"\nBackend initialization failed. If the error above mentions invalid_grant, "
|
|
204
|
+
"invalid_rapt, reauthentication or missing default credentials, "
|
|
205
|
+
"refresh your Google application-default credentials:\n\n"
|
|
206
|
+
" gcloud auth application-default login\n\n"
|
|
207
|
+
"Then rerun caisson-ops init (init in the REPL).\n"
|
|
208
|
+
"OpenTofu uses these credentials separately from gcloud auth login. "
|
|
209
|
+
"For other errors, check the state bucket and your access permissions.",
|
|
210
|
+
err=True,
|
|
211
|
+
)
|
|
212
|
+
raise
|
|
213
|
+
click.echo("Backend initialized. Run doctor to check the deployed state.")
|
|
214
|
+
|
|
215
|
+
|
|
216
|
+
@cli.command()
|
|
217
|
+
@click.pass_obj
|
|
218
|
+
def doctor(state):
|
|
219
|
+
"""Check configuration, executables, login and initialized state (read-only)."""
|
|
220
|
+
env = environment(state)
|
|
221
|
+
console.print(f"Project: {env['PROJECT_ID']} | Region: {env['REGION']}")
|
|
222
|
+
missing = []
|
|
223
|
+
for executable in ("bash", "git", "ssh", "gcloud", "tofu", "nix", "skopeo", "go"):
|
|
224
|
+
found = shutil.which(executable)
|
|
225
|
+
click.echo(f"{executable}: {found or 'MISSING'}")
|
|
226
|
+
if not found:
|
|
227
|
+
missing.append(executable)
|
|
228
|
+
if missing:
|
|
229
|
+
raise click.ClickException("Missing dependencies: " + ", ".join(missing))
|
|
230
|
+
click.echo(f"Account: {account(env)}")
|
|
231
|
+
try:
|
|
232
|
+
data = outputs(env)
|
|
233
|
+
except click.exceptions.Exit:
|
|
234
|
+
click.echo(
|
|
235
|
+
"If OpenTofu reports backend initialization is required, run caisson-ops init "
|
|
236
|
+
"(init in the REPL) after verifying STATE_BUCKET.",
|
|
237
|
+
err=True,
|
|
238
|
+
)
|
|
239
|
+
raise
|
|
240
|
+
click.echo(f"Management: {data['mgmt_instance']['name']}")
|
|
241
|
+
click.echo(
|
|
242
|
+
"Initialized state matches project/region. ADC is checked by OpenTofu when planning."
|
|
243
|
+
)
|
|
244
|
+
|
|
245
|
+
|
|
246
|
+
@cli.group()
|
|
247
|
+
def image():
|
|
248
|
+
"""Build, push and deploy digest-pinned workstation images."""
|
|
249
|
+
|
|
250
|
+
|
|
251
|
+
@image.command("build")
|
|
252
|
+
@click.option("--deploy", "deploy_after", is_flag=True, help="Push and deploy after building.")
|
|
253
|
+
@click.pass_context
|
|
254
|
+
def image_build(ctx, deploy_after):
|
|
255
|
+
"""Build the image; optionally push and deploy it with --deploy."""
|
|
256
|
+
build_image(ctx.obj)
|
|
257
|
+
if deploy_after:
|
|
258
|
+
ctx.invoke(image_deploy)
|
|
259
|
+
|
|
260
|
+
|
|
261
|
+
def build_image(state):
|
|
262
|
+
"""Build the current committed checkout and record its exact archive."""
|
|
263
|
+
env = environment(state)
|
|
264
|
+
dirty = run(["git", "status", "--porcelain"], capture=True, cwd=env["root"])
|
|
265
|
+
if dirty.strip():
|
|
266
|
+
raise click.ClickException("Commit changes first: release builds require a clean checkout")
|
|
267
|
+
commit = run(["git", "rev-parse", "HEAD"], capture=True, cwd=env["root"]).strip()
|
|
268
|
+
archive = run(
|
|
269
|
+
[
|
|
270
|
+
"nix",
|
|
271
|
+
"--extra-experimental-features",
|
|
272
|
+
"nix-command flakes",
|
|
273
|
+
"build",
|
|
274
|
+
".#workstation-image",
|
|
275
|
+
"--out-link",
|
|
276
|
+
deploy_dir(env) / f"image-{env['PROJECT_ID']}",
|
|
277
|
+
"--print-out-paths",
|
|
278
|
+
"--no-update-lock-file",
|
|
279
|
+
],
|
|
280
|
+
capture=True,
|
|
281
|
+
cwd=env["root"],
|
|
282
|
+
).strip()
|
|
283
|
+
if not Path(archive).is_file():
|
|
284
|
+
raise click.ClickException("Nix did not return one image archive")
|
|
285
|
+
record = {
|
|
286
|
+
"project": env["PROJECT_ID"],
|
|
287
|
+
"image": env["IMAGE"],
|
|
288
|
+
"tag": env["TAG"],
|
|
289
|
+
"commit": commit,
|
|
290
|
+
"archive": archive,
|
|
291
|
+
"sha256": sha256(archive),
|
|
292
|
+
}
|
|
293
|
+
write_release(env, record)
|
|
294
|
+
click.echo(json.dumps(record, indent=2))
|
|
295
|
+
|
|
296
|
+
|
|
297
|
+
@image.command("push")
|
|
298
|
+
@click.pass_obj
|
|
299
|
+
def image_push(state):
|
|
300
|
+
"""Push the recorded archive; save its immutable registry digest."""
|
|
301
|
+
env = environment(state)
|
|
302
|
+
record = read_release(env)
|
|
303
|
+
if not all(key in record for key in ("archive", "sha256", "tag")):
|
|
304
|
+
raise click.ClickException("Incomplete build record; run caisson-ops image build again")
|
|
305
|
+
try:
|
|
306
|
+
archive_hash = sha256(record["archive"])
|
|
307
|
+
except OSError as exc:
|
|
308
|
+
raise click.ClickException(
|
|
309
|
+
"Recorded image archive is unavailable; run caisson-ops image build again"
|
|
310
|
+
) from exc
|
|
311
|
+
if archive_hash != record["sha256"]:
|
|
312
|
+
raise click.ClickException("Archive checksum changed; refusing to push")
|
|
313
|
+
registry = env["IMAGE"].split("/")[0]
|
|
314
|
+
expected = f"{env['REGION']}-docker.pkg.dev/{env['PROJECT_ID']}/"
|
|
315
|
+
if not env["IMAGE"].startswith(expected):
|
|
316
|
+
raise click.ClickException("IMAGE must point to this project's regional Artifact Registry")
|
|
317
|
+
approve(env, f"Push {env['IMAGE']}:{record['tag']}?")
|
|
318
|
+
# Skopeo expands the whole archive here; /tmp may be a small tmpfs.
|
|
319
|
+
with tempfile.TemporaryDirectory(dir=deploy_dir(env), prefix="caisson-push-") as directory:
|
|
320
|
+
auth = Path(directory) / "auth.json"
|
|
321
|
+
digest = Path(directory) / "digest"
|
|
322
|
+
policy = Path(directory) / "policy.json"
|
|
323
|
+
# Nix's Skopeo need not ship a system policy. Only trust local archives
|
|
324
|
+
# here: the exact source archive was verified against our build record.
|
|
325
|
+
policy.write_text(json.dumps({
|
|
326
|
+
"default": [{"type": "reject"}],
|
|
327
|
+
"transports": {"docker-archive": {"": [{"type": "insecureAcceptAnything"}]}},
|
|
328
|
+
}))
|
|
329
|
+
token = cloud(env, "auth", "print-access-token", capture=True)
|
|
330
|
+
try:
|
|
331
|
+
run(
|
|
332
|
+
[
|
|
333
|
+
"skopeo",
|
|
334
|
+
"login",
|
|
335
|
+
"--authfile",
|
|
336
|
+
auth,
|
|
337
|
+
"--username",
|
|
338
|
+
"oauth2accesstoken",
|
|
339
|
+
"--password-stdin",
|
|
340
|
+
registry,
|
|
341
|
+
],
|
|
342
|
+
input=token,
|
|
343
|
+
)
|
|
344
|
+
finally:
|
|
345
|
+
del token
|
|
346
|
+
run(
|
|
347
|
+
[
|
|
348
|
+
"skopeo",
|
|
349
|
+
"--policy",
|
|
350
|
+
policy,
|
|
351
|
+
"--tmpdir",
|
|
352
|
+
directory,
|
|
353
|
+
"copy",
|
|
354
|
+
"--authfile",
|
|
355
|
+
auth,
|
|
356
|
+
"--digestfile",
|
|
357
|
+
digest,
|
|
358
|
+
f"docker-archive:{record['archive']}",
|
|
359
|
+
f"docker://{env['IMAGE']}:{record['tag']}",
|
|
360
|
+
]
|
|
361
|
+
)
|
|
362
|
+
value = digest.read_text().strip()
|
|
363
|
+
if not re.fullmatch(r"sha256:[a-f0-9]{64}", value):
|
|
364
|
+
raise click.ClickException("Invalid digest returned by Skopeo")
|
|
365
|
+
record["digest"] = value
|
|
366
|
+
write_release(env, record)
|
|
367
|
+
click.echo(f"{env['IMAGE']}@{value}")
|
|
368
|
+
|
|
369
|
+
|
|
370
|
+
def image_plan_blockers(rendered, reference):
|
|
371
|
+
blockers = []
|
|
372
|
+
for change in rendered.get("resource_changes", []):
|
|
373
|
+
detail = change["change"]
|
|
374
|
+
actions = detail["actions"]
|
|
375
|
+
label = change.get("address", change.get("type", "unknown resource"))
|
|
376
|
+
reason = None
|
|
377
|
+
if "delete" in actions:
|
|
378
|
+
reason = "deletes/replaces resources"
|
|
379
|
+
elif actions not in (["no-op"], ["read"]):
|
|
380
|
+
before, after = dict(detail.get("before") or {}), dict(detail.get("after") or {})
|
|
381
|
+
old, new = before.pop("container", []), after.pop("container", [])
|
|
382
|
+
if change.get("type") != "google_workstations_workstation_config" or before != after:
|
|
383
|
+
reason = "non-image changes"
|
|
384
|
+
elif len(old) != 1 or len(new) != 1:
|
|
385
|
+
reason = "unexpected container plan"
|
|
386
|
+
else:
|
|
387
|
+
old, new = dict(old[0]), dict(new[0])
|
|
388
|
+
old.pop("image", None)
|
|
389
|
+
if new.pop("image", None) != reference or old != new:
|
|
390
|
+
reason = "non-image container changes"
|
|
391
|
+
if reason:
|
|
392
|
+
blockers.append(f"{label}: {reason} ({', '.join(actions)})")
|
|
393
|
+
return blockers
|
|
394
|
+
|
|
395
|
+
|
|
396
|
+
def plan_recovery(env, directory, plan, reference, override):
|
|
397
|
+
# Recovery commands must survive copy/paste: Rich's hard wrapping can
|
|
398
|
+
# otherwise insert newlines into long digests and quoted filesystem paths.
|
|
399
|
+
def emit(text):
|
|
400
|
+
click.echo(text, err=True)
|
|
401
|
+
|
|
402
|
+
base = ["tofu", f"-chdir={env['root'] / 'infra/opentofu'}"]
|
|
403
|
+
pin = directory / "image.auto.tfvars.json"
|
|
404
|
+
emit(f"Private plan/evidence retained in {directory}. Plans may contain sensitive data.")
|
|
405
|
+
if plan.exists():
|
|
406
|
+
emit("Review saved plan:\n " + shlex.join([*base, "show", str(plan)]))
|
|
407
|
+
else:
|
|
408
|
+
emit("Planning did not produce a complete saved plan; inspect the original error.")
|
|
409
|
+
fresh = directory / "reviewed.tfplan"
|
|
410
|
+
emit(
|
|
411
|
+
"For manual recovery, create a FRESH plan with the same image:\n "
|
|
412
|
+
+ shlex.join([*base, "plan", f"-var=workstation_image={reference}", f"-out={fresh}"])
|
|
413
|
+
)
|
|
414
|
+
emit(
|
|
415
|
+
"Only after inspecting that entire plan (saved-plan apply does NOT prompt):\n "
|
|
416
|
+
+ shlex.join([*base, "apply", f"-var=workstation_image={reference}", str(fresh)])
|
|
417
|
+
)
|
|
418
|
+
emit(
|
|
419
|
+
"After successful manual apply, persist the image pin:\n "
|
|
420
|
+
+ shlex.join(["cp", str(pin), str(override)])
|
|
421
|
+
)
|
|
422
|
+
emit("Or resolve the unrelated drift and rerun: caisson-ops image deploy")
|
|
423
|
+
|
|
424
|
+
|
|
425
|
+
def offer_retain_workstation_access(env, rendered):
|
|
426
|
+
"""Persist explicitly approved existing grants, never apply a rejected plan."""
|
|
427
|
+
members = set()
|
|
428
|
+
for change in rendered.get("resource_changes", []):
|
|
429
|
+
if (
|
|
430
|
+
change.get("type") == "google_service_account_iam_member"
|
|
431
|
+
and change.get("name") == "workstation_act_as"
|
|
432
|
+
and change.get("mode", "managed") == "managed"
|
|
433
|
+
and change["change"]["actions"] == ["delete"]
|
|
434
|
+
):
|
|
435
|
+
before = change["change"].get("before") or {}
|
|
436
|
+
member = before.get("member", "")
|
|
437
|
+
if (
|
|
438
|
+
before.get("role") == "roles/iam.serviceAccountUser"
|
|
439
|
+
and isinstance(member, str)
|
|
440
|
+
and re.fullmatch(r"(user|group):[^:@\s]+@[^:@\s]+", member)
|
|
441
|
+
):
|
|
442
|
+
members.add(member)
|
|
443
|
+
if not members:
|
|
444
|
+
return
|
|
445
|
+
configured = rendered.get("variables", {}).get("workstation_act_as_members", {}).get("value")
|
|
446
|
+
if not isinstance(configured, list) or not all(isinstance(m, str) for m in configured):
|
|
447
|
+
return
|
|
448
|
+
path = env["root"] / "infra/opentofu/zz-caisson-access.auto.tfvars.json"
|
|
449
|
+
# Never overwrite an existing or unfamiliar local override.
|
|
450
|
+
if path.exists() or path.is_symlink():
|
|
451
|
+
click.echo(f"Review workstation_act_as_members in {path} and your private tfvars.")
|
|
452
|
+
return
|
|
453
|
+
click.echo("The plan would remove existing workstation service-account access:\n "
|
|
454
|
+
+ "\n ".join(sorted(members)))
|
|
455
|
+
click.echo(f"Local configuration: {path}")
|
|
456
|
+
if not click.confirm("Retain these grants in local configuration? No cloud changes.", default=False):
|
|
457
|
+
return
|
|
458
|
+
with path.open("x") as stream:
|
|
459
|
+
json.dump({"workstation_act_as_members": sorted(set(configured) | members)}, stream, indent=2)
|
|
460
|
+
stream.write("\n")
|
|
461
|
+
click.echo(
|
|
462
|
+
"Saved existing access grants. Back up this file with your private deployment config.\n"
|
|
463
|
+
"Nothing was applied. Rerun caisson-ops image deploy to review a fresh plan."
|
|
464
|
+
)
|
|
465
|
+
|
|
466
|
+
|
|
467
|
+
def deploy_image(state):
|
|
468
|
+
"""Review/apply a digest-pinned plan; never restart existing workspaces."""
|
|
469
|
+
env = environment(state)
|
|
470
|
+
outputs(env) # fail closed if the initialized backend belongs to another project
|
|
471
|
+
record = read_release(env)
|
|
472
|
+
digest = record.get("digest", "")
|
|
473
|
+
if not re.fullmatch(r"sha256:[a-f0-9]{64}", digest):
|
|
474
|
+
raise click.ClickException("Push the image first")
|
|
475
|
+
reference = f"{env['IMAGE']}@{digest}"
|
|
476
|
+
# Do not rewrite the operator's tfvars, including their IAM/user settings.
|
|
477
|
+
override = env["root"] / "infra/opentofu/zz-caisson-image.auto.tfvars.json"
|
|
478
|
+
directory = Path(tempfile.mkdtemp(dir=deploy_dir(env), prefix="image-plan-"))
|
|
479
|
+
plan = directory / "image.tfplan"
|
|
480
|
+
write_json(directory / "image.auto.tfvars.json", {"workstation_image": reference})
|
|
481
|
+
write_json(directory / "release.json", {"project": env["PROJECT_ID"], "image": reference})
|
|
482
|
+
try:
|
|
483
|
+
tofu(env, "plan", "-input=false", f"-var=workstation_image={reference}", f"-out={plan}")
|
|
484
|
+
rendered = json.loads(tofu(env, "show", "-json", plan, capture=True))
|
|
485
|
+
blockers = image_plan_blockers(rendered, reference)
|
|
486
|
+
if blockers:
|
|
487
|
+
offer_retain_workstation_access(env, rendered)
|
|
488
|
+
raise click.ClickException("Image-only deploy refused:\n " + "\n ".join(blockers))
|
|
489
|
+
approve(env, f"Apply reviewed image plan for {reference}?")
|
|
490
|
+
# OpenTofu 1.13 validates current inputs against saved-plan inputs.
|
|
491
|
+
# Keep the old persistent pin until apply succeeds, but pass the same
|
|
492
|
+
# explicit override to both commands.
|
|
493
|
+
tofu(env, "apply", "-input=false", f"-var=workstation_image={reference}", plan)
|
|
494
|
+
except (
|
|
495
|
+
click.ClickException,
|
|
496
|
+
click.exceptions.Exit,
|
|
497
|
+
click.Abort,
|
|
498
|
+
KeyboardInterrupt,
|
|
499
|
+
ValueError,
|
|
500
|
+
OSError,
|
|
501
|
+
):
|
|
502
|
+
plan_recovery(env, directory, plan, reference, override)
|
|
503
|
+
raise
|
|
504
|
+
try:
|
|
505
|
+
write_json(override, {"workstation_image": reference})
|
|
506
|
+
except OSError as exc:
|
|
507
|
+
console.print("The image WAS APPLIED, but saving its local pin failed.")
|
|
508
|
+
plan_recovery(env, directory, plan, reference, override)
|
|
509
|
+
raise click.ClickException(
|
|
510
|
+
"Persist the image pin using the copy command above before further plans."
|
|
511
|
+
) from exc
|
|
512
|
+
console.print(f"Saved image pin: {override}. Back up with your private deployment config.")
|
|
513
|
+
console.print("Running workspaces are unchanged. Owners rebuild to pick up the new image.")
|
|
514
|
+
|
|
515
|
+
|
|
516
|
+
@image.command("deploy")
|
|
517
|
+
@click.pass_context
|
|
518
|
+
def image_deploy(ctx):
|
|
519
|
+
"""Push and deploy the most recent recorded build without rebuilding."""
|
|
520
|
+
ctx.invoke(image_push)
|
|
521
|
+
deploy_image(ctx.obj)
|
|
522
|
+
|
|
523
|
+
|
|
524
|
+
@cli.group()
|
|
525
|
+
def mgmt():
|
|
526
|
+
"""Management binary and configuration."""
|
|
527
|
+
|
|
528
|
+
|
|
529
|
+
@cli.group("config")
|
|
530
|
+
def config_group():
|
|
531
|
+
"""Manage shared workspace config in Secret Manager."""
|
|
532
|
+
|
|
533
|
+
|
|
534
|
+
def config_document(document):
|
|
535
|
+
try:
|
|
536
|
+
result = validate_workspace_config(document)
|
|
537
|
+
conflicts = result["allowlists"].keys() & set(load_manifest()["catalogs"]["lists"])
|
|
538
|
+
if conflicts:
|
|
539
|
+
raise ValueError("Fleet allowlist conflicts with a packaged list: " + min(conflicts))
|
|
540
|
+
return result
|
|
541
|
+
except ValueError as exc:
|
|
542
|
+
raise click.ClickException(str(exc)) from None
|
|
543
|
+
|
|
544
|
+
|
|
545
|
+
def config_secret(state):
|
|
546
|
+
env = environment(state)
|
|
547
|
+
resource = outputs(env).get("workstation_environment_secret")
|
|
548
|
+
if not resource:
|
|
549
|
+
raise click.ClickException(
|
|
550
|
+
"Workspace config secret is disabled or not provisioned. Apply the one-time "
|
|
551
|
+
"workstation_environment_secret_id setup first.")
|
|
552
|
+
show_identity(env)
|
|
553
|
+
click.echo(f"Workspace config secret: {resource}")
|
|
554
|
+
return env, SecretDocument(env, resource, cloud, error=click.ClickException)
|
|
555
|
+
|
|
556
|
+
|
|
557
|
+
def confirm_config_publish():
|
|
558
|
+
return click.confirm("Publish a new workspace config secret version?", default=False)
|
|
559
|
+
|
|
560
|
+
|
|
561
|
+
def config_published():
|
|
562
|
+
click.echo("Published a new workspace config secret version. No image build or OpenTofu apply.")
|
|
563
|
+
click.echo("Restart workstations to load the new settings; running processes are unchanged.")
|
|
564
|
+
|
|
565
|
+
|
|
566
|
+
@config_group.command("deploy")
|
|
567
|
+
@click.option("--file", "source", required=True,
|
|
568
|
+
type=LocalPath(exists=True, dir_okay=False, path_type=Path),
|
|
569
|
+
help='Complete config JSON; omitted environment maps and grants are cleared.')
|
|
570
|
+
@click.pass_obj
|
|
571
|
+
def config_deploy(state, source):
|
|
572
|
+
"""Publish a complete workspace config JSON file as a new secret version."""
|
|
573
|
+
try:
|
|
574
|
+
raw = json.loads(source.read_text())
|
|
575
|
+
except (ValueError, OSError) as exc:
|
|
576
|
+
raise click.ClickException("Could not read workspace config JSON") from exc
|
|
577
|
+
document = config_document(raw)
|
|
578
|
+
_, secret = config_secret(state)
|
|
579
|
+
if publish_secret(secret, document, secret.latest(), confirm=confirm_config_publish, emit=click.echo):
|
|
580
|
+
config_published()
|
|
581
|
+
|
|
582
|
+
|
|
583
|
+
@config_group.command("edit")
|
|
584
|
+
@click.pass_obj
|
|
585
|
+
def config_edit(state):
|
|
586
|
+
"""Fetch a pinned secret version, edit with $EDITOR, validate and publish."""
|
|
587
|
+
env, secret = config_secret(state)
|
|
588
|
+
if edit_secret(
|
|
589
|
+
secret, config_document, run=run, cwd=env["root"],
|
|
590
|
+
confirm=confirm_config_publish,
|
|
591
|
+
emit=click.echo,
|
|
592
|
+
warning=(
|
|
593
|
+
"Editing workspace config. Environment values are visible to workstation users; "
|
|
594
|
+
"agent values are visible to the agent. Your editor may create backups or swap files."
|
|
595
|
+
),
|
|
596
|
+
):
|
|
597
|
+
config_published()
|
|
598
|
+
|
|
599
|
+
|
|
600
|
+
def build_mgmt(state):
|
|
601
|
+
env = environment(state)
|
|
602
|
+
run(
|
|
603
|
+
["go", "build", "-buildvcs=true", "-trimpath", "-o", "bin/mgmtd", "./cmd/mgmtd"],
|
|
604
|
+
cwd=env["root"] / "mgmt",
|
|
605
|
+
env={**os.environ, "CGO_ENABLED": "0", "GOOS": "linux", "GOARCH": "amd64"},
|
|
606
|
+
)
|
|
607
|
+
directory = Path(tempfile.mkdtemp(dir=deploy_dir(env), prefix="mgmt-build-"))
|
|
608
|
+
binary = directory / "mgmtd"
|
|
609
|
+
shutil.copy2(env["root"] / "mgmt/bin/mgmtd", binary)
|
|
610
|
+
record = {
|
|
611
|
+
"project": env["PROJECT_ID"],
|
|
612
|
+
"binary": str(binary),
|
|
613
|
+
"sha256": sha256(binary),
|
|
614
|
+
}
|
|
615
|
+
write_release(env, record, kind="mgmt")
|
|
616
|
+
click.echo(json.dumps(record, indent=2))
|
|
617
|
+
|
|
618
|
+
|
|
619
|
+
def check_mgmt_config(env, settings, users):
|
|
620
|
+
run(
|
|
621
|
+
["go", "run", "./cmd/mgmtd", "check-config", "--settings", settings, "--users", users],
|
|
622
|
+
cwd=env["root"] / "mgmt",
|
|
623
|
+
)
|
|
624
|
+
|
|
625
|
+
|
|
626
|
+
def read_mgmt_build(env):
|
|
627
|
+
try:
|
|
628
|
+
record = json.loads(release_path(env, "mgmt").read_text())
|
|
629
|
+
if not isinstance(record, dict) or record.get("project") != env["PROJECT_ID"]:
|
|
630
|
+
raise ValueError("Wrong project or invalid record")
|
|
631
|
+
binary = Path(record["binary"])
|
|
632
|
+
if sha256(binary) != record["sha256"]:
|
|
633
|
+
raise ValueError("Binary checksum changed")
|
|
634
|
+
return binary
|
|
635
|
+
except (OSError, ValueError, KeyError, TypeError) as exc:
|
|
636
|
+
raise click.ClickException(
|
|
637
|
+
"Management build missing or invalid; run caisson-ops mgmt build first"
|
|
638
|
+
) from exc
|
|
639
|
+
|
|
640
|
+
|
|
641
|
+
@mgmt.command("build")
|
|
642
|
+
@click.option("--deploy", "deploy_after", is_flag=True, help="Deploy after building.")
|
|
643
|
+
@click.option(
|
|
644
|
+
"--users",
|
|
645
|
+
type=LocalPath(exists=True, dir_okay=False, path_type=Path),
|
|
646
|
+
help="Initial users file only; requires --deploy.",
|
|
647
|
+
)
|
|
648
|
+
@click.pass_context
|
|
649
|
+
def mgmt_build(ctx, deploy_after, users):
|
|
650
|
+
"""Build and record management; optionally deploy with --deploy."""
|
|
651
|
+
if users and not deploy_after:
|
|
652
|
+
raise click.UsageError("--users requires --deploy")
|
|
653
|
+
build_mgmt(ctx.obj)
|
|
654
|
+
if deploy_after:
|
|
655
|
+
ctx.invoke(mgmt_deploy, users=users)
|
|
656
|
+
|
|
657
|
+
|
|
658
|
+
@mgmt.command("deploy")
|
|
659
|
+
@click.option(
|
|
660
|
+
"--users",
|
|
661
|
+
type=LocalPath(exists=True, dir_okay=False, path_type=Path),
|
|
662
|
+
help="Initial users file only. Omit on existing deployments.",
|
|
663
|
+
)
|
|
664
|
+
@click.pass_obj
|
|
665
|
+
def mgmt_deploy(state, users):
|
|
666
|
+
"""Deploy the latest management build/settings; preserve live user policy."""
|
|
667
|
+
env = environment(state)
|
|
668
|
+
binary = read_mgmt_build(env)
|
|
669
|
+
data = outputs(env)
|
|
670
|
+
bucket = data["artifacts_bucket"]
|
|
671
|
+
approve(env, f"Deploy management binary/settings to gs://{bucket}?")
|
|
672
|
+
with tempfile.TemporaryDirectory(dir=deploy_dir(env), prefix="mgmt-") as directory:
|
|
673
|
+
directory = Path(directory)
|
|
674
|
+
settings, policy = directory / "settings.yaml", directory / "users.yaml"
|
|
675
|
+
settings.write_text(data["mgmtd_settings"])
|
|
676
|
+
url = f"gs://{bucket}/config/users.yaml"
|
|
677
|
+
if users:
|
|
678
|
+
# Strong create-only precondition below; never replace live policy here.
|
|
679
|
+
if (env["root"] / "mgmt/config") in users.resolve().parents:
|
|
680
|
+
raise click.ClickException("Refusing checked-in example users file")
|
|
681
|
+
policy.write_bytes(users.read_bytes())
|
|
682
|
+
else:
|
|
683
|
+
cloud(env, "storage", "cp", url, policy)
|
|
684
|
+
check_mgmt_config(env, settings, policy)
|
|
685
|
+
if users:
|
|
686
|
+
# Reserve initial policy before touching other live objects. A live
|
|
687
|
+
# policy makes this fail atomically, without changing binary/settings.
|
|
688
|
+
cloud(env, "storage", "cp", "--if-generation-match=0", policy, url)
|
|
689
|
+
cloud(env, "storage", "cp", binary, f"gs://{bucket}/mgmtd/mgmtd")
|
|
690
|
+
cloud(env, "storage", "cp", settings, f"gs://{bucket}/config/settings.yaml")
|
|
691
|
+
console.print("Uploaded. VM syncs within five minutes; check logs and the management endpoint.")
|
|
692
|
+
|
|
693
|
+
|
|
694
|
+
@cli.group()
|
|
695
|
+
def users():
|
|
696
|
+
"""Edit the live access policy safely."""
|
|
697
|
+
|
|
698
|
+
|
|
699
|
+
@users.command("edit")
|
|
700
|
+
@click.pass_obj
|
|
701
|
+
def users_edit(state):
|
|
702
|
+
"""Fetch, edit, validate, review, and conditionally upload the live policy."""
|
|
703
|
+
import difflib
|
|
704
|
+
|
|
705
|
+
env = environment(state)
|
|
706
|
+
data = outputs(env)
|
|
707
|
+
url = f"gs://{data['artifacts_bucket']}/config/users.yaml"
|
|
708
|
+
generation = cloud(
|
|
709
|
+
env, "storage", "objects", "describe", url, "--format=value(generation)", capture=True
|
|
710
|
+
).strip()
|
|
711
|
+
if not generation.isdigit():
|
|
712
|
+
raise click.ClickException("Could not read live policy generation")
|
|
713
|
+
original = cloud(env, "storage", "cat", f"{url}#{generation}", capture=True)
|
|
714
|
+
with tempfile.TemporaryDirectory(prefix="caisson-users-") as directory:
|
|
715
|
+
directory = Path(directory)
|
|
716
|
+
policy, settings = directory / "users.yaml", directory / "settings.yaml"
|
|
717
|
+
policy.write_text(original)
|
|
718
|
+
settings.write_text(data["mgmtd_settings"])
|
|
719
|
+
click.edit(filename=str(policy), require_save=False)
|
|
720
|
+
changed = policy.read_text()
|
|
721
|
+
if changed == original:
|
|
722
|
+
click.echo("No changes.")
|
|
723
|
+
return
|
|
724
|
+
check_mgmt_config(env, settings, policy)
|
|
725
|
+
click.echo(
|
|
726
|
+
"".join(
|
|
727
|
+
difflib.unified_diff(
|
|
728
|
+
original.splitlines(True),
|
|
729
|
+
changed.splitlines(True),
|
|
730
|
+
fromfile="live",
|
|
731
|
+
tofile="edited",
|
|
732
|
+
)
|
|
733
|
+
)
|
|
734
|
+
)
|
|
735
|
+
approve(
|
|
736
|
+
env, "Upload this complete policy? Removed users lose access and their workspaces stop."
|
|
737
|
+
)
|
|
738
|
+
cloud(env, "storage", "cp", f"--if-generation-match={generation}", policy, url)
|
|
739
|
+
|
|
740
|
+
|
|
741
|
+
@cli.command("status")
|
|
742
|
+
@click.pass_obj
|
|
743
|
+
def status(state):
|
|
744
|
+
"""Show management VM and all workstations (read-only)."""
|
|
745
|
+
env = environment(state)
|
|
746
|
+
data = outputs(env)
|
|
747
|
+
instance = data["mgmt_instance"]
|
|
748
|
+
cloud(
|
|
749
|
+
env,
|
|
750
|
+
"compute",
|
|
751
|
+
"instances",
|
|
752
|
+
"describe",
|
|
753
|
+
instance["name"],
|
|
754
|
+
f"--zone={instance['zone']}",
|
|
755
|
+
"--format=table(name,status)",
|
|
756
|
+
)
|
|
757
|
+
cluster = data["workstation_cluster"].rsplit("/", 1)[-1]
|
|
758
|
+
config = data["workstation_config"].rsplit("/", 1)[-1]
|
|
759
|
+
cloud(
|
|
760
|
+
env,
|
|
761
|
+
"workstations",
|
|
762
|
+
"list",
|
|
763
|
+
f"--region={env['REGION']}",
|
|
764
|
+
f"--cluster={cluster}",
|
|
765
|
+
f"--config={config}",
|
|
766
|
+
"--format=table(name.basename(),state,annotations)",
|
|
767
|
+
)
|
|
768
|
+
|
|
769
|
+
|
|
770
|
+
@cli.command("logs")
|
|
771
|
+
@click.option("--freshness", default="15m", show_default=True)
|
|
772
|
+
@click.option("--limit", default=50, type=click.IntRange(1, 10000))
|
|
773
|
+
@click.pass_obj
|
|
774
|
+
def logs(state, freshness, limit):
|
|
775
|
+
"""Read management/startup logs."""
|
|
776
|
+
env = environment(state)
|
|
777
|
+
data = outputs(env)
|
|
778
|
+
instance = data["mgmt_instance"]
|
|
779
|
+
# Resolve instance ID so another VM's units are never mixed into these logs.
|
|
780
|
+
identifier = cloud(
|
|
781
|
+
env,
|
|
782
|
+
"compute",
|
|
783
|
+
"instances",
|
|
784
|
+
"describe",
|
|
785
|
+
instance["name"],
|
|
786
|
+
f"--zone={instance['zone']}",
|
|
787
|
+
"--format=value(id)",
|
|
788
|
+
capture=True,
|
|
789
|
+
).strip()
|
|
790
|
+
cloud(
|
|
791
|
+
env,
|
|
792
|
+
"logging",
|
|
793
|
+
"read",
|
|
794
|
+
f'{LOGS} AND resource.labels.instance_id="{identifier}"',
|
|
795
|
+
f"--freshness={freshness}",
|
|
796
|
+
f"--limit={limit}",
|
|
797
|
+
"--format=value(timestamp,jsonPayload.MESSAGE)",
|
|
798
|
+
)
|
|
799
|
+
|
|
800
|
+
|
|
801
|
+
@cli.group()
|
|
802
|
+
def creds():
|
|
803
|
+
"""Manage shared workstation credentials."""
|
|
804
|
+
|
|
805
|
+
|
|
806
|
+
@creds.command("edit")
|
|
807
|
+
@click.pass_obj
|
|
808
|
+
def creds_edit(state):
|
|
809
|
+
env = environment(state)
|
|
810
|
+
data = outputs(env)
|
|
811
|
+
secret = data.get("workstation_credentials_secret")
|
|
812
|
+
if not secret:
|
|
813
|
+
raise click.ClickException("Shared workstation credentials are disabled")
|
|
814
|
+
show_identity(env)
|
|
815
|
+
click.echo(f"Editing shared credentials in {secret}")
|
|
816
|
+
run(
|
|
817
|
+
[
|
|
818
|
+
sys.executable,
|
|
819
|
+
env["root"] / "infra/tools/gcp-credentials/gcp-credentials",
|
|
820
|
+
"edit",
|
|
821
|
+
"--secret",
|
|
822
|
+
secret,
|
|
823
|
+
],
|
|
824
|
+
cwd=env["root"],
|
|
825
|
+
)
|
|
826
|
+
|
|
827
|
+
|
|
828
|
+
def main():
|
|
829
|
+
run_cli(cli)
|
|
830
|
+
|
|
831
|
+
|
|
832
|
+
add_version_commands(cli, "caisson-ops")
|
|
833
|
+
|
|
834
|
+
cli.help_sections = {
|
|
835
|
+
"Start here": ["init", "doctor", "status"],
|
|
836
|
+
"Release": ["image", "env", "mgmt"],
|
|
837
|
+
"Access & diagnostics": ["users", "creds", "logs", "version"],
|
|
838
|
+
}
|
|
839
|
+
cli.help_on_empty = False
|