feat: add reusable jump-host node onboarding runtime
Docker Build and Publish / build (push) Waiting to run

This commit is contained in:
hellcat committed 2026-10-17 15:22:30 +08:00
1 parent 1de59971f6
commit 5c9157f5d7
16 files changed
+1418 -4

No files matched your search

+97 -4
View File
@@ -6,6 +6,7 @@ import contextlib
import fcntl
import hashlib
import ipaddress
import importlib.util
import json
import os
from pathlib import Path
@@ -20,6 +21,7 @@ import time
PHASES = ('stage', 'dns', 'provision', 'relay', 'verify', 'publish', 'audit')
SHARED = {'stage': 'panel', 'dns': 'dns', 'relay': 'relay', 'publish': 'panel'}
STOP = threading.Event()
EVENTS = False
def digest(value):
@@ -85,7 +87,8 @@ def validate(plan):
if type(n['formal_group_id']) is not int or n['formal_group_id'] < 1:
raise ValueError('An existing formal group is required')
ipaddress.ip_address(n['node_address'])
ipaddress.ip_address(n['expected_exit'])
exit_address=ipaddress.ip_address(n['expected_exit'])
if getattr(exit_address,'scope_id',None):raise ValueError('Scoped/link-local exit addresses are not supported')
for k in ('relay_host', 'tls_domain'):
if not re.fullmatch(r'[a-z0-9](?:[a-z0-9.-]*[a-z0-9])?\.[a-z]{2,}', n[k]):
raise ValueError('Invalid DNS name: ' + k)
@@ -143,16 +146,21 @@ class Ledger:
CREATE TABLE IF NOT EXISTS batches(id TEXT PRIMARY KEY, digest TEXT NOT NULL);
CREATE TABLE IF NOT EXISTS claims(namespace TEXT, kind TEXT, value TEXT,
owner TEXT NOT NULL, PRIMARY KEY(namespace,kind,value));
CREATE TABLE IF NOT EXISTS evidence(batch TEXT,node TEXT,phase TEXT,
dependency TEXT,expires REAL,request TEXT,PRIMARY KEY(batch,node,phase));
CREATE TABLE IF NOT EXISTS phases(batch TEXT, node TEXT, phase TEXT,
status TEXT NOT NULL, attempts INTEGER NOT NULL DEFAULT 0,
updated REAL NOT NULL, PRIMARY KEY(batch,node,phase));
''')
os.chmod(self.path, 0o600)
@contextlib.contextmanager
def db(self):
c = sqlite3.connect(self.path, timeout=30)
c.execute('PRAGMA synchronous=FULL')
return c
try:
c.execute('PRAGMA synchronous=FULL')
with c: yield c
finally: c.close()
def reserve(self, plan):
namespace = plan['context']['panel_vps'] + ':' + plan['context']['app_root']
@@ -185,6 +193,15 @@ class Ledger:
if old and old[0] != owner:
raise ValueError('Another batch reserved the gateway SOCKS port')
c.execute('INSERT OR IGNORE INTO claims VALUES(?,?,?,?)', (scope, 'socks_port', value, owner))
formal_port=plan['context'].get('formal_socks_port')
if formal_port is not None:
if type(formal_port) is not int or not 1024<=formal_port<=65535 or any(n['socks_port']==formal_port for n in plan['nodes']):
raise ValueError('A distinct formal SOCKS port is required')
scope,value='gateway:'+plan['context']['gateway_vps'],str(formal_port)
owner=digest({'context':plan['context'],'formal_port':formal_port})
old=c.execute('SELECT owner FROM claims WHERE namespace=? AND kind=? AND value=?',(scope,'socks_port',value)).fetchone()
if old and old[0]!=owner:raise ValueError('Formal SOCKS port already reserved')
c.execute('INSERT OR IGNORE INTO claims VALUES(?,?,?,?)',(scope,'socks_port',value,owner))
c.execute('INSERT OR IGNORE INTO batches VALUES(?,?)', (plan['batch_id'], digest(plan)))
def state(self, batch, key, phase):
@@ -193,11 +210,31 @@ class Ledger:
(batch, key, phase)).fetchone()
return row[0] if row else 'pending'
def reusable(self, batch, key, phase, dependency, request):
if not dependency or self.state(batch, key, phase) != 'done':
return False
with self.db() as c:
row = c.execute('SELECT dependency,expires,request FROM evidence WHERE batch=? AND node=? AND phase=?', (batch,key,phase)).fetchone()
return bool(row and row[0] == dependency and time.time() <= row[1] <= time.time()+900 and row[2] == request)
def proof(self, batch, key, phase, dependency, expires, request):
with self.db() as c:
c.execute('INSERT OR REPLACE INTO evidence VALUES(?,?,?,?,?,?)',(batch,key,phase,dependency,expires,request))
def mark(self, batch, key, phase, status, attempt=False):
previous=self.state(batch,key,phase)
with self.db() as c:
c.execute('''INSERT INTO phases VALUES(?,?,?,?,?,?) ON CONFLICT(batch,node,phase)
DO UPDATE SET status=excluded.status,attempts=phases.attempts+?,updated=excluded.updated''',
(batch, key, phase, status, int(attempt), time.time(), int(attempt)))
if previous!=status or attempt:
fd=os.open(self.root/'events.jsonl',os.O_CREAT|os.O_WRONLY|os.O_APPEND,0o600)
try:
os.fchmod(fd,0o600)
event=json.dumps({'batch':batch,'node':key,'phase':phase,'status':status,'time':time.time()})+'\n'
os.write(fd,event.encode())
if EVENTS:sys.stdout.write(event);sys.stdout.flush()
finally:os.close(fd)
class Coordinator:
@@ -206,11 +243,35 @@ class Coordinator:
self.ledger = Ledger(root)
self.jobs = jobs
self.timeout = timeout
self.dependencies = {}
self.runtime = None
self.ledger.reserve(plan)
self.dir = self.ledger.root / plan['batch_id']
self.dir.mkdir(mode=0o700, exist_ok=True)
self.plan_file = self.dir / 'plan.json'
atomic_json(self.plan_file, plan)
if plan.get('runtime'):
self.check_runtime()
directory = str(Path(__file__).resolve().parent)
if directory not in sys.path: sys.path.insert(0, directory)
from site_adapter import SiteAdapter
self.runtime = SiteAdapter(plan, self.dir, atomic_writer=atomic_json, resource_lock=lock)
def check_runtime(self):
runtime = self.plan['runtime']
if runtime.get('kind') != 'ssh-site-v1': raise ValueError('Unknown runtime')
if runtime.get('python') != str(Path(sys.executable).resolve()):raise ValueError('Use the frozen runtime interpreter')
import paramiko
if paramiko.__version__ != runtime.get('paramiko_version'):raise ValueError('Runtime dependency version changed')
base = Path(__file__).resolve().parent
required = [base/n for n in ('batch.py','site_adapter.py','ssh_pool.py','acceptance.py')]
required += [Path(self.plan['context'][k]) for k in ('ssh_config','exit_registry')]
files = runtime.get('files', {})
if any(str(f) not in files for f in required): raise ValueError('Runtime source pin missing')
for f, sha in files.items():
if not Path(f).is_absolute() or hashlib.sha256(Path(f).read_bytes()).hexdigest() != sha:
raise ValueError('Runtime code/config changed')
def call(self, n, phase, action):
fingerprint = digest({'context': self.plan['context'], 'node': n})
@@ -218,6 +279,14 @@ class Coordinator:
atomic_json(path, dict(n, request_sha256=fingerprint))
argv = self.plan['adapter'] + ['--plan', str(self.plan_file), '--node', str(path),
'--phase', phase, '--action', action, '--state-dir', str(self.dir)]
if self.runtime:
self.check_runtime()
r = self.runtime.call(dict(n, request_sha256=fingerprint), phase, action)
if (r.get('key'),r.get('phase'),r.get('request_sha256')) != (n['key'],phase,fingerprint):
raise RuntimeError('Runtime identity mismatch')
if r.get('status') not in ('ready','absent','waiting','unknown','conflict'):
raise RuntimeError('Runtime status invalid')
return r
with subprocess.Popen(argv, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL,
start_new_session=True) as p:
deadline = time.monotonic() + self.timeout
@@ -258,8 +327,20 @@ class Coordinator:
if resource in ('dns', 'relay'):
namespace = 'dpl-external'
with lock(self.ledger.root, namespace + ':' + resource):
dependency = self.dependencies.get(key, {}).get(phase)
request = digest({'plan': self.plan, 'node': n})
# Publish/audit/preflight are always live; unknown or running phases cannot use a cache.
if phase in ('stage','dns','provision','relay','verify') and self.ledger.reusable(batch,key,phase,dependency,request):
if self.runtime: self.check_runtime()
return True
r = self.call(n, phase, 'probe')
if phase == 'preflight' and r['status'] == 'ready':
deps = r.get('resume_dependencies', {})
clean = {k:v for k,v in deps.items() if k in PHASES and isinstance(v,str) and re.fullmatch('[0-9a-f]{64}',v)}
self.dependencies[key] = {k:digest({p:clean.get(p) for p in PHASES[:PHASES.index(k)+1]}) for k in clean}
if r['status'] == 'ready':
if dependency and type(r.get('valid_until')) in (int,float) and time.time() < r['valid_until'] <= time.time()+900:
self.ledger.proof(batch,key,phase,dependency,r['valid_until'],request)
self.ledger.mark(batch, key, phase, 'done')
return True
if r['status'] == 'conflict':
@@ -278,6 +359,8 @@ class Coordinator:
return False
r = self.call(n, phase, 'probe')
self.ledger.mark(batch, key, phase, 'done' if r['status'] == 'ready' else r['status'])
if r['status'] == 'ready' and dependency and type(r.get('valid_until')) in (int,float) and time.time()<r['valid_until']<=time.time()+900:
self.ledger.proof(batch,key,phase,dependency,r['valid_until'],request)
if r['status'] == 'conflict':
STOP.set()
return r['status'] == 'ready'
@@ -324,8 +407,11 @@ def main():
p.add_argument('--state-root', required=True)
p.add_argument('--jobs', type=int, default=4)
p.add_argument('--timeout', type=int, default=900)
p.add_argument('--events', action='store_true', help='Emit token-free phase transition JSON lines; final result is last line')
p.add_argument('--execute', action='store_true', help='Required for a run that may write remotely')
a = p.parse_args()
global EVENTS
EVENTS = a.events
os.umask(0o077)
if not 1 <= a.jobs <= 16 or not 1 <= a.timeout <= 3600:
p.error('jobs must be 1..16; timeout 1..3600')
@@ -354,7 +440,14 @@ def main():
runner = Coordinator(plan, a.state_root, a.jobs, a.timeout)
for sig in (signal.SIGINT, signal.SIGTERM):
signal.signal(sig, lambda *_: STOP.set())
success = runner.run()
try:
success = runner.run()
finally:
if runner.runtime:
try:runner.runtime.close()
except Exception:
for node in plan['nodes']:runner.ledger.mark(plan['batch_id'],node['key'],'coordinator','unknown')
raise
print(json.dumps({'batch_id': plan['batch_id'], 'complete': success,
'next': None if success else 'Inspect status, resolve waiting/conflict, rerun the exact plan'}))
return 0 if success else 2