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
import argparse
import gzip
import hashlib
import json
import subprocess
import time
import uuid
from pathlib import Path
parser = argparse.ArgumentParser()
parser.add_argument('--binary',type=Path,required=True)
parser.add_argument('--output',type=Path,required=True)
parser.add_argument('--hours',type=int,default=24)
parser.add_argument('--app')
args=parser.parse_args()
assert 0 <= args.hours <= 168
source=Path(__file__).resolve().parent
args.output.mkdir(parents=True,exist_ok=True)
if args.app and not args.app.startswith('zlay-zkv-canary-'): parser.error('only isolated canary app names may be reused')
app=args.app or 'zlay-zkv-canary-'+uuid.uuid4().hex[:6]
expires=int(time.time())+args.hours*3600 if args.hours else 0
state={'app':app,'url':f'https://{app}.fly.dev','expires_at_unix':expires,'cpu_kind':'performance','cpus':1,'memory_mib':2048,'rootfs_gb':2,'volume_created':False,'retention_seconds':120,'event_budget_bytes':268435456,'ram_history':False,'source_revision':subprocess.check_output(['git','rev-parse','HEAD'],cwd=source.parents[1],text=True).strip(),'binary_sha256':hashlib.sha256(args.binary.read_bytes()).hexdigest(),'active':False}
def save():
(args.output/'canary-resources.json').write_text(json.dumps(state,indent=2)+'\n')
def run(command,timeout=60):
try:return subprocess.run(command,capture_output=True,text=True,check=True,timeout=timeout).stdout
except subprocess.CalledProcessError as e:
state.setdefault('errors',[]).append({'command':command[:4],'stderr':e.stderr[-3000:]});save();raise
save()
success=False
try:
print('Creating '+app,flush=True)
if args.app:
assert not json.loads(run(['fly','machine','list','-a',app,'--json'])), 'reused canary app must have no running machines'
else:
run(['fly','apps','create',app,'--org','personal','--yes'])
run(['fly','machine','run','node:24-bookworm-slim','sh','/tmp/canary-launch.sh','--file-local','/tmp/canary-launch.sh='+str((source/'canary-launch.sh').resolve()),'-a',app,'-r','ord','--name','canary','--vm-cpu-kind','performance','--vm-cpus','1','--vm-memory','2048','--rootfs-size','2','--rootfs-persist','always','--restart','no','--rm','--autostart=false','-p','443:3000/tcp:http:tls','-p','80:3000/tcp:http','--detach'],timeout=180)
machine=json.loads(run(['fly','machine','list','-a',app,'--json']))[0]
state['machine_id']=machine['id'];save()
run(['fly','ssh','console','-a',app,'-C','mkdir -p /opt/canary'])
binary=args.output/'zlay.gz';binary.write_bytes(gzip.compress(args.binary.read_bytes(),mtime=0))
deadline=args.output/'expires-at';deadline.write_text(str(expires)+'\n')
for local,remote in [(binary,'zlay.gz'),(deadline,'expires-at'),(source/'canary-setup.sh','setup.sh'),(source/'canary-serve.sh','serve.sh'),(source/'canary-probe.mjs','probe.mjs')]:
run(['fly','ssh','sftp','put','-a',app,'--mode','0755',str(local.resolve()),'/opt/canary/'+remote],timeout=240)
print('Installing PostgreSQL and preparing the isolated canary',flush=True)
run(['fly','ssh','console','-a',app,'-C','sh /opt/canary/setup.sh'],timeout=300)
run(['fly','ssh','console','-a',app,'-C','touch /opt/canary/ready'])
if not args.app:
run(['fly','ips','allocate-v4','--shared','-a',app])
run(['fly','ips','allocate-v6','-a',app])
run(['curl','--retry','15','--retry-delay','2','--retry-connrefused','--retry-all-errors','--fail','--silent','--show-error','--max-time','5',state['url']+'/_healthz'],timeout=120)
state['active']=True;save()
print('Canary responding at '+state['url'],flush=True)
print('Checking live delivery, disk replay and expiry on the VM',flush=True)
output=run(['fly','ssh','console','-a',app,'-C','node /opt/canary/probe.mjs '+state['url']],timeout=330)
(args.output/'probe-console.txt').write_text(output)
run(['fly','ssh','sftp','get','-a',app,'/opt/canary/probe.json',str((args.output/'probe.json').resolve())],timeout=60)
probe=json.loads((args.output/'probe.json').read_text())
state['verification_passed']=probe['ok'];save()
assert probe['ok'], 'canary probe failed'
success=True
print('Canary live and replay checks passed',flush=True)
finally:
if not success:
try:
run(['fly','ssh','sftp','get','-a',app,'/opt/canary/probe.json',str((args.output/'failed-probe.json').resolve())],timeout=20)
except subprocess.SubprocessError:pass
if state['active']:
deadline=int(time.time())+1800
run(['fly','ssh','console','-a',app,'-C',f"sh -c 'echo {deadline} > /opt/canary/expires-at'"],timeout=30)
state['expires_at_unix']=deadline;state['needs_diagnosis']=True;save()
else:
run(['fly','apps','destroy',app,'--yes'],timeout=120)
state['deleted_after_failure']=True;save()