canyonos 0.2.3.dev2__py3-none-any.whl → 0.2.3.dev3__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.
Files changed (60) hide show
  1. canyonos/api.py +562 -0
  2. canyonos/auth.py +75 -9
  3. canyonos/aws_provision.py +14 -10
  4. canyonos/chat.py +18 -12
  5. canyonos/clean.py +14 -10
  6. canyonos/config.py +2 -2
  7. canyonos/constants.py +26 -31
  8. canyonos/context.py +35 -30
  9. canyonos/convert.py +7 -5
  10. canyonos/curl.py +142 -0
  11. canyonos/dashboard.compose.yml +15 -4
  12. canyonos/dashboard.py +3 -8
  13. canyonos/dashboard_registration.py +42 -47
  14. canyonos/dashboard_stack.py +200 -55
  15. canyonos/deploy.py +232 -710
  16. canyonos/deployment.py +134 -104
  17. canyonos/dev_machine.py +47 -36
  18. canyonos/docker_cmd.py +50 -0
  19. canyonos/doctor.py +81 -244
  20. canyonos/env.py +2 -2
  21. canyonos/forwards.py +4 -9
  22. canyonos/init.py +242 -229
  23. canyonos/internal_ca.py +13 -13
  24. canyonos/kubernetes_local.py +50 -16
  25. canyonos/kubernetes_target.py +139 -999
  26. canyonos/logs.py +29 -31
  27. canyonos/new_app.py +7 -6
  28. canyonos/new_app_template/agents/workflow.py.tmpl +1 -1
  29. canyonos/new_app_template/config/workflow_config.yaml +1 -1
  30. canyonos/port_utils.py +1 -1
  31. canyonos/ports.py +17 -10
  32. canyonos/quickstart.py +56 -54
  33. canyonos/resources.py +20 -15
  34. canyonos/sdk/__init__.py +9 -0
  35. canyonos/sdk/models.py +179 -0
  36. canyonos/selection.py +25 -18
  37. canyonos/serve.py +194 -37
  38. canyonos/starters/helloworld/README.md +17 -16
  39. canyonos/starters/helloworld/{deployment.yaml → workflow_group.yaml} +1 -1
  40. canyonos/starters/portfolio/{deployment.yaml → workflow_group.yaml} +1 -1
  41. canyonos/status.py +52 -41
  42. canyonos/stop.py +170 -120
  43. canyonos/sync.py +171 -356
  44. canyonos/test.py +49 -37
  45. canyonos/ui.py +9 -2
  46. canyonos/usage/outbox.py +7 -4
  47. canyonos/validate.py +17 -32
  48. canyonos/workflow_group.yaml +20 -0
  49. {canyonos-0.2.3.dev2.dist-info → canyonos-0.2.3.dev3.dist-info}/METADATA +4 -4
  50. canyonos-0.2.3.dev3.dist-info/RECORD +96 -0
  51. cli.py +186 -180
  52. utils/help_screen.py +25 -16
  53. canyonos/deployment.yaml +0 -20
  54. canyonos/gc.py +0 -171
  55. canyonos/target.py +0 -130
  56. canyonos/verify.py +0 -77
  57. canyonos-0.2.3.dev2.dist-info/RECORD +0 -95
  58. {canyonos-0.2.3.dev2.dist-info → canyonos-0.2.3.dev3.dist-info}/WHEEL +0 -0
  59. {canyonos-0.2.3.dev2.dist-info → canyonos-0.2.3.dev3.dist-info}/entry_points.txt +0 -0
  60. {canyonos-0.2.3.dev2.dist-info → canyonos-0.2.3.dev3.dist-info}/top_level.txt +0 -0
