fix: preserve live verification owners across windows and durable stops
This commit is contained in:
1 parent
6175bdb254
commit
a606ed9179
5 files changed
+170
-12
No files matched your search
@@ -4,12 +4,14 @@ from threading import Event,Thread,RLock
|
||||
from uuid import uuid4
|
||||
from .contracts import ACTIVE,digest,fail
|
||||
from .store import encode,now
|
||||
from .ownership import owner_path,write_owner,read_owner,RunStop
|
||||
|
||||
|
||||
class VerificationControl:
|
||||
def __init__(self,service):
|
||||
self.service=service;self.repo=service.repo;self.lock=RLock();self.events={};self.thread=None;self.closing=False
|
||||
self.last_error=None
|
||||
self.owner_id=uuid4().hex;self._owned_runs=set()
|
||||
|
||||
@property
|
||||
def busy(self):
|
||||
@@ -40,14 +42,18 @@ class VerificationControl:
|
||||
if wanted and wanted-{(m['item_id'],m['input_version']) for m in members}:fail('所选版本已变化或正在执行,请刷新。')
|
||||
self.repo.connection.execute('INSERT INTO verification_runs(run_id,task_id,members_json,state,created) VALUES (?,?,?,?,?)',
|
||||
(run_id,task_id,encode(members),'queued' if members else 'completed',now()))
|
||||
write_owner(self.service,'runs',run_id,self.owner_id)
|
||||
result={'run_id':run_id,'members':members}
|
||||
self.repo._remember('start',request_id,body,result)
|
||||
owner=read_owner(self.service,'runs',result['run_id'])
|
||||
if owner.get('owner_id')==self.owner_id and result['members']:
|
||||
with self.lock:self._owned_runs.add(result['run_id'])
|
||||
self.wake()
|
||||
return result
|
||||
|
||||
def wake(self):
|
||||
with self.lock:
|
||||
if not self.closing and not self.busy:
|
||||
if self._owned_runs and not self.closing and not self.busy:
|
||||
self.thread=Thread(target=self._dispatch,name='verification-runner',daemon=True);self.thread.start()
|
||||
|
||||
def stop(self,run_id,*,request_id):
|
||||
@@ -55,7 +61,7 @@ class VerificationControl:
|
||||
old=self.repo._request('stop',request_id,run_id)
|
||||
if old is not None:return old
|
||||
run=self.repo._one('verification_runs','run_id',run_id)
|
||||
self.repo.connection.execute("UPDATE verification_runs SET stop_requested=1,state=CASE WHEN state IN ('queued','running') THEN 'stopping' ELSE state END WHERE run_id=?",(run_id,))
|
||||
self.repo.connection.execute("UPDATE verification_runs SET stop_requested=1,state=CASE WHEN state='queued' THEN 'stopped' WHEN state='running' THEN 'stopping' ELSE state END WHERE run_id=?",(run_id,))
|
||||
for member in json.loads(run['members_json']):
|
||||
self.repo.connection.execute("UPDATE verification_attempts SET state='cancelled',reason='run_stopped_before_dispatch',resource_state='released',updated=? WHERE attempt_id=? AND state='queued'",(now(),member['attempt_id']))
|
||||
self.repo._touch(run['task_id']);result={'run_id':run_id,'stop_requested':True}
|
||||
@@ -63,31 +69,39 @@ class VerificationControl:
|
||||
with self.lock:self.events.setdefault(run_id,Event()).set()
|
||||
return result
|
||||
|
||||
def _next_run(self):
|
||||
with self.lock:owned=tuple(self._owned_runs)
|
||||
if not owned:return None
|
||||
placeholders=','.join('?' for _ in owned)
|
||||
return self.repo.connection.execute(f"SELECT * FROM verification_runs WHERE state='queued' AND run_id IN ({placeholders}) ORDER BY created LIMIT 1",owned).fetchone()
|
||||
|
||||
def _dispatch(self):
|
||||
from .runner import run_attempt
|
||||
try:
|
||||
while not self.closing:
|
||||
with self.repo.store.transaction():
|
||||
run=self.repo.connection.execute("SELECT * FROM verification_runs WHERE state IN ('queued','running','stopping') ORDER BY created LIMIT 1").fetchone()
|
||||
run=self._next_run()
|
||||
if run is None:return
|
||||
run=dict(run)
|
||||
if not run['stop_requested']:
|
||||
self.repo.connection.execute("UPDATE verification_runs SET state='running' WHERE run_id=?",(run['run_id'],))
|
||||
with self.lock:event=self.events.setdefault(run['run_id'],Event())
|
||||
stop=RunStop(self.service,run['run_id'],event)
|
||||
if run['stop_requested']:event.set()
|
||||
blocked=False
|
||||
for member in json.loads(run['members_json']):
|
||||
result={}
|
||||
if event.is_set() or self.closing:break
|
||||
while not event.is_set() and not self.closing:
|
||||
if stop.is_set() or self.closing:break
|
||||
while not stop.is_set() and not self.closing:
|
||||
result=run_attempt(self.service,member['attempt_id'],stop_event=event)
|
||||
if not result.get('waiting'):break
|
||||
event.wait(.2)
|
||||
if result.get('blocked'):blocked=True;break
|
||||
with self.repo.store.transaction():
|
||||
state='blocked' if blocked else 'stopped' if event.is_set() or self.closing else 'completed'
|
||||
state='blocked' if blocked else 'stopped' if stop.is_set() or self.closing else 'completed'
|
||||
self.repo.connection.execute('UPDATE verification_runs SET state=? WHERE run_id=?',(state,run['run_id']))
|
||||
self.repo._touch(run['task_id'])
|
||||
with self.lock:self._owned_runs.discard(run['run_id'])
|
||||
except Exception as error:
|
||||
self.closing=True;self.last_error=str(error)
|
||||
from ..batch_resources import write_record
|
||||
@@ -100,16 +114,26 @@ class VerificationControl:
|
||||
# Close the enqueue/empty-dispatch race without polling from the UI.
|
||||
if not self.closing:
|
||||
with self.repo.store._lock:
|
||||
pending=self.repo.connection.execute("SELECT 1 FROM verification_runs WHERE state IN ('queued','running','stopping') LIMIT 1").fetchone()
|
||||
pending=self._next_run()
|
||||
if pending:self.wake()
|
||||
|
||||
def recover(self):
|
||||
if self.busy:return {'interrupted':0,'blocked':0,'published':0}
|
||||
result={'interrupted':0,'blocked':0,'published':0}
|
||||
result={'interrupted':0,'blocked':0,'published':0,'live_owners':0}
|
||||
with self.repo.store.transaction():
|
||||
active_runs=self.repo.connection.execute("SELECT run_id FROM verification_runs WHERE state IN ('queued','running','stopping')").fetchall()
|
||||
protected=set()
|
||||
for run in active_runs:
|
||||
owner=read_owner(self.service,'runs',run[0])
|
||||
if owner['state']=='live' and owner.get('owner_id')!=self.owner_id:protected.add(run[0])
|
||||
rows=self.repo.connection.execute("SELECT * FROM verification_attempts WHERE state IN ('queued','running','publishing','stopping')").fetchall()
|
||||
for raw in rows:
|
||||
row=dict(raw);identity=row['attempt_id'];directory=self.service.data_root/'verification'/'attempts'/identity
|
||||
if row['run_id'] in protected:continue
|
||||
owner=read_owner(self.service,'attempts',identity,row['owner_id'])
|
||||
if owner['state']=='live' and owner.get('owner_id')!=self.owner_id:
|
||||
if row['run_id']:protected.add(row['run_id'])
|
||||
continue
|
||||
if row['state']=='queued':state,resource='interrupted','released'
|
||||
else:
|
||||
try:
|
||||
@@ -130,14 +154,15 @@ class VerificationControl:
|
||||
(state,resource,'上次执行中断;未自动重跑' if resource=='released' else '上次原生进程退出缺少证明,保留现场',now(),identity))
|
||||
self.repo._touch(self.repo.item(row['item_id'])['task_id'])
|
||||
result['blocked' if resource=='unknown' else 'interrupted']+=1
|
||||
self.repo.connection.execute("UPDATE verification_runs SET state='interrupted' WHERE state IN ('queued','running','stopping')")
|
||||
for run in active_runs:
|
||||
if run[0] not in protected:self.repo.connection.execute("UPDATE verification_runs SET state='interrupted' WHERE run_id=?",(run[0],))
|
||||
result['live_owners']=len(protected)
|
||||
return result
|
||||
|
||||
def begin_shutdown(self):
|
||||
if self.closing:return
|
||||
self.closing=True
|
||||
with self.repo.store._lock:
|
||||
runs=[r[0] for r in self.repo.connection.execute("SELECT run_id FROM verification_runs WHERE state IN ('queued','running','stopping')")]
|
||||
with self.lock:runs=tuple(self._owned_runs)
|
||||
for identity in runs:self.stop(identity,request_id='shutdown:'+identity)
|
||||
with self.lock:
|
||||
for event in self.events.values():event.set()
|
||||
@@ -0,0 +1,56 @@
|
||||
"""Process creation identities for recovery; never terminate a recorded PID."""
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
import time
|
||||
from types import SimpleNamespace
|
||||
from ..batch_resources import process_identity,_process_gone,write_record
|
||||
from .contracts import fail
|
||||
|
||||
|
||||
def owner_path(service,kind,identity):
|
||||
if kind not in {'runs','attempts'} or re.fullmatch('[0-9a-f]{32}',identity or '') is None:fail('执行归属标识无效。')
|
||||
root=(service.data_root/'verification').resolve()
|
||||
path=root/kind/identity/'owner.json'
|
||||
if not path.resolve().is_relative_to(root):fail('执行归属目录越界。')
|
||||
return path
|
||||
|
||||
|
||||
def write_owner(service,kind,identity,owner_id):
|
||||
process={'pid':os.getpid(),'creation_time':None}
|
||||
if os.name=='nt':
|
||||
import win32api
|
||||
process=process_identity(SimpleNamespace(pid=os.getpid(),handle=win32api.GetCurrentProcess()))
|
||||
write_record(owner_path(service,kind,identity),{'version':1,'identity':identity,'owner_id':owner_id,
|
||||
'process':process,'scope':'OwnedCliScope','kill_on_owner_exit':True})
|
||||
|
||||
|
||||
def read_owner(service,kind,identity,expected_owner=None):
|
||||
try:
|
||||
value=json.loads(owner_path(service,kind,identity).read_text(encoding='utf-8'))
|
||||
if (value.get('version')!=1 or value.get('identity')!=identity or value.get('scope')!='OwnedCliScope'
|
||||
or value.get('kill_on_owner_exit') is not True or not isinstance(value.get('owner_id'),str)
|
||||
or (expected_owner and value['owner_id']!=expected_owner)):raise ValueError('归属证明不符')
|
||||
identity_record=value['process']
|
||||
if type(identity_record.get('pid')) is not int or identity_record['pid']<=0:raise ValueError('进程证明无效')
|
||||
if os.name!='nt' or not identity_record.get('creation_time'):state='unknown'
|
||||
else:state='gone' if _process_gone(identity_record) else 'live'
|
||||
return dict(value,state=state)
|
||||
except Exception:return {'state':'unknown'} # An inaccessible process is never proof of release.
|
||||
|
||||
|
||||
class RunStop:
|
||||
"""An Event-compatible token that observes another window's durable stop."""
|
||||
def __init__(self,service,run_id,event):self.service=service;self.run_id=run_id;self.event=event
|
||||
def is_set(self):
|
||||
if self.event.is_set():return True
|
||||
with self.service.repo.store._lock:
|
||||
row=self.service.repo.connection.execute('SELECT stop_requested FROM verification_runs WHERE run_id=?',(self.run_id,)).fetchone()
|
||||
return row is None or bool(row[0])
|
||||
def wait(self,timeout=None):
|
||||
deadline=None if timeout is None else time.monotonic()+timeout
|
||||
while not self.is_set():
|
||||
if deadline is not None and time.monotonic()>=deadline:return False
|
||||
self.event.wait(.05 if deadline is None else min(.05,max(0,deadline-time.monotonic())))
|
||||
return True
|
||||
@@ -35,8 +35,13 @@ def run_attempt(service,attempt_id,*,stop_event):
|
||||
attempt=None
|
||||
try:
|
||||
check_cancelled(stop_event)
|
||||
attempt=service.repo.claim(attempt_id,owner_id=uuid4().hex)
|
||||
from .ownership import write_owner,RunStop
|
||||
with service.repo.store.transaction():
|
||||
attempt=service.repo.claim(attempt_id,owner_id=service.control.owner_id)
|
||||
if attempt:write_owner(service,'attempts',attempt_id,attempt['owner_id'])
|
||||
if attempt is None:return {'published':False}
|
||||
if attempt['run_id']:stop_event=RunStop(service,attempt['run_id'],stop_event)
|
||||
check_cancelled(stop_event)
|
||||
payload=service.repo.revision(attempt['item_id'],attempt['input_version'])['payload']
|
||||
output=service.data_root/'verification'/'attempts'/attempt_id
|
||||
left,right=export_inputs(service,payload['before_ref'],payload['after_ref'],output=output,stop_event=stop_event)
|
||||
|
||||
Reference in new issue
Block a user