367 files, from working commit b1a079a. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
192 lines
9.5 KiB
Python
192 lines
9.5 KiB
Python
#!/usr/bin/env python3
|
|
"""Private exact-child lifecycle receipts; no authentication or engine operations."""
|
|
import json
|
|
import os
|
|
import re
|
|
import stat
|
|
import time
|
|
import uuid
|
|
from pathlib import Path
|
|
|
|
KIND='owned-native-client-lifecycle-v1'
|
|
IDENTITY=('native_pid','native_starttime','owner_pid','owner_starttime','launch_id','launch_monotonic_ns')
|
|
UNKNOWN_EXIT=object()
|
|
|
|
|
|
def process_identity(pid,proc_root=Path('/proc')):
|
|
if type(pid) is not int or pid<=0:raise ValueError('Invalid process identity')
|
|
base=Path(proc_root)/str(pid)
|
|
if base.stat().st_uid!=os.getuid():raise ValueError('Foreign process owner')
|
|
raw=(base/'stat').read_text();prefix,tail=raw.rsplit(')',1)
|
|
if int(prefix.split(' ',1)[0])!=pid:raise ValueError('Process PID differs')
|
|
fields=tail.split()
|
|
return {'starttime':int(fields[19]),'parent_pid':int(fields[1]),'state':fields[0]}
|
|
|
|
|
|
def _directory(root,create=False):
|
|
parent=os.open(Path(root)/'runtime',os.O_RDONLY|os.O_DIRECTORY|os.O_NOFOLLOW)
|
|
try:
|
|
if os.fstat(parent).st_uid!=os.getuid():raise ValueError('Foreign runtime owner')
|
|
if create:
|
|
try:os.mkdir('client-lifecycle',0o700,dir_fd=parent)
|
|
except FileExistsError:pass
|
|
fd=os.open('client-lifecycle',os.O_RDONLY|os.O_DIRECTORY|os.O_NOFOLLOW,dir_fd=parent)
|
|
finally:os.close(parent)
|
|
st=os.fstat(fd)
|
|
if st.st_uid!=os.getuid() or stat.S_IMODE(st.st_mode)!=0o700:
|
|
os.close(fd);raise ValueError('Lifecycle directory must be private')
|
|
return fd
|
|
|
|
|
|
def _check_file(st):
|
|
if not stat.S_ISREG(st.st_mode) or st.st_uid!=os.getuid() or stat.S_IMODE(st.st_mode)!=0o600 or st.st_nlink!=1 or st.st_size>4096:
|
|
raise ValueError('Lifecycle file must be bounded private regular metadata')
|
|
|
|
|
|
def _unique_object(pairs):
|
|
value={}
|
|
for key,item in pairs:
|
|
if key in value:raise ValueError('Duplicate lifecycle field')
|
|
value[key]=item
|
|
return value
|
|
|
|
|
|
def _read(root,name):
|
|
directory=_directory(root)
|
|
try:
|
|
fd=os.open(name,os.O_RDONLY|os.O_NOFOLLOW,dir_fd=directory)
|
|
try:
|
|
_check_file(os.fstat(fd));data=os.read(fd,4097)
|
|
if len(data)>4096:raise ValueError('Lifecycle file too large')
|
|
value=json.loads(data,object_pairs_hook=_unique_object)
|
|
if not isinstance(value,dict):raise ValueError('Lifecycle object required')
|
|
return value
|
|
finally:os.close(fd)
|
|
finally:os.close(directory)
|
|
|
|
|
|
def _write(root,name,value):
|
|
data=(json.dumps(value,separators=(',',':'))+'\n').encode()
|
|
if len(data)>4096:raise ValueError('Lifecycle record too large')
|
|
directory=_directory(root,True);temporary='.'+uuid.uuid4().hex+'.tmp'
|
|
try:
|
|
try:_check_file(os.stat(name,dir_fd=directory,follow_symlinks=False))
|
|
except FileNotFoundError:pass
|
|
fd=os.open(temporary,os.O_WRONLY|os.O_CREAT|os.O_EXCL|os.O_NOFOLLOW,0o600,dir_fd=directory)
|
|
try:
|
|
with os.fdopen(fd,'wb') as stream:stream.write(data);stream.flush();os.fsync(stream.fileno())
|
|
os.replace(temporary,name,src_dir_fd=directory,dst_dir_fd=directory);os.fsync(directory)
|
|
finally:
|
|
try:os.unlink(temporary,dir_fd=directory)
|
|
except FileNotFoundError:pass
|
|
finally:os.close(directory)
|
|
|
|
|
|
def _identity(row):
|
|
if not isinstance(row,dict) or type(row.get('schema_version')) is not int or row.get('schema_version')!=1 or row.get('kind')!=KIND:raise ValueError('Lifecycle schema differs')
|
|
for name in IDENTITY[:-2]:
|
|
if type(row.get(name)) is not int or row[name]<=0:raise ValueError('Lifecycle PID or starttime differs')
|
|
if not isinstance(row.get('launch_id'),str) or not re.fullmatch('[0-9a-f]{32}',row['launch_id']):raise ValueError('Lifecycle launch identity differs')
|
|
if type(row.get('launch_monotonic_ns')) is not int or row['launch_monotonic_ns']<=0:raise ValueError('Lifecycle launch clock differs')
|
|
return {k:row[k] for k in ('schema_version','kind')+IDENTITY}
|
|
|
|
|
|
def _launch_record(root):
|
|
row=_read(root,'launch.json');identity=_identity(row)
|
|
if set(row)!=set(identity):raise ValueError('Launch receipt fields differ')
|
|
return identity
|
|
|
|
|
|
def begin(root,native_pid,*,proc_root=Path('/proc')):
|
|
owner=os.getpid();native=process_identity(native_pid,proc_root);parent=process_identity(owner,proc_root)
|
|
if native['parent_pid']!=owner or native['state'] in ('Z','X'):raise ValueError('Require current exact child')
|
|
value=dict(schema_version=1,kind=KIND,native_pid=native_pid,native_starttime=native['starttime'],
|
|
owner_pid=owner,owner_starttime=parent['starttime'],launch_id=uuid.uuid4().hex,launch_monotonic_ns=time.monotonic_ns())
|
|
_write(root,'launch.json',value)
|
|
return value
|
|
|
|
|
|
def read_launch(root,native_pid,*,proc_root=Path('/proc')):
|
|
try:
|
|
row=_launch_record(root)
|
|
if row['native_pid']!=native_pid:return None
|
|
child=process_identity(native_pid,proc_root);owner=process_identity(row['owner_pid'],proc_root)
|
|
if (child['starttime']!=row['native_starttime'] or child['parent_pid']!=row['owner_pid']
|
|
or owner['starttime']!=row['owner_starttime'] or child['state'] in ('Z','X')):return None
|
|
return row
|
|
except (OSError,ValueError,TypeError,KeyError,IndexError):return None
|
|
|
|
|
|
def poll_owned_child(child,*,waitpid=os.waitpid,clock=time.monotonic_ns):
|
|
"""Never use Popen.poll's synthetic zero after ECHILD/another reaper."""
|
|
try:pid,status=waitpid(child.pid,os.WNOHANG)
|
|
except ChildProcessError:return UNKNOWN_EXIT
|
|
if not pid:return None
|
|
if pid!=child.pid or not (os.WIFEXITED(status) or os.WIFSIGNALED(status)):return UNKNOWN_EXIT
|
|
child.returncode=os.waitstatus_to_exitcode(status)
|
|
return (pid,status,clock())
|
|
|
|
|
|
def record_exit(root,identity,witness,*,proc_root=Path('/proc')):
|
|
expected=_identity(identity)
|
|
if expected['owner_pid']!=os.getpid() or process_identity(os.getpid(),proc_root)['starttime']!=expected['owner_starttime']:
|
|
raise ValueError('Original owner identity differs')
|
|
if _launch_record(root)!=expected:raise ValueError('Current launch identity differs')
|
|
if not isinstance(witness,tuple) or len(witness)!=3:raise ValueError('Actual waitpid witness required')
|
|
pid,status,observed=witness
|
|
if (type(pid) is not int or pid!=expected['native_pid'] or type(status) is not int or not 0<=status<=65535
|
|
or not(os.WIFEXITED(status) or os.WIFSIGNALED(status)) or type(observed) is not int or observed<expected['launch_monotonic_ns']):
|
|
raise ValueError('Terminal child wait status differs')
|
|
result=dict(expected,wait_status=status,exit_status=os.waitstatus_to_exitcode(status),observed_monotonic_ns=observed)
|
|
_write(root,'exit.json',result)
|
|
return result
|
|
|
|
|
|
def inspect_exit(root,expected,*,proc_root=Path('/proc')):
|
|
try:
|
|
identity=_identity(expected)
|
|
if _launch_record(root)!=identity:return {'state':'unknown'}
|
|
try:row=_read(root,'exit.json')
|
|
except FileNotFoundError:return {'state':'pending'}
|
|
if _identity(row)!=identity:return {'state':'pending'}
|
|
if set(row)!=set(identity)|{'wait_status','exit_status','observed_monotonic_ns'}:return {'state':'unknown'}
|
|
status=row['wait_status'];observed=row['observed_monotonic_ns']
|
|
if (type(status) is not int or not 0<=status<=65535 or not(os.WIFEXITED(status) or os.WIFSIGNALED(status))
|
|
or type(observed) is not int or observed<identity['launch_monotonic_ns']
|
|
or type(row['exit_status']) is not int or row['exit_status']!=os.waitstatus_to_exitcode(status)):return {'state':'unknown'}
|
|
try:
|
|
current=process_identity(identity['native_pid'],proc_root)
|
|
if current['starttime']==identity['native_starttime']:return {'state':'unknown'}
|
|
except FileNotFoundError:pass
|
|
return {'state':'success' if os.WIFEXITED(status) and row['exit_status']==0 else 'abnormal','exit_status':row['exit_status']}
|
|
except (OSError,ValueError,TypeError,KeyError,IndexError):return {'state':'unknown'}
|
|
|
|
|
|
def await_exit(root,expected,*,timeout=30,interval=.1,monotonic=time.monotonic,sleep=time.sleep,proc_root=Path('/proc')):
|
|
if type(timeout) not in (int,float) or not 0<=timeout<=60 or type(interval) not in (int,float) or not 0<interval<=1:
|
|
raise ValueError('Bounded shutdown observation required')
|
|
if expected is None:return {'state':'unknown'}
|
|
deadline=monotonic()+timeout
|
|
while True:
|
|
result=inspect_exit(root,expected,proc_root=proc_root)
|
|
if result['state']!='pending':return result
|
|
if monotonic()>=deadline:
|
|
try:
|
|
current=process_identity(expected['native_pid'],proc_root)
|
|
return {'state':'live' if current['starttime']==expected['native_starttime'] else 'unknown'}
|
|
except (OSError,ValueError,TypeError,KeyError,IndexError):return {'state':'unknown'}
|
|
sleep(interval)
|
|
|
|
|
|
def save_outcome(root,expected,result,pipe,*,proc_root=Path('/proc')):
|
|
identity=_identity(expected)
|
|
if result.get('state')!='success' or result.get('exit_status')!=0 or inspect_exit(root,identity,proc_root=proc_root)!=result:
|
|
raise ValueError('Successful actual exit required')
|
|
error=pipe.get('error') if isinstance(pipe,dict) else None
|
|
closed=pipe.get('closed') if isinstance(pipe,dict) else None
|
|
value=dict(identity,event='verified-child-exit',exit_status=0,
|
|
pipe_error=error if type(error) is int and 0<=error<=0xffffffff else None,
|
|
pipe_closed=bool(closed) if type(closed) in (bool,int) and closed in (0,1) else None)
|
|
_write(root,'backend-outcome.json',value)
|
|
return {k:value[k] for k in ('exit_status','pipe_error','pipe_closed')}
|