canyonos/api.py ADDED
@@ -0,0 +1,562 @@
1
+ # SPDX-FileCopyrightText: 2026 Canyon Code, Inc.
2
+ # SPDX-License-Identifier: AGPL-3.0-only
3
+
4
+ """
5
+ The CanyonOS API's `/v1/workflow-groups` routes, so the commands that deploy, stop and
6
+ read a workflow group don't each restate the same routes, payloads and failure modes.
7
+
8
+ On Docker the API is the local stack's (`dashboard_stack`), on 127.0.0.1 at its host
9
+ port, and every call sends this machine's control key; the API runs each workflow
10
+ group's Global Controller container through Docker. On Kubernetes it is the cluster's,
11
+ the one the operator's chart installs, reached through a port-forward with the user's
12
+ kubectl login (`kubernetes_target.kubernetes_state`); it runs each workflow group as a
13
+ CanyonProject. Both answer the same routes and shapes, and an error is
14
+ `{error, message, findings?, warnings?}`.
15
+ """
16
+
17
+ import json
18
+ import os
19
+ import time
20
+ import urllib.error
21
+ import urllib.parse
22
+ import urllib.request
23
+
24
+ from canyonos import deployment, env
25
+ from canyonos.auth import control_header, control_key_path
26
+ from canyonos.init import load_state
27
+
28
+ REQUEST_TIMEOUT_SECONDS = 60
29
+ STATUS_TIMEOUT_SECONDS = 5
30
+ # Longer than the API's wait for the deploy to stop, which drains every replica first:
31
+ # on Docker, and on Kubernetes, where it waits up to 15 minutes for the operator.
32
+ CLEAN_REQUEST_TIMEOUT_SECONDS = 270
33
+ KUBERNETES_CLEAN_REQUEST_TIMEOUT_SECONDS = 905
34
+ # Longer than one log read on a replica's machine, which may take up to 180s over SSH.
35
+ LOGS_REQUEST_TIMEOUT_SECONDS = 200
36
+ # The API stores a registration without reaching the workflow group's Redis.
37
+ DASHBOARD_REQUEST_TIMEOUT_SECONDS = 10
38
+ # How long a just-started API may take to connect to and migrate its database, which
39
+ # it does after it starts listening.
40
+ READY_TIMEOUT_SECONDS = 60
41
+ READY_POLL_SECONDS = 1
42
+
43
+ PREFIX = "/v1/workflow-groups"
44
+ # The CanyonOS API names its errors `workflow_groups.<code>`.
45
+ ERROR_PREFIX = "workflow_groups."
46
+ UNKNOWN_WORKFLOW_GROUP = "unknown_workflow_group"
47
+ # What an older chart's API answers on Kubernetes: no route there (a release before
48
+ # the /v1 routes), or the /v1 routes of an API that drives only Docker, without Docker
49
+ # or the control key.
50
+ OLDER_CHART_ERRORS = {
51
+ 404: (None, "not_found"),
52
+ 503: ("docker.disabled",),
53
+ 401: ("auth.control_key_unset",),
54
+ }
55
+
56
+ # What the API answers a /v1 call whose control key it was not started with, or when
57
+ # it was started with none.
58
+ CONTROL_KEY_REFUSALS = (
59
+ "auth.missing_key",
60
+ "auth.invalid_key",
61
+ "auth.control_key_unset",
62
+ )
63
+ DATABASE_UNAVAILABLE = "database.unavailable"
64
+
65
+ # Where the CanyonOS API answers on this machine, found once per command: the
66
+ # commands that start it (`serve.ensure_api`) forget it, since it may move.
67
+ _docker_url = None
68
+
69
+
70
+ class ApiError(RuntimeError):
71
+ """A failed CanyonOS API request, carrying a message fit to print, the HTTP
72
+ `status` the API answered (None when it could not be reached), its error `code`
73
+ without the `workflow_groups.` prefix and, for a rejected workflow, its `findings`
74
+ and `warnings`."""
75
+
76
+ def __init__(self, message, status=None, code=None, findings=(), warnings=()):
77
+ super().__init__(message)
78
+ self.status = status
79
+ self.code = code
80
+ self.findings = findings
81
+ self.warnings = warnings
82
+
83
+ @property
84
+ def error_code(self):
85
+ """The code `--json` reports for this failure."""
86
+ return self.code
87
+
88
+
89
+ class NoDeployError(RuntimeError):
90
+ """No deploy of this workflow group is running; `canyonos` exits with 3."""
91
+
92
+ exit_code = 3
93
+ error_code = "no_deploy"
94
+
95
+
96
+ def docker_api_url():
97
+ """Where the CanyonOS API answers on this machine: the port its running container
98
+ publishes, else the one it starts on next."""
99
+ global _docker_url
100
+ if _docker_url is None:
101
+ # Imported here: the stack's module reads ports this one has no need of.
102
+ from canyonos.dashboard_stack import running_api_port, service_ports
103
+
104
+ _docker_url = f"http://127.0.0.1:{running_api_port() or service_ports()['api']}"
105
+ return _docker_url
106
+
107
+
108
+ def forget_api_url():
109
+ """Find the CanyonOS API again on the next call, after it was started or moved."""
110
+ global _docker_url
111
+ _docker_url = None
112
+
113
+
114
+ def _on_kubernetes(state):
115
+ """Whether `state`'s workflow group is reached through the cluster's API."""
116
+ return bool(state and "api_url" in state)
117
+
118
+
119
+ def _connection(state):
120
+ """The base URL and headers a call about `state`'s workflow group goes to: the
121
+ cluster's API on Kubernetes, else this machine's with the control key; this
122
+ machine's when `state` is None."""
123
+ if _on_kubernetes(state):
124
+ return state["api_url"], state["api_headers"]
125
+ return docker_api_url(), control_header()
126
+
127
+
128
+ def error_detail(body, status):
129
+ """The error object of an answer's `body`, raw bytes, as `{error, code, findings,
130
+ warnings}`, `error` its message and `code` its code without the prefix, from the
131
+ CanyonOS API's `{error: code, message}`; each check that is not ok as `error` for
132
+ `/readyz`'s answer, and the raw body as `error` when it is neither."""
133
+ text = body.decode(errors="replace").strip()
134
+ try:
135
+ parsed = json.loads(text)
136
+ except ValueError:
137
+ parsed = None
138
+ if isinstance(parsed, dict) and isinstance(parsed.get("checks"), dict):
139
+ failing = [
140
+ f"{name} {state}"
141
+ for name, state in parsed["checks"].items()
142
+ if state not in ("ok", "disabled")
143
+ ]
144
+ text = ", ".join(failing) or "not ready"
145
+ parsed = None
146
+ if not isinstance(parsed, dict) or not parsed.get("error"):
147
+ return {
148
+ "error": text or f"HTTP {status}",
149
+ "code": None,
150
+ "findings": (),
151
+ "warnings": (),
152
+ }
153
+ return {
154
+ "error": parsed.get("message") or str(parsed["error"]),
155
+ "code": str(parsed["error"]).removeprefix(ERROR_PREFIX),
156
+ "findings": parsed.get("findings") or (),
157
+ "warnings": parsed.get("warnings") or (),
158
+ }
159
+
160
+
161
+ def _database_hint(state):
162
+ """What to do about the API's database being down: on this machine, `canyonos
163
+ serve` starts it again; "" on Kubernetes, where it is the cluster's."""
164
+ if _on_kubernetes(state):
165
+ return ""
166
+ return " If it stays down, run `canyonos serve`, which starts it again."
167
+
168
+
169
+ def _next_step(state, code):
170
+ """What to do about the API refusing a call with `code`, as a sentence to add to
171
+ its message; "" when there is nothing to add."""
172
+ if _on_kubernetes(state):
173
+ return ""
174
+ if code in CONTROL_KEY_REFUSALS:
175
+ # deploy, sync and stop restart such an API themselves (`serve.ensure_api`).
176
+ return (
177
+ " Run `canyonos serve` to restart the CanyonOS API with this machine's "
178
+ f"control key, in {control_key_path()}."
179
+ )
180
+ if code == DATABASE_UNAVAILABLE:
181
+ return _database_hint(state)
182
+ return ""
183
+
184
+
185
+ def _open(state, method, path, action, data=None, headers=None, timeout=None):
186
+ """Send `method` to `path` of the API `state`'s workflow group is reached at and
187
+ return the open response; any failure is raised as `ApiError`, with what to do
188
+ next when the API names a fix this machine has."""
189
+ base_url, auth = _connection(state)
190
+ request = urllib.request.Request(
191
+ f"{base_url}{path}",
192
+ data=data,
193
+ headers={**auth, **(headers or {})},
194
+ method=method,
195
+ )
196
+ try:
197
+ return urllib.request.urlopen(request, timeout=timeout)
198
+ except urllib.error.HTTPError as e:
199
+ detail = error_detail(e.read(), e.code)
200
+ message = detail["error"]
201
+ if _on_kubernetes(state) and detail["code"] in OLDER_CHART_ERRORS.get(
202
+ e.code, ()
203
+ ):
204
+ # Imported here: kubernetes_target imports this module.
205
+ from canyonos.kubernetes_target import UPGRADE_CHART
206
+
207
+ message = f"{UPGRADE_CHART} (the cluster's API answered: {message})"
208
+ next_step = _next_step(state, detail["code"])
209
+ if next_step:
210
+ message = f"{message.rstrip('.')}.{next_step}"
211
+ raise ApiError(
212
+ f"{action} failed: {message}",
213
+ status=e.code,
214
+ code=detail["code"],
215
+ findings=detail["findings"],
216
+ warnings=detail["warnings"],
217
+ ) from None
218
+ except TimeoutError:
219
+ raise ApiError(
220
+ f"{action} failed: the CanyonOS API at {base_url} did not answer within "
221
+ f"{timeout}s"
222
+ ) from None
223
+ except OSError as e:
224
+ reason = getattr(e, "reason", e)
225
+ hint = (
226
+ ""
227
+ if _on_kubernetes(state)
228
+ else "Run `canyonos deploy` or `canyonos serve` to start it."
229
+ )
230
+ raise ApiError(
231
+ f"Could not reach the CanyonOS API at {base_url}: {reason}. {hint}".strip()
232
+ ) from None
233
+
234
+
235
+ def _request(
236
+ state,
237
+ method,
238
+ path,
239
+ action,
240
+ body=None,
241
+ timeout=REQUEST_TIMEOUT_SECONDS,
242
+ archive=None,
243
+ ):
244
+ """Call the API with `body` as JSON, or the open file `archive` as a gzip upload,
245
+ and return its JSON answer as a dict; any failure is raised as `ApiError`."""
246
+ data, headers = None, {}
247
+ if body is not None:
248
+ data, headers = json.dumps(body).encode(), {"Content-Type": "application/json"}
249
+ elif archive is not None:
250
+ # Without a length, urllib sends a file chunked.
251
+ data = archive
252
+ headers = {
253
+ "Content-Type": "application/gzip",
254
+ "Content-Length": str(os.fstat(archive.fileno()).st_size),
255
+ }
256
+ with _open(state, method, path, action, data, headers, timeout) as response:
257
+ try:
258
+ answer = json.loads(response.read())
259
+ except (OSError, ValueError):
260
+ answer = None
261
+ if not isinstance(answer, dict):
262
+ raise ApiError(
263
+ f"{action} failed: the CanyonOS API returned an invalid response"
264
+ )
265
+ return answer
266
+
267
+
268
+ def _quoted(name):
269
+ return urllib.parse.quote(name, safe="")
270
+
271
+
272
+ def _group_path(state, route=""):
273
+ """The path of `state`'s workflow group, with `route` under it."""
274
+ return f"{PREFIX}/{_quoted(state['workflow_group_id'])}{route}"
275
+
276
+
277
+ def require_state():
278
+ """Recorded container state; raise NoDeployError when there is none. On Docker the
279
+ CanyonOS API is started when it is down, so the command can ask it."""
280
+ try:
281
+ state = load_state()
282
+ except FileNotFoundError:
283
+ raise NoDeployError(
284
+ "No workflow group is running. Run `canyonos deploy <workflow folder>...` "
285
+ "first."
286
+ ) from None
287
+ start_api_for(state)
288
+ return state
289
+
290
+
291
+ def start_api_for(state):
292
+ """Start the CanyonOS API when it is down and the Global Controller container
293
+ `state` records is on this machine, so a command that only reads can ask it. A
294
+ running API is left as it is, and one that won't start is left to the request that
295
+ follows to report."""
296
+ if _on_kubernetes(state):
297
+ return
298
+ # Imported here: serve imports this module.
299
+ from canyonos.serve import start_api_if_down
300
+
301
+ start_api_if_down(state)
302
+
303
+
304
+ def existing_deploy():
305
+ """The running deploy's state if one is already up, else None."""
306
+ try:
307
+ state = load_state()
308
+ except FileNotFoundError:
309
+ return None
310
+ start_api_for(state)
311
+ if is_running(workflow_group_status(state)):
312
+ return state
313
+ return None
314
+
315
+
316
+ def is_running(status):
317
+ """Whether the deploy a status answer describes runs; False for None."""
318
+ return bool(status and status.get("running"))
319
+
320
+
321
+ def list_workflow_groups(state=None):
322
+ """Return the workflow groups the API holds or finds a Global Controller of, each
323
+ with its `workflow_group_id` and `name`; this machine's API without `state`.
324
+ Raises ApiError on failure."""
325
+ return _request(state, "GET", PREFIX, "List workflow groups")["workflow_groups"]
326
+
327
+
328
+ def _wait_until_ready(state=None):
329
+ """Wait up to READY_TIMEOUT_SECONDS for the API to answer `/readyz`: it listens
330
+ before its database is ready, and its `/v1` routes answer 503 until then. An older
331
+ API without `/readyz` is not waited for. Raises ApiError with its last answer when
332
+ it is still not ready: its database, the one thing `/readyz` waits on, is not."""
333
+ deadline = time.monotonic() + READY_TIMEOUT_SECONDS
334
+ while True:
335
+ try:
336
+ _open(
337
+ state,
338
+ "GET",
339
+ "/readyz",
340
+ "Readiness check",
341
+ timeout=STATUS_TIMEOUT_SECONDS,
342
+ ).close()
343
+ return
344
+ except ApiError as e:
345
+ if e.status == 404:
346
+ return
347
+ if time.monotonic() >= deadline:
348
+ # A 503 is `/readyz` waiting on the database.
349
+ answer = str(e)
350
+ if e.status == 503:
351
+ answer = f"{answer.rstrip('.')}.{_database_hint(state)}"
352
+ raise ApiError(
353
+ f"The CanyonOS API at {_connection(state)[0]} was not ready within "
354
+ f"{READY_TIMEOUT_SECONDS}s. {answer}",
355
+ status=e.status,
356
+ code=e.code,
357
+ ) from None
358
+ time.sleep(READY_POLL_SECONDS)
359
+
360
+
361
+ def probe(state=None):
362
+ """Wait until the API is ready, then check that it answers `/v1`, so a command
363
+ fails at once, naming the fix, when it runs an older image without these routes.
364
+ Raises ApiError."""
365
+ _wait_until_ready(state)
366
+ try:
367
+ list_workflow_groups(state)
368
+ except ApiError as e:
369
+ if e.status != 404:
370
+ raise
371
+ raise ApiError(
372
+ f"The CanyonOS API at {_connection(state)[0]} has no {PREFIX} routes: it "
373
+ f"runs an older image than this CLI ({env.api_image}). In a checkout, build "
374
+ "it with `bun run canyonos:dev` or point CANYONOS_API_IMAGE at an image "
375
+ "built from it.",
376
+ status=404,
377
+ code=e.code,
378
+ ) from None
379
+
380
+
381
+ def put_workflow_group(state, config, env_text, workflows=None, api_key_hash=None):
382
+ """Upload the workflow group's name, the text `config` of its `workflow_group.yaml`
383
+ and the text `env_text` of the `.env` beside it (None when there is none); with
384
+ `workflows`, the API removes the uploaded workflows not among them; with
385
+ `api_key_hash`, the SHA-256 of the deploy's API key ("" for none), it keeps that as
386
+ the deploy's key. Return the new generation and the upload's warnings. Raises
387
+ ApiError on failure."""
388
+ body = {
389
+ "name": deployment.folder_name(),
390
+ "config": config,
391
+ "env": env_text,
392
+ "workflows": workflows,
393
+ "api_key_hash": api_key_hash,
394
+ }
395
+ return _request(state, "PUT", _group_path(state), "Sync", body)
396
+
397
+
398
+ def put_workflow(state, name, archive):
399
+ """Make `archive`, an open gzip tar file of workflow `name`'s folder, that workflow's
400
+ files in the Global Controller's workspace and return the new generation and the
401
+ upload's warnings. Raises ApiError on failure, with the `findings` `canyonos
402
+ validate` would print when the workflow breaks the contract."""
403
+ return _request(
404
+ state,
405
+ "PUT",
406
+ _group_path(state, f"/workflows/{_quoted(name)}"),
407
+ "Sync",
408
+ archive=archive,
409
+ )
410
+
411
+
412
+ def put_dashboard(state, registration):
413
+ """Register the workflow group with the dashboard: `registration` names each of its
414
+ workflows by workflow_id and the Redis its Global Controller uses, which the
415
+ dashboard reads them from. Returns the dashboard's `{workflow_id, name}` of each
416
+ workflow under `workflows`. Raises ApiError on failure."""
417
+ return _request(
418
+ state,
419
+ "PUT",
420
+ _group_path(state, "/dashboard"),
421
+ "Dashboard registration",
422
+ registration,
423
+ timeout=DASHBOARD_REQUEST_TIMEOUT_SECONDS,
424
+ )
425
+
426
+
427
+ def delete_workflow_group(state):
428
+ """Stop the workflow group's deploy and remove every upload, waiting until the deploy
429
+ has stopped: what removes the replicas and Redis it started. Raises ApiError on
430
+ failure."""
431
+ return _request(
432
+ state,
433
+ "DELETE",
434
+ _group_path(state),
435
+ "Stop",
436
+ timeout=KUBERNETES_CLEAN_REQUEST_TIMEOUT_SECONDS
437
+ if _on_kubernetes(state)
438
+ else CLEAN_REQUEST_TIMEOUT_SECONDS,
439
+ )
440
+
441
+
442
+ def workflow_group_status(state):
443
+ """The workflow group's status: whether its deploy runs, its phase, progress,
444
+ verdict, endpoint, agents and what the last apply did; None when the API knows no
445
+ such workflow group. Raises ApiError when the API can't say, and when the Global
446
+ Controller runs another CanyonOS release than this CLI, outside development."""
447
+ try:
448
+ status = _request(
449
+ state,
450
+ "GET",
451
+ _group_path(state),
452
+ "Read deploy status",
453
+ timeout=STATUS_TIMEOUT_SECONDS,
454
+ )
455
+ except ApiError as e:
456
+ if e.code == UNKNOWN_WORKFLOW_GROUP:
457
+ return None
458
+ raise
459
+ version = status.get("version")
460
+ # A checkout's CLI runs whatever core image it is pointed at, as on Kubernetes.
461
+ # A Global Controller that has not reported yet has no version to compare.
462
+ if not env.is_development and version is not None and version != env.VERSION:
463
+ # On Kubernetes it is the cluster's API's, the chart's, which a deploy keeps.
464
+ if _on_kubernetes(state):
465
+ runs = "The cluster's CanyonOS API runs"
466
+ fix = f"Upgrade the CanyonOS operator chart to {env.VERSION}."
467
+ else:
468
+ runs = "This workflow group's Global Controller runs"
469
+ fix = (
470
+ f"Run `canyonos deploy <workflow folder>...` to restart it on "
471
+ f"{env.VERSION}."
472
+ )
473
+ raise ApiError(
474
+ f"{runs} CanyonOS {version or 'an older release'} and this CLI is "
475
+ f"{env.VERSION}. {fix}",
476
+ code="version_mismatch",
477
+ )
478
+ return status
479
+
480
+
481
+ def deploy_status(state):
482
+ """`workflow_group_status` for a caller that polls: None also when the API can't be
483
+ reached or read, which the poll counts as a miss. Still raises ApiError for a
484
+ Global Controller of another release."""
485
+ try:
486
+ return workflow_group_status(state)
487
+ except ApiError as e:
488
+ if e.code == "version_mismatch":
489
+ raise
490
+ return None
491
+
492
+
493
+ def deployed_endpoint(state):
494
+ """Return the endpoint record the running deploy published (`public_host`,
495
+ `api_port`, and `routes`, each with its `agent`, `method`, `arguments` and `url`);
496
+ raise ApiError when the deploy has none yet."""
497
+ status = workflow_group_status(state) or {}
498
+ endpoint = status.get("endpoint")
499
+ if endpoint is None:
500
+ # The API names why it could not read the endpoint, e.g. its Redis refused it.
501
+ reasons = "".join(f" {error}." for error in status.get("errors") or [])
502
+ raise ApiError(
503
+ f"The running deploy has no endpoint yet.{reasons} Run `canyonos status` "
504
+ "to see when it is up."
505
+ )
506
+ return endpoint
507
+
508
+
509
+ def test_queries(state):
510
+ """Return the query each uploaded workflow ships in its `config/test_query.txt`, by
511
+ workflow, leaving out a workflow with none; raise ApiError when the API can't
512
+ say."""
513
+ workflows = _request(
514
+ state, "GET", _group_path(state, "/workflows"), "Read test queries", timeout=10
515
+ )["workflows"]
516
+ return {
517
+ workflow["name"]: workflow["test_query"]
518
+ for workflow in workflows
519
+ if workflow["test_query"]
520
+ }
521
+
522
+
523
+ def deploy_health(state):
524
+ """Return the health of the running deploy for `canyonos doctor`: `ok`, and under
525
+ `checks` each part of it with its `name`, `ok`, `detail` and `fix`; raise ApiError
526
+ when the API can't say, including when no deploy runs."""
527
+ return _request(state, "GET", _group_path(state, "/health"), "Health check")
528
+
529
+
530
+ def controller_log(state, tail="all", follow=False):
531
+ """Yield the deploy's own output from its Global Controller log, line by line: its
532
+ last `tail` lines, then with `follow` each new one until the deploy exits. Raises
533
+ ApiError when the log can't be read."""
534
+ query = urllib.parse.urlencode({"tail": tail, "follow": str(follow).lower()})
535
+ response = _open(
536
+ state,
537
+ "GET",
538
+ _group_path(state, f"/logs/controller?{query}"),
539
+ "Read the Global Controller log",
540
+ # A deploy can print nothing for minutes, so a followed log has no timeout.
541
+ timeout=None if follow else REQUEST_TIMEOUT_SECONDS,
542
+ )
543
+ try:
544
+ with response:
545
+ for line in response:
546
+ yield line.decode(errors="replace")
547
+ except OSError as e:
548
+ raise ApiError(f"Could not read the Global Controller log: {e}") from None
549
+
550
+
551
+ def deployed_logs(state, name, tail):
552
+ """Return the last `tail` lines of each running replica of agent `name`, or of the
553
+ one replica whose ID is `name`, keyed by replica ID; raise ApiError when the API
554
+ can't say, naming the agents when `name` is neither."""
555
+ query = urllib.parse.urlencode({"tail": tail})
556
+ return _request(
557
+ state,
558
+ "GET",
559
+ _group_path(state, f"/logs/agents/{_quoted(name)}?{query}"),
560
+ "Read logs",
561
+ timeout=LOGS_REQUEST_TIMEOUT_SECONDS,
562
+ )["logs"]
canyonos/auth.py CHANGED
@@ -3,10 +3,16 @@
3
3
 
4
4
  """This machine's API key: one string the user picks with `--api-key`, kept in
5
5
  `~/.canyonos/api_key`, that opens every endpoint deployed here and the dashboard API.
6
- The containers get only its SHA-256 hash. Without a key nothing is checked."""
6
+ The containers get only its SHA-256 hash. Without a key nothing is checked.
7
+
8
+ Also this machine's control key, which the CLI makes itself and keeps in
9
+ `~/.canyonos/control_key`: the CanyonOS API's `/v1` routes, which run and stop each
10
+ workflow group's Global Controller, answer only a call that sends it, whatever the
11
+ API key. The API gets only its hash."""
7
12
 
8
13
  import hashlib
9
14
  import os
15
+ import secrets
10
16
  from pathlib import Path
11
17
 
12
18
  from canyonos import ui
@@ -16,6 +22,8 @@ from canyonos.os_support import make_private_dir, write_private_file
16
22
  # canyonos_core, and both sides must agree on it.
17
23
  API_KEY_HASH_ENV = "CANYONOS_API_KEY_HASH"
18
24
  API_KEY_ENV = "CANYONOS_API_KEY"
25
+ # What the dashboard's `.env` hands the API the control key's hash in.
26
+ CONTROL_KEY_HASH_ENV = "CANYONOS_CONTROL_KEY_HASH"
19
27
 
20
28
  # The header every printed `curl` sends; the key itself is never printed.
21
29
  BEARER_PLACEHOLDER = '-H "Authorization: Bearer <your api key>"'
@@ -24,6 +32,7 @@ NO_KEY_WARNING = (
24
32
  "No API key is set: the endpoint and the dashboard answer anyone who reaches "
25
33
  "them. Set one with --api-key <key>."
26
34
  )
35
+ KEY_SET = "Your deploys now use an API key for secure connections."
27
36
 
28
37
 
29
38
  def api_key_path() -> Path:
@@ -66,14 +75,12 @@ def _save(key: str) -> None:
66
75
  raise RuntimeError(
67
76
  f"Could not write {path}: {error.strerror or error}"
68
77
  ) from error
69
- if not replaced:
70
- ui.ok(f"Saved this machine's API key to {path}")
71
- return
72
- ui.ok("Replaced this machine's API key.")
73
- ui.hint(
74
- "The dashboard and this deployment use the new key; other running "
75
- "deployments keep the old one until you redeploy them."
76
- )
78
+ ui.ok(KEY_SET)
79
+ if replaced:
80
+ ui.hint(
81
+ "The dashboard and this workflow group use the new key; other running "
82
+ "workflow groups keep the old one until you redeploy them."
83
+ )
77
84
 
78
85
 
79
86
  def _remove() -> None:
@@ -109,6 +116,16 @@ def resolve_api_key(api_key: str | None, no_api_key: bool) -> str | None:
109
116
  return key
110
117
 
111
118
 
119
+ def ensure_machine_api_key() -> str:
120
+ """This machine's API key, made and saved to `~/.canyonos/api_key` when there is
121
+ none, as `canyonos cluster up` needs one for the cluster's dashboard."""
122
+ key = machine_api_key()
123
+ if key is None:
124
+ key = secrets.token_hex(32)
125
+ _save(key)
126
+ return key
127
+
128
+
112
129
  def auth_header(key: str | None = None) -> dict[str, str]:
