Files
ukmesh/scripts/full-dev/qualification/startup_readiness.py
T

293 lines
16 KiB
Python

"""One nonauthorizing reconnect preparation; target protection remains separate."""
import json
from contextlib import contextmanager
import os
from pathlib import Path
import shlex
import signal
import subprocess
import sys
import tempfile
import time
import uuid
from common import REPO,STATE,clean_environment,write_json,utc_now
from target_lease import child_context
from target_observation import APPS,stable_identities
sys.path.insert(0,str(REPO/'scripts/companion-dev'))
from ingest_state import read_core_connection,read_beacon,timestamp
SECONDS=60
LIMIT=8*1024**2
HEALTH='ukmesh-full-mesh-health-check-1'
class Unavailable(RuntimeError):
"""Supported native state is temporarily unavailable, not an empty queue."""
@contextmanager
def _cancellation_scope():
"""Latch FIRST cancellation without interrupting mandatory settlement/save."""
state={'signal':None,'on_cancel':None}
def latch(signum,_frame):
if state['signal']is None:state['signal']=signum
blocked=signal.pthread_sigmask(signal.SIG_BLOCK,{signal.SIGTERM,signal.SIGINT})
handlers={}
try:
for sig in(signal.SIGTERM,signal.SIGINT):handlers[sig]=signal.signal(sig,latch)
finally:signal.pthread_sigmask(signal.SIG_SETMASK,blocked)
try:yield state
finally:
# Close the latch-check/handler-restore race. A signal that becomes
# pending after this block reaches the restored outer/default handler.
blocked=signal.pthread_sigmask(signal.SIG_BLOCK,{signal.SIGTERM,signal.SIGINT})
try:
if state['signal']is not None:
if state['on_cancel']is not None:state['on_cancel']()
raise InterruptedError('startup readiness canceled by '+signal.Signals(state['signal']).name)
finally:
try:
for sig,handler in handlers.items():signal.signal(sig,handler)
finally:signal.pthread_sigmask(signal.SIG_SETMASK,blocked)
def _check_cancellation(state):
if state['signal']is not None:raise InterruptedError('startup readiness canceled')
def _members(pid):
result=[]
for path in Path('/proc').iterdir():
if not path.name.isdecimal():continue
try:
fields=(path/'stat').read_text().rsplit(')',1)[1].split()
if int(fields[2])==pid and int(fields[3])==pid and fields[0]!='Z':result.append(int(fields[19]))
except (FileNotFoundError,ProcessLookupError,PermissionError):continue
return result
def _settle(child,ticks):
try:
# The leader is kept unreaped by waitid(WNOWAIT), reserving its PID/PGID.
for sig,grace in ((signal.SIGTERM,.2),(signal.SIGKILL,.5)):
leader=Path(f'/proc/{child.pid}/stat')
if ticks is None or not leader.exists()or int(leader.read_text().rsplit(')',1)[1].split()[19])!=ticks:
raise RuntimeError('probe leader identity unavailable')
members=_members(child.pid)
if not members:break
if any(value<ticks for value in members):raise RuntimeError('probe group identity differs')
try:os.killpg(child.pid,sig)
except ProcessLookupError:pass
end=time.monotonic()+grace
while _members(child.pid)and time.monotonic()<end:time.sleep(.01)
if _members(child.pid):raise RuntimeError('owned probe group not settled')
finally:
# Even an identity refusal must reap our direct child. Popen.kill polls
# its own waitpid state first, so it does not signal an already reaped PID.
if child.returncode is None:child.kill()
child.wait(timeout=1)
def _run_owned(argv,deadline,*,cancellation,after_spawn=None,merge_stderr=False,spawn=subprocess.Popen):
"""Own only short read-only probe processes, including local sg descendants."""
_check_cancellation(cancellation)
left=deadline-time.monotonic()
if left<=0:raise TimeoutError('startup readiness60 expired')
end=time.monotonic()+min(2,left)
inherited,descriptors=child_context();child=None;ticks=None
with tempfile.TemporaryFile()as out,tempfile.TemporaryFile()as err:
try:
previous=signal.pthread_sigmask(signal.SIG_BLOCK,{signal.SIGTERM,signal.SIGINT})
try:
# The tiny exec wrapper clears the inherited blocked mask in
# the child; no unsafe preexec_fn or blocked CLI signals.
child_argv=[sys.executable,'-c',
'import os,signal,sys;signal.pthread_sigmask(signal.SIG_SETMASK,());os.execvpe(sys.argv[1],sys.argv[1:],os.environ)',*argv]
child=spawn(child_argv,cwd=REPO,env={**clean_environment(),**inherited},pass_fds=descriptors,
start_new_session=True,stdout=out,stderr=subprocess.STDOUT if merge_stderr else err)
fields=Path(f'/proc/{child.pid}/stat').read_text().rsplit(')',1)[1].split()
if int(fields[2])!=child.pid or int(fields[3])!=child.pid:raise RuntimeError('probe session differs')
ticks=int(fields[19])
finally:signal.pthread_sigmask(signal.SIG_SETMASK,previous)
if after_spawn is not None:after_spawn(child)
_check_cancellation(cancellation)
while os.waitid(os.P_PID,child.pid,os.WEXITED|os.WNOHANG|os.WNOWAIT)is None:
_check_cancellation(cancellation)
if os.fstat(out.fileno()).st_size>LIMIT or os.fstat(err.fileno()).st_size>65536:raise ValueError('probe output bound exceeded')
if time.monotonic()>=end:raise Unavailable('probe-timeout')
time.sleep(min(.02,max(0,end-time.monotonic())))
if os.fstat(out.fileno()).st_size>LIMIT or os.fstat(err.fileno()).st_size>65536:raise ValueError('probe output bound exceeded')
out.seek(0);err.seek(0);stdout,stderr=out.read(),err.read()
finally:
if child is not None:
_settle(child,ticks)
if time.monotonic()>deadline:raise TimeoutError('startup readiness60 expired')
return subprocess.CompletedProcess(argv,child.returncode,stdout,stderr)
def _run(argv,deadline,*,after_spawn=None,merge_stderr=False,spawn=subprocess.Popen):
with _cancellation_scope()as cancellation:
return _run_owned(argv,deadline,cancellation=cancellation,after_spawn=after_spawn,
merge_stderr=merge_stderr,spawn=spawn)
def docker_probe(args,deadline,**options):
result=_run(['sg','docker','-c',shlex.join(['docker','--host','unix:///var/run/docker.sock',*args])],deadline,merge_stderr=options.get('merge_stderr',False))
if result.returncode:raise RuntimeError('native Docker read failed')
return result
def _http(url,deadline):
# Isolate the existing synchronous HTTP owner so slow trickle IO cannot
# outlive the deadline or leave a background thread. No new endpoint/API.
code='''import sys
sys.path.insert(0,sys.argv[1])
from loopback_http import http_get
from urllib.error import HTTPError,URLError
try:
data,_=http_get(sys.argv[2],timeout=float(sys.argv[3]));sys.stdout.buffer.write(data)
except HTTPError as e:sys.exit(75 if e.code in(502,503,504)else 76)
except(URLError,TimeoutError,ConnectionError):sys.exit(75)
'''
remaining=deadline-time.monotonic()
if remaining<=0:raise TimeoutError('startup readiness60 expired')
result=_run([sys.executable,'-c',code,str(REPO/'scripts/full-dev/qualification'),url,str(min(2,remaining))],deadline)
if result.returncode==75:raise Unavailable('native-http-unavailable')
if result.returncode:raise ValueError('native HTTP response unsupported')
return json.loads(result.stdout)
def _env(item):return dict(row.split('=',1)for row in item['Config'].get('Env',[]))
def _beacon_events(raw,item,broker,configured):
if len(raw)>LIMIT or not raw.endswith(b'\n'):raise ValueError('Beacon log incomplete')
rows=[]
for line in raw.decode().splitlines():
stamp,separator,message=line.partition(' ')
if not separator:raise ValueError('Beacon log malformed')
fields=json.loads(message)if message.startswith('{')else dict(v.split('=',1)for v in shlex.split(message)if '='in v)
rows.append((timestamp(stamp),fields))
if not any(row.get('msg')=='beacon starting'for _,row in rows):raise ValueError('Beacon process epoch missing')
events={};epoch=max(timestamp(item['State']['StartedAt']),timestamp(broker['started_at']))
for name in configured:
connected=[index for index,(at,row)in enumerate(rows)if row.get('component')=='ingest'and row.get('broker')==name and row.get('msg')=='connected'and at>=epoch]
if not connected:raise Unavailable('Beacon native OnConnect pending')
index=connected[-1]
for _,row in rows[index+1:]:
if row.get('component')!='ingest'or row.get('broker')!=name:continue
message=str(row.get('msg','')).lower()
if 'subscribe'in message and('fail'in message or 'error'in message):raise ValueError('Beacon native subscription failed')
if any(word in message for word in('connection lost','stopped')):raise Unavailable('Beacon native connection lost')
if str(row.get('level','')).upper()in('ERROR','FATAL'):raise ValueError('Beacon native connection error')
events[name]={'native_onconnect_at':rows[index][0],'suback_or_socket_claim':False}
return events
def _backend_ready(value,now):
stamp=value['ts'];status=value['status'];database=value['checks']['database'];mqtt=value['checks']['mqtt']['state']
if type(stamp)not in(int,float)or not 0<=now-stamp/1000<=5:raise ValueError('backend native sample stale')
if type(status)is not str or status not in('ready','degraded'):raise ValueError('backend native status unsupported')
if type(database)is not bool:raise ValueError('backend native database status malformed')
if type(mqtt)is not str or mqtt not in('starting','connected','disconnected','reconnecting','error'):
raise ValueError('backend native MQTT status unsupported')
if status!='ready'or not database or mqtt!='connected':raise Unavailable('backend native readiness pending')
return {'ready':True,'mqtt_connected':True,'quiescence_claim':False}
def probe(app,item,snapshot,deadline):
execute=lambda args,**kwargs:docker_probe(args,deadline,**kwargs)
if app=='ukmesh':
if _env(item).get('MQTT_INGEST_MODE','durable')!='durable':raise ValueError('normal durable intake required')
return _backend_ready(_http('http://127.0.0.1:3100/readyz',deadline),time.time())
if app=='corescope':
value=read_core_connection(item,execute=execute,timeout=min(2,max(0,deadline-time.monotonic())))
if not value['ready']or value['mqtt_connected']is False:raise Unavailable('Core native source pending')
return value
if app=='healthcheck':
value=_http('http://127.0.0.1:3090/api/bootstrap',deadline)['mqtt']['connected']
if type(value)is not bool:raise ValueError('Health Check native status malformed')
if not value:raise Unavailable('Health Check native reconnect pending')
return {'ready':True,'mqtt_connected':True,'suback_claim':False}
if app!='beacon':raise ValueError('unsupported native readiness owner')
native=read_beacon(item,execute=execute,timeout=min(2,max(0,deadline-time.monotonic())))
rows=_http('http://127.0.0.1:3103/api/v1/brokers/',deadline)
if not isinstance(rows,list)or len(rows)!=2 or any(set(row)!={'name','connected'}or type(row['connected'])is not bool for row in rows):raise ValueError('Beacon native broker status malformed')
states={row['name']:row['connected']for row in rows}
if set(states)!={'mqtt1','mqtt2'}:raise ValueError('Beacon native broker identities differ')
configured={f'mqtt{i}'for i in(1,2)if _env(item).get(f'MQTT_BROKER_{i}_URL')}
if any(states[name]is not(name in configured)for name in states):raise Unavailable('Beacon native broker status pending')
events={}
if configured:
raw=execute(['logs','--timestamps','--since',item['State']['StartedAt'],item['Id']],merge_stderr=True).stdout
events=_beacon_events(raw,item,snapshot['broker'],configured)
return {'ready':True,'process_started_at':native['process_started_at'],'native_events':events,
'api_state_is_only_hint':True,'quiescence_claim':False}
def _identities(snapshot):
owners={}
for app,name in {**APPS,'healthcheck':HEALTH}.items():
item=snapshot['containers'].get(name)
if item and item['State']['Running']:
expected={'ukmesh':('ukmesh-full','backend'),'corescope':('ukmesh-companions','corescope-ingestor'),
'beacon':('ukmesh-companions','beacon'),'healthcheck':('ukmesh-full','mesh-health-check')}[app]
labels=item['Config'].get('Labels',{})
if (labels.get('com.docker.compose.project'),labels.get('com.docker.compose.service'))!=expected:
raise ValueError('native readiness owner role identity differs')
owners[app]={'name':name,'id':item['Id'],'image':item['Image'],'pid':item['State']['Pid'],'started_at':item['State']['StartedAt']}
return {'consumers':stable_identities(snapshot),'broker':snapshot['broker'],'owners':owners}
def _wait_running_consumers(snapshot_reader,initial,*,cancellation,clock=time.monotonic,sleep=time.sleep,probe_fn=probe,save=None):
started=clock();deadline=started+SECONDS;identity=_identities(initial);reads=0;last={}
result={'passed':False,'scope':'startup reconnect preparation ONLY, not target protection','max_seconds':SECONDS,
'started_at':utc_now(),'quiescence_claim':False,'identities':identity,'skipped':{app:'missing-or-stopped-explicit'for app in{**APPS,'healthcheck':HEALTH}if app not in identity['owners']}}
execute=lambda args,**options:docker_probe(args,deadline,**options)
path=STATE/'runtime/startup-readiness'/('readiness-'+uuid.uuid4().hex+'.json')
def emit():
if save is None:write_json(path,result)
else:save(result)
def canceled_receipt():
result.update(passed=False,cancellation=signal.Signals(cancellation['signal']).name,
error=result.get('error','InterruptedError'),duration_seconds=clock()-started)
emit()
cancellation['on_cancel']=canceled_receipt
try:
while True:
reads+=1
_check_cancellation(cancellation)
if clock()>=deadline:raise TimeoutError('startup readiness60 expired')
current=snapshot_reader(deadline,execute_fn=execute)
if _identities(current)!=identity:raise ValueError('startup owner/ref/broker identity changed')
try:
last={app:probe_fn(app,current['containers'][row['name']],current,deadline)for app,row in identity['owners'].items()}
if any(type(row)is not dict or type(row.get('ready'))is not bool for row in last.values()):raise ValueError('native readiness schema malformed')
if not all(row['ready']for row in last.values()):raise Unavailable('native readiness pending')
except Unavailable:
last={};sleep(min(1,max(0,deadline-clock())));continue
_check_cancellation(cancellation)
if clock()>deadline:raise TimeoutError('startup readiness60 expired')
final=snapshot_reader(deadline,execute_fn=execute)
if _identities(final)!=identity:raise ValueError('startup owner/ref/broker identity changed')
result.update(passed=True,observations=last);return result
except BaseException as error:
result.update(passed=False,error=type(error).__name__);raise
finally:
result.update(finished_at=utc_now(),duration_seconds=clock()-started,reads=reads)
if cancellation['signal']is not None:
canceled_receipt()
else:
if clock()>deadline:result['passed']=False
emit()
if clock()>deadline and not result.get('error'):
result.update(passed=False,error='TimeoutError',duration_seconds=clock()-started)
emit();raise TimeoutError('startup readiness finalization exceeded60')
def wait_running_consumers(snapshot_reader,initial,*,clock=time.monotonic,sleep=time.sleep,probe_fn=probe,save=None):
with _cancellation_scope()as cancellation:
return _wait_running_consumers(snapshot_reader,initial,cancellation=cancellation,
clock=clock,sleep=sleep,probe_fn=probe_fn,save=save)