184 lines
11 KiB
Python
184 lines
11 KiB
Python
"""Сценарии pipeline внутри сети стенда. Приватный контекст только в stdin/stdout оператора."""
|
|
import argparse
|
|
import base64
|
|
from datetime import datetime
|
|
import hashlib
|
|
import io
|
|
import json
|
|
import os
|
|
from pathlib import Path
|
|
import sys
|
|
import time
|
|
import uuid
|
|
|
|
sys.path.insert(0,str(Path(__file__).resolve().parents[1]))
|
|
sys.path.insert(0,str(Path(__file__).resolve().parents[1]/'tests'))
|
|
from client import Client,check
|
|
from src.jobs import connection,inspect,payload,event,replay,new_version
|
|
from src.broker import connect,publish,STREAM,GROUP
|
|
from src.storage import ObjectStore
|
|
from src.cleanup import run as cleanup
|
|
|
|
|
|
def main():
|
|
p=argparse.ArgumentParser();p.add_argument('mode',choices=['config','create','queued','wait','snapshot','duplicate','arm',
|
|
'fault-fired','unready','published','drained','audit','missing-stage','restore-stage','replay','version','failed','cleanup','privacy','invalid-job'])
|
|
p.add_argument('--phase');p.add_argument('--state',default='ready');p.add_argument('--timeout',type=int,default=100)
|
|
args=p.parse_args();ctx=json.load(sys.stdin)
|
|
if args.mode=='config':
|
|
from src.config import JOB_MAX_ATTEMPTS,JOB_TIMEOUT,JOB_LEASE,STAGING_RETENTION,MAX_PENDING_JOBS,WORKER_CONCURRENCY
|
|
return dict(job_max_attempts=JOB_MAX_ATTEMPTS,job_timeout_seconds=JOB_TIMEOUT,job_lease_seconds=JOB_LEASE,
|
|
staging_retention_seconds=STAGING_RETENTION,max_pending_jobs=MAX_PENDING_JOBS,
|
|
worker_concurrency=WORKER_CONCURRENCY,prefetch_per_consumer=1)
|
|
c=Client(os.getenv('BASE_URL','http://localhost:8080'),timeout=15)
|
|
fixture=(Path(__file__).resolve().parents[1]/'tests/fixtures/sample.png').read_bytes()
|
|
storage=ObjectStore()
|
|
if args.mode=='create':
|
|
alice,bob,_,chat=c.bootstrap()
|
|
response=c.call('POST','/api/v1/chats/'+chat['id']+'/attachments?filename=pipeline.png',202,actor=alice,
|
|
raw=fixture,headers={'Content-Type':'image/png'},schema='Attachment')
|
|
att=response['json'];assert att['status']=='queued'
|
|
with connection() as db:
|
|
job=db.execute('SELECT * FROM jobs WHERE attachment_id=%s',(att['id'],)).fetchone()
|
|
assert storage.head(job['staging_key']) and job['status']=='queued'
|
|
return dict(actor=alice,reader=bob,chat=chat,attachment=att,job_id=str(job['id']),uploader=response['headers']['X-Instance-Id'])
|
|
info=inspect(ctx['job_id']);job=info['job'];att=info['attachment']
|
|
path='/api/v1/attachments/'+str(job['attachment_id'])
|
|
if args.mode=='queued':
|
|
result=c.call('GET',path,actor=ctx['actor'],schema='Attachment')['json'];assert result['status']=='queued'
|
|
c.call('GET',path+'/content',409,actor=ctx['reader'])
|
|
c.message(ctx['actor'],ctx['chat'],'',attachments=[str(job['attachment_id'])])
|
|
c.message(ctx['actor'],ctx['chat'],'Worker выключен, сообщения работают')
|
|
return dict(status='PASS',attachment_id=str(job['attachment_id']),job_id=ctx['job_id'],accepted_status=202,content_status=409)
|
|
if args.mode in {'wait','fault-fired'}:
|
|
deadline=time.monotonic()+args.timeout
|
|
while time.monotonic()<deadline:
|
|
info=inspect(ctx['job_id'])
|
|
if args.mode=='fault-fired':
|
|
if any(r['phase']==args.phase and r['fired_at'] is not None for r in info['faults']):return dict(status='PASS',phase=args.phase)
|
|
elif info['job']['status']==args.state:return dict(status='PASS',state=args.state,attempts=info['job']['attempts'])
|
|
time.sleep(.2)
|
|
raise AssertionError('Pipeline deadline exceeded: '+args.mode)
|
|
if args.mode=='unready':
|
|
import urllib.request,urllib.error
|
|
codes=[]
|
|
for suffix in ['/health/ready',path+'/content']:
|
|
request=urllib.request.Request(c.base+suffix,headers={'Authorization':'Bearer '+ctx['actor']['token']})
|
|
try:
|
|
with urllib.request.urlopen(request,timeout=10) as response:codes.append(response.status)
|
|
except urllib.error.HTTPError as exc:codes.append(exc.code)
|
|
assert codes==[503,503],codes
|
|
return dict(status='PASS',readiness_and_content=codes)
|
|
if args.mode=='audit':return info
|
|
if args.mode in {'published','drained'}:
|
|
client=connect();deadline=time.monotonic()+args.timeout
|
|
try:
|
|
while time.monotonic()<deadline:
|
|
if args.mode=='published':
|
|
current=inspect(ctx['job_id']);ids=[r['stream_id'] for r in current['outbox'] if r['published_at']]
|
|
if ids and all(client.xrange(STREAM,identifier,identifier) for identifier in ids):
|
|
return dict(status='PASS',stream_ids=ids)
|
|
else:
|
|
ids=ctx['stream_ids'];last=max(tuple(map(int,x.split('-'))) for x in ids)
|
|
groups=client.xinfo_groups(STREAM);group=next(r for r in groups if r['name']==GROUP)
|
|
delivered=tuple(map(int,group['last-delivered-id'].split('-')))
|
|
pending={r['message_id'] for r in client.xpending_range(STREAM,GROUP,'-','+',10000)}
|
|
if delivered>=last and not pending.intersection(ids):return dict(status='PASS',acked=len(ids))
|
|
time.sleep(.2)
|
|
finally:client.close()
|
|
raise AssertionError('Broker state deadline exceeded')
|
|
if args.mode=='arm':
|
|
with connection() as db:
|
|
db.execute('INSERT INTO pipeline_faults(job_id,phase) VALUES (%s,%s) ON CONFLICT (job_id,phase) DO UPDATE SET fired_at=NULL',
|
|
(ctx['job_id'],args.phase))
|
|
return dict(armed=True,phase=args.phase)
|
|
if args.mode=='snapshot':
|
|
current=c.call('GET',path,actor=ctx['reader'],schema='Attachment')['json']
|
|
assert current['status']=='ready' and current['error_code'] is None
|
|
content=c.call('GET',path+'/content',actor=ctx['reader'])['bytes']
|
|
assert content==fixture
|
|
variants={v['name']:v for v in current['variants']};assert set(variants)=={'thumbnail','crop','optimized'}
|
|
digests={}
|
|
for name,meta in variants.items():
|
|
data=c.call('GET',path+'/content?variant='+name,actor=ctx['reader'])['bytes']
|
|
assert len(data)==meta['size_bytes'] and hashlib.sha256(data).hexdigest()==meta['sha256']
|
|
digests[name]=meta['sha256']
|
|
keys=[]
|
|
for prefix in ['originals/','variants/']:
|
|
keys.extend(r['Key'] for r in storage.objects(prefix+str(job['attachment_id'])+'/'))
|
|
expected=1+3
|
|
# После новой версии прежние объекты остаются для аудита; текущий набор ровно 4.
|
|
current_keys=[k for k in keys if '/v'+str(att['pipeline_version'])+'/' in k]
|
|
assert len(current_keys)==expected and len(set(current_keys))==expected
|
|
info=inspect(ctx['job_id'])
|
|
assert info['job']['status']=='ready' and info['attachment']['current_job_id']==job['id']
|
|
assert len([r for r in info['events'] if r['event']=='ready'])==1
|
|
deadline=time.monotonic()+5
|
|
while storage.head(info['job']['staging_key']) is not None and time.monotonic()<deadline:time.sleep(.1)
|
|
assert storage.head(info['job']['staging_key']) is None,'Staging not cleaned after ready'
|
|
return dict(status='PASS',attachment=current,job_id=ctx['job_id'],pipeline_version=att['pipeline_version'],
|
|
attempts=info['job']['attempts'],current_keys=sorted(current_keys),all_final_keys=sorted(keys),
|
|
variants_sha256=digests,original_sha256=hashlib.sha256(content).hexdigest(),
|
|
ready_commits=1,staging_deleted=True,queued_to_ready_seconds=round((datetime.fromisoformat(current['updated_at'].replace('Z','+00:00'))-job['created_at']).total_seconds(),6),
|
|
events=info['events'],outbox=info['outbox'])
|
|
if args.mode=='duplicate':
|
|
client=connect()
|
|
try:
|
|
result=[]
|
|
for _ in range(ctx.get('copies',1)):
|
|
result.append(publish(client,payload(job,ctx.get('attempt',max(1,job['attempts'])))))
|
|
finally:client.close()
|
|
return dict(stream_ids=result)
|
|
if args.mode=='invalid-job':
|
|
client=connect();bad=payload(job,max(1,job['attempts']));bad['url']='http://not-allowed.invalid/'
|
|
try:identifier=publish(client,bad)
|
|
finally:client.close()
|
|
deadline=time.monotonic()+10
|
|
while time.monotonic()<deadline:
|
|
with connection() as db:
|
|
row=db.execute('SELECT error_code FROM broker_rejections WHERE stream_id=%s',(identifier,)).fetchone()
|
|
if row:return dict(status='PASS',error_code=row['error_code'])
|
|
time.sleep(.2)
|
|
raise AssertionError('Invalid broker message not rejected')
|
|
if args.mode=='missing-stage':
|
|
storage.delete(job['staging_key']);return dict(deleted=True)
|
|
if args.mode=='restore-stage':
|
|
storage.put(io.BytesIO(fixture),job['staging_key'],len(fixture),'image/png',hashlib.sha256(fixture).hexdigest(),
|
|
base64.b64encode(hashlib.md5(fixture).digest()).decode())
|
|
return dict(restored=True)
|
|
if args.mode=='replay':return replay(job['id'])
|
|
if args.mode=='version':
|
|
result=new_version(job['attachment_id'],ctx.get('version',2))
|
|
return dict(ctx,job_id=result['job_id'])
|
|
if args.mode=='failed':
|
|
failed=c.call('GET',path,actor=ctx['reader'],schema='Attachment')['json']
|
|
assert failed['status']=='failed' and failed['error_code']
|
|
c.call('GET',path+'/content',409,actor=ctx['reader'])
|
|
c.call('POST','/api/v1/chats/'+ctx['chat']['id']+'/messages',409,actor=ctx['actor'],
|
|
body={'text':'','attachment_ids':[str(job['attachment_id'])]},headers={'Idempotency-Key':uuid.uuid4().hex})
|
|
return dict(status='PASS',error_code=failed['error_code'],attempts=job['attempts'],events=info['events'])
|
|
if args.mode=='cleanup':
|
|
# Вызывается при остановленном worker: текущий queued не должен быть удалён.
|
|
old_key='staging/'+str(uuid.uuid4())+'/'+str(uuid.uuid4())
|
|
def put(key):storage.put(io.BytesIO(fixture),key,len(fixture),'image/png',hashlib.sha256(fixture).hexdigest(),
|
|
base64.b64encode(hashlib.md5(fixture).digest()).decode())
|
|
put(old_key);time.sleep(3.2)
|
|
fresh_key='staging/'+str(uuid.uuid4())+'/'+str(uuid.uuid4());put(fresh_key)
|
|
dry=cleanup(2,False);assert storage.head(old_key)
|
|
applied=cleanup(2,True)
|
|
assert storage.head(old_key) is None and storage.head(fresh_key) and storage.head(job['staging_key'])
|
|
storage.delete(fresh_key)
|
|
return dict(status='PASS',orphan_removed=True,fresh_and_queued_preserved=True,dry_run=dry,apply=applied)
|
|
if args.mode=='privacy':
|
|
import urllib.request,urllib.error
|
|
from src.config import S3_ENDPOINT,S3_BUCKET
|
|
try:urllib.request.urlopen(S3_ENDPOINT+'/'+S3_BUCKET+'/'+att['object_key'],timeout=5)
|
|
except urllib.error.HTTPError as exc:assert exc.code==403
|
|
else:raise AssertionError('Public bucket')
|
|
return dict(status='PASS',anonymous_get=403)
|
|
|
|
|
|
if __name__=='__main__':
|
|
result=main()
|
|
print(json.dumps(result,ensure_ascii=False,default=str))
|