Repository navigation
Expand file tree
/
Copy pathdev2-site
More file actions
executable file
·2110 lines (1961 loc) · 141 KB
/
Copy pathdev2-site
File metadata and controls
executable file
·2110 lines (1961 loc) · 141 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
#!/usr/bin/env python3
"""
dev2-site: move a Railway-hosted site onto dev2 and keep it deploying on merge.
dev2-site registry rebuild sites.json from Railway (the truth)
dev2-site list [--kind pg|none|supabase|turso]
dev2-site show <site>
dev2-site scaffold <site> deploy-dev2.yml (+ .nixpacks Dockerfile) in the repo, as a PR
dev2-site provision <site> ~/www/<site> on dev2: env, compose, deploy script, deploy key, secrets
dev2-site db <site> database in the shared cluster + copy from Railway Postgres
dev2-site volumes <site> copy Railway volume contents into ~/www/<site>/volumes
dev2-site deploy <site> [ref] build + start on dev2 (as the deploy account)
dev2-site cert <site> Let's Encrypt via Porkbun DNS-01, before DNS moves
dev2-site vhost <site> nginx server block -> 127.0.0.1:<port>
dev2-site limits <site>... | --all [--dry-run] [--no-recreate]
mem_limit = memswap_limit on every container (sites.d
mem_limit / mem_limits / node_heap_mb), applied live
dev2-site healthchecks <site>... | --all [--dry-run] [--no-recreate]
a healthcheck on every app (bun/node GET, any status
under 500) and redis container, so watchdog-autoheal
can restart a wedged one; kept across re-renders
dev2-site verify <site> [--public] curl the site through nginx (pinned to dev2, or via DNS)
dev2-site dns <site> flip every domain at Porkbun to dev2
dev2-site railway-stop <site> remove Railway deployments + disconnect the repo watch
dev2-site merge <site> merge the scaffold PR (CI then deploys the default branch)
dev2-site migrate <site> all of the above, in order, resumable
dev2-site retire <site> --yes delete the Railway services (only after migrate)
dev2-site supabase-services <site> [--dry-run]
drop (or restore) a Supabase stack's optional services
(studio meta imgproxy supavisor realtime functions;
sites.d keep_services)
Run from dev1. dev2 is production: this tool is the only thing that writes to it,
and everything it writes is derived from Railway + these templates, so a re-run
reproduces the box. State per site lives in ~/.local/state/dev2-fleet/<site>.json.
"""
import argparse
import base64
import datetime as dt
import difflib
import glob
import html
import html.parser
import json
import os
import re
import secrets
import shlex
import shutil
import subprocess
import sys
import tempfile
import time
import urllib.parse
import urllib.request
HERE = os.path.dirname(os.path.realpath(__file__))
TEMPLATES = os.path.join(HERE, "templates")
REGISTRY = os.path.join(HERE, "sites.json")
OVERRIDES = os.path.join(HERE, "sites.overrides.json")
STATE_DIR = os.path.expanduser(os.environ.get("DEV2_STATE_DIR", "~/.local/state/dev2-fleet"))
DEV2_HOST = os.environ.get("DEV2_HOST", "dev2.profullstack.com")
DEV2_IP = os.environ.get("DEV2_IP", "23.95.228.174")
DEPLOY_USER = "anthony"
# When dev2's provider blocks this box (it happened after too many parallel sessions),
# DEV2_JUMP=<ssh host> routes every ssh through a jump host and DEV2_PROBE=<ssh host>
# runs the public curl checks from there.
DEV2_JUMP = os.environ.get("DEV2_JUMP", "")
DEV2_PROBE = os.environ.get("DEV2_PROBE", "")
SSH_BASE = ["ssh", "-o", "BatchMode=yes", "-o", "ConnectTimeout=25"] + (["-J", DEV2_JUMP] if DEV2_JUMP else [])
SSH_BASE_STR = " ".join(map(shlex.quote, SSH_BASE))
WWW = f"/home/{DEPLOY_USER}/www"
SRC_ROOT = os.path.expanduser("~/src/profullstack")
CLUSTER_ENV = "/home/anthony/www/crawlproof.com/supabase/.env" # the shared Supabase cluster
PG_CONTAINER = "supabase-db"
WORKSPACE_ID = "50db2758-e580-4af6-b904-366b6bb2a71b"
FIRST_PORT = 3200
RAILWAY_SSH_KEY = os.path.expanduser("~/.ssh/id_ed25519")
ACME_EMAIL = "anthony@profullstack.com"
# ------------------------------------------------------------------ utils
def log(msg): print(f"\n===> {msg}", file=sys.stderr, flush=True)
def note(msg): print(f" {msg}", file=sys.stderr, flush=True)
def warn(msg): print(f"WARNING: {msg}", file=sys.stderr, flush=True)
def die(msg, code=1):
print(f"ERROR: {msg}", file=sys.stderr, flush=True); sys.exit(code)
def sh(cmd, check=True, input=None, capture=True, env=None, timeout=None):
"""Run a command (list or string). Returns stdout (str) when capture."""
if isinstance(cmd, str):
cmd = ["bash", "-o", "pipefail", "-c", cmd]
p = subprocess.run(cmd, input=input, text=True, capture_output=capture, env=env, timeout=timeout)
if check and p.returncode != 0:
raise RuntimeError(f"command failed ({p.returncode}): {cmd if isinstance(cmd, str) else ' '.join(map(shlex.quote, cmd))}\n{(p.stdout or '')[-1500:]}\n{(p.stderr or '')[-2000:]}")
return p.stdout if capture else ""
def ssh(user, cmd, input=None, check=True, timeout=None):
argv = SSH_BASE + [f"{user}@{DEV2_HOST}", cmd]
for attempt in range(3): # sshd drops attempts under parallel load (exit 255); retry those only
p = subprocess.run(argv, input=input, text=True, capture_output=True, timeout=timeout)
if p.returncode != 255 or attempt == 2: break
time.sleep(3 * (attempt + 1))
if check and p.returncode != 0:
raise RuntimeError(f"command failed ({p.returncode}): {' '.join(map(shlex.quote, argv))}\n{(p.stdout or '')[-1500:]}\n{(p.stderr or '')[-2000:]}")
return p.stdout
def ssh_put(content, path, mode="0644", owner=None, user="root"):
"""Write a file on dev2 from stdin: temp file beside the target, then an atomic move."""
q = shlex.quote(path)
chown = f" && chown {shlex.quote(owner)} {q}.tmp" if owner else ""
ssh(user, f"umask 077 && cat > {q}.tmp && chmod {mode} {q}.tmp{chown} && mv -f {q}.tmp {q}", input=content)
def state_path(site): return os.path.join(STATE_DIR, f"{site}.json")
def load_state(site):
p = state_path(site)
return json.load(open(p)) if os.path.exists(p) else {"site": site, "steps": {}}
def save_state(site, st):
os.makedirs(STATE_DIR, mode=0o700, exist_ok=True)
tmp = state_path(site) + ".tmp"
with open(tmp, "w") as f: json.dump(st, f, indent=1); f.write("\n")
os.chmod(tmp, 0o600); os.replace(tmp, state_path(site))
def mark(site, step, **extra):
st = load_state(site); st["steps"][step] = dt.datetime.now(dt.timezone.utc).isoformat(timespec="seconds")
st.update(extra); save_state(site, st)
def tmpl(name):
with open(os.path.join(TEMPLATES, name)) as f: return f.read()
# ---------------------------------------------------------------- railway
def rw_token():
cfg = json.load(open(os.path.expanduser("~/.railway/config.json")))
exp = cfg.get("user", {}).get("tokenExpiresAt", 0)
if isinstance(exp, str):
exp = int(dt.datetime.fromisoformat(exp.replace("Z", "+00:00")).timestamp())
if exp < time.time() + 300:
subprocess.run(["railway", "whoami"], capture_output=True)
cfg = json.load(open(os.path.expanduser("~/.railway/config.json")))
tok = cfg.get("user", {}).get("accessToken")
if not tok: die("no Railway token: run `railway login`")
return tok
def gql(query, variables=None, retries=4):
body = json.dumps({"query": query, "variables": variables or {}}).encode()
for attempt in range(retries):
req = urllib.request.Request("https://backboard.railway.com/graphql/v2", data=body, headers={
"Authorization": f"Bearer {rw_token()}", "Content-Type": "application/json", "User-Agent": "dev2-site"})
try:
with urllib.request.urlopen(req, timeout=120) as r: out = json.load(r)
except urllib.error.HTTPError as e:
out = {"errors": [{"message": f"http {e.code}: {e.read()[:300]!r}"}]}
if "errors" in out:
msg = json.dumps(out["errors"])
if "Too many" in msg or "Not Authorized" in msg and attempt < retries - 1:
time.sleep(5 * (attempt + 1)); subprocess.run(["railway", "whoami"], capture_output=True); continue
raise RuntimeError(f"railway api: {msg[:800]}")
return out["data"]
raise RuntimeError("railway api: gave up")
def rw_variables(pid, eid, sid):
return gql("query($p:String!,$e:String!,$s:String!){variables(projectId:$p,environmentId:$e,serviceId:$s)}",
{"p": pid, "e": eid, "s": sid})["variables"] or {}
def parse_env_file(text):
"""A compose env file as `render_env` writes it (double-quoted values may hold newlines)."""
out, key, buf = {}, None, None
for line in text.split("\n"):
if key is not None:
buf += "\n" + line
if line.endswith('"') and not line.endswith('\\"'):
out[key] = buf[1:-1].replace('\\"', '"').replace("\\\\", "\\"); key, buf = None, None
continue
if not line or line.startswith("#") or "=" not in line: continue
k, v = line.split("=", 1)
if v.startswith('"') and not (v.endswith('"') and len(v) > 1 and not v.endswith('\\"')): key, buf = k, v; continue
if v.startswith('"') and v.endswith('"') and len(v) > 1: v = v[1:-1].replace('\\"', '"').replace("\\\\", "\\")
out[k] = v
return out
def site_variables(s, sid=None, envfile="app.env"):
"""The service's environment: Railway while the service exists, else the live app.env on
dev2 (a retired service has no variables left anywhere else). Values from dev2 are already
the rendered ones, which is what a re-render should start from."""
vars_ = {}
# A site born on dev2 has no Railway project: never ask Railway (its token may be gone).
if s.get("project_id"):
try: vars_ = rw_variables(s["project_id"], s["environment_id"], sid or s["service_id"])
except RuntimeError as e: warn(f"railway variables: {str(e)[:120]}")
if vars_: return vars_
txt = ssh("root", f"cat {WWW}/{shlex.quote(s['site'])}/{shlex.quote(envfile)} 2>/dev/null", check=False)
if not txt.strip():
# A site born on dev2 (sites.d "project": null) has never had Railway variables;
# start it from nothing and let env_overrides, db-create and the vault fill it.
if not s.get("project_id"):
note(f"{s['site']}: no Railway project and no {envfile} yet; starting from env_overrides"); return {}
die(f"{s['site']}: no variables on Railway and no {envfile} on dev2 to fall back to")
note(f"{s['site']}: Railway has no variables (service retired); using the live {envfile} from dev2")
return parse_env_file(txt)
def rw_ssh_user(pid, eid, service_name):
out = sh(["railway", "ssh", "config", "--dry-run", "-i", RAILWAY_SSH_KEY, "--project", pid,
"--environment", eid, "--service", service_name])
m = re.search(r"^\s*User\s+(\S+)", out, re.M)
if not m: die(f"railway ssh config gave no User for {service_name}")
return m.group(1)
def rw_ssh_cmd(user, remote_cmd):
"""The ssh argv that runs remote_cmd inside a Railway container."""
return ["ssh", "-o", "StrictHostKeyChecking=accept-new", "-o", f"UserKnownHostsFile={os.path.expanduser('~/.ssh/known_hosts_railway')}",
"-o", "ServerAliveInterval=30", "-o", "LogLevel=ERROR", "-i", RAILWAY_SSH_KEY, "-l", user, "ssh.railway.com", remote_cmd]
def rw_deployments(pid, eid, sid, first=10):
d = gql("query($p:String!,$e:String!,$s:String!,$n:Int!){deployments(first:$n,input:{projectId:$p,environmentId:$e,serviceId:$s}){edges{node{id status createdAt}}}}",
{"p": pid, "e": eid, "s": sid, "n": first})
return [e["node"] for e in d["deployments"]["edges"]]
# --------------------------------------------------------------- registry
DB_HOST_KINDS = (
(re.compile(r"postgres(ql)?://[^\s]*railway\.internal"), "pg"),
(re.compile(r"postgres(ql)?://[^\s]*\.rlwy\.net"), "pg"),
(re.compile(r"\.supabase\.co"), "supabase"),
(re.compile(r"libsql://|\.turso\.io"), "turso"),
(re.compile(r"postgres(ql)?://"), "pg-ext"),
)
def classify_db(vars_):
kinds = set()
for k, v in vars_.items():
if not isinstance(v, str): continue
if re.search(r"REDIS", k): continue
for rx, kind in DB_HOST_KINDS:
if rx.search(v):
kinds.add(kind); break
for pref in ("pg", "supabase", "turso", "pg-ext"):
if pref in kinds: return pref, sorted(kinds)
return "none", []
def uses_redis(vars_):
return any("redis" in str(v).lower() and "railway.internal" in str(v) for v in vars_.values())
def primary_domain(domains):
customs = [d for d in domains if not d.endswith(".up.railway.app")]
if not customs: return None
apex = [d for d in customs if d.count(".") == 1 and not d.startswith("www.")]
if apex: return apex[0]
nonwww = [d for d in customs if not d.startswith("www.") and not d.startswith("*.")]
return (nonwww or customs)[0]
def slug(name):
return re.sub(r"[^a-z0-9]+", "-", name.lower()).strip("-")
def infra_role(src):
img = (src or {}).get("image") or ""
repo = (src or {}).get("repo") or ""
if re.match(r"(ghcr\.io/railwayapp-templates/postgres|postgres:|.*supabase-postgres)", img): return "pg"
if re.match(r"redis", img): return "redis"
if repo == "6ixfalls/supabase" or "postgres-meta" in img: return "supabase-infra"
return "app"
def cmd_registry(args):
log("Reading every project, service, domain, volume and database variable from Railway")
ws = gql("query($w:String!){workspace(workspaceId:$w){projects{edges{node{id name environments{edges{node{id name}}} services{edges{node{id name serviceInstances{edges{node{environmentId source{repo image} domains{serviceDomains{domain} customDomains{domain}}}}}}}} volumes{edges{node{id name volumeInstances{edges{node{serviceId environmentId mountPath currentSizeMB}}}}}}}}}}}",
{"w": WORKSPACE_ID})["workspace"]["projects"]["edges"]
overrides = json.load(open(OVERRIDES)) if os.path.exists(OVERRIDES) else {}
old = json.load(open(REGISTRY)) if os.path.exists(REGISTRY) else {"sites": {}}
used_ports = {s["port"] for s in old["sites"].values() if s.get("port")}
used_ports |= {3010, 3020, 3100, 5432, 6379, 6543, 8000}
sites = {}
for pe in ws:
p = pe["node"]
envs = {e["node"]["id"]: e["node"]["name"] for e in p["environments"]["edges"]}
prod = [k for k, v in envs.items() if v == "production"] or list(envs)
if not prod: continue
eid = prod[0]
mounts = {}
for ve in p["volumes"]["edges"]:
for vi in ve["node"]["volumeInstances"]["edges"]:
n = vi["node"]
if n["environmentId"] != eid: continue
mounts.setdefault(n["serviceId"], []).append({"name": ve["node"]["name"], "id": ve["node"]["id"], "mountPath": n["mountPath"], "sizeMB": round(n["currentSizeMB"] or 0)})
svcs = []
for se in p["services"]["edges"]:
s = se["node"]
inst = [i["node"] for i in s["serviceInstances"]["edges"] if i["node"]["environmentId"] == eid]
if not inst: continue
i = inst[0]
doms = [d["domain"] for d in (i["domains"] or {}).get("customDomains", [])] + [d["domain"] for d in (i["domains"] or {}).get("serviceDomains", [])]
try: vars_ = rw_variables(p["id"], eid, s["id"])
except RuntimeError as e: warn(f"{p['name']}/{s['name']}: variables: {e}"); vars_ = {}
kind, kinds = classify_db(vars_)
db_host = redis_host = None
for v in vars_.values():
if not isinstance(v, str): continue
m = re.search(r"postgres(?:ql)?://[^@\s]*@([a-z0-9.-]+\.railway\.internal)", v)
if m and not db_host: db_host = m.group(1)
m = re.search(r"redis://[^@\s]*@?([a-z0-9.-]+\.railway\.internal)", v)
if m and not redis_host: redis_host = m.group(1)
svcs.append({"db_host": db_host, "redis_host": redis_host, "id": s["id"], "name": s["name"], "role": infra_role(i["source"]), "repo": (i["source"] or {}).get("repo"),
"image": (i["source"] or {}).get("image"), "domains": doms, "volumes": mounts.get(s["id"], []),
"db": kind, "db_kinds": kinds, "redis": uses_redis(vars_), "nvars": len(vars_),
"port_var": vars_.get("PORT") if isinstance(vars_.get("PORT"), str) and vars_.get("PORT", "").isdigit() else None})
apps = [s for s in svcs if s["role"] == "app"]
infra = [s for s in svcs if s["role"] != "app"]
# One site per app service that has a custom domain; same-repo, domain-less
# app services in the same project ride along as companions (workers).
fronts = [s for s in apps if primary_domain(s["domains"])]
orphans = [s for s in apps if not primary_domain(s["domains"])]
for s in fronts:
site = primary_domain(s["domains"])
comps = [o for o in orphans if o["repo"] and o["repo"] == s["repo"]]
shared_repo = sum(1 for f in fronts if f["repo"] == s["repo"]) > 1
entry = {
"site": site, "project": p["name"], "project_id": p["id"], "environment_id": eid,
"service": s["name"], "service_id": s["id"], "repo": s["repo"], "image": s["image"],
"domains": [d for d in s["domains"] if not d.endswith(".up.railway.app")],
"railway_domains": [d for d in s["domains"] if d.endswith(".up.railway.app")],
"db": s["db"], "db_kinds": s["db_kinds"], "redis": s["redis"], "volumes": s["volumes"], "port_var": s["port_var"],
"companions": [{"name": c["name"], "id": c["id"], "volumes": c["volumes"], "db": c["db"], "redis": c["redis"]} for c in comps],
"db_host": s["db_host"], "redis_host": s["redis_host"],
# Data services that belong to this site: in a one-app project all of them,
# otherwise the ones whose internal hostname (service name slug) the app points at.
"infra": [{"name": i["name"], "id": i["id"], "role": i["role"], "image": i["image"], "volumes": i["volumes"]} for i in infra
if len(fronts) == 1 or slug(i["name"]) in {(s["db_host"] or "").split(".")[0], (s["redis_host"] or "").split(".")[0]}],
"shared_repo": shared_repo,
}
entry.update(overrides.get(site, {}))
prev = old["sites"].get(site, {})
port = entry.get("port") or prev.get("port")
if not port:
port = FIRST_PORT
while port in used_ports: port += 1
used_ports.add(port); entry["port"] = port
for k in ("status", "notes", "moved_at"):
if k in prev and k not in entry: entry[k] = prev[k]
sites[site] = entry
for o in orphans:
if not any(o["repo"] and o["repo"] == f["repo"] for f in fronts):
note(f"{p['name']}/{o['name']}: app service with no custom domain and no same-repo front; skipped (add to sites.overrides.json to include)")
reg = {"generated_at": dt.datetime.now(dt.timezone.utc).isoformat(timespec="seconds"), "dev2": {"host": DEV2_HOST, "ip": DEV2_IP},
"sites": dict(sorted(sites.items()))}
with open(REGISTRY, "w") as f: json.dump(reg, f, indent=1); f.write("\n")
log(f"{len(sites)} sites -> {REGISTRY}")
cmd_list(argparse.Namespace(kind=None, status=None))
def registry():
if not os.path.exists(REGISTRY): die("no sites.json: run `dev2-site registry`")
return json.load(open(REGISTRY))
SITES_D = os.path.join(HERE, "sites.d")
# ── Secrets ─────────────────────────────────────────────────────────────────
# sites.d/ is committed, and cli-tools is a public repository, so a value that
# is a credential never goes in it. It goes here -- 0600, outside every
# checkout, the same file `cli-tools config` already writes -- and sites.d
# carries "secret:<KEY>" in its place.
CREDENTIALS = os.path.expanduser("~/.config/cli-tools/credentials.json")
def credentials():
try:
with open(CREDENTIALS) as f: return json.load(f)
except FileNotFoundError: return {}
def cred(*names):
"""First of `names` present in credentials.json, then the environment. The
file holds both shapes it has accumulated: a bare string and {"value": ...}."""
c = credentials()
for n in names:
v = c.get(n)
if isinstance(v, dict): v = v.get("value")
if v: return v
return os.environ.get(names[-1])
def put_cred(name, value):
c = credentials(); c[name] = value
os.makedirs(os.path.dirname(CREDENTIALS), exist_ok=True)
fd = os.open(CREDENTIALS, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
with os.fdopen(fd, "w") as f: json.dump(c, f, indent=1, sort_keys=True); f.write("\n")
os.chmod(CREDENTIALS, 0o600)
SECRET_REF = re.compile(r"^secret:([A-Za-z0-9_]+)$")
# What must never be written into sites.d. The cutover also marks the values it
# knows to be secret by provenance; this is the backstop for everything else,
# because the cost of a wrong guess is one extra entry in credentials.json and
# the cost of the opposite is a published key.
SECRET_KEY = re.compile(r"SECRET|PASSWORD|PASSWD|TOKEN|APIKEY|CREDENTIAL|DATABASE_URL|_DSN|_KEY$", re.I)
def resolved_env_overrides(s):
"""env_overrides with every "secret:<KEY>" replaced by its value."""
out = {}
for k, v in (s.get("env_overrides") or {}).items():
m = SECRET_REF.match(v) if isinstance(v, str) else None
if not m: out[k] = v; continue
name = m.group(1)
val = cred(f"{s['site']}.{name}", name)
if not val:
die(f"{s['site']}: env_overrides[{k}] is {v!r}, but neither "
f'"{s["site"]}.{name}" nor "{name}" is in {CREDENTIALS}.\n'
f" Add it there (0600, outside every checkout). sites.d/ is committed to a\n"
f" public repository, so the value itself must not go back into it.")
out[k] = val
return out
def with_overrides(s):
"""sites.d/<site>.json is merged over the registry entry: one small file per site,
so parallel migrations never edit a shared file. Keys are the entry's keys
(port, health_path, start_command, companion_commands, env_overrides, pg_service, proxies,
nginx_locations (raw location blocks, __APP_PORT__ substituted, placed before `location /`),
db, db_host, infra, branch, max_body, notes, keep_services (Supabase optional services to run))."""
p = os.path.join(SITES_D, f"{s['site']}.json")
if os.path.exists(p):
s = dict(s); s.update(json.load(open(p)))
return s
def site(name):
reg = registry()
if name in reg["sites"]: return with_overrides(reg["sites"][name])
# allow a service name or a repo tail
for s in reg["sites"].values():
if s["service"] == name or (s["repo"] or "").split("/")[-1] == name: return with_overrides(s)
# A site that never lived on Railway (bittorrented.com: only its Supabase is
# here) has no registry row; its sites.d file is then the whole entry.
p = os.path.join(SITES_D, f"{name}.json")
if os.path.exists(p):
s = json.load(open(p))
if s.get("site") == name: return s
die(f"unknown site {name!r}; `dev2-site list`")
def cmd_list(args):
reg = registry()
rows = [with_overrides(s) for s in reg["sites"].values() if (not args.kind or with_overrides(s)["db"] == args.kind)]
def status(s):
st = load_state(s["site"])["steps"]
if "retire" in st: return "retired"
if "verify-public" in st: return "on-dev2"
if "dns" in st: return "dns-flipped"
if st: return f"{len(st)} steps"
return "-"
rows = [s for s in rows if not getattr(args, "status", None) or status(s) == args.status]
print(f"{'site':<34} {'port':>5} {'db':<9} {'redis':<5} {'vols':<4} {'comp':<4} {'status':<12} repo")
for s in rows:
print(f"{s['site']:<34} {s['port']:>5} {s['db']:<9} {'y' if s['redis'] else '-':<5} {len(s['volumes']) or '-':<4} {len(s['companions']) or '-':<4} {status(s):<12} {s['repo'] or s['image']}")
print(f"{len(rows)} sites")
def cmd_show(args):
print(json.dumps(site(args.site), indent=1)); print(json.dumps(load_state(args.site), indent=1))
# ------------------------------------------------------------ local repo
def checkout_dir(s):
repo = s["repo"]
if not repo: die(f"{s['site']} is image-only ({s['image']}); nothing to scaffold")
org, name = repo.split("/")
cands = [f"{SRC_ROOT}/{name}", f"{SRC_ROOT}/{name}.com", f"{SRC_ROOT}/{name.removesuffix('.com')}",
os.path.expanduser(f"~/src/{org}/{name}"), os.path.expanduser(f"~/src/{name}")]
for c in cands:
if os.path.isdir(os.path.join(c, ".git")): return c
dest = f"{SRC_ROOT}/{name}" if org == "profullstack" else os.path.expanduser(f"~/src/{org}/{name}")
log(f"Cloning {repo} -> {dest}")
os.makedirs(os.path.dirname(dest), exist_ok=True)
sh(["gh", "repo", "clone", repo, dest, "--", "-q"])
return dest
def default_branch(repo):
return sh(["gh", "api", f"repos/{repo}", "--jq", ".default_branch"]).strip()
def repo_config(d):
"""rootDirectory-free reading of railway.json/toml for healthcheckPath, dockerfilePath, startCommand."""
cfg = {}
for fn in ("railway.json", "railway.toml"):
p = os.path.join(d, fn)
if not os.path.exists(p): continue
txt = open(p).read()
for key in ("healthcheckPath", "dockerfilePath", "startCommand"):
m = re.search(rf'"?{key}"?\s*[:=]\s*"([^"]+)"', txt)
if m: cfg[key] = m.group(1)
return cfg
def find_dockerfile(d, cfg):
if cfg.get("dockerfilePath") and os.path.exists(os.path.join(d, cfg["dockerfilePath"])): return cfg["dockerfilePath"]
for c in ("Dockerfile", "docker/Dockerfile", "apps/web/Dockerfile"):
if os.path.exists(os.path.join(d, c)): return c
if os.path.exists(os.path.join(d, ".nixpacks", "Dockerfile")): return ".nixpacks/Dockerfile"
return None
def dockerfile_port(checkout, dockerfile):
"""The port the image expects when Railway set none: HEALTHCHECK's localhost:<port>
first (that is what Docker will probe), else the first EXPOSE."""
if not checkout or not dockerfile: return None
p = os.path.join(checkout, dockerfile)
if not os.path.exists(p): return None
txt = open(p).read()
m = re.search(r"HEALTHCHECK[^\n]*?(?:localhost|127\.0\.0\.1|0\.0\.0\.0):(\d{2,5})", txt, re.S)
if m: return m.group(1)
m = re.search(r"^EXPOSE\s+(\d{2,5})", txt, re.M)
return m.group(1) if m else None
def workflow_name(s):
return "deploy-dev2.yml" if not s.get("shared_repo") else f"deploy-dev2-{s['site'].replace('.', '-')}.yml"
def health_url(s, cfg):
hp = s.get("health_path") or cfg.get("healthcheckPath") or "/"
return f"https://{s['site']}{hp}", hp
def cmd_scaffold(args):
s = site(args.site)
d = checkout_dir(s)
branch = s.get("branch") or default_branch(s["repo"])
log(f"Scaffold {s['site']}: {s['repo']}@{branch} in {d}")
sh(["git", "-C", d, "fetch", "-q", "origin", branch])
wt = tempfile.mkdtemp(prefix=f"dev2-{s['site']}-", dir=os.path.join(d, ".claude", "worktrees") if os.path.isdir(os.path.join(d, ".claude", "worktrees")) else os.environ.get("CLAUDE_JOB_DIR", tempfile.gettempdir()))
os.rmdir(wt)
wbranch = f"ops/dev2-deploy" if not s.get("shared_repo") else f"ops/dev2-deploy-{s['site'].replace('.', '-')}"
sh(["git", "-C", d, "worktree", "add", "-q", "-B", wbranch, wt, f"origin/{branch}"])
try:
cfg = repo_config(wt)
# Railway keeps build settings in service variables too: a custom Dockerfile path and
# the railpack/nixpacks command overrides. Honour them before guessing.
rvars = rw_variables(s["project_id"], s["environment_id"], s["service_id"])
if rvars.get("RAILWAY_DOCKERFILE_PATH") and os.path.exists(os.path.join(wt, rvars["RAILWAY_DOCKERFILE_PATH"])):
cfg["dockerfilePath"] = rvars["RAILWAY_DOCKERFILE_PATH"]
for rk, nk in (("RAILPACK_INSTALL_CMD", "NIXPACKS_INSTALL_CMD"), ("RAILPACK_BUILD_CMD", "NIXPACKS_BUILD_CMD"), ("RAILPACK_START_CMD", "NIXPACKS_START_CMD"),
("NIXPACKS_INSTALL_CMD", "NIXPACKS_INSTALL_CMD"), ("NIXPACKS_BUILD_CMD", "NIXPACKS_BUILD_CMD"), ("NIXPACKS_START_CMD", "NIXPACKS_START_CMD"), ("NIXPACKS_NODE_VERSION", "NIXPACKS_NODE_VERSION")):
if isinstance(rvars.get(rk), str) and rvars[rk]: cfg[nk] = rvars[rk]
if getattr(args, "regen", False) and os.path.isdir(os.path.join(wt, ".nixpacks")):
shutil.rmtree(os.path.join(wt, ".nixpacks")); note("removed the previous .nixpacks to regenerate it")
df = find_dockerfile(wt, cfg)
if not df:
log("No Dockerfile: generating one with nixpacks (the same builder Railway used)")
nix = shutil.which("nixpacks") or os.path.expanduser("~/.local/bin/nixpacks")
env = dict(os.environ)
if cfg.get("startCommand"): env["NIXPACKS_START_CMD"] = cfg["startCommand"]
# nixpacks reads NIXPACKS_* from the build environment it is given (--env), not
# from its own process environment; the default Node 18 is too old for Next 16.
node_v = s.get("node_version") or cfg.get("NIXPACKS_NODE_VERSION") or "22"
nix_env = [f"NIXPACKS_NODE_VERSION={node_v}"]
if s.get("start_command"): cfg["NIXPACKS_START_CMD"] = s["start_command"]
if cfg.get("startCommand") and not cfg.get("NIXPACKS_START_CMD"): cfg["NIXPACKS_START_CMD"] = cfg["startCommand"]
for k in ("NIXPACKS_INSTALL_CMD", "NIXPACKS_BUILD_CMD", "NIXPACKS_START_CMD"):
if cfg.get(k): nix_env.append(f"{k}={cfg[k]}"); note(f"nixpacks {k}: {cfg[k]}")
cmd = [nix, "build", wt, "--out", wt]
for e in nix_env: cmd += ["--env", e]
sh(cmd, env=env)
for nf in glob.glob(os.path.join(wt, ".nixpacks", "*.nix")):
txt = open(nf).read()
if "nodejs_18" in txt and not re.search(r'"node"\s*:\s*"[^"]*18', open(os.path.join(wt, "package.json")).read() if os.path.exists(os.path.join(wt, "package.json")) else ""):
open(nf, "w").write(txt.replace("nodejs_18", f"nodejs_{node_v}")); note(f"{os.path.basename(nf)}: nodejs_18 -> nodejs_{node_v}")
# Public build-time variables (NEXT_PUBLIC_*, VITE_*, ...) are baked into the bundle at
# `build`; Railway had them in the build environment. Declare them as ARGs so the
# compose build args (provision) reach the build, then keep them as ENV for runtime.
pub = public_keys(rvars)
dfp = os.path.join(wt, ".nixpacks", "Dockerfile")
# nixpacks 1.41 installs corepack 0.24, which cannot launch pnpm >= 10 on Node 22/24
# (ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING). Pin a current one.
if os.path.exists(dfp):
txt = open(dfp).read()
new_txt = re.sub(r"corepack@0\.2\d\.\d+", "corepack@0.36.0", txt)
if new_txt != txt: open(dfp, "w").write(new_txt); note("corepack pinned to 0.36.0 in .nixpacks/Dockerfile")
if pub and os.path.exists(dfp):
lines = open(dfp).read().split("\n")
at = next((i for i, l in enumerate(lines) if l.startswith("WORKDIR")), 0) + 1
lines[at:at] = [f"ARG {k}\nENV {k}=${k}" for k in pub]
open(dfp, "w").write("\n".join(lines))
note(f"build args declared in .nixpacks/Dockerfile: {', '.join(pub)}")
gi = os.path.join(wt, ".gitignore")
if os.path.exists(gi) and re.search(r"^\.?nixpacks", open(gi).read(), re.M):
with open(gi, "a") as f: f.write("\n!.nixpacks\n")
df = ".nixpacks/Dockerfile"
if not os.path.exists(os.path.join(wt, df)): die("nixpacks produced no .nixpacks/Dockerfile")
hurl, hp = health_url(s, cfg)
wf = tmpl("deploy-dev2.yml").replace("__SITE__", s["site"]).replace("__BRANCH__", branch).replace("__HEALTH_URL__", hurl)
os.makedirs(os.path.join(wt, ".github", "workflows"), exist_ok=True)
with open(os.path.join(wt, ".github", "workflows", workflow_name(s)), "w") as f: f.write(wf)
for path in (".github/workflows", ".nixpacks", ".gitignore"):
if os.path.exists(os.path.join(wt, path)): sh(["git", "-C", wt, "add", "-A", path])
if not sh(["git", "-C", wt, "status", "--porcelain"]).strip():
note("nothing to commit: scaffold already on the branch")
else:
sh(["git", "-C", wt, "commit", "-q", "--no-verify", "-m", f"ops: deploy {s['site']} to dev2 on merge\n\nRailway deployed this on push; dev2 does not by itself. The workflow ssh's\nto the box and runs /home/anthony/www/{s['site']}/deploy-app.sh, which builds\nthe image from this checkout and restarts the compose stack. Generated by\ncli-tools dev2/dev2-site scaffold.\n\nCo-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>"])
sh(["git", "-C", wt, "push", "-q", "-u", "origin", f"+{wbranch}"])
pr = sh(["gh", "pr", "list", "--repo", s["repo"], "--head", wbranch, "--json", "url,number", "--jq", ".[0].url"]).strip()
if not pr:
pr = sh(["gh", "pr", "create", "--repo", s["repo"], "--head", wbranch, "--base", branch, "--title", f"ops: deploy {s['site']} to dev2 on merge",
"--body", f"Moves {s['site']} off Railway onto dev2 (`/home/anthony/www/{s['site']}`). Adds the merge-to-deploy workflow" + (" and a nixpacks-generated Dockerfile" if df == ".nixpacks/Dockerfile" else "") + ".\n\nGenerated by cli-tools `dev2/dev2-site scaffold`.\n\n🤖 Generated with [Claude Code](https://claude.com/claude-code)"]).strip()
note(f"PR {pr}")
mark(s["site"], "scaffold", pr=pr, scaffold_branch=wbranch, branch=branch, dockerfile=df, health_path=hp, checkout=d)
finally:
sh(["git", "-C", d, "worktree", "remove", "--force", wt], check=False)
# --------------------------------------------------------------- render
def env_quote(v):
s = "" if v is None else str(v)
if not re.search(r'[\n\r"#]|^\s|\s$', s): return s
return '"' + s.replace("\\", "\\\\").replace('"', '\\"') + '"'
PUBLIC_PREFIXES = ("NEXT_PUBLIC_", "VITE_", "PUBLIC_", "NUXT_PUBLIC_", "EXPO_PUBLIC_", "REACT_APP_", "SVELTEKIT_PUBLIC_")
def public_keys(vars_):
return sorted(k for k in vars_ if k.startswith(PUBLIC_PREFIXES) and isinstance(vars_[k], str))
def render_env(vars_, s, st, service_name=None):
"""Railway's rendered variables, minus Railway, with the data services re-pointed."""
out = {}
for k, v in sorted(vars_.items()):
if k.startswith("RAILWAY_"): continue
if k in ("PORT",) and not s.get("port_var"): continue
out[k] = v
if s["db"] == "pg" and st.get("database_url"):
for k, v in list(out.items()):
if isinstance(v, str) and re.search(r"postgres(ql)?://", v) and ("railway.internal" in v or ".rlwy.net" in v):
out[k] = st["database_url"]
for k in ("PGHOST", "PGPORT", "PGUSER", "PGPASSWORD", "PGDATABASE", "PGSSLMODE"):
if k in out:
out[k] = {"PGHOST": DEV2_HOST, "PGPORT": "5432", "PGUSER": st["db_user"], "PGPASSWORD": st["db_password"], "PGDATABASE": st["db_name"], "PGSSLMODE": (s.get("db_sslparams") or sslparams_for(s, st)).split("=")[-1]}[k]
# A site born on dev2 (no Railway project, so no Railway URL to re-point) gets its
# db-create database as DATABASE_URL, the same way a Turso port does.
if not s.get("project_id"): out.setdefault("DATABASE_URL", st["database_url"])
if s["db"] == "turso" and st.get("database_url"):
# After `db-create` + the app's Postgres port: every libsql:// URL becomes the new
# DATABASE_URL, the Turso token goes, DATABASE_URL is set if the app never had one.
for k, v in list(out.items()):
if isinstance(v, str) and (v.startswith("libsql://") or ".turso.io" in v): out[k] = st["database_url"]
if k in ("TURSO_AUTH_TOKEN",): del out[k]
out.setdefault("DATABASE_URL", st["database_url"])
if s["redis"]:
for k, v in list(out.items()):
if isinstance(v, str) and "redis" in v.lower() and "railway.internal" in v:
out[k] = "redis://redis:6379"
if k in ("REDISHOST",): out[k] = "redis"
if k in ("REDISPORT",): out[k] = "6379"
if k in ("REDISPASSWORD", "REDIS_PASSWORD"): out[k] = ""
if k in ("REDISUSER",): out[k] = "default"
for k, v in resolved_env_overrides(s).items(): out[k] = v
for k in s.get("env_remove") or []: out.pop(k, None) # settings a ported app refuses outright
lines = [f"# {s['site']}{' ' + service_name if service_name else ''}: rendered by dev2-site provision from Railway on {dt.datetime.now(dt.timezone.utc).isoformat(timespec='seconds')}"]
lines += [f"{k}={env_quote(v)}" for k, v in out.items()]
return "\n".join(lines) + "\n", out
def render_compose(s, st, app_port_inside, build_args=(), node_preset=()):
df = st.get("dockerfile") or "Dockerfile"
img = s["site"].replace(".", "-")
y = [f"# {s['site']} on dev2: rendered by cli-tools dev2/dev2-site provision. Re-run provision to change.",
"# nginx on the host terminates TLS and proxies to 127.0.0.1:${APP_PORT}.", "services:"]
image_only = bool(s.get("image")) and not s.get("repo")
def service(name, envfile, command=None, ports=True, vols=(), port_inside=None):
port_inside = port_inside or app_port_inside
y.append(f" {name}:")
lim, heap = mem_plan(s, name)
mem = mem_lines(lim)
if image_only: # Railway ran a stock image with a start command; no repo, nothing to build
y.append(f" image: {s['image']}\n restart: unless-stopped\n{mem}\n env_file: {envfile}")
else:
y.append(f" build:\n context: ./app\n dockerfile: {df}")
if build_args: # deploy-app.sh exports app.env before `compose build`, so ${K} resolves
y.append(" args:"); y.extend(f" {k}: \"${{{k}:-}}\"" for k in build_args)
y.append(f" image: {img}-{name}:latest\n restart: unless-stopped\n{mem}\n env_file: {envfile}")
y.append(" environment:")
if heap and name not in node_preset: y.append(heap_line(heap, list_style=False))
y.append(f" PORT: \"{port_inside}\"\n HOST: \"0.0.0.0\"\n NODE_ENV: production")
if command:
# A nixpacks image's entrypoint is `/bin/bash -l -c`, and bash -c takes ONE script
# argument: an argv list would run only the first word (Bun's help text, exit 0,
# restart loop). Hand it the whole string. Other images exec the argv directly.
y.append(f" command: {json.dumps([command] if (df or '').startswith('.nixpacks/') else shlex.split(command))}")
if ports: y.append(f" ports:\n - \"127.0.0.1:${{APP_PORT}}:{app_port_inside}\"")
if vols:
y.append(" volumes:")
for v in vols: y.append(f" - ./volumes/{v['name']}:{v['mountPath']}")
if s["redis"]:
y.append(" depends_on:\n redis:\n condition: service_started")
y.append(" logging:\n driver: json-file\n options: { max-size: \"50m\", max-file: \"3\" }")
service("app", "app.env", command=s.get("start_command"), vols=s["volumes"])
for c in s["companions"]:
# companion_ports {"name": {"host": 3301, "inside": 3000}} publishes a companion on
# loopback so a `proxies` entry can give it its own hostname (an API the web app calls).
cp = (s.get("companion_ports") or {}).get(c["name"])
service(c["name"], f"{c['name']}.env", command=(s.get("companion_commands") or {}).get(c["name"]), ports=False, vols=c.get("volumes", []), port_inside=(cp or {}).get("inside"))
if cp: y.insert(len(y) - (2 if s["redis"] else 1), f" ports:\n - \"127.0.0.1:{cp['host']}:{cp['inside']}\"")
if s["redis"]:
y.append(" redis:\n image: redis:8-alpine\n restart: unless-stopped\n" + mem_lines(mem_plan(s, "redis", is_redis=True, maxmemory="1gb")[0]) + "\n command: [\"redis-server\", \"--appendonly\", \"yes\", \"--maxmemory\", \"1gb\", \"--maxmemory-policy\", \"noeviction\"]\n volumes:\n - redisdata:/data\n logging:\n driver: json-file\n options: { max-size: \"20m\", max-file: \"2\" }")
y.append("volumes:\n redisdata:")
# An explicit subnet per site: Docker's default address pools (15 x /16 + 16 x /20)
# ran out at 34 networks on dev2, and widening them means restarting dockerd
# under every container. 10.200.<port-3200>.0/24 is deterministic and allowlisted
# on the data ports.
# `subnet_octet` in sites.d moves a site off a /24 another stack already holds
# (bittorrented.com was hand-built on c0ncerts.com's 10.200.78.0/24).
n = s.get("subnet_octet", s["port"] - FIRST_PORT)
y.append(f"networks:\n default:\n ipam:\n config:\n - subnet: 10.200.{n}.0/24")
# Healthchecks chosen by `dev2-site healthchecks` survive a re-render.
return health_compose("\n".join(y) + "\n", st.get("healthchecks") or {})
# ------------------------------------------------------------- memory limits
#
# Every container gets a cgroup memory ceiling (mem_limit) with memswap_limit equal
# to it, so a runaway process is killed and restarted (restart: unless-stopped) on
# its own instead of pushing a 91 GB box into swap until earlyoom shoots Postgres.
# Node processes also get --max-old-space-size at 75% of the ceiling, so V8 collects
# garbage harder before the kernel kills the container. Measured 2026-10-01: almost
# every app sits under 300 MB, so 1g is the default and sites.d raises the heavy ones.
MEM_DEFAULT = "1g" # every app and companion service unless sites.d says otherwise
MEM_FLOOR_MB = 512
HEAP_SHARE = 0.75 # V8 old space as a share of the container's limit
LIMIT_MARK = "# dev2-site limits"
def mem_mb(v):
m = re.fullmatch(r"\s*(\d+(?:\.\d+)?)\s*([kmgKMG])?[bB]?\s*", str(v))
if not m: die(f"cannot read memory size {v!r} (use e.g. 768m or 2g)")
n, u = float(m.group(1)), (m.group(2) or "m").lower()
return int(n / 1024 if u == "k" else n * 1024 if u == "g" else n)
def mem_str(mb): return f"{mb // 1024}g" if mb % 1024 == 0 else f"{mb}m"
def redis_limit_mb(maxmemory):
"""maxmemory x 1.5 in 512m steps, at least 1g: an AOF rewrite forks, and the pages
written meanwhile are copied on top of the dataset. No maxmemory: 1g."""
if not maxmemory: return 1024
return max(1024, -(-mem_mb(maxmemory) * 3 // 2 // 512) * 512)
def mem_plan(s, svc, is_redis=False, maxmemory=None):
"""(limit_mb, heap_mb or None) for one compose service of site `s`. sites.d keys:
"mem_limit" (every app/companion service), "mem_limits" {service: size} (wins; also
for redis), "node_heap_mb" int | {service|"*": int}, where 0 leaves NODE_OPTIONS to
the image or the app (it budgets its own heap)."""
per = (s.get("mem_limits") or {}).get(svc)
if is_redis:
return (mem_mb(per) if per else redis_limit_mb(maxmemory)), None
lim = max(MEM_FLOOR_MB, mem_mb(per or s.get("mem_limit") or MEM_DEFAULT))
h = s.get("node_heap_mb")
if isinstance(h, dict): h = h.get(svc, h.get("*"))
if h is None: h = int(lim * HEAP_SHARE) // 64 * 64
if h and h >= lim: die(f"{s['site']} {svc}: node_heap_mb {h} is not below its {mem_str(lim)} limit")
return lim, (h or None)
def mem_lines(lim):
return f" mem_limit: {mem_str(lim)}\n memswap_limit: {mem_str(lim)}"
def heap_line(heap, list_style):
v = f"--max-old-space-size={heap}"
return (f" - NODE_OPTIONS={v} {LIMIT_MARK}" if list_style else f" NODE_OPTIONS: \"{v}\" {LIMIT_MARK}")
def compose_services(lines):
"""[(name, start, end)] for each service of the top-level `services:` block."""
out, inside, cur = [], False, None
for i, l in enumerate(lines):
if re.match(r"^\S", l):
if cur: out.append((cur[0], cur[1], i)); cur = None
inside = l.split("#")[0].rstrip() == "services:"
continue
m = re.match(r"^ ([A-Za-z0-9_.-]+):\s*(#.*)?$", l) if inside else None
if m:
if cur: out.append((cur[0], cur[1], i))
cur = (m.group(1), i)
if cur: out.append((cur[0], cur[1], len(lines)))
return out
def limit_compose(text, s, node_preset=()):
"""The live compose file with mem_limit/memswap_limit (and our NODE_OPTIONS line) set on
every service, everything else byte for byte. Idempotent. Returns (text, {svc: (lim, heap)})."""
lines = text.split("\n")
plan, out, pos = {}, [], 0
for name, a, b in compose_services(lines):
out += lines[pos:a]; pos = b
blk = [l for l in lines[a:b] if not re.match(r"^ (mem_limit|memswap_limit):", l) and LIMIT_MARK not in l]
body = "\n".join(blk)
is_redis = bool(re.search(r"^ image:\s*[\"']?redis[:@\s\"']", body + "\n", re.M))
mm = re.search(r"--maxmemory[\"']?\s*,?\s*[\"']?([0-9]+[kmgKMG]?[bB]?)", body)
lim, heap = mem_plan(s, name, is_redis=is_redis, maxmemory=mm.group(1) if mm else None)
if heap and (name in node_preset or re.search(r"^\s+-?\s*NODE_OPTIONS\s*[:=].*max-old-space-size", body, re.M)):
heap = None # the app budgets its own heap; keep it
plan[name] = (lim, heap)
r = next((i for i, l in enumerate(blk) if re.match(r"^ restart:", l)), None)
if r is None: # an OOM-killed container must come back
blk.insert(1, " restart: unless-stopped"); r = 1
blk[r + 1:r + 1] = mem_lines(lim).split("\n")
if heap:
e = next((i for i, l in enumerate(blk) if re.match(r"^ environment:\s*$", l)), None)
if e is None:
k = r + 3
blk[k:k] = [" environment:", heap_line(heap, False)]
else:
nxt = next((l for l in blk[e + 1:] if l.strip()), "")
blk.insert(e + 1, heap_line(heap, nxt.lstrip().startswith("- ")))
out += blk
out += lines[pos:]
return "\n".join(out), plan
def box_sites():
out = ssh(DEPLOY_USER, f"ls -1 {WWW}/*/docker-compose.app.yml 2>/dev/null || true", check=False)
return sorted(p.split("/")[-2] for p in out.split())
def limits_site(name):
"""A registry site with its overrides; a site that predates the kit (nichedb.dev,
rssamplifier.com, crawlproof.com) is just its sites.d file."""
if name in registry()["sites"]: return site(name)
return with_overrides({"site": name})
LIMITS_PROBE = r'''
cd "$1" || exit 3
echo "@@ENV"
for f in *.env; do [ -f "$f" ] && grep -qs '^NODE_OPTIONS=.*max-old-space-size' "$f" && echo "$f"; done
echo "@@CTR"
docker ps -a --filter "label=com.docker.compose.project.working_dir=$PWD" --format '{{.ID}} {{.Label "com.docker.compose.service"}} {{.Image}}' |
while read -r id svc img; do
n=$(docker image inspect --format '{{range .Config.Env}}{{println .}}{{end}}' "$img" 2>/dev/null | grep -c '^NODE_OPTIONS=.*max-old-space-size')
echo "$id $svc $n"
done
echo "@@COMPOSE"
cat docker-compose.app.yml
'''
def cmd_limits(args):
names = box_sites() if args.all else args.sites
if not names: die("name sites, or --all for every ~/www/<site>/docker-compose.app.yml on dev2")
failed = []
for name in names:
s = limits_site(name); root = f"{WWW}/{name}"
raw = ssh(DEPLOY_USER, f"bash -s -- {shlex.quote(root)}", input=LIMITS_PROBE, check=False)
if "@@COMPOSE" not in raw: warn(f"{name}: no {root}/docker-compose.app.yml"); failed.append(name); continue
head, text = raw.split("@@COMPOSE\n", 1)
envs = head.split("@@ENV\n", 1)[1].split("@@CTR\n")[0].split()
ctrs = [l.split() for l in head.split("@@CTR\n", 1)[1].splitlines() if l.strip()]
lines = text.split("\n")
# env_file per service, so an env file that sets NODE_OPTIONS keeps its own heap
preset = set()
for svc, a, b in compose_services(lines):
files = re.findall(r"^\s+(?:env_file:\s*|-\s*)\.?/?([\w.-]+\.env)\s*$", "\n".join(lines[a:b]), re.M)
if any(f in envs for f in files): preset.add(svc)
preset |= {c[1] for c in ctrs if len(c) == 3 and c[2] != "0"} # the image sets NODE_OPTIONS
new, plan = limit_compose(text, s, preset)
kit = "rendered by cli-tools dev2/dev2-site" in text[:400]
log(f"{name}: " + ", ".join(f"{svc} {mem_str(l)}" + (f" heap {h}" if h else "") for svc, (l, h) in plan.items()))
if new != text:
for l in difflib.unified_diff(text.split("\n"), new.split("\n"), "live", "limited", n=0, lineterm=""):
if not l.startswith(("---", "+++")): note(l)
if args.dry_run: continue
try:
if new != text:
ssh(DEPLOY_USER, f"cd {shlex.quote(root)} && n=1; while [ -e docker-compose.app.bak-$(printf %03d $n).yml ]; do n=$((n+1)); done; cp -p docker-compose.app.yml docker-compose.app.bak-$(printf %03d $n).yml")
ssh_put(new, f"{root}/docker-compose.app.yml", "0640", user=DEPLOY_USER)
# Takes effect now, without a restart; the compose file carries it into every later recreate.
ups = [f"docker update --memory {plan[svc][0]}m --memory-swap {plan[svc][0]}m {cid} >/dev/null" for cid, svc, *_ in ctrs if svc in plan]
if ups: ssh(DEPLOY_USER, " && ".join(ups))
# NODE_OPTIONS only reaches a new container. A kit-rendered file interpolates nothing
# but deploy.env, so recreating from the built images is safe; the hand-made ones
# (crawlproof's interpolates secrets the deploy script exports) wait for their next deploy.
env_changed = [l for l in new.split("\n") if LIMIT_MARK in l] != [l for l in text.split("\n") if LIMIT_MARK in l]
if env_changed and kit and not args.no_recreate:
ssh(DEPLOY_USER, f"cd {shlex.quote(root)} && docker compose -f docker-compose.app.yml --env-file deploy.env up -d --no-build 2>&1 | tail -n 4", timeout=900)
note("recreated with NODE_OPTIONS")
elif env_changed:
note("limits live now; NODE_OPTIONS arrives with the next deploy")
got = ssh(DEPLOY_USER, f"docker ps --filter label=com.docker.compose.project.working_dir={shlex.quote(root)} --format '{{{{.Names}}}}' | xargs -r docker inspect --format '{{{{.Name}}}} {{{{.HostConfig.Memory}}}}'", check=False)
zero = [l.split()[0].lstrip("/") for l in got.splitlines() if l.split()[-1] == "0"]
if zero: warn(f"{name}: still unlimited: {', '.join(zero)}"); failed.append(name)
except RuntimeError as e:
warn(f"{name}: {str(e)[-600:]}"); failed.append(name)
if failed: die(f"limits not fully applied on: {', '.join(failed)}")
# --------------------------------------------------------------- healthchecks
#
# Docker marks a container `unhealthy` and then does nothing; restart policies fire
# only when the process exits, and a blocked event loop never exits. watchdog-autoheal
# (@profullstack/watchdog, cron on dev2) restarts what Docker marked unhealthy, but it
# can only see a container that HAS a healthcheck. On 2026-10-06, 47 of 230 had none.
#
# The probe runs inside the container with the runtime the image already has (bun or
# node), against 127.0.0.1:<port inside>, and passes on any HTTP status below 500
# without following redirects: the question is "is the server answering", and a 404
# or a redirect to /login is an answer. A blocked event loop is not. Redis gets
# `redis-cli ping`. The chosen test is kept in the site state, so a re-render by
# `provision` writes it back (render_compose -> health_block).
HEALTH_MARK = "# dev2-site healthcheck"
HEALTH_PATHS = ("/healthz", "/api/health", "/api/healthz", "/health")
HEALTH_TIMING = ("30s", "5s", 3, "60s") # interval, timeout, retries, start_period
def http_health_test(runtime, port, path):
js = (f"fetch('http://127.0.0.1:{port}{path}',{{redirect:'manual',signal:AbortSignal.timeout(4000)}})"
".then(r=>process.exit(r.status<500?0:1),()=>process.exit(1))")
return ["CMD", runtime, "-e", js]
REDIS_HEALTH_TEST = ["CMD-SHELL", "redis-cli ping | grep -q PONG"]
def test_path(t):
"""The path an http_health_test probes, or None for anything else."""
m = re.search(r"http://127\.0\.0\.1:\d+(/[^']*)'", t[3]) if t[0] == "CMD" and len(t) > 3 else None
return m.group(1) if m else None
def describe_test(t):
return f"{t[1]} GET {test_path(t)}" if test_path(t) else "redis-cli ping"
def health_block(test):
interval, timeout, retries, start = HEALTH_TIMING
return [f" healthcheck: {HEALTH_MARK}", f" test: {json.dumps(test)}",
f" interval: {interval}", f" timeout: {timeout}",
f" retries: {retries}", f" start_period: {start}"]
def strip_health_block(blk):
"""Drop a healthcheck block this tool wrote (marked), leave a hand-written one alone."""
out, skip = [], False
for l in blk:
if HEALTH_MARK in l: skip = True; continue
if skip and (l.startswith(" ") or not l.strip()): continue
skip = False; out.append(l)
return out
def health_compose(text, tests):
"""The live compose file with our healthcheck on every service in `tests`
({svc: test argv}), everything else byte for byte. Idempotent."""
lines = text.split("\n")
out, pos = [], 0
for name, a, b in compose_services(lines):
out += lines[pos:a]; pos = b
blk = strip_health_block(lines[a:b])
if name in tests:
end = len(blk)
while end > 1 and not blk[end - 1].strip(): end -= 1 # before trailing blank lines
blk[end:end] = health_block(tests[name])
out += blk
out += lines[pos:]
return "\n".join(out)
HEALTH_PROBE = r'''
cd "$1" || exit 3
f=docker-compose.app.yml
APP_PORT=$(sed -n 's/^APP_PORT=//p' deploy.env 2>/dev/null | tr -d '"' | head -1)
echo "@@APP_PORT $APP_PORT"
docker ps --filter "label=com.docker.compose.project.working_dir=$PWD" --format '{{.ID}} {{.Label "com.docker.compose.service"}} {{.Image}}' |
while read -r id svc img; do
# the CONTAINER's config: it carries the image's HEALTHCHECK, and the tag may have moved since
hc=$(docker inspect --format '{{if .Config.Healthcheck}}{{len .Config.Healthcheck.Test}}{{else}}0{{end}}' "$id" 2>/dev/null)
rt=$(docker exec "$id" sh -c 'for b in bun node redis-cli; do command -v $b >/dev/null 2>&1 && { echo $b; exit; }; done; echo none' 2>/dev/null || echo noexec)
pong=-; [ "$rt" = redis-cli ] && pong=$(docker exec "$id" redis-cli ping 2>&1 | head -1 | tr ' ' _)
echo "@@CTR $id $svc ${hc:-0} $rt $pong"
done
echo "@@COMPOSE"
cat "$f"
'''
def service_ports(lines, a, b):
"""[(host, inside)] from `- "127.0.0.1:<host>:<inside>"` lines; host may be ${APP_PORT}."""
return re.findall(r"^\s+-\s*[\"']?(?:127\.0\.0\.1:)?(\$\{APP_PORT\}|\d+):(\d+)[\"']?\s*$", "\n".join(lines[a:b]), re.M)
def pick_health_path(host_port):
"""The first health route that answers 200, else "/" (any answer under 500 passes)."""
script = "for p in " + " ".join(HEALTH_PATHS) + "; do c=$(curl -s -o /dev/null -m 5 -w '%{http_code}' " \
f"http://127.0.0.1:{int(host_port)}$p); [ \"$c\" = 200 ] && {{ echo $p; exit; }}; done; echo /"
return (ssh(DEPLOY_USER, script, check=False).strip().splitlines() or ["/"])[-1]
def plan_healthchecks(name, raw, st):
"""({svc: test}, {svc: reason skipped}) for one site from HEALTH_PROBE output."""
head, text = raw.split("@@COMPOSE\n", 1)
app_port = (re.search(r"^@@APP_PORT (\d*)", head, re.M) or [None, ""])[1]
ctrs = [l.split()[1:] for l in head.splitlines() if l.startswith("@@CTR ")]
lines = text.split("\n")
blocks = {svc: (a, b) for svc, a, b in compose_services(lines)}
keep = (st.get("healthchecks") or {})
tests, skipped = {}, {}
for cid, svc, img_hc, rt, pong in ctrs:
if svc not in blocks: skipped[svc] = "not in docker-compose.app.yml"; continue
a, b = blocks[svc]
body = "\n".join(lines[a:b])
if re.search(r"^ healthcheck:", body, re.M) and HEALTH_MARK not in body:
skipped[svc] = "has its own healthcheck"; continue
# Ours (marked in the compose file) is what the container is running, so a re-run must
# re-plan it, not read it as "already has one" and strip it (hqtui.com, 2026-10-06).
if img_hc != "0" and HEALTH_MARK not in body: skipped[svc] = "already has a healthcheck (image or container)"; continue
if rt == "redis-cli":
if pong != "PONG": skipped[svc] = f"redis-cli ping answered {pong} (auth?)"; continue
tests[svc] = REDIS_HEALTH_TEST; continue
ports = service_ports(lines, a, b)
if not ports: skipped[svc] = "publishes no port to probe"; continue
if rt not in ("bun", "node"): skipped[svc] = f"no bun or node in the image ({rt})"; continue
host, inside = ports[0]
host = app_port if host == "${APP_PORT}" else host
if not host: skipped[svc] = "no APP_PORT in deploy.env"; continue
path = (test_path(keep[svc]) if svc in keep and keep[svc][0] == "CMD" else None) or pick_health_path(host)
tests[svc] = http_health_test(rt, inside, path)
return tests, skipped, text
def cmd_healthchecks(args):
names = box_sites() if args.all else args.sites
if not names: die("name sites, or --all for every ~/www/<site>/docker-compose.app.yml on dev2")
failed, summary = [], []
for name in names:
root = f"{WWW}/{name}"; st = load_state(name)
raw = ssh(DEPLOY_USER, f"bash -s -- {shlex.quote(root)}", input=HEALTH_PROBE, check=False)
if "@@COMPOSE" not in raw: warn(f"{name}: no {root}/docker-compose.app.yml"); failed.append(name); continue
tests, skipped, text = plan_healthchecks(name, raw, st)
new = health_compose(text, tests)
kit = "rendered by cli-tools dev2/dev2-site" in text[:400]
log(f"{name}: " + (", ".join(f"{svc} {describe_test(t)}" for svc, t in tests.items()) or "nothing to add"))
for svc, why in skipped.items(): note(f"skip {svc}: {why}")
if new == text: summary.append((name, "unchanged")); continue