-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathops.py
More file actions
2763 lines (2332 loc) · 86.9 KB
/
ops.py
File metadata and controls
2763 lines (2332 loc) · 86.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from __future__ import annotations
import json
import os
import secrets
import shlex
import shutil
import socket
import subprocess
import sys
import threading
import urllib.error
import urllib.request
from dataclasses import dataclass
from pathlib import Path
from typing import TextIO
from typing import Any, Iterable
from marvain_cli.config import ConfigError, ResolvedEnv, find_config_path, load_config_dict, resolve_env, save_config_dict
MARVAIN_CONDA_ENV_NAME = "marvain"
MARVAIN_CONDA_ENV_FILE = "config/marvain_conda.yaml"
MARVAIN_ALLOW_VENV_ENVVAR = "MARVAIN_ALLOW_VENV"
@dataclass(frozen=True)
class Ctx:
config_path: Path
cfg: dict[str, Any]
env: ResolvedEnv
def _eprint(msg: str) -> None:
print(msg, file=sys.stderr)
def _fmt_cmd(cmd: list[str]) -> str:
return " ".join(shlex.quote(c) for c in cmd)
def _fmt_cmd_redacted(cmd: list[str]) -> str:
"""
Format a command for logging, redacting known sensitive arguments.
Currently redacts values passed to flags like ``--secret-arn``.
"""
# Work on a shallow copy so we don't mutate the original command.
redacted_cmd = list(cmd)
# Flags whose following argument should be treated as sensitive.
sensitive_flags = {"--secret-arn"}
i = 0
while i < len(redacted_cmd) - 1:
if redacted_cmd[i] in sensitive_flags:
# Replace the following argument with a redacted marker.
redacted_cmd[i + 1] = "***REDACTED***"
i += 2
else:
i += 1
return _fmt_cmd(redacted_cmd)
def load_ctx(
*,
config_override: str | None,
env: str | None,
profile: str | None,
region: str | None,
stack: str | None,
) -> Ctx:
p = find_config_path(config_override)
if p is None:
raise ConfigError("No config found. Create one with: marvain config init")
cfg = load_config_dict(p)
resolved = resolve_env(cfg, env=env, profile_override=profile, region_override=region, stack_override=stack)
return Ctx(config_path=p, cfg=cfg, env=resolved)
def cmd_env(resolved: ResolvedEnv) -> dict[str, str]:
# We prefer explicit configuration. Many AWS/SAM tools honor these env vars.
return {
"AWS_PROFILE": resolved.aws_profile,
"AWS_REGION": resolved.aws_region,
"AWS_DEFAULT_REGION": resolved.aws_region,
}
def aws_cli_args(resolved: ResolvedEnv) -> list[str]:
"""Explicit AWS CLI args.
We still pass env vars via `cmd_env()` for tools that only honor env, but the
AWS CLI supports explicit `--profile/--region` which we prefer.
"""
return ["--profile", resolved.aws_profile, "--region", resolved.aws_region]
def sam_cli_args(resolved: ResolvedEnv) -> list[str]:
# SAM CLI supports `--profile/--region` for deploy/logs.
return ["--profile", resolved.aws_profile, "--region", resolved.aws_region]
def run_cmd(
cmd: list[str],
*,
env: dict[str, str] | None,
dry_run: bool,
check: bool = True,
cwd: str | None = None,
) -> int:
_eprint(f"$ {_fmt_cmd_redacted(cmd)}")
if dry_run:
return 0
merged = os.environ.copy()
if env:
merged.update(env)
p = subprocess.run(cmd, env=merged, cwd=cwd)
if check and p.returncode != 0:
raise subprocess.CalledProcessError(p.returncode, cmd)
return p.returncode
def run_json(
cmd: list[str],
*,
env: dict[str, str] | None,
dry_run: bool,
cwd: str | None = None,
) -> Any:
_eprint(f"$ {_fmt_cmd_redacted(cmd)}")
if dry_run:
return {}
merged = os.environ.copy()
if env:
merged.update(env)
out = subprocess.check_output(cmd, env=merged, cwd=cwd)
return json.loads(out.decode("utf-8"))
def require_tools(names: Iterable[str]) -> list[str]:
missing: list[str] = []
for n in names:
if shutil.which(n) is None:
missing.append(n)
return missing
def _truthy_env(name: str) -> bool:
v = (os.environ.get(name) or "").strip().lower()
return v in ("1", "true", "yes", "y", "on")
def _conda_env_is_active(env_name: str) -> bool:
if (os.environ.get("CONDA_DEFAULT_ENV") or "") == env_name:
return True
prefix = os.environ.get("CONDA_PREFIX") or ""
if prefix:
return os.path.basename(prefix.rstrip("/")) == env_name
return False
def _conda_env_exists(env_name: str) -> bool:
if shutil.which("conda") is None:
return False
try:
out = subprocess.check_output(["conda", "env", "list", "--json"])
data = json.loads(out.decode("utf-8"))
envs = data.get("envs") or []
for p in envs:
if isinstance(p, str) and os.path.basename(p.rstrip("/")) == env_name:
return True
return False
except Exception:
return False
def _python_is_311() -> bool:
return sys.version_info[:2] == (3, 11)
def _conda_preflight(*, enforce: bool) -> int:
"""Ensure the primary Conda env exists and is active.
We keep an escape hatch via MARVAIN_ALLOW_VENV=1.
Returns:
0 on success
2 on preflight failure (matches other CLI error semantics)
"""
if not enforce:
return 0
if _truthy_env(MARVAIN_ALLOW_VENV_ENVVAR):
return 0
if shutil.which("conda") is None:
_eprint(
"Conda is required for marvain. Install Miniconda/Mambaforge, then create env with: "
f"conda env create -f {MARVAIN_CONDA_ENV_FILE} (or set {MARVAIN_ALLOW_VENV_ENVVAR}=1 to bypass)"
)
return 2
if not _conda_env_exists(MARVAIN_CONDA_ENV_NAME):
_eprint(
f"Conda env '{MARVAIN_CONDA_ENV_NAME}' not found. Create it with: conda env create -f {MARVAIN_CONDA_ENV_FILE}"
)
return 2
if not _conda_env_is_active(MARVAIN_CONDA_ENV_NAME):
_eprint(
f"Conda env '{MARVAIN_CONDA_ENV_NAME}' exists but is not active. Activate with: conda activate {MARVAIN_CONDA_ENV_NAME} (or source ./marvain_activate)"
)
return 2
if not _python_is_311():
_eprint(
f"Python {sys.version_info.major}.{sys.version_info.minor} detected; marvain requires Python 3.11 (activate conda env '{MARVAIN_CONDA_ENV_NAME}')."
)
return 2
# SAM's Python builder specifically looks for `python3.11` on PATH.
if shutil.which("python3.11") is None:
_eprint(
"python3.11 not found on PATH (required by `sam build` for runtime python3.11). "
f"Activate conda env '{MARVAIN_CONDA_ENV_NAME}' (or source ./marvain_activate)."
)
return 2
return 0
def aws_stack_outputs(ctx: Ctx, *, dry_run: bool) -> dict[str, str]:
cmd = [
"aws",
"cloudformation",
"describe-stacks",
*aws_cli_args(ctx.env),
"--stack-name",
ctx.env.stack_name,
"--output",
"json",
]
data = run_json(cmd, env=cmd_env(ctx.env), dry_run=dry_run)
outs: dict[str, str] = {}
stacks = (data or {}).get("Stacks") or []
if not stacks:
return outs
for o in stacks[0].get("Outputs") or []:
k = o.get("OutputKey")
v = o.get("OutputValue")
if isinstance(k, str) and isinstance(v, str):
outs[k] = v
return outs
def _env_resources_from_config(ctx: Ctx) -> dict[str, Any]:
envs = ctx.cfg.get("envs")
if not isinstance(envs, dict):
return {}
env_cfg = envs.get(ctx.env.env)
if not isinstance(env_cfg, dict):
return {}
res = env_cfg.get("resources")
return res if isinstance(res, dict) else {}
def resolve_stack_output(ctx: Ctx, *, key: str, dry_run: bool) -> str:
"""Resolve a CloudFormation output by key.
Prefers config.envs[env].resources (populated by `marvain monitor outputs --write-config`).
Falls back to live `describe-stacks` only when not dry-run.
"""
res = _env_resources_from_config(ctx)
v = res.get(key)
if isinstance(v, str) and v:
return v
if dry_run:
raise ConfigError(
f"Missing stack output '{key}' in config. Run: marvain monitor outputs --write-config"
)
outs = aws_stack_outputs(ctx, dry_run=False)
v2 = outs.get(key)
if isinstance(v2, str) and v2:
return v2
raise ConfigError(f"Missing stack output '{key}' (not in config and not in live stack outputs)")
def _redact_secret(s: str, *, keep: int = 6) -> str:
s = str(s or "")
if len(s) <= keep:
return "***"
return s[:keep] + "..."
def resolve_access_token(access_token: str | None) -> str:
tok = (access_token or os.getenv("MARVAIN_ACCESS_TOKEN") or "").strip()
if not tok:
raise ConfigError("Missing access token (pass --access-token or set MARVAIN_ACCESS_TOKEN)")
return tok
def resolve_hub_rest_api_base(ctx: Ctx, *, hub_rest_api_base: str | None, dry_run: bool) -> str:
base = (hub_rest_api_base or os.getenv("MARVAIN_HUB_REST_API_BASE") or "").strip()
if base:
return base.rstrip("/")
return resolve_stack_output(ctx, key="HubRestApiBase", dry_run=dry_run).rstrip("/")
def _hub_url(base: str, path: str) -> str:
p = "/" + str(path or "").lstrip("/")
return base.rstrip("/") + p
def hub_api_json(
ctx: Ctx,
*,
method: str,
path: str,
payload: dict[str, Any] | None,
access_token: str,
hub_rest_api_base: str | None,
dry_run: bool,
timeout_s: int = 30,
) -> dict[str, Any]:
"""Call Hub REST API with Bearer access token.
Uses stdlib urllib; intended for CLI automation and is dry-run testable.
"""
base = resolve_hub_rest_api_base(ctx, hub_rest_api_base=hub_rest_api_base, dry_run=dry_run)
url = _hub_url(base, path)
method_u = str(method).upper()
# Avoid printing secrets; but log enough to reproduce.
_eprint(f"$ HTTP {method_u} {url} (Authorization: Bearer {_redact_secret(access_token)})")
if payload is not None:
_eprint(f"$ json={json.dumps(payload, sort_keys=True)}")
if dry_run:
return {}
body = None if payload is None else json.dumps(payload).encode("utf-8")
req = urllib.request.Request(url, data=body, method=method_u)
req.add_header("Authorization", f"Bearer {access_token}")
if payload is not None:
req.add_header("Content-Type", "application/json")
try:
with urllib.request.urlopen(req, timeout=timeout_s) as resp:
raw = resp.read()
except urllib.error.HTTPError as e:
raw = e.read() if hasattr(e, "read") else b""
msg = raw.decode("utf-8", errors="replace")
raise RuntimeError(f"Hub API HTTP {getattr(e, 'code', '?')}: {msg}")
txt = raw.decode("utf-8") if raw else "{}"
return json.loads(txt)
def hub_claim_first_owner(
ctx: Ctx,
*,
agent_id: str,
access_token: str | None,
hub_rest_api_base: str | None,
dry_run: bool,
) -> dict[str, Any]:
tok = resolve_access_token(access_token)
return hub_api_json(
ctx,
method="POST",
path=f"/v1/agents/{agent_id}/claim_owner",
payload=None,
access_token=tok,
hub_rest_api_base=hub_rest_api_base,
dry_run=dry_run,
)
def hub_list_memberships(
ctx: Ctx,
*,
agent_id: str,
access_token: str | None,
hub_rest_api_base: str | None,
dry_run: bool,
) -> dict[str, Any]:
tok = resolve_access_token(access_token)
return hub_api_json(
ctx,
method="GET",
path=f"/v1/agents/{agent_id}/memberships",
payload=None,
access_token=tok,
hub_rest_api_base=hub_rest_api_base,
dry_run=dry_run,
)
def hub_grant_membership(
ctx: Ctx,
*,
agent_id: str,
email: str,
role: str,
relationship_label: str | None,
access_token: str | None,
hub_rest_api_base: str | None,
dry_run: bool,
) -> dict[str, Any]:
tok = resolve_access_token(access_token)
payload: dict[str, Any] = {"email": email, "role": role}
if relationship_label is not None:
payload["relationship_label"] = relationship_label
return hub_api_json(
ctx,
method="POST",
path=f"/v1/agents/{agent_id}/memberships",
payload=payload,
access_token=tok,
hub_rest_api_base=hub_rest_api_base,
dry_run=dry_run,
)
def hub_update_membership(
ctx: Ctx,
*,
agent_id: str,
user_id: str,
role: str,
relationship_label: str | None,
access_token: str | None,
hub_rest_api_base: str | None,
dry_run: bool,
) -> dict[str, Any]:
tok = resolve_access_token(access_token)
payload: dict[str, Any] = {"role": role}
if relationship_label is not None:
payload["relationship_label"] = relationship_label
return hub_api_json(
ctx,
method="PATCH",
path=f"/v1/agents/{agent_id}/memberships/{user_id}",
payload=payload,
access_token=tok,
hub_rest_api_base=hub_rest_api_base,
dry_run=dry_run,
)
def hub_revoke_membership(
ctx: Ctx,
*,
agent_id: str,
user_id: str,
access_token: str | None,
hub_rest_api_base: str | None,
dry_run: bool,
) -> dict[str, Any]:
tok = resolve_access_token(access_token)
return hub_api_json(
ctx,
method="DELETE",
path=f"/v1/agents/{agent_id}/memberships/{user_id}",
payload=None,
access_token=tok,
hub_rest_api_base=hub_rest_api_base,
dry_run=dry_run,
)
def hub_register_device(
ctx: Ctx,
*,
agent_id: str,
name: str | None,
scopes: list[str] | None,
access_token: str | None,
hub_rest_api_base: str | None,
dry_run: bool,
) -> dict[str, Any]:
tok = resolve_access_token(access_token)
payload: dict[str, Any] = {"agent_id": agent_id}
if name is not None:
payload["name"] = name
if scopes is not None:
payload["scopes"] = scopes
return hub_api_json(
ctx,
method="POST",
path="/v1/devices/register",
payload=payload,
access_token=tok,
hub_rest_api_base=hub_rest_api_base,
dry_run=dry_run,
)
def sam_build_simple(*, dry_run: bool, template: str = "template.yaml") -> int:
"""Run `sam build` without requiring a config file."""
rc = _conda_preflight(enforce=not dry_run)
if rc != 0:
return rc
# Note: --clean was removed in newer SAM CLI versions; use --cached=false if needed.
return run_cmd(["sam", "build", "-t", template], env=None, dry_run=dry_run)
def sam_build(ctx: Ctx, *, dry_run: bool) -> int:
rc = _conda_preflight(enforce=not dry_run)
if rc != 0:
return rc
sam_cfg = (ctx.env.raw.get("sam") or {}) if isinstance(ctx.env.raw.get("sam"), dict) else {}
template = str(sam_cfg.get("template") or "template.yaml")
return run_cmd(["sam", "build", "-t", template], env=cmd_env(ctx.env), dry_run=dry_run)
def sam_deploy(ctx: Ctx, *, dry_run: bool, guided: bool, no_confirm: bool = False) -> int:
rc = _conda_preflight(enforce=not dry_run)
if rc != 0:
return rc
sam_cfg = (ctx.env.raw.get("sam") or {}) if isinstance(ctx.env.raw.get("sam"), dict) else {}
source_template = str(sam_cfg.get("template") or "template.yaml")
caps = sam_cfg.get("capabilities") or ["CAPABILITY_IAM"]
if not isinstance(caps, list):
caps = ["CAPABILITY_IAM"]
param_overrides = sam_cfg.get("parameter_overrides") or {}
if not isinstance(param_overrides, dict):
param_overrides = {}
# Check for LIVEKIT_URL environment variable and add to parameter overrides
livekit_url = os.environ.get("LIVEKIT_URL", "").strip()
if livekit_url:
param_overrides["LiveKitUrl"] = livekit_url
_eprint(f"Using LIVEKIT_URL from environment: {livekit_url}")
elif "LiveKitUrl" not in param_overrides:
_eprint("ERROR: LIVEKIT_URL environment variable is not set and LiveKitUrl is not in parameter_overrides.")
_eprint("Please set LIVEKIT_URL or add LiveKitUrl to your marvain config.")
_eprint("Hint: export LIVEKIT_URL=<your-livekit-url> or add LiveKitUrl to sam.parameter_overrides in marvain-config.yaml")
return 1
# Always build before deploy so Lambda functions include vendored dependencies.
# This prevents the common failure mode where deployed Lambdas are missing
# runtime deps (e.g., mangum) if `sam deploy` is run against the source template.
build_rc = run_cmd(["sam", "build", "-t", source_template], env=cmd_env(ctx.env), dry_run=dry_run)
if build_rc != 0:
return build_rc
# Deploy the built template.
template = ".aws-sam/build/template.yaml"
cmd = [
"sam",
"deploy",
*sam_cli_args(ctx.env),
"--template-file",
template,
"--stack-name",
ctx.env.stack_name,
"--resolve-s3",
"--no-fail-on-empty-changeset",
]
if guided:
cmd.append("--guided")
else:
# Non-guided deploys must be fully non-interactive by default.
# Keep `--no-confirm` as a legacy flag, but `--no-guided` should never
# require stdin input.
cmd.append("--no-confirm-changeset")
if caps:
cmd.append("--capabilities")
cmd.extend([str(c) for c in caps])
if param_overrides:
cmd.append("--parameter-overrides")
for k, v in param_overrides.items():
cmd.append(f"{k}={v}")
return run_cmd(cmd, env=cmd_env(ctx.env), dry_run=dry_run)
def _stream_process(
*,
prefix: str | None,
cmd: list[str],
env: dict[str, str],
log_fh: TextIO | None,
log_lock: threading.Lock | None,
) -> int:
"""Run a command and stream combined stdout/stderr to stdout (and optionally a file)."""
p = subprocess.Popen(cmd, env={**os.environ, **env}, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True)
assert p.stdout is not None
try:
for line in p.stdout:
out_line = f"[{prefix}] {line}" if prefix else line
sys.stdout.write(out_line)
sys.stdout.flush()
if log_fh is not None:
if log_lock is not None:
with log_lock:
log_fh.write(out_line)
log_fh.flush()
else:
log_fh.write(out_line)
log_fh.flush()
except KeyboardInterrupt:
# Ctrl-C will generally be handled in the main thread; this keeps streaming helpers quiet.
pass
finally:
try:
p.terminate()
except Exception:
pass
return p.wait()
def _tail_one(
function_name: str,
cmd: list[str],
env: dict[str, str],
*,
log_fh: TextIO | None,
log_lock: threading.Lock | None,
) -> None:
_stream_process(prefix=function_name, cmd=cmd, env=env, log_fh=log_fh, log_lock=log_lock)
def _since_to_sam_start_time(since: str) -> str:
"""Convert our compact --since (e.g. 10m, 1h) into `sam logs -s` format.
SAM CLI accepts natural language like: '10min ago', '2hour ago'.
If `since` doesn't match the compact form, we pass it through as-is.
"""
s = since.strip()
if not s:
return s
# Compact form: <int><unit>
if len(s) >= 2 and s[:-1].isdigit() and s[-1] in ("s", "m", "h", "d"):
n = int(s[:-1])
unit = s[-1]
if unit == "s":
return f"{n}sec ago"
if unit == "m":
return f"{n}min ago"
if unit == "h":
return f"{n}hour ago"
if unit == "d":
return f"{n}day ago"
return s
def sam_logs(
ctx: Ctx,
*,
dry_run: bool,
functions: list[str] | None,
tail: bool,
since: str | None,
output_file: str | None = None,
suppress_sam_warnings: bool = False,
) -> int:
rc = _conda_preflight(enforce=not dry_run)
if rc != 0:
return rc
base = ["sam", "logs", *sam_cli_args(ctx.env), "--stack-name", ctx.env.stack_name]
if since:
# SAM CLI uses -s/--start-time (not --since).
base.extend(["-s", _since_to_sam_start_time(since)])
if tail:
base.append("--tail")
if dry_run:
if functions:
for f in functions:
_eprint(f"$ {_fmt_cmd([*base, '--name', f])}")
else:
_eprint(f"$ {_fmt_cmd(base)}")
return 0
env = cmd_env(ctx.env)
if suppress_sam_warnings:
# SAM CLI is a Python program; this suppresses a known, non-actionable warning
# emitted by SAM's dependencies on some Python versions.
env["PYTHONWARNINGS"] = (
"ignore:Core Pydantic V1 functionality isn't compatible with Python 3.14 or greater.*:UserWarning"
)
log_fh: TextIO | None = None
log_lock: threading.Lock | None = None
if output_file:
p = Path(output_file)
if p.parent and str(p.parent) != ".":
p.parent.mkdir(parents=True, exist_ok=True)
log_fh = p.open("a", encoding="utf-8")
log_lock = threading.Lock()
try:
# Preferred UX: one `sam logs` call for all stack resources (no per-function `--name`).
if not functions:
return _stream_process(prefix=None, cmd=base, env=env, log_fh=log_fh, log_lock=log_lock)
# If functions were specified, tail each explicitly (repeatable --function).
threads: list[threading.Thread] = []
for f in functions:
cmd = [*base, "--name", f]
t = threading.Thread(
target=_tail_one,
args=(f, cmd, env),
kwargs={"log_fh": log_fh, "log_lock": log_lock},
daemon=True,
)
threads.append(t)
t.start()
for t in threads:
t.join()
return 0
finally:
if log_fh is not None:
try:
log_fh.close()
except Exception:
pass
def monitor_outputs(ctx: Ctx, *, dry_run: bool, write_config: bool) -> int:
rc = _conda_preflight(enforce=not dry_run)
if rc != 0:
return rc
outs = aws_stack_outputs(ctx, dry_run=dry_run)
print(json.dumps({"stack": ctx.env.stack_name, "outputs": outs}, indent=2, sort_keys=True))
if write_config and not dry_run:
envs = ctx.cfg.setdefault("envs", {})
if isinstance(envs, dict):
env_cfg = envs.setdefault(ctx.env.env, {})
if isinstance(env_cfg, dict):
res = env_cfg.setdefault("resources", {})
if isinstance(res, dict):
for k, v in outs.items():
res[k] = v
save_config_dict(ctx.config_path, ctx.cfg)
_eprint(f"Updated resources in config: {ctx.config_path}")
return 0
def monitor_status(ctx: Ctx, *, dry_run: bool) -> int:
rc = _conda_preflight(enforce=not dry_run)
if rc != 0:
return rc
cmd = [
"aws",
"cloudformation",
"describe-stacks",
*aws_cli_args(ctx.env),
"--stack-name",
ctx.env.stack_name,
"--output",
"json",
]
data = run_json(cmd, env=cmd_env(ctx.env), dry_run=dry_run)
if dry_run:
return 0
stacks = (data or {}).get("Stacks") or []
if not stacks:
_eprint("No stack found")
return 1
s0 = stacks[0]
print(json.dumps({"stack": ctx.env.stack_name, "status": s0.get("StackStatus")}, indent=2, sort_keys=True))
return 0
def _pretty_print_status(result: dict[str, Any]) -> None:
"""Pretty print status result."""
stack = result.get("stack", "unknown")
exists = result.get("exists", False)
status_val = result.get("status", "UNKNOWN")
outputs = result.get("outputs", {})
# Status color indicators
if not exists:
status_indicator = "⚪" # Not deployed
status_color = ""
elif "COMPLETE" in status_val and "ROLLBACK" not in status_val:
status_indicator = "🟢" # Healthy
status_color = ""
elif "IN_PROGRESS" in status_val:
status_indicator = "🟡" # In progress
status_color = ""
else:
status_indicator = "🔴" # Error/rollback
status_color = ""
print(f"\n{status_indicator} Stack: {stack}")
print(f" Status: {status_val if exists else 'NOT DEPLOYED'}")
if exists and outputs:
print(f"\n Resources ({len(outputs)}):")
# Group outputs by type for better readability
for key in sorted(outputs.keys()):
value = outputs[key]
# Truncate long values
display_val = value if len(value) <= 60 else value[:57] + "..."
print(f" {key}: {display_val}")
print()
def status(ctx: Ctx, *, dry_run: bool, output_json: bool = False) -> int:
"""Show deployment status: stack existence, status, and key resources."""
rc = _conda_preflight(enforce=not dry_run)
if rc != 0:
return rc
cmd = [
"aws",
"cloudformation",
"describe-stacks",
*aws_cli_args(ctx.env),
"--stack-name",
ctx.env.stack_name,
"--output",
"json",
]
data = run_json(cmd, env=cmd_env(ctx.env), dry_run=dry_run)
if dry_run:
return 0
stacks = (data or {}).get("Stacks") or []
if not stacks:
result = {"stack": ctx.env.stack_name, "exists": False}
if output_json:
print(json.dumps(result, indent=2, sort_keys=True))
else:
_pretty_print_status(result)
return 0
s0 = stacks[0]
stack_status = s0.get("StackStatus", "UNKNOWN")
# Extract key outputs
outputs = {}
for o in s0.get("Outputs") or []:
k = o.get("OutputKey")
v = o.get("OutputValue")
if isinstance(k, str) and isinstance(v, str):
outputs[k] = v
result = {
"stack": ctx.env.stack_name,
"exists": True,
"status": stack_status,
"outputs": outputs,
}
if output_json:
print(json.dumps(result, indent=2, sort_keys=True))
else:
_pretty_print_status(result)
return 0
def _pretty_print_info(result: dict[str, Any]) -> None:
"""Pretty print info result."""
env = result.get("environment", "unknown")
stack = result.get("stack_name", "unknown")
profile = result.get("aws_profile", "default")
region = result.get("aws_region", "unknown")
resources = result.get("resources") or {}
print(f"\n📦 Environment: {env}")
print(f" Stack: {stack}")
print(f" Profile: {profile}")
print(f" Region: {region}")
if resources:
print(f"\n Resources ({len(resources)}):")
for key in sorted(resources.keys()):
value = resources[key]
# Truncate long values
display_val = value if len(value) <= 60 else value[:57] + "..."
print(f" {key}: {display_val}")
else:
print("\n Resources: (stack not deployed or no outputs)")
print()
def info(ctx: Ctx, *, dry_run: bool, output_json: bool = False) -> int:
"""Show deployment info: stack name, region, profile, and resource details."""
rc = _conda_preflight(enforce=not dry_run)
if rc != 0:
return rc
# Get stack outputs if stack exists
outputs = {}
cmd = [
"aws",
"cloudformation",
"describe-stacks",
*aws_cli_args(ctx.env),
"--stack-name",
ctx.env.stack_name,
"--output",
"json",
]
data = run_json(cmd, env=cmd_env(ctx.env), dry_run=dry_run)
if not dry_run and data:
stacks = (data or {}).get("Stacks") or []
if stacks:
for o in stacks[0].get("Outputs") or []:
k = o.get("OutputKey")
v = o.get("OutputValue")
if isinstance(k, str) and isinstance(v, str):
outputs[k] = v
result = {
"environment": ctx.env.env,
"stack_name": ctx.env.stack_name,
"aws_profile": ctx.env.aws_profile,
"aws_region": ctx.env.aws_region,
"resources": outputs if outputs else None,
}
if output_json:
print(json.dumps(result, indent=2, sort_keys=True))
else:
_pretty_print_info(result)
return 0
def teardown(ctx: Ctx, *, dry_run: bool, yes: bool, wait: bool) -> int:
rc = _conda_preflight(enforce=not dry_run)
if rc != 0:
return rc
if dry_run and not yes:
# In dry-run, don't force confirmation; just show what would happen.
yes = True
if not yes:
_eprint(f"About to delete CloudFormation stack: {ctx.env.stack_name}")
_eprint("Re-run with --yes to confirm.")
return 2
run_cmd(
["aws", "cloudformation", "delete-stack", *aws_cli_args(ctx.env), "--stack-name", ctx.env.stack_name],
env=cmd_env(ctx.env),
dry_run=dry_run,
)
if wait:
run_cmd(
[
"aws",
"cloudformation",
"wait",
"stack-delete-complete",
*aws_cli_args(ctx.env),
"--stack-name",
ctx.env.stack_name,
],
env=cmd_env(ctx.env),
dry_run=dry_run,
)
return 0
def doctor(ctx: Ctx, *, dry_run: bool) -> int:
rc = _conda_preflight(enforce=True)
if rc != 0:
return rc
missing = require_tools(["aws", "sam", "python3.11"])
if missing:
_eprint(f"Missing required tools on PATH: {', '.join(missing)}")
return 2
# Validate credentials.
run_cmd(["aws", "sts", "get-caller-identity", *aws_cli_args(ctx.env)], env=cmd_env(ctx.env), dry_run=dry_run)
_eprint("doctor OK")
return 0
def gui_run(
ctx: Ctx,
*,
dry_run: bool,
host: str,
port: int,
reload: bool,
stack_prefix: str | None,
) -> int:
"""Start the local GUI server.
The GUI runs locally (developer laptop or EC2) and connects to deployed
AWS resources (Aurora Data API, Cognito, S3, SQS) via environment variables.
Args:
host: Host to bind to (default: 127.0.0.1)
port: Port to bind to (default: 8084)
reload: Enable auto-reload on code changes
stack_prefix: Unused (kept for backward CLI compatibility)
"""