113
130
  """The header that sends `key`, by default this machine's API key; none when there
114
131
  is no key."""
@@ -128,3 +145,52 @@ def gc_env(key: str | None) -> list[str]:
128
145
  """The `docker run` options that hand the Global Controller the hash of `key`; an
129
146
  empty hash when there is no key, so nothing is checked."""
130
147
  return ["-e", f"{API_KEY_HASH_ENV}={hash_api_key(key)}"]
148
+
149
+
150
+ def control_key_path() -> Path:
151
+ """Where this machine keeps its control key: `~/.canyonos/control_key`."""
152
+ return Path.home() / ".canyonos" / "control_key"
153
+
154
+
155
+ def _new_control_key(path: Path) -> None:
156
+ """Write a new random control key to `path` unless one is there already: written
157
+ beside it and linked into place, so two commands making one at the same moment
158
+ end up with the same key."""
159
+ make_private_dir(path.parent)
160
+ draft = path.with_name(f".{path.name}.{os.getpid()}")
161
+ try:
162
+ write_private_file(draft, secrets.token_hex(32) + "\n")
163
+ try:
164
+ os.link(draft, path)
165
+ except FileExistsError:
166
+ pass
167
+ finally:
168
+ draft.unlink(missing_ok=True)
169
+
170
+
171
+ def control_key() -> str:
172
+ """This machine's control key, made the first time it is needed; raise RuntimeError
173
+ when `~/.canyonos/control_key` can't be read or written."""
174
+ path = control_key_path()
175
+ try:
176
+ if not path.is_file():
177
+ _new_control_key(path)
178
+ key = path.read_text(encoding="utf-8").strip()
179
+ except OSError as error:
180
+ raise RuntimeError(
181
+ f"Could not read or write {path}: {error.strerror or error}"
182
+ ) from error
183
+ if not key:
184
+ raise RuntimeError(f"{path} is empty: delete it and run the command again.")
185
+ return key
186
+
187
+
188
+ def control_key_hash() -> str:
189
+ """The SHA-256 of this machine's control key in lowercase hex, as the CanyonOS API
190
+ holds it."""
191
+ return hash_api_key(control_key())
192
+
193
+
194
+ def control_header() -> dict[str, str]:
195
+ """The header that sends this machine's control key to the CanyonOS API."""
196
+ return {"Authorization": f"Bearer {control_key()}"}