-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
1792 lines (1562 loc) · 62.1 KB
/
Copy pathmain.py
File metadata and controls
1792 lines (1562 loc) · 62.1 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
"""NetEngine CLI — operator surface for world management."""
import asyncio
import json
import os
import subprocess
import sys
import time
from pathlib import Path
from typing import Any
import click
from netengine.cli.doctor import doctor
from netengine.diagnostic.preflight import (
DoctorCheckResult,
DoctorStatus,
build_context,
run_preflight,
)
from netengine.cli.env import db_url_from_env
from netengine.config.loader import ConfigOverrideError, parse_dotted_overrides
from netengine.core.migrations import MigrationService, MigrationStatus
from netengine.core.orchestrator import Orchestrator
from netengine.core.state import RuntimeState, get_state_file
from netengine.db.migrations import (
MIGRATIONS_DIR,
MigrationRunResult,
migration_status,
run_migrations,
)
from netengine.events.queues import PRIMARY_QUEUES, Queue, dlq_for
from netengine.logs import get_logger
from netengine.phase_labels import PHASE_LABELS
from netengine.spec.loader import (
SpecLoadError,
_is_active_feature_value,
_resolve_feature_state_paths,
load_spec,
load_spec_with_composition,
load_spec_with_environment,
)
logger = get_logger(__name__)
LOCAL_SETUP_DB_URL = "postgresql://netengine:dev_password@localhost:5432/netengine"
def _parse_set_overrides(set_values: tuple[str, ...]) -> dict[str, Any]:
"""Convert repeatable dotted key=value CLI overrides into a nested dictionary."""
try:
return parse_dotted_overrides(set_values)
except ConfigOverrideError as exc:
raise click.BadParameter(str(exc), param_hint="--set") from exc
def _load_spec_for_cli(
spec_file: str,
*,
environment: str | None = None,
set_values: tuple[str, ...] = (),
validate_feature_states: bool = True,
):
"""Load a spec using the same composition semantics as ``up``."""
overrides = _parse_set_overrides(set_values)
feature_state_kwargs = {} if validate_feature_states else {"validate_feature_states": False}
if environment:
return load_spec_with_environment(
spec_file,
environment=environment,
overrides=overrides or None,
**feature_state_kwargs,
)
if overrides:
return load_spec_with_composition(spec_file, overrides=overrides, **feature_state_kwargs)
return load_spec(spec_file, **feature_state_kwargs)
def _feature_state_explanations(spec: Any) -> list[str]:
"""Return noteworthy active feature-state lines for ``validate --explain``."""
lines: list[str] = []
for entry, path, value, default_value in _resolve_feature_state_paths(spec):
if not _is_active_feature_value(value, default_value):
continue
value_text = getattr(value, "value", value)
lines.append(
f"{path}: {entry.state} ({entry.stage}) - {entry.reason}; value={value_text!r}"
)
return lines
def _jsonable_feature_value(value: Any) -> Any:
"""Return a JSON-serializable representation for feature-state values."""
if hasattr(value, "value"):
return value.value
if hasattr(value, "model_dump"):
return value.model_dump(mode="json")
return value
def _active_feature_state_results(spec: Any) -> list[dict[str, Any]]:
"""Return machine-readable active feature-state validation results."""
results: list[dict[str, Any]] = []
for entry, path, value, default_value in _resolve_feature_state_paths(spec):
if not _is_active_feature_value(value, default_value):
continue
results.append(
{
"path": path,
"state": entry.state,
"stage": entry.stage,
"reason": entry.reason,
"current_value": _jsonable_feature_value(value),
"default_value": _jsonable_feature_value(default_value),
}
)
return results
async def _run_migrations(db_url: str) -> MigrationRunResult:
"""Run SQL migrations using the shared migration service."""
result = await run_migrations(db_url)
for migration in result.results:
if migration.status == "applied":
logger.info(
f"Applied migration: {migration.filename} " f"({migration.duration_seconds:.3f}s)"
)
elif migration.status == "skipped":
logger.info(f"Skipped migration: {migration.filename} (already applied)")
logger.info(
f"Migrations complete: {result.applied_count} applied, "
f"{result.skipped_count} skipped, {result.failed_count} failed"
)
return result
def _db_url_from_env() -> str | None:
"""Return the database URL used by CLI migration operations."""
return db_url_from_env()
def _require_db_url() -> str:
"""Return the configured DB URL or exit with migration-oriented guidance."""
db_url = _db_url_from_env()
if not db_url:
click.echo("No database URL configured for migrations", err=True)
sys.exit(2)
return db_url
def _print_migration_status(status: MigrationStatus) -> None:
click.echo("Migration status")
click.echo(f" Applied: {len(status.applied)}")
for record in status.applied:
applied_at = record.applied_at.isoformat() if record.applied_at else "unknown time"
click.echo(f" ✓ {record.version} {record.name} ({applied_at})")
click.echo(f" Pending: {len(status.pending)}")
for migration in status.pending:
click.echo(f" • {migration.version} {migration.name} ({migration.path.name})")
click.echo(f" Failed: {len(status.failed)}")
for record in status.failed:
detail = f": {record.error}" if record.error else ""
click.echo(f" ✗ {record.version} {record.name}{detail}")
click.echo(f" Checksum drift: {len(status.checksum_drifted)}")
for migration, record in status.checksum_drifted:
click.echo(
f" ! {migration.version} {migration.name}: "
f"database={record.checksum or 'unknown'} file={migration.checksum}"
)
click.echo(" pgmq prerequisites:")
click.echo(f" Extension available: {'yes' if status.pgmq_available else 'no'}")
click.echo(f" Extension installed: {'yes' if status.pgmq_installed else 'no'}")
if status.missing_queues:
click.echo(f" Missing queues: {', '.join(status.missing_queues)}")
else:
click.echo(" Missing queues: none")
_STATUS_LABELS = {
DoctorStatus.OK: "PASS",
DoctorStatus.WARN: "WARN",
DoctorStatus.FAIL: "FAIL",
DoctorStatus.SKIP: "SKIP",
}
def _readiness_line(status: DoctorStatus, name: str, detail: str, hint: str | None = None) -> None:
"""Print one readiness check line with an optional remediation hint."""
click.echo(f"[{_STATUS_LABELS[status]}] {name}: {detail}")
if hint and status in {DoctorStatus.WARN, DoctorStatus.FAIL}:
click.echo(f" Hint: {hint}")
def _migration_readiness_results(status: MigrationStatus) -> list[DoctorCheckResult]:
"""Convert migration status into concise readiness check results."""
results = [
DoctorCheckResult(
"migrations:pending",
DoctorStatus.FAIL if status.pending else DoctorStatus.OK,
f"{len(status.pending)} pending migration(s)",
"Run `netengine migrate up` before booting." if status.pending else None,
"migrations",
),
DoctorCheckResult(
"migrations:failed",
DoctorStatus.FAIL if status.failed else DoctorStatus.OK,
f"{len(status.failed)} failed migration record(s)",
(
"Inspect netengine_schema_migrations errors and rerun migrations."
if status.failed
else None
),
"migrations",
),
DoctorCheckResult(
"migrations:checksum-drift",
DoctorStatus.FAIL if status.checksum_drifted else DoctorStatus.OK,
f"{len(status.checksum_drifted)} drifted checksum(s)",
(
"Restore the expected migration files or reconcile database history."
if status.checksum_drifted
else None
),
"migrations",
),
DoctorCheckResult(
"migrations:pgmq",
(
DoctorStatus.OK
if status.pgmq_available and status.pgmq_installed and not status.missing_queues
else DoctorStatus.FAIL
),
(
"pgmq available, installed, and queues present"
if status.pgmq_available and status.pgmq_installed and not status.missing_queues
else "pgmq unavailable/absent or queues missing"
),
(
"Install pgmq and run migrations to create queues."
if not (
status.pgmq_available and status.pgmq_installed and not status.missing_queues
)
else None
),
"migrations",
),
]
return results
async def _check_migration_readiness(db_url: str | None) -> list[DoctorCheckResult]:
"""Inspect database migrations for readiness."""
if not db_url:
return [
DoctorCheckResult(
"migrations:database-url",
DoctorStatus.FAIL,
"NETENGINE_DB_URL/DATABASE_URL is not set",
"Set NETENGINE_DB_URL or DATABASE_URL to a PostgreSQL connection string.",
"migrations",
)
]
service = MigrationService(db_url, MIGRATIONS_DIR)
try:
status = await service.status()
except Exception as exc:
return [
DoctorCheckResult(
"migrations:status",
DoctorStatus.FAIL,
f"unable to inspect migrations: {exc}",
"Verify database connectivity, credentials, and pgmq/Postgres availability.",
"migrations",
)
]
return _migration_readiness_results(status)
def _feature_state_readiness_results(spec: Any) -> list[DoctorCheckResult]:
"""Return readiness warnings/failures for active feature-state fields."""
results: list[DoctorCheckResult] = []
for line in _feature_state_explanations(spec):
status = (
DoctorStatus.FAIL
if ": unsupported " in line or ": reserved " in line
else DoctorStatus.WARN
)
results.append(
DoctorCheckResult(
"feature-state",
status,
line,
(
"Disable this field or use a NetEngine release that supports it."
if status == DoctorStatus.FAIL
else "Review alpha/experimental behavior before relying on it in production."
),
"spec",
required=status == DoctorStatus.FAIL,
)
)
if not results:
results.append(
DoctorCheckResult(
"feature-state",
DoctorStatus.OK,
"no active unsupported or experimental feature-state fields",
group="spec",
)
)
return results
def _required_setup_failed(results: list[DoctorCheckResult]) -> bool:
"""Return True when required setup checks should stop bootstrapping."""
return any(result.status == DoctorStatus.FAIL and result.required for result in results)
def _print_setup_results(results: list[DoctorCheckResult]) -> None:
for result in results:
_readiness_line(result.status, result.name, result.detail, result.hint)
def _setup_host_probes() -> tuple[Any, ...]:
"""Doctor probes that are valid before local Postgres has been started."""
from netengine.diagnostic import preflight as preflight
return (
lambda ctx: preflight._check_python(),
lambda ctx: preflight._check_python_dependencies(),
preflight._check_required_commands,
preflight._check_optional_commands,
lambda ctx: preflight._check_step_version(),
lambda ctx: preflight._check_docker_daemon(),
lambda ctx: preflight._check_compose(),
preflight._check_ports,
preflight._check_filesystem,
preflight._check_docker_conflicts,
lambda ctx: preflight._check_docker_subnet_conflicts(ctx),
)
def _run_setup_host_checks(
db_url: str | None, state_file: Path, spec_subnets: tuple[str, ...]
) -> list[DoctorCheckResult]:
"""Run pre-Postgres setup checks with database probes intentionally omitted."""
ctx = build_context(
db_url,
state_file,
skip_db=True,
spec_subnets=spec_subnets,
)
return run_preflight(ctx, probes=_setup_host_probes())
def _docker_compose_up(services: tuple[str, ...] = ("postgres",)) -> None:
command = ["docker", "compose", "up", "-d", *services]
result = subprocess.run(command, text=True, capture_output=True, check=False)
if result.returncode != 0:
detail = (result.stderr or result.stdout or "docker compose failed").strip()
raise click.ClickException(
"Unable to start required compose services. "
f"Command `{' '.join(command)}` failed: {detail}\n\n"
"Remediation: ensure Docker Desktop/daemon is running, remove stale "
"containers with `netengine down` or `docker compose down`, and retry."
)
def _wait_for_postgres_health(timeout_seconds: float = 120.0, interval: float = 2.0) -> None:
"""Wait until the compose Postgres container reports healthy/running."""
deadline = time.monotonic() + timeout_seconds
last_status = "unknown"
while time.monotonic() < deadline:
result = subprocess.run(
[
"docker",
"inspect",
"--format",
"{{if .State.Health}}{{.State.Health.Status}}{{else}}{{.State.Status}}{{end}}",
"netengine_postgres",
],
text=True,
capture_output=True,
check=False,
)
if result.returncode == 0:
last_status = result.stdout.strip() or "unknown"
if last_status in {"healthy", "running"}:
return
else:
last_status = (result.stderr or result.stdout or "inspect failed").strip()
time.sleep(interval)
raise click.ClickException(
f"Postgres did not become healthy within {timeout_seconds:.0f}s "
f"(last status: {last_status}).\n\n"
"Remediation: run `docker compose ps postgres` and "
"`docker logs netengine_postgres`; verify port 5432 is free and the "
"postgres_data volume is not from an incompatible database version."
)
@click.group()
def cli() -> None:
"""NetEngine — spin up, reload, and tear down authority-autonomous worlds."""
cli.add_command(doctor)
@cli.group()
def migrate() -> None:
"""Manage NetEngine database migrations."""
@migrate.command("up")
def migrate_up() -> None:
"""Apply pending database migrations."""
asyncio.run(_migrate_up())
async def _migrate_up() -> None:
db_url = _require_db_url()
service = MigrationService(db_url, MIGRATIONS_DIR)
click.echo(f"Applying migrations from {MIGRATIONS_DIR}...")
try:
applied = await service.apply_pending()
except Exception as exc:
click.echo(f"Migration failed: {exc}", err=True)
sys.exit(1)
if applied:
click.echo(f"Applied {len(applied)} migration(s):")
for record in applied:
click.echo(f" ✓ {record.version} {record.name}")
else:
click.echo("No pending migrations.")
@migrate.command("status")
def migrate_status_service() -> None:
"""Print applied, pending, failed, and drifted migrations."""
asyncio.run(_migrate_status(exit_on_unhealthy=False))
@migrate.command("check")
def migrate_check_service() -> None:
"""Validate migrations and pgmq prerequisites for CI."""
asyncio.run(_migrate_status(exit_on_unhealthy=True))
async def _migrate_status(*, exit_on_unhealthy: bool) -> None:
db_url = _require_db_url()
service = MigrationService(db_url, MIGRATIONS_DIR)
try:
status = await service.status()
except Exception as exc:
click.echo(f"Unable to inspect migrations: {exc}", err=True)
sys.exit(1)
_print_migration_status(status)
if exit_on_unhealthy:
if status.ok:
click.echo("Migration check passed.")
else:
click.echo("Migration check failed.", err=True)
sys.exit(1)
@cli.command("readiness")
@click.argument("spec_file", type=click.Path(exists=True))
@click.option("--db-url", default=db_url_from_env, help="PostgreSQL URL for migration checks.")
@click.option(
"--state-file",
type=click.Path(path_type=Path),
default=get_state_file,
help="Runtime state file path for host preflight checks.",
)
@click.option(
"--skip-db",
is_flag=True,
help="Skip doctor database probes; migration status is still checked.",
)
@click.option(
"--env",
"environment",
help="Merge spec.{ENV}.yaml next to SPEC_FILE before validating.",
)
@click.option(
"--set",
"set_values",
multiple=True,
metavar="KEY=VALUE",
help="Override a spec value; repeat for multiple dotted keys.",
)
def readiness(
spec_file: str,
db_url: str | None,
state_file: Path,
skip_db: bool,
environment: str | None,
set_values: tuple[str, ...],
) -> None:
"""Validate SPEC_FILE and report host, migration, and feature readiness."""
asyncio.run(_readiness(spec_file, db_url, state_file, skip_db, environment, set_values))
async def _readiness(
spec_file: str,
db_url: str | None,
state_file: Path,
skip_db: bool,
environment: str | None = None,
set_values: tuple[str, ...] = (),
) -> None:
results: list[DoctorCheckResult] = []
try:
spec = _load_spec_for_cli(spec_file, environment=environment, set_values=set_values)
except SpecLoadError as exc:
_readiness_line(
DoctorStatus.FAIL,
"spec",
f"validation failed: {exc}",
"Fix the spec validation error and rerun readiness.",
)
sys.exit(1)
results.append(
DoctorCheckResult(
"spec",
DoctorStatus.OK,
f"validated {spec.metadata.name}",
group="spec",
)
)
ctx = build_context(
db_url,
state_file,
skip_db=skip_db,
spec_subnets=tuple(
str(network.subnet)
for network in spec.substrate.networks.values()
if getattr(network, "subnet", None)
),
)
results.extend(run_preflight(ctx))
results.extend(await _check_migration_readiness(db_url))
results.extend(_feature_state_readiness_results(spec))
click.echo(f"NetEngine readiness summary for {spec.metadata.name}")
counts = {
status: sum(1 for result in results if result.status == status) for status in DoctorStatus
}
click.echo(
"Summary: "
f"{counts[DoctorStatus.OK]} pass, "
f"{counts[DoctorStatus.WARN]} warn, "
f"{counts[DoctorStatus.FAIL]} fail, "
f"{counts[DoctorStatus.SKIP]} skip"
)
for result in results:
_readiness_line(result.status, result.name, result.detail, result.hint)
if any(result.status == DoctorStatus.FAIL and result.required for result in results):
sys.exit(1)
@cli.command()
@click.argument("spec_file", type=click.Path(exists=True))
@click.option(
"--explain",
is_flag=True,
default=False,
help="Print active experimental, reserved, unsupported, or otherwise noteworthy fields.",
)
@click.option(
"--format",
"output_format",
type=click.Choice(["text", "json"]),
default="text",
show_default=True,
help="Emit human-readable text or machine-readable JSON support-matrix results.",
)
@click.option(
"--env",
"environment",
help="Merge spec.{ENV}.yaml next to SPEC_FILE before validating.",
)
@click.option(
"--set",
"set_values",
multiple=True,
metavar="KEY=VALUE",
help="Override a spec value; repeat for multiple dotted keys.",
)
def validate(
spec_file: str,
explain: bool,
output_format: str,
environment: str | None,
set_values: tuple[str, ...],
) -> None:
"""Validate SPEC_FILE without booting a world."""
try:
spec = _load_spec_for_cli(
spec_file,
environment=environment,
set_values=set_values,
validate_feature_states=False,
)
except SpecLoadError as exc:
if output_format == "json":
click.echo(json.dumps({"ok": False, "error": str(exc), "feature_states": []}, indent=2))
else:
click.echo(f"Spec validation failed: {exc}", err=True)
sys.exit(1)
feature_states = _active_feature_state_results(spec)
unsupported = [item for item in feature_states if item["state"] == "unsupported"]
if output_format == "json":
click.echo(
json.dumps(
{
"ok": not unsupported,
"spec": spec.metadata.name,
"feature_states": feature_states,
},
indent=2,
)
)
else:
if unsupported:
click.echo("Spec validation failed: Unsupported spec features enabled:", err=True)
for item in unsupported:
click.echo(
f" - {item['path']} is {item['state']} in {item['stage']}: {item['reason']}",
err=True,
)
else:
click.echo(f"Spec validation succeeded: {spec.metadata.name}")
if explain:
explanations = _feature_state_explanations(spec)
if explanations:
click.echo("Feature-state details:")
for line in explanations:
prefix = "WARNING: " if ": experimental " in line else ""
click.echo(f" - {prefix}{line}")
else:
click.echo("Feature-state details: no active noteworthy fields.")
if unsupported:
sys.exit(1)
@cli.command("setup")
@click.argument("mode", type=click.Choice(["local"]))
@click.argument("spec_file", type=click.Path(exists=True))
@click.option(
"--db-url", default=db_url_from_env, help="PostgreSQL URL for migration and doctor checks."
)
@click.option(
"--state-file",
type=click.Path(path_type=Path),
default=get_state_file,
help="Runtime state file path for host preflight checks.",
)
@click.option(
"--env",
"environment",
help="Merge spec.{ENV}.yaml next to SPEC_FILE before validating.",
)
@click.option(
"--set",
"set_values",
multiple=True,
metavar="KEY=VALUE",
help="Override a spec value; repeat for multiple dotted keys.",
)
@click.option(
"--postgres-timeout",
default=120.0,
show_default=True,
help="Seconds to wait for Postgres health.",
)
def setup(
mode: str,
spec_file: str,
db_url: str | None,
state_file: Path,
environment: str | None,
set_values: tuple[str, ...],
postgres_timeout: float,
) -> None:
"""Guided first-time setup for a local NetEngine world."""
asyncio.run(
_setup_local(spec_file, db_url, state_file, environment, set_values, postgres_timeout)
)
async def _setup_local(
spec_file: str,
db_url: str | None,
state_file: Path,
environment: str | None = None,
set_values: tuple[str, ...] = (),
postgres_timeout: float = 120.0,
) -> None:
try:
spec = _load_spec_for_cli(spec_file, environment=environment, set_values=set_values)
except SpecLoadError as exc:
raise click.ClickException(
f"spec validation failed: {exc}\n\n"
"Remediation: fix the spec validation error and rerun `netengine setup local`."
) from exc
spec_subnets = tuple(
str(network.subnet)
for network in spec.substrate.networks.values()
if getattr(network, "subnet", None)
)
click.echo(f"NetEngine local setup for {spec.metadata.name}")
click.echo("Step 1/5: host checks before Postgres starts")
host_results = _run_setup_host_checks(db_url, state_file, spec_subnets)
_print_setup_results(host_results)
if _required_setup_failed(host_results):
raise click.ClickException(
"required host checks failed; fix the remediation hints above before running `netengine up`."
)
click.echo("Step 2/5: starting compose services")
_docker_compose_up(("postgres",))
click.echo("Step 3/5: waiting for Postgres health")
_wait_for_postgres_health(timeout_seconds=postgres_timeout)
effective_db_url = db_url or _db_url_from_env() or LOCAL_SETUP_DB_URL
click.echo("Step 4/5: running migrations")
try:
await _run_migrations(effective_db_url)
except Exception as exc:
raise click.ClickException(
f"migrations failed: {exc}\n\n"
"Remediation: verify database credentials, inspect `docker logs netengine_postgres`, "
"then rerun `netengine migrate up`."
) from exc
click.echo("Step 5/5: spec-aware doctor checks")
ctx = build_context(
effective_db_url,
state_file,
skip_db=False,
spec_subnets=spec_subnets,
)
readiness_results = []
readiness_results.extend(run_preflight(ctx))
readiness_results.extend(await _check_migration_readiness(effective_db_url))
readiness_results.extend(_feature_state_readiness_results(spec))
_print_setup_results(readiness_results)
if _required_setup_failed(readiness_results):
raise click.ClickException(
"required setup checks failed; NetEngine stopped before `netengine up`. "
"Apply the remediation hints above and rerun `netengine setup local`."
)
click.echo("Setup checks passed; bootstrapping world with existing `netengine up` path.")
await _up(
spec_file,
up_to=9,
mock=False,
skip_migrations=True,
allow_migration_failure=False,
environment=environment,
set_values=set_values,
)
@cli.command()
@click.argument("spec_file", type=click.Path(exists=True))
@click.option("--up-to", default=9, help="Stop after this phase number (0-9).")
@click.option(
"--mock",
is_flag=True,
default=False,
envvar="NETENGINE_MOCK",
help="Run in mock mode (no real Docker/DNS calls).",
)
@click.option(
"--skip-migrations",
is_flag=True,
default=False,
help="Skip running database migrations on startup.",
)
@click.option(
"--allow-migration-failure",
is_flag=True,
default=False,
help="Continue booting if database migrations fail (development escape hatch).",
)
@click.option(
"--env",
"environment",
help="Merge spec.{ENV}.yaml next to SPEC_FILE before booting.",
)
@click.option(
"--set",
"set_values",
multiple=True,
metavar="KEY=VALUE",
help="Override a spec value; repeat for multiple dotted keys.",
)
def up(
spec_file: str,
up_to: int,
mock: bool,
skip_migrations: bool,
allow_migration_failure: bool,
environment: str | None,
set_values: tuple[str, ...],
) -> None:
"""Boot a world from SPEC_FILE."""
asyncio.run(
_up(
spec_file,
up_to,
mock,
skip_migrations,
allow_migration_failure,
environment,
set_values,
)
)
async def _up(
spec_file: str,
up_to: int,
mock: bool,
skip_migrations: bool,
allow_migration_failure: bool = False,
environment: str | None = None,
set_values: tuple[str, ...] = (),
) -> None:
spec = _load_spec_for_cli(spec_file, environment=environment, set_values=set_values)
if mock:
click.echo("WARNING: running in mock mode — no real infrastructure will be created.")
if not skip_migrations and not mock:
db_url = _db_url_from_env()
if db_url:
try:
await _run_migrations(db_url)
except Exception as exc:
if allow_migration_failure:
logger.warning(f"Migrations failed (continuing anyway): {exc}")
else:
message = f"Migrations failed: {exc}"
logger.error(message)
click.echo(message, err=True)
sys.exit(1)
orchestrator = Orchestrator(spec, mock_mode=mock)
click.echo(f"Booting world from {spec_file} (phases 0–{up_to})…")
import time
_phase_start_times: dict[int, float] = {}
def _on_start(phase_num: int, phase_name: str) -> None:
_phase_start_times[phase_num] = time.monotonic()
click.echo(f" ⧗ Phase {phase_num}: {phase_name}…")
def _on_complete(phase_num: int, phase_name: str) -> None:
elapsed = time.monotonic() - _phase_start_times.get(phase_num, time.monotonic())
click.echo(
click.style(f" ✓ Phase {phase_num}: {phase_name}", fg="green")
+ click.style(f" ({elapsed:.1f}s)", fg="bright_black")
)
def _on_skip(phase_num: int, phase_name: str) -> None:
click.echo(
click.style(
f" – Phase {phase_num}: {phase_name} (already done)",
fg="bright_black",
)
)
def _on_error(phase_num: int, phase_name: str, exc: Exception) -> None:
click.echo(
click.style(f" ✗ Phase {phase_num}: {phase_name} — {exc}", fg="red", bold=True),
err=True,
)
try:
await orchestrator.execute_phases(
up_to_phase=up_to,
on_phase_start=_on_start,
on_phase_complete=_on_complete,
on_phase_skip=_on_skip,
on_phase_error=_on_error,
)
except Exception as exc:
click.echo(f"Bootstrap failed: {exc}", err=True)
sys.exit(1)
click.echo("World bootstrapped.")
_print_status(orchestrator.runtime_state)
# Start background consumers if any were registered
if orchestrator.consumer_supervisor.consumers:
logger.info("Starting background consumers (Ctrl+C to stop).")
await orchestrator.start_consumers()
try:
await asyncio.sleep(float("inf"))
except (KeyboardInterrupt, asyncio.CancelledError):
pass
finally:
await orchestrator.consumer_supervisor.stop_all()
logger.info("Consumers stopped.")
@cli.group()
def migrate() -> None:
"""Inspect and apply database migrations."""
@migrate.command("run")
def migrate_run() -> None:
"""Apply pending database migrations."""
db_url = os.environ.get("NETENGINE_DB_URL") or os.environ.get("DATABASE_URL")
if not db_url:
click.echo("No database URL configured for migrations", err=True)
sys.exit(2)
try:
asyncio.run(_run_migrations(db_url))
except Exception as exc:
click.echo(f"Migrations failed: {exc}", err=True)
sys.exit(1)
@migrate.command("status")
def migrate_status() -> None:
"""Show database migration status without applying migrations."""
db_url = os.environ.get("NETENGINE_DB_URL") or os.environ.get("DATABASE_URL")
if not db_url:
click.echo("No database URL configured for migrations", err=True)
sys.exit(2)
try:
report = asyncio.run(migration_status(db_url))
except Exception as exc:
click.echo(f"Migration status failed: {exc}", err=True)
sys.exit(1)
for migration in report.results:
click.echo(f"{migration.status}: {migration.filename}")
click.echo(
f"Migrations status: {report.applied_count} applied, "
f"{report.pending_count} pending, {report.failed_count} failed, "
f"{report.drifted_count} drifted"
)
@migrate.command("check")
def migrate_check() -> None:
"""Exit non-zero when migrations are pending, failed, or drifted."""
db_url = os.environ.get("NETENGINE_DB_URL") or os.environ.get("DATABASE_URL")
if not db_url:
click.echo("No database URL configured for migrations", err=True)
sys.exit(2)
try:
report = asyncio.run(migration_status(db_url))
except Exception as exc:
click.echo(f"Migration check failed: {exc}", err=True)
sys.exit(1)
if report.pending_count or report.failed_count or report.drifted_count:
click.echo(
f"Migrations not current: {report.pending_count} pending, "
f"{report.failed_count} failed, {report.drifted_count} drifted"
)
sys.exit(1)
click.echo("Migrations current.")
@cli.command()
@click.argument("spec_file", type=click.Path(exists=True))
def reload(spec_file: str) -> None:
"""Diff SPEC_FILE against the running world and apply changes."""
from netengine.core.reload import apply_reload
from netengine.spec.models import NetEngineSpec
state = RuntimeState.load()
if not state.world_spec:
click.echo("No running world found — use `netengine up` first.", err=True)
sys.exit(1)
new_spec = load_spec(spec_file)
try: