forked from mtusi2026/mtusi2026lab5
Реализовать лабораторную работу 5
This commit is contained in:
@@ -0,0 +1,83 @@
|
||||
#!/usr/bin/env python3
|
||||
from support import *
|
||||
import random,threading,concurrent.futures,statistics,datetime,hashlib
|
||||
from client import arguments,run
|
||||
|
||||
def worker_sample():
|
||||
command='''printf 'memory ';cat /sys/fs/cgroup/memory.current; printf 'cpu ';awk '/^usage_usec/{print $2}' /sys/fs/cgroup/cpu.stat; printf 'rss '; for p in $(cat /sys/fs/cgroup/cgroup.procs); do if [ "$(cat /proc/$p/comm 2>/dev/null)" = dotnet ]; then awk '/^VmRSS:/{print $2}' /proc/$p/status 2>/dev/null; fi; done'''
|
||||
lines=compose('exec','-T','worker','sh','-c',command).splitlines()
|
||||
mem=int(lines[0].split()[1]);cpu=int(lines[1].split()[1]);rss=sum(int(x) for x in ('\n'.join(lines[2:]).replace('rss ','').split()))*1024
|
||||
return {'time':time.time(),'memory_bytes':mem,'cpu_usec':cpu,'rss_bytes':rss}
|
||||
def main():
|
||||
args=arguments('Concurrency/prefetch overload research');c=Client(args.base_url,args.ca_file,timeout=100);a,b,e,chat=c.bootstrap()
|
||||
rng=random.Random(202605)
|
||||
large=Image.frombytes('RGB',(1024,1024),rng.randbytes(1024*1024*3));out=io.BytesIO();large.save(out,format='PNG',compress_level=1)
|
||||
images={'small':(ROOT/'tests/fixtures/sample.png').read_bytes(),'large':out.getvalue()}
|
||||
report={'hypothesis':'With fixed worker CPU, more simultaneous image processes need not improve throughput and can increase RSS; bounded admission protects the queue when the worker stops.',
|
||||
'profile':{'settings':[[1,1],[2,2],[4,4]],'repeats':3,'batch':8,'upload_clients':4,'worker_cpu':1,'worker_memory_limit_mib':1024,'warmup_images':1,'image_sizes_bytes':{k:len(v) for k,v in images.items()}},'runs':[]}
|
||||
configurations=[(1,1),(2,2),(4,4)]
|
||||
try:
|
||||
wait(lambda:sql("SELECT count(*) FROM attachment_jobs WHERE state IN ('queued','processing')")=='0')
|
||||
for repeat in range(3):
|
||||
for label in (['small','large'] if repeat%2==0 else ['large','small']):
|
||||
for concurrency,prefetch in configurations[repeat:]+configurations[:repeat]:
|
||||
env={'WORKER_CONCURRENCY':str(concurrency),'WORKER_PREFETCH':str(prefetch)}
|
||||
compose('up','-d','--no-deps','--force-recreate','worker',env=env)
|
||||
wait(lambda:'Worker ready:' in compose('logs','--tail','5','worker'),40)
|
||||
warm=upload(c,a,chat,images[label],name='warm.png')['json'];ready(c,a,warm)
|
||||
samples=[];stop=threading.Event()
|
||||
def poll():
|
||||
while not stop.is_set():
|
||||
try:samples.append(worker_sample())
|
||||
except Exception:pass
|
||||
stop.wait(.2)
|
||||
thread=threading.Thread(target=poll);thread.start();started=time.monotonic();requests=[]
|
||||
def submit(index):
|
||||
begin=time.monotonic();result=upload(c,a,chat,images[label],name=f'{label}-{repeat}-{index}.png')
|
||||
requests.append({'upload_seconds':time.monotonic()-begin,'status':result['status']});return result['json']
|
||||
try:
|
||||
with concurrent.futures.ThreadPoolExecutor(max_workers=4) as pool:attachments=list(pool.map(submit,range(8)))
|
||||
ids=','.join("'"+item['id']+"'" for item in attachments)
|
||||
wait(lambda:sql('SELECT count(*) FROM attachment_jobs WHERE state=\'ready\' AND attachment_id IN ('+ids+')')=='8',180)
|
||||
finally:stop.set();thread.join()
|
||||
elapsed=time.monotonic()-started
|
||||
values=json.loads(sql('''SELECT json_agg(json_build_object('id',j.id,'ready_seconds',extract(epoch from j.completed_at-j.created_at),'queue_lag_seconds',extract(epoch from (SELECT min(e.created_at) FROM attachment_job_events e WHERE e.job_id=j.id AND e.event='processing')-j.created_at),'attempts',j.attempts)) FROM attachment_jobs j WHERE j.attachment_id IN ('''+ids+')'))
|
||||
check(all(row['attempts']==1 for row in values),'unplanned retries in comparison run')
|
||||
row={'repeat':repeat+1,'image':label,'concurrency':concurrency,'prefetch':prefetch,'successful_jobs':8,'errors':0,'seconds':elapsed,'throughput':8/elapsed,
|
||||
'p95_ready_seconds':sorted(v['ready_seconds'] for v in values)[-1], 'p95_queue_lag_seconds':sorted(v['queue_lag_seconds'] for v in values)[-1],
|
||||
'peak_rss_bytes':max(v['rss_bytes'] for v in samples),'peak_cgroup_memory_bytes':max(v['memory_bytes'] for v in samples),
|
||||
'worker_cpu_seconds':(samples[-1]['cpu_usec']-samples[0]['cpu_usec'])/1e6,'requests':requests,'jobs':values,'samples':samples}
|
||||
report['runs'].append(row)
|
||||
(ROOT/'evidence/overload-progress.json').write_text(json.dumps(report,indent=2)+'\n')
|
||||
print(f"run {len(report['runs'])}/18: {label}, {concurrency}/{prefetch}, {row['throughput']:.2f} ready/s",flush=True)
|
||||
compose('stop','worker');compose('up','-d','--no-deps','--force-recreate','--wait','api',env={'PIPELINE_CAPACITY':'4'});wait_api(c)
|
||||
def pressure(index):return upload(c,a,chat,name='pressure-'+str(index)+'.png',expected=[202,429])
|
||||
with concurrent.futures.ThreadPoolExecutor(max_workers=8) as pool:attempts=list(pool.map(pressure,range(8)))
|
||||
accepted=[json.loads(r['bytes']) for r in attempts if r['status']==202];rejected=sum(r['status']==429 for r in attempts)
|
||||
pending=int(sql("SELECT count(*) FROM attachment_jobs WHERE state IN ('queued','processing')"))
|
||||
check(len(accepted)==4 and rejected==4 and pending==4,'admission bound was exceeded')
|
||||
before=time.monotonic();compose('up','-d','--no-deps','--force-recreate','worker')
|
||||
for att in accepted:ready(c,a,att)
|
||||
report['backpressure']={'attempted':8,'accepted':4,'rejected_429':4,'pending_at_limit':pending,'all_accepted_recovered':True,'recovery_seconds':time.monotonic()-before}
|
||||
report['environment']=subprocess.check_output(['docker','info','--format','{{.OSType}} {{.Architecture}} {{.NCPU}} CPUs {{.MemTotal}} bytes RAM']).decode().strip()
|
||||
h=hashlib.sha256()
|
||||
for source in sorted((ROOT/'src/Messenger.Api').rglob('*.cs')):
|
||||
if 'obj' in source.parts or 'bin' in source.parts:continue
|
||||
h.update(str(source.relative_to(ROOT)).encode());h.update(source.read_bytes())
|
||||
report['source_sha256']=h.hexdigest()
|
||||
(ROOT/'evidence/overload.json').write_text(json.dumps(report,indent=2)+'\n')
|
||||
lines=['# Очередь под нагрузкой','','Три повтора; одинаковые CPU/RAM worker; batch 8, четыре HTTP-клиента.','',
|
||||
'| Файл | Concurrency / prefetch | Готовых/с, медиана | p95 до ready, s | p95 ожидания, s | RSS процессов, MiB |','| --- | --- | ---: | ---: | ---: | ---: |']
|
||||
for label in images:
|
||||
for concurrency,prefetch in configurations:
|
||||
group=[r for r in report['runs'] if r['image']==label and r['concurrency']==concurrency]
|
||||
med=lambda key:statistics.median(r[key] for r in group)
|
||||
lines.append(f"| {label} | {concurrency}/{prefetch} | {med('throughput'):.3f} | {med('p95_ready_seconds'):.3f} | {med('p95_queue_lag_seconds'):.3f} | {med('peak_rss_bytes')/1048576:.1f} |")
|
||||
lines+=['','p95: nearest rank; при batch 8 это максимальная задержка. RSS: сумма VmRSS','процессов dotnet внутри worker, включая дочерние декодеры; общие страницы могут','считаться несколько раз. memory.current измерен отдельно. Период выборок 200 ms','плюс docker exec; короткие пики могут быть пропущены. Время включает загрузку','batch и ожидание последнего ready, без регистрации и прогрева. Queue lag: от','создания записи задания до первой processing. Время до ready — по часам PostgreSQL.','',
|
||||
'Backpressure: при остановленном worker лимит 4 принял ровно 4 из 8 файлов;','остальные получили 429. После запуска обработались все четыре принятых задания.','',
|
||||
'Исходные результаты: evidence/overload.json. Один Docker-host, небольшие batch,','параллельно могут работать другие локальные приложения. Эти значения не являются','пределом производительности сервера. Вывод сравнения относится к этому профилю.']
|
||||
lines+=['','','','В этом профиле для small один обработчик оказался быстрее двух и четырёх.','Для large вариант 2/2 дал лучшую медиану throughput и меньшую p95 готовности,','чем 1/1, при большем RSS. Четыре обработчика уменьшили время ожидания начала,','но увеличили полное время обработки и память. Поэтому по умолчанию оставлены','2/1: два параллельных обработчика с небольшим prefetch. Низкий prefetch','ограничивает число взятых сообщений; пара 2/1 отдельно не входит в сравнение,','поэтому не заявляется как измеренный оптимум.']
|
||||
(ROOT/'docs/OVERLOAD.md').write_text('\n'.join(lines)+'\n')
|
||||
print('PASS: overload research and bounded admission',flush=True)
|
||||
finally:compose('up','-d','--no-deps','--force-recreate','--wait','api','worker')
|
||||
if __name__=='__main__':run(main)
|
||||
@@ -0,0 +1,101 @@
|
||||
#!/usr/bin/env python3
|
||||
from support import *
|
||||
import hashlib,concurrent.futures
|
||||
from client import arguments,run
|
||||
|
||||
def main():
|
||||
args=arguments('Pipeline durability, image variants and controlled failures');c=Client(args.base_url,args.ca_file,timeout=100)
|
||||
a,b,e,chat=c.bootstrap();checks=[]
|
||||
png_bytes=(ROOT/'tests/fixtures/sample.png').read_bytes()
|
||||
upload(c,a,chat,b'bad',expected=415);upload(c,a,chat,png_bytes,mime='image/jpeg',expected=415)
|
||||
upload(c,a,chat,b'x'*(10485760+1),expected=413)
|
||||
upload(c,a,chat,png_bytes,name='../unsafe.png',expected=400)
|
||||
other=c.call('POST','/api/v1/chats',201,actor=a,body={'title':'Other','member_ids':[a['id']]},schema='Chat')['json']
|
||||
checks.append('HTTP size/MIME/corruption/filename validation remains compatible with Lab4')
|
||||
faultenv={'PIPELINE_FAULT_FILE':'/run/faults/control.json','JOB_MAX_ATTEMPTS':'3'}
|
||||
try:
|
||||
compose('stop','worker','dispatcher')
|
||||
att=upload(c,a,chat)['json'];id=job_id(att)
|
||||
check(att['status']=='queued','upload is not a queued snapshot')
|
||||
c.message(a,chat,'Queued image',attachments=[att['id']]);c.call('GET','/api/v1/attachments/'+att['id']+'/content',409,actor=b)
|
||||
check(sql("SELECT published_at IS NULL FROM attachment_outbox WHERE job_id='"+id+"'")=='t','outbox not retained')
|
||||
compose('restart','api');compose('restart','broker');wait_api(c)
|
||||
compose('up','-d','--wait','dispatcher',env=faultenv)
|
||||
wait(lambda:sql("SELECT published_at IS NOT NULL FROM attachment_outbox WHERE job_id='"+id+"'")=='t')
|
||||
queue_before=compose('exec','-T','-e','RABBITMQ_CTL_ERL_ARGS=+S 1:1','broker','rabbitmqctl','list_queues','-p','messenger','name','messages_ready','--formatter=json')
|
||||
compose('restart','broker');compose('up','-d','--wait','--wait-timeout','90','broker')
|
||||
compose('up','-d','--no-deps','worker',env=faultenv);meta=ready(c,b,att)
|
||||
check(c.call('GET','/api/v1/attachments/'+att['id']+'/content',actor=b)['bytes']==(ROOT/'tests/fixtures/sample.png').read_bytes(),'original changed')
|
||||
checks.append('202 while worker stopped; durable outbox survives API restart; published queue survives broker restart; same ID becomes ready')
|
||||
dimensions={v['name']:(v['width'],v['height']) for v in meta['variants']}
|
||||
check(dimensions=={'thumbnail':(256,160),'crop':(128,128),'optimized':(320,200)},'wrong image dimensions')
|
||||
for variant in meta['variants']:
|
||||
data=c.call('GET','/api/v1/attachments/'+att['id']+'/content?variant='+variant['name'],actor=b)['bytes']
|
||||
image=Image.open(io.BytesIO(data));check(image.size==dimensions[variant['name']],'encoded image dimensions differ')
|
||||
check(hashlib.sha256(data).hexdigest()==variant['sha256'] and len(data)==variant['size_bytes'],'variant checksum mismatch')
|
||||
check(not image.getexif(),'EXIF was retained in a variant')
|
||||
for endpoint in ('','/content?variant=thumbnail'):c.call('GET','/api/v1/attachments/'+att['id']+endpoint,404,actor=e)
|
||||
oriented=upload(c,a,chat,image_bytes(320,200,orientation=6),'rotated.jpg','image/jpeg')['json'];om=ready(c,a,oriented)
|
||||
check(next(v for v in om['variants'] if v['name']=='thumbnail')['width']==160,'EXIF orientation ignored')
|
||||
small=upload(c,a,chat,image_bytes(64,32,alpha=True),'alpha.png')['json'];sm=ready(c,a,small)
|
||||
thumb=c.call('GET','/api/v1/attachments/'+small['id']+'/content?variant=thumbnail',actor=a)['bytes'];im=Image.open(io.BytesIO(thumb))
|
||||
check(im.size==(64,32) and min(im.convert('RGB').getpixel((0,0)))>=250,'alpha is not white or small image upscaled')
|
||||
checks.append('thumbnail/crop/WebP bytes and dimensions; no EXIF; orientation applied; transparent small image remains small with white background; private variants')
|
||||
before=sql("SELECT attempts||':'||completed_at FROM attachment_jobs WHERE id='"+id+"'")
|
||||
for _ in range(3):compose('exec','-T','dispatcher','dotnet','Messenger.Api.dll','--redeliver',id)
|
||||
time.sleep(2);check(sql("SELECT attempts||':'||completed_at FROM attachment_jobs WHERE id='"+id+"'")==before,'ready duplicate reprocessed')
|
||||
checks.append('three duplicate ready deliveries are no-op')
|
||||
# Pause deterministically after all S3 writes, kill worker before result COMMIT/ack.
|
||||
for point in ('after_objects','after_commit'):
|
||||
compose('stop','worker')
|
||||
interrupted=upload(c,a,chat,name=point+'.png')['json'];jid=job_id(interrupted);fault(point,jid)
|
||||
compose('up','-d','--no-deps','--force-recreate','worker',env=faultenv);wait_fault()
|
||||
compose('kill','-s','SIGKILL','worker');clear_fault()
|
||||
compose('up','-d','--no-deps','worker',env=faultenv);ready(c,a,interrupted,130)
|
||||
count=int(sql("SELECT count(*) FROM attachment_job_events WHERE job_id='"+jid+"' AND event='ready'"))
|
||||
check(count==1,'completion was duplicated')
|
||||
checks.append(point+': worker killed, same logical job recovered, one published result')
|
||||
# Publish confirmed, dispatcher killed before marking the outbox.
|
||||
compose('stop','dispatcher','worker');pub=upload(c,a,chat,name='publisher.png')['json'];pubid=job_id(pub);fault('after_publish',pubid)
|
||||
compose('up','-d','--no-deps','--force-recreate','dispatcher',env=faultenv);wait_fault();compose('kill','-s','SIGKILL','dispatcher');clear_fault()
|
||||
compose('up','-d','--no-deps','dispatcher','worker',env=faultenv);ready(c,a,pub)
|
||||
check(sql("SELECT count(*) FROM attachment_job_events WHERE job_id='"+pubid+"' AND event='ready'")=='1','confirm-window duplicate effect')
|
||||
checks.append('publisher confirm before outbox COMMIT crash recovers without lost task or duplicate effect')
|
||||
# Permanent failure, without retrying invalid input forever.
|
||||
compose('stop','worker');bad=upload(c,a,chat,name='invalid-stage.png')['json'];bid=job_id(bad)
|
||||
staging=sql("SELECT staging_key FROM attachment_jobs WHERE id='"+bid+"'");s3('PUT',staging,b'broken')
|
||||
compose('up','-d','--no-deps','worker',env=faultenv)
|
||||
wait(lambda:sql("SELECT state FROM attachment_jobs WHERE id='"+bid+"'")=='failed')
|
||||
check(sql("SELECT attempts FROM attachment_jobs WHERE id='"+bid+"'")=='1','permanent failure retried')
|
||||
c.call('POST','/api/v1/chats/'+chat['id']+'/messages',409,actor=a,body={'text':'','attachment_ids':[bad['id']]},headers={'Idempotency-Key':uuid.uuid4().hex})
|
||||
checks.append('invalid staging checksum becomes failed after one attempt; failed attachment cannot be linked')
|
||||
compose('stop','worker');huge=upload(c,a,chat,name='worker-pixels.png')['json'];hid=job_id(huge)
|
||||
import struct,zlib
|
||||
payload=bytearray(png_bytes);payload[16:24]=struct.pack('>II',10000,10000);payload[29:33]=struct.pack('>I',zlib.crc32(payload[12:29]));payload=bytes(payload)
|
||||
staging=sql("SELECT staging_key FROM attachment_jobs WHERE id='"+hid+"'");s3('PUT',staging,payload)
|
||||
sql("UPDATE attachments SET sha256='"+hashlib.sha256(payload).hexdigest()+"',size_bytes="+str(len(payload))+" WHERE id='"+huge['id']+"'")
|
||||
compose('up','-d','--no-deps','worker',env=faultenv)
|
||||
wait(lambda:sql("SELECT state FROM attachment_jobs WHERE id='"+hid+"'")=='failed')
|
||||
check(sql("SELECT attempts||':'||error_code FROM attachment_jobs WHERE id='"+hid+"'")=='1:invalid_image','worker pixel guard failed')
|
||||
checks.append('worker independently rejects >40 million pixels before bitmap allocation')
|
||||
# Transient SQL failure after object writes: bounded retries, jitter/backoff, explicit replay.
|
||||
sql("CREATE FUNCTION test_pipeline_failure() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN IF NEW.filename='retry-me.png' AND NEW.status='ready' THEN RAISE EXCEPTION 'injected'; END IF; RETURN NEW; END $$; CREATE TRIGGER test_pipeline_failure BEFORE UPDATE ON attachments FOR EACH ROW EXECUTE FUNCTION test_pipeline_failure();")
|
||||
retry=upload(c,a,chat,name='retry-me.png')['json'];rid=job_id(retry)
|
||||
wait(lambda:sql("SELECT state FROM attachment_jobs WHERE id='"+rid+"'")=='failed',120)
|
||||
check(sql("SELECT attempts||':'||error_code FROM attachment_jobs WHERE id='"+rid+"'")=='3:retry_exhausted','retry limit failed')
|
||||
sql('DROP TRIGGER test_pipeline_failure ON attachments; DROP FUNCTION test_pipeline_failure();')
|
||||
compose('exec','-T','dispatcher','dotnet','Messenger.Api.dll','--replay',rid);ready(c,a,retry)
|
||||
finished=sql("SELECT completed_at FROM attachment_jobs WHERE id='"+rid+"'")
|
||||
compose('exec','-T','dispatcher','dotnet','Messenger.Api.dll','--replay',rid)
|
||||
check(sql("SELECT completed_at FROM attachment_jobs WHERE id='"+rid+"'")==finished,'replay reran successful job')
|
||||
checks.append('transient failure retries with bounded attempts then failed; explicit replay succeeds; replay of ready is no-op')
|
||||
wait(lambda:sql("SELECT staging_deleted_at IS NOT NULL FROM attachment_jobs WHERE id='"+rid+"'")=='t')
|
||||
check(sql("SELECT staging_deleted_at IS NULL FROM attachment_jobs WHERE id='"+bid+"'")=='t','failed staging was cleaned too soon')
|
||||
checks.append('ready staging cleaned after durable publication; failed staging retained for replay')
|
||||
report={'checks':checks,'broker_queue_before_restart':queue_before,'retry_test_max_attempts':3,'default_max_attempts':5}
|
||||
(ROOT/'evidence/pipeline.json').write_text(json.dumps(report,indent=2)+'\n');print('PASS: '+str(len(checks))+' pipeline scenarios')
|
||||
finally:
|
||||
clear_fault()
|
||||
sql('DROP TRIGGER IF EXISTS test_pipeline_failure ON attachments; DROP FUNCTION IF EXISTS test_pipeline_failure();')
|
||||
compose('up','-d','--no-deps','--force-recreate','dispatcher','worker')
|
||||
if __name__=='__main__':run(main)
|
||||
@@ -0,0 +1,57 @@
|
||||
import sys,subprocess,time,json,uuid,io
|
||||
from pathlib import Path
|
||||
ROOT=Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0,str(ROOT/'tests'))
|
||||
from client import Client,check
|
||||
from PIL import Image
|
||||
|
||||
def compose(*args,env=None,input=None,timeout=180):
|
||||
import os
|
||||
r=subprocess.run([str(ROOT/'scripts/compose.sh'),*args],cwd=ROOT,env={**os.environ,**(env or {})},input=input,capture_output=True,timeout=timeout)
|
||||
check(r.returncode==0,'Infrastructure command failed: '+r.stderr.decode()[-500:]);return r.stdout.decode()
|
||||
def sql(text):return compose('exec','-T','postgres','psql','-U','messenger','-d','messenger','-At','-c',text).strip()
|
||||
def parsed(c,method,path,expected=200,**kwargs):
|
||||
result=c.call(method,path,expected,**kwargs);return json.loads(result['bytes'])
|
||||
def upload(c,actor,chat,data=None,name='image.png',mime='image/png',expected=202):
|
||||
if data is None:data=(ROOT/'tests/fixtures/sample.png').read_bytes()
|
||||
from urllib.parse import quote
|
||||
return c.call('POST','/api/v1/chats/'+chat['id']+'/attachments?filename='+quote(name,safe=''),expected,actor=actor,raw=data,headers={'Content-Type':mime},schema='Attachment' if expected==202 else None)
|
||||
def job_id(attachment):return sql("SELECT id FROM attachment_jobs WHERE attachment_id='"+attachment['id']+"'")
|
||||
def wait(predicate,timeout=120):
|
||||
deadline=time.monotonic()+timeout
|
||||
while time.monotonic()<deadline:
|
||||
result=predicate()
|
||||
if result:return result
|
||||
time.sleep(.25)
|
||||
raise AssertionError('Condition timed out')
|
||||
def ready(c,actor,attachment,timeout=120):
|
||||
def status():
|
||||
meta=c.call('GET','/api/v1/attachments/'+attachment['id'],actor=actor,schema='Attachment')['json']
|
||||
check(meta['status']!='failed','Unexpected failed attachment: '+str(meta.get('error_code')))
|
||||
return meta if meta['status']=='ready' else None
|
||||
return wait(status,timeout)
|
||||
def wait_api(c):
|
||||
def status():
|
||||
try:c.call('GET','/health/ready');return True
|
||||
except Exception:return False
|
||||
wait(status,100)
|
||||
def s3(method,key,data=b''):
|
||||
import hashlib
|
||||
command='curl -fsS --max-time 20 --aws-sigv4 aws:amz:us-east-1:s3 --user "$(cat /run/secrets/s3_access):$(cat /run/secrets/s3_secret)" -H x-amz-content-sha256:'+hashlib.sha256(data).hexdigest()+' -X '+method+' '
|
||||
if method=='PUT':command+='--data-binary @- '
|
||||
command+='http://s3:8333/messenger/'+key
|
||||
return compose('exec','-T','api','sh','-c',command,input=data)
|
||||
def image_bytes(width,height,alpha=False,orientation=None):
|
||||
image=Image.new('RGBA' if alpha else 'RGB',(width,height),(0,0,0,0) if alpha else (50,140,220))
|
||||
out=io.BytesIO()
|
||||
if orientation:
|
||||
exif=Image.Exif();exif[274]=orientation;image.save(out,format='JPEG',exif=exif)
|
||||
else:image.save(out,format='PNG')
|
||||
return out.getvalue()
|
||||
def fault(point,id):
|
||||
folder=ROOT/'.local/faults';folder.mkdir(exist_ok=True,parents=True);folder.chmod(0o777)
|
||||
for suffix in ('','.used','.hit'):(folder/('control.json'+suffix)).unlink(missing_ok=True)
|
||||
p=folder/'control.json';p.write_text(json.dumps({'point':point,'job_id':id}));p.chmod(0o666)
|
||||
def wait_fault():return wait(lambda:(ROOT/'.local/faults/control.json.hit').exists(),60)
|
||||
def clear_fault():
|
||||
for suffix in ('','.used','.hit'):(ROOT/'.local/faults'/('control.json'+suffix)).unlink(missing_ok=True)
|
||||
Reference in New Issue
Block a user