526 lines
32 KiB
Python
526 lines
32 KiB
Python
|
|
"""Opt-in real business API regression against a localhost-only scanner fixture.
|
|||
|
|
|
|||
|
|
--manage-dev temporarily restarts only this project's idle dev backend, builds the
|
|||
|
|
current sources, and supplies ephemeral scanner settings. Finally restores normal
|
|||
|
|
dev settings and cleans only this run's marked business data. No hardware used.
|
|||
|
|
"""
|
|||
|
|
from __future__ import annotations
|
|||
|
|
|
|||
|
|
import argparse
|
|||
|
|
import datetime as dt
|
|||
|
|
import io
|
|||
|
|
import json
|
|||
|
|
import os
|
|||
|
|
from pathlib import Path
|
|||
|
|
import subprocess
|
|||
|
|
import threading
|
|||
|
|
import time
|
|||
|
|
import urllib.parse
|
|||
|
|
import urllib.request
|
|||
|
|
import uuid
|
|||
|
|
import struct
|
|||
|
|
from concurrent.futures import ThreadPoolExecutor
|
|||
|
|
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
|||
|
|
|
|||
|
|
from bootstrap_db import insert_new
|
|||
|
|
from cleanup_verification import cleanup
|
|||
|
|
from robot_simulator import ResourceStore
|
|||
|
|
from verify_cmvr_native import Client, require, safe
|
|||
|
|
from verify_scan_only import ScanOnlyVerifier, NOTE
|
|||
|
|
|
|||
|
|
ROOT = Path(__file__).resolve().parents[1]
|
|||
|
|
JAVA = Path(os.environ.get('JAVA_HOME', r'C:\Users\Administrator\.jdks\ms-17.0.19')) / 'bin/java.exe'
|
|||
|
|
MAVEN = Path(os.environ.get('AM_FREESCAN_MAVEN', r'E:\soft\IntelliJ IDEA 2025.2.5\plugins\maven\lib\maven3\bin\mvn.cmd'))
|
|||
|
|
REPORT = ROOT / '.local/scanner-workflow-verification.json'
|
|||
|
|
JAR = ROOT / 'am-backend/yudao-server/target/yudao-server.jar'
|
|||
|
|
CREATE_NO_WINDOW = getattr(subprocess, 'CREATE_NO_WINDOW', 0)
|
|||
|
|
PLY = b'ply\nformat ascii 1.0\nelement vertex 3\nproperty float x\nproperty float y\nproperty float z\nend_header\n0 0 0\n1 0 0\n0 1 0\n'
|
|||
|
|
STL = b'solid fixture\nfacet normal 0 0 1\nouter loop\nvertex 0 0 0\nvertex 1 0 0\nvertex 0 1 0\nendloop\nendfacet\nendsolid fixture\n'
|
|||
|
|
|
|||
|
|
|
|||
|
|
def wait_for(fn, timeout=30, message='condition'):
|
|||
|
|
deadline = time.monotonic() + timeout
|
|||
|
|
last = None
|
|||
|
|
while time.monotonic() < deadline:
|
|||
|
|
try:
|
|||
|
|
last = fn()
|
|||
|
|
if last:
|
|||
|
|
return last
|
|||
|
|
except (OSError, ValueError):
|
|||
|
|
pass
|
|||
|
|
time.sleep(.2)
|
|||
|
|
raise AssertionError('Timed out: ' + message + ' ' + str(last))
|
|||
|
|
|
|||
|
|
|
|||
|
|
class Supplier:
|
|||
|
|
def __init__(self,preview_width=8):
|
|||
|
|
self.key = uuid.uuid4().hex
|
|||
|
|
self.session = uuid.uuid4().hex
|
|||
|
|
self.project = ''
|
|||
|
|
self.scanning = False
|
|||
|
|
self.preview = False
|
|||
|
|
self.uncertain = False
|
|||
|
|
self.hold_controls = False
|
|||
|
|
self.failed_operation = None
|
|||
|
|
self.tasks = {}
|
|||
|
|
self.files = {}
|
|||
|
|
self.posts = []
|
|||
|
|
self.sequence = 1
|
|||
|
|
self.lock = threading.RLock()
|
|||
|
|
from PIL import Image
|
|||
|
|
pixels = io.BytesIO()
|
|||
|
|
if preview_width > 8:
|
|||
|
|
Image.effect_noise((preview_width,round(preview_width*9/16)),60).convert('RGB').save(pixels,format='JPEG',quality=85)
|
|||
|
|
else:Image.new('RGB', (8, 8), '#224466').save(pixels, format='JPEG')
|
|||
|
|
self.jpeg = pixels.getvalue()
|
|||
|
|
supplier = self
|
|||
|
|
|
|||
|
|
class Handler(BaseHTTPRequestHandler):
|
|||
|
|
def log_message(self, *_): pass
|
|||
|
|
def reply(self, value, code=200, content='application/json', headers=None):
|
|||
|
|
payload = value if isinstance(value, bytes) else json.dumps(value).encode()
|
|||
|
|
self.send_response(code)
|
|||
|
|
self.send_header('Content-Type', content)
|
|||
|
|
self.send_header('Content-Length', str(len(payload)))
|
|||
|
|
for k, v in (headers or {}).items(): self.send_header(k, str(v))
|
|||
|
|
self.end_headers()
|
|||
|
|
self.wfile.write(payload)
|
|||
|
|
|
|||
|
|
def do_GET(self):
|
|||
|
|
with supplier.lock:
|
|||
|
|
if self.path != '/' and self.headers.get('X-Api-Key') != supplier.key:
|
|||
|
|
return self.reply({'error': {'code': 'unauthorized'}}, 401)
|
|||
|
|
if self.path == '/api/v1/status':
|
|||
|
|
return self.reply(dict(sessionId=supplier.session, projectId=supplier.project,
|
|||
|
|
projectReady=bool(supplier.project), scanning=supplier.scanning,
|
|||
|
|
previewEnabled=supplier.preview, busy=supplier.hold_controls, stateUncertain=supplier.uncertain,
|
|||
|
|
restartRequired=False, deviceOnline=True, state='ready', meshState='none'))
|
|||
|
|
if self.path == '/api/v1/preview/metrics':
|
|||
|
|
return self.reply(dict(latestSequence=supplier.sequence, encoderRunning=supplier.preview))
|
|||
|
|
if self.path == '/api/v1/preview/image':
|
|||
|
|
supplier.sequence += 1
|
|||
|
|
return self.reply(supplier.jpeg, content='image/jpeg', headers={'X-Frame-Sequence': supplier.sequence})
|
|||
|
|
if self.path.startswith('/api/v1/tasks/'):
|
|||
|
|
result = supplier.tasks.get(self.path.rsplit('/', 1)[1])
|
|||
|
|
return self.reply(result or {'error': {'code': 'task_not_found'}}, 200 if result else 404)
|
|||
|
|
if self.path.startswith('/api/v1/files/'):
|
|||
|
|
payload = supplier.files.get(self.path.rsplit('/', 1)[1])
|
|||
|
|
return self.reply(payload or b'', 200 if payload else 404, 'application/octet-stream')
|
|||
|
|
return self.reply(dict(service='LOCALHOST REGRESSION FIXTURE', running=True))
|
|||
|
|
|
|||
|
|
def do_POST(self):
|
|||
|
|
with supplier.lock:
|
|||
|
|
if self.headers.get('X-Api-Key') != supplier.key:
|
|||
|
|
return self.reply({'error': {'code': 'unauthorized'}}, 401)
|
|||
|
|
body = json.loads(self.rfile.read(int(self.headers.get('Content-Length', 0))))
|
|||
|
|
supplier.posts.append(dict(path=self.path, body=body))
|
|||
|
|
task_id = uuid.uuid4().hex
|
|||
|
|
result = {}
|
|||
|
|
failure = supplier.failed_operation == self.path
|
|||
|
|
if failure:
|
|||
|
|
supplier.failed_operation = None
|
|||
|
|
elif self.path == '/api/v1/projects':
|
|||
|
|
supplier.project = uuid.uuid4().hex
|
|||
|
|
result['projectId'] = supplier.project
|
|||
|
|
elif self.path == '/api/v1/scan/start': supplier.scanning = True
|
|||
|
|
elif self.path == '/api/v1/scan/stop': supplier.scanning = False
|
|||
|
|
elif self.path == '/api/v1/preview/start': supplier.preview = True
|
|||
|
|
elif self.path == '/api/v1/preview/stop': supplier.preview = False
|
|||
|
|
elif self.path in ('/api/v1/exports', '/api/v1/data/snapshots'):
|
|||
|
|
ext, payload = ('stl', STL) if self.path.endswith('exports') else ('ply', PLY)
|
|||
|
|
file_id = uuid.uuid4().hex
|
|||
|
|
supplier.files[file_id] = payload
|
|||
|
|
result['files'] = [dict(fileId=file_id, name='fixture.' + ext, format=ext,
|
|||
|
|
bytes=len(payload), downloadUrl='/api/v1/files/' + file_id)]
|
|||
|
|
supplier.tasks[task_id] = dict(taskId=task_id, state='failed' if failure else 'succeeded',
|
|||
|
|
result=result, error=dict(code='fixture_sdk_error', message='Intentional regression failure', httpStatus=409) if failure else None)
|
|||
|
|
self.reply(dict(taskId=task_id, statusUrl='/api/v1/tasks/' + task_id), 202)
|
|||
|
|
|
|||
|
|
self.server = ThreadingHTTPServer(('127.0.0.1', 0), Handler)
|
|||
|
|
self.port = self.server.server_address[1]
|
|||
|
|
|
|||
|
|
def start(self): threading.Thread(target=self.server.serve_forever, daemon=True).start()
|
|||
|
|
def close(self): self.server.shutdown(); self.server.server_close()
|
|||
|
|
def count(self, path): return sum(p['path'] == path for p in self.posts)
|
|||
|
|
|
|||
|
|
|
|||
|
|
def scanner_flow(sleep_ms=5000, missing=None):
|
|||
|
|
specs = [('connect', 'SCANNER_INITIALIZE', {}), ('project', 'SCANNER_CREATE_PROJECT', {'name':'REGRESSION','mode':'laser'}),
|
|||
|
|
('parameters', 'SCANNER_PARAMETERS', {'brightness': 10}), ('preview', 'SCANNER_PREVIEW_START', {}),
|
|||
|
|
('startScan', 'SCANNER_START', {}), ('wait', 'SLEEP', None),
|
|||
|
|
('snapshot', 'SCANNER_SNAPSHOT', {'maxPoints':1000, 'include':['points','markers','meshes']}),
|
|||
|
|
('stopScan', 'SCANNER_STOP', {}), ('mesh', 'SCANNER_MESH', {}),
|
|||
|
|
('confirmMesh', 'SCANNER_MESH_CONFIRM', {}), ('export', 'SCANNER_EXPORT', {'name':'REGRESSION','formats':['stl']}),
|
|||
|
|
('previewStop', 'SCANNER_PREVIEW_STOP', {})]
|
|||
|
|
nodes = [dict(id='start', type='start', properties=dict(name='开始', action='START', schemaVersion=2,
|
|||
|
|
inputParams=[dict(name='verificationMarker',type='String',required=True)],
|
|||
|
|
resourceRoles=[dict(roleKey='scanner',displayName='扫描工位',required=True,
|
|||
|
|
deviceSlots=[dict(slotKey='scanner',displayName='扫描仪',deviceKind=14,required=True,allowReuse=False)])]))]
|
|||
|
|
for identifier, action, body in specs:
|
|||
|
|
p = dict(name=identifier, action=action, inputParams=[], nodeParams=[])
|
|||
|
|
if action == 'SLEEP': p['nodeParams'] = [dict(name='delayMs',type='input',input=str(sleep_ms))]
|
|||
|
|
else:
|
|||
|
|
p.update(nodeType='EDGE',executionTarget=dict(roleKey='scanner',deviceSlotKey='scanner'))
|
|||
|
|
p['nodeParams'] = [dict(name='requestJson',type='input',input=json.dumps(body)),
|
|||
|
|
dict(name='timeoutMs',type='input',input=120000)]
|
|||
|
|
if missing == identifier: p['nodeParams'].pop()
|
|||
|
|
nodes.append(dict(id=identifier, type='sleep' if action == 'SLEEP' else 'serviceNode', properties=p))
|
|||
|
|
nodes.append(dict(id='end',type='end',properties=dict(name='结束',action='END')))
|
|||
|
|
for i,n in enumerate(nodes): n.update(x=100+250*i,y=180)
|
|||
|
|
return dict(schemaVersion=2,nodes=nodes,edges=[dict(id='edge-'+str(i),sourceNodeId=nodes[i]['id'],targetNodeId=nodes[i+1]['id']) for i in range(len(nodes)-1)])
|
|||
|
|
|
|||
|
|
|
|||
|
|
class ScannerVerifier(ScanOnlyVerifier):
|
|||
|
|
def __init__(self, prefix, supplier):
|
|||
|
|
super().__init__()
|
|||
|
|
self.prefix = prefix
|
|||
|
|
self.sample_code = prefix + '-SAMPLE'
|
|||
|
|
self.robot = prefix + '-robot'
|
|||
|
|
self.device = prefix + '-device'
|
|||
|
|
self.supplier = supplier
|
|||
|
|
self.report.update(prefix=prefix, hardwareRequests=0)
|
|||
|
|
self.review_seconds = 0
|
|||
|
|
self.live_review_seconds = 0
|
|||
|
|
self.performance = False
|
|||
|
|
|
|||
|
|
def check(self, name, **detail):
|
|||
|
|
self.report['checks'].append(dict(name=name,passed=True,**safe(detail)))
|
|||
|
|
print('PASS',name,flush=True)
|
|||
|
|
REPORT.write_text(json.dumps(self.report,ensure_ascii=False,indent=2),encoding='utf-8')
|
|||
|
|
|
|||
|
|
def create_scanner_case(self, suffix, **kwargs):
|
|||
|
|
case=self.create_case(suffix)
|
|||
|
|
case['graph']=scanner_flow(**kwargs)
|
|||
|
|
version=self.native.publish(case['itemId'],case['graph'],NOTE)
|
|||
|
|
case.update(versionId=version['id'],versionNo=version['versionNo'])
|
|||
|
|
return case
|
|||
|
|
|
|||
|
|
def prepare_body(self, task_id, case_id, **overrides):
|
|||
|
|
options=dict(robotId=self.robot,runParams=dict(verificationMarker='LOCALHOST-SCANNER-FIXTURE'),
|
|||
|
|
runtimeAssignments=[dict(roleKey='scanner',members=[dict(memberKey='scanner-1',robotId=self.robot,devices={'scanner':self.device})])])
|
|||
|
|
options.update(overrides)
|
|||
|
|
return super().prepare_body(task_id,case_id,**options)
|
|||
|
|
|
|||
|
|
def assert_occupied(self, task_id, occupied=True):
|
|||
|
|
rows=self.native.db.select('SELECT task_id FROM lab_scan_robot_occupation WHERE robot_id=%s AND deleted=0',(self.robot,))
|
|||
|
|
require(bool(rows)==occupied,'Scanner occupation was not retained/released correctly')
|
|||
|
|
if rows: require(str(rows[0]['task_id'])==str(task_id),'Wrong occupation owner')
|
|||
|
|
|
|||
|
|
def waiting(self, execution_id):
|
|||
|
|
inst=self.binding(execution_id)['cmvr_inst_id']
|
|||
|
|
wait_for(lambda:any(r.get('action')=='SLEEP' and str(r.get('status')) in ('RUNNING','1') for r in self.native.node_logs(inst)),20,'scan acquisition wait')
|
|||
|
|
|
|||
|
|
def view(self, execution_id, suffix='', rejected=False):
|
|||
|
|
return self.api('GET','/lab/execution/scanner-view'+suffix,query=dict(executionId=execution_id),rejected=rejected)
|
|||
|
|
|
|||
|
|
def binary(self, path, execution_id):
|
|||
|
|
req=urllib.request.Request(self.client.base_url+'/admin-api/lab/execution/scanner-view'+path+'?'+urllib.parse.urlencode(dict(executionId=execution_id)),
|
|||
|
|
headers={'tenant-id':'1','Authorization':'Bearer '+self.client._token})
|
|||
|
|
with urllib.request.urlopen(req,timeout=15) as response: return response.headers,response.read()
|
|||
|
|
|
|||
|
|
def snapshot(self, execution_id, nonce):
|
|||
|
|
req=urllib.request.Request(self.client.base_url+'/admin-api/lab/execution/scanner-view/snapshot?'+urllib.parse.urlencode(dict(executionId=execution_id)),
|
|||
|
|
method='POST',data=b'',headers={'tenant-id':'1','Authorization':'Bearer '+self.client._token,'X-Scanner-Command-Key':nonce})
|
|||
|
|
with urllib.request.urlopen(req,timeout=15) as response: result=json.load(response)
|
|||
|
|
require(result['code']==0,'Snapshot rejected: '+str(result))
|
|||
|
|
return result['data']
|
|||
|
|
|
|||
|
|
def run_flow(self):
|
|||
|
|
bad=self.create_scanner_case('missing-timeout',missing='startScan')
|
|||
|
|
task=self.import_task('bad',bad['caseId'],1)
|
|||
|
|
self.prepare(task,bad['caseId'],expect_ready=False)
|
|||
|
|
result=self.api('POST','/lab/scan-task/precheck',dict(taskId=task))
|
|||
|
|
require(any(not i['passed'] and 'timeoutMs' in i['message'] for i in result['items']),'Missing timeout not reported before start')
|
|||
|
|
self.start_rejected(task)
|
|||
|
|
self.check('缺少扫描节点超时参数:预检和开始均阻止,未发送设备操作')
|
|||
|
|
|
|||
|
|
good=self.create_scanner_case('complete',sleep_ms=5000+self.live_review_seconds*1000)
|
|||
|
|
task=self.import_task('two-units',good['caseId'],2)
|
|||
|
|
self.api('PUT','/lab/scan-task/prepare',self.prepare_body(task,good['caseId'],runParams={}))
|
|||
|
|
result=self.api('POST','/lab/scan-task/precheck',dict(taskId=task))
|
|||
|
|
require(not result['passed'] and any('verificationMarker' in i['message'] for i in result['items']),'Required start parameter not checked')
|
|||
|
|
self.start_rejected(task)
|
|||
|
|
detail=self.prepare(task,good['caseId'])
|
|||
|
|
first,body=self.start(task,detail['units'][0])
|
|||
|
|
require(str(self.api('POST','/lab/scan-task/start-unit',body))==str(first),'Repeated start duplicated execution')
|
|||
|
|
self.waiting(first)
|
|||
|
|
view=wait_for(lambda:self.view(first) if self.view(first).get('available') else None,10,'bound scanner view')
|
|||
|
|
headers,jpeg=self.binary('/image',first)
|
|||
|
|
require(headers['Content-Type'].startswith('image/jpeg') and jpeg==self.supplier.jpeg,'Live image not relayed')
|
|||
|
|
before=self.supplier.count('/api/v1/data/snapshots')
|
|||
|
|
nonce=uuid.uuid4().hex
|
|||
|
|
accepted=self.snapshot(first,nonce)
|
|||
|
|
again=self.snapshot(first,nonce)
|
|||
|
|
require(again['commandKey']==accepted['commandKey'] and self.supplier.count('/api/v1/data/snapshots')==before+1,'Snapshot re-POSTed')
|
|||
|
|
assets=wait_for(lambda:self.view(first,'/assets'),10,'point cloud snapshot')
|
|||
|
|
_,payload=self.binary('/asset/'+assets[0]['fileId'],first)
|
|||
|
|
require(payload==PLY,'Point cloud bytes differ')
|
|||
|
|
self.check('真实业务开始幂等、实时画面与本件绑定、点云快照重复点击仅下发一次')
|
|||
|
|
|
|||
|
|
if self.performance:
|
|||
|
|
def image_probe(_):
|
|||
|
|
started=time.perf_counter()
|
|||
|
|
_,frame=self.binary('/image',first)
|
|||
|
|
require(frame==self.supplier.jpeg,'Concurrent image differed')
|
|||
|
|
return round((time.perf_counter()-started)*1000,2)
|
|||
|
|
with ThreadPoolExecutor(max_workers=8) as pool:latencies=sorted(pool.map(image_probe,range(16)))
|
|||
|
|
self.report['imagePerformance']=dict(concurrentReaders=8,requests=16,bytes=len(self.supplier.jpeg),
|
|||
|
|
p50Ms=latencies[len(latencies)//2],p95Ms=latencies[-2],maxMs=latencies[-1],hardwareRequests=0)
|
|||
|
|
print('IMAGE PERFORMANCE '+json.dumps(self.report['imagePerformance']),flush=True)
|
|||
|
|
|
|||
|
|
self.review_browser(task,first,live=True)
|
|||
|
|
self.api('POST','/lab/scan-task/pause',dict(taskId=task))
|
|||
|
|
self.wait_execution(first,'PAUSED',5)
|
|||
|
|
require(not self.supplier.scanning,'Pause did not stop acquisition')
|
|||
|
|
self.assert_occupied(task)
|
|||
|
|
self.api('POST','/lab/scan-task/resume',dict(taskId=task))
|
|||
|
|
require(self.supplier.scanning,'Resume did not restore acquisition')
|
|||
|
|
self.wait_execution(first,timeout=30+self.live_review_seconds)
|
|||
|
|
self.verify_logs(first)
|
|||
|
|
require(not self.supplier.scanning,'Completion left scanner acquiring')
|
|||
|
|
self.assert_occupied(task)
|
|||
|
|
history=self.view(first)
|
|||
|
|
require(not history['available'] and history['state']=='history','Historical execution attached to live scanner')
|
|||
|
|
files=self.view(first,'/assets')
|
|||
|
|
require(any(f.get('format')=='stl' for f in files),'Completed mesh export absent')
|
|||
|
|
self.check('暂停停止采集并保留占用、恢复同一工程、首件完成保留任务资源与成果')
|
|||
|
|
self.review_browser(task,first)
|
|||
|
|
|
|||
|
|
second,_=self.start(task,self.task(task)['units'][1])
|
|||
|
|
self.waiting(second)
|
|||
|
|
require(self.view(second)['projectId']!=view['projectId'],'Second sample reused first project binding')
|
|||
|
|
require(self.view(second,'/assets')==[],'Second sample sees previous assets')
|
|||
|
|
self.view(first,'/image',rejected=True)
|
|||
|
|
self.api('GET','/lab/execution/scanner-view/asset/'+files[0]['fileId'],query=dict(executionId=second),rejected=True)
|
|||
|
|
self.wait_execution(second,timeout=30+self.live_review_seconds)
|
|||
|
|
self.verify_logs(second)
|
|||
|
|
wait_for(lambda:self.task(task)['task']['status']=='COMPLETED',10,'two-unit task completion')
|
|||
|
|
self.assert_occupied(task,False)
|
|||
|
|
self.active_tasks.discard(task)
|
|||
|
|
self.check('第二件独立工程,跨件图像和文件访问阻止,全部完成后释放资源')
|
|||
|
|
|
|||
|
|
fail=self.create_scanner_case('sdk-failure',sleep_ms=200)
|
|||
|
|
task=self.import_task('sdk-failure',fail['caseId'],1)
|
|||
|
|
detail=self.prepare(task,fail['caseId'])
|
|||
|
|
self.supplier.failed_operation='/api/v1/parameters'
|
|||
|
|
execution,_=self.start(task,detail['units'][0])
|
|||
|
|
self.wait_execution(execution,'FAILED',30)
|
|||
|
|
self.assert_occupied(task)
|
|||
|
|
self.wait_stop_confirmation(task)
|
|||
|
|
detail=self.task(task)
|
|||
|
|
execution,_=self.start(task,detail['units'][0],reason='LOCALHOST regression retry')
|
|||
|
|
self.wait_execution(execution,timeout=30)
|
|||
|
|
self.assert_occupied(task,False)
|
|||
|
|
self.active_tasks.discard(task)
|
|||
|
|
self.check('设备任务HTTP成功但SDK失败时整件失败,人工重试建立新执行并成功')
|
|||
|
|
|
|||
|
|
task=self.import_task('cancel-stop',good['caseId'],1)
|
|||
|
|
detail=self.prepare(task,good['caseId'])
|
|||
|
|
execution,_=self.start(task,detail['units'][0])
|
|||
|
|
self.waiting(execution)
|
|||
|
|
self.supplier.uncertain=True
|
|||
|
|
self.api('POST','/lab/scan-task/cancel',dict(taskId=task,reason='LOCALHOST stop uncertainty regression'))
|
|||
|
|
require(self.task(task)['config']['stopPending'],'Unconfirmed stop silently released resources')
|
|||
|
|
self.assert_occupied(task)
|
|||
|
|
self.supplier.uncertain=False
|
|||
|
|
self.api('POST','/lab/scan-task/confirm-stop',dict(taskId=task,reason='LOCALHOST fixture status restored'))
|
|||
|
|
wait_for(lambda:not self.task(task)['config'].get('stopPending'),15,'stop acknowledgement')
|
|||
|
|
self.assert_occupied(task,False)
|
|||
|
|
require(not self.supplier.scanning,'Cancel failed to stop scanner')
|
|||
|
|
self.active_tasks.discard(task)
|
|||
|
|
self.check('取消时停止未确认保留资源,状态恢复并确认停止后释放')
|
|||
|
|
|
|||
|
|
def verify_logs(self,execution):
|
|||
|
|
inst=self.binding(execution)['cmvr_inst_id']
|
|||
|
|
full=self.client.native('GET','/test/inst/log/detail',query=dict(instId=inst,pageNum=1,pageSize=1000))
|
|||
|
|
rows=full['rows']
|
|||
|
|
require(rows and all(str(r.get('status')).upper() in ('SUCCESS','SUCCEEDED','SKIPPED','0') for r in rows),'Successful execution has unfinished/failed node logs')
|
|||
|
|
cursor=rows[len(rows)//2]['id']
|
|||
|
|
delta=self.client.native('GET','/test/inst/log/detail',query=dict(instId=inst,afterId=cursor,pageNum=1,pageSize=1000))
|
|||
|
|
require([str(r['id']) for r in delta['rows']]==[str(r['id']) for r in rows if int(r['id'])>=int(cursor)],'Incremental log query lost or duplicated rows')
|
|||
|
|
rejected=self.client.native('GET','/test/inst/log/detail',query=dict(instId=inst,afterId=-1),expected=None)
|
|||
|
|
require(rejected['code'] not in (0,200,500),'Negative log cursor was not rejected')
|
|||
|
|
self.report.setdefault('completedExecutionLogs',[]).append(dict(executionId=str(execution),nodes=len(rows),incrementalNodes=len(delta['rows']),allTerminal=True))
|
|||
|
|
|
|||
|
|
def review_browser(self,task,execution,live=False):
|
|||
|
|
seconds=self.live_review_seconds if live else self.review_seconds
|
|||
|
|
if not seconds:return
|
|||
|
|
# Inspect immutable files after the first item completes, while waiting
|
|||
|
|
# for the next item. Never race a human review against a control POST.
|
|||
|
|
phase='scanner-live-browser-review' if live else 'scanner-browser-review'
|
|||
|
|
review=ROOT/'.local'/f'{phase}.json'
|
|||
|
|
done=ROOT/'.local'/f'{phase}.done'
|
|||
|
|
review.write_text(json.dumps(dict(prefix=self.prefix,taskId=str(task),executionId=str(execution)),ensure_ascii=False),encoding='utf-8')
|
|||
|
|
print('BROWSER REVIEW READY: '+str(review),flush=True)
|
|||
|
|
deadline=time.monotonic()+seconds
|
|||
|
|
try:
|
|||
|
|
while time.monotonic()<deadline:
|
|||
|
|
if done.exists() and done.read_text(encoding='utf-8').strip()==self.prefix:break
|
|||
|
|
time.sleep(.2)
|
|||
|
|
finally:
|
|||
|
|
review.unlink(missing_ok=True)
|
|||
|
|
if done.exists() and done.read_text(encoding='utf-8').strip()==self.prefix:done.unlink()
|
|||
|
|
|
|||
|
|
def start_rejected(self, task):
|
|||
|
|
body=dict(taskId=task,unitId=self.task(task)['units'][0]['id'],expectedRevision=self.task(task)['config']['revision'],
|
|||
|
|
loadedConfirmed=True,idempotencyKey=uuid.uuid4().hex,physicalSerial='LOCALHOST-FIXTURE')
|
|||
|
|
before=len(self.supplier.posts)
|
|||
|
|
self.api('POST','/lab/scan-task/start-unit',body,rejected=True)
|
|||
|
|
require(len(self.supplier.posts)==before,'Rejected start reached scanner')
|
|||
|
|
|
|||
|
|
|
|||
|
|
class LocalResources:
|
|||
|
|
def __init__(self,prefix,port):
|
|||
|
|
self.store=ResourceStore()
|
|||
|
|
self.prefix=prefix
|
|||
|
|
self.robot=prefix+'-robot'
|
|||
|
|
self.device=prefix+'-device'
|
|||
|
|
self.port=port
|
|||
|
|
self.stop=threading.Event()
|
|||
|
|
self.error=None
|
|||
|
|
|
|||
|
|
def provision(self):
|
|||
|
|
with self.store.cursor() as c:
|
|||
|
|
for table in ('lab_resource_occupation','lab_scan_robot_occupation'):
|
|||
|
|
c.execute('SELECT COUNT(*) n FROM '+table+' WHERE deleted=0')
|
|||
|
|
require(c.fetchone()['n']==0,'Dev backend has active resource occupations')
|
|||
|
|
insert_new(c,'iot_robot',dict(id=uuid.uuid4().hex,robot_id=self.robot,robot_code=self.robot,
|
|||
|
|
robot_name=self.prefix,robot_type='GENERIC',archived_status='0',connect_status='1',
|
|||
|
|
create_by=self.prefix,update_by=self.prefix,remark='LOCALHOST SCANNER REGRESSION'),['robot_id'])
|
|||
|
|
insert_new(c,'iot_device',dict(id=uuid.uuid4().hex,robot_id=self.robot,device_id=self.device,device_name=self.prefix,
|
|||
|
|
device_kind=14,device_type='LOCALHOST_SCANNER_FIXTURE',device_index=0,enabled='1',online_status='1',
|
|||
|
|
has_error='0',manager_state=1,health_status=1,create_by=self.prefix,update_by=self.prefix,remark='LOCALHOST SCANNER REGRESSION'),['robot_id','device_id'])
|
|||
|
|
self.store.connection.commit()
|
|||
|
|
self.beat()
|
|||
|
|
self.thread=threading.Thread(target=self.heartbeat,daemon=True)
|
|||
|
|
self.thread.start()
|
|||
|
|
|
|||
|
|
def beat(self):
|
|||
|
|
now=dt.datetime.now()
|
|||
|
|
with self.store.cursor() as c:
|
|||
|
|
c.execute("UPDATE iot_robot SET connect_status='1',ip_address='127.0.0.1',port=%s,last_heartbeat_time=%s,runtime_status='2',update_time=%s WHERE robot_id=%s AND create_by=%s",(self.port,now,now,self.robot,self.prefix))
|
|||
|
|
c.execute("UPDATE iot_device SET online_status='1',last_seen_time=%s,status_updated_time=%s,update_time=%s WHERE robot_id=%s AND device_id=%s AND create_by=%s",(now,now,now,self.robot,self.device,self.prefix))
|
|||
|
|
self.store.connection.commit()
|
|||
|
|
|
|||
|
|
def heartbeat(self):
|
|||
|
|
while not self.stop.wait(1):
|
|||
|
|
try:self.beat()
|
|||
|
|
except Exception as e:self.error=str(e);return
|
|||
|
|
|
|||
|
|
def close(self):
|
|||
|
|
self.stop.set()
|
|||
|
|
if hasattr(self,'thread'):self.thread.join(5)
|
|||
|
|
with self.store.cursor() as c:
|
|||
|
|
c.execute('SELECT COUNT(*) n FROM lab_resource_occupation WHERE robot_id=%s AND deleted=0',(self.robot,))
|
|||
|
|
require(c.fetchone()['n']==0,'Scanner still occupied: refusing fixture removal')
|
|||
|
|
c.execute('SELECT lab_device_id FROM lab_runtime_device_link WHERE robot_id=%s AND device_id=%s',(self.robot,self.device))
|
|||
|
|
for r in c.fetchall():
|
|||
|
|
c.execute("DELETE FROM lab_device WHERE id=%s AND external_type='CMVR' AND external_id IN (SELECT id FROM iot_device WHERE robot_id=%s AND device_id=%s AND create_by=%s)",
|
|||
|
|
(r['lab_device_id'],self.robot,self.device,self.prefix))
|
|||
|
|
c.execute('DELETE FROM lab_runtime_device_link WHERE robot_id=%s AND device_id=%s',(self.robot,self.device))
|
|||
|
|
c.execute('DELETE FROM iot_device WHERE robot_id=%s AND device_id=%s AND create_by=%s',(self.robot,self.device,self.prefix))
|
|||
|
|
c.execute('DELETE FROM iot_robot WHERE robot_id=%s AND create_by=%s',(self.robot,self.prefix))
|
|||
|
|
self.store.connection.commit()
|
|||
|
|
self.store.connection.close()
|
|||
|
|
|
|||
|
|
|
|||
|
|
class DevBackend:
|
|||
|
|
def __init__(self): self.process=None; self.log=None; self.changed=False
|
|||
|
|
def stop_existing(self):
|
|||
|
|
# Exact project JAR match; no other Java process is touched.
|
|||
|
|
script="$p=Get-CimInstance Win32_Process -Filter \"name = 'java.exe'\" | Where-Object { $_.CommandLine -like '*-jar*' -and $_.CommandLine.Contains('"+str(JAR)+"') }; if (@($p).Count -gt 1) { throw 'Multiple project backends' }; $listeners=@(Get-NetTCPConnection -LocalPort 48090 -State Listen -ErrorAction SilentlyContinue); if ($listeners | Where-Object { $_.OwningProcess -notin @($p.ProcessId) }) { throw 'Port 48090 belongs to an unrecognized process; no process stopped' }; $p | ForEach-Object { Stop-Process -Id $_.ProcessId -Force }"
|
|||
|
|
subprocess.run(['powershell','-NoProfile','-Command',script],check=True,creationflags=CREATE_NO_WINDOW)
|
|||
|
|
self.changed=True
|
|||
|
|
time.sleep(2)
|
|||
|
|
|
|||
|
|
def build(self):
|
|||
|
|
print('Building current dev backend',flush=True)
|
|||
|
|
env=os.environ.copy();env['JAVA_HOME']=str(JAVA.parent.parent)
|
|||
|
|
with (ROOT/'.local/logs/scanner-workflow-build.log').open('w') as log:
|
|||
|
|
subprocess.run([str(MAVEN),'-pl','yudao-server','-am','package','-DskipTests'],cwd=ROOT/'am-backend',env=env,stdout=log,stderr=subprocess.STDOUT,check=True,creationflags=CREATE_NO_WINDOW)
|
|||
|
|
|
|||
|
|
def start(self,supplier=None,resources=None):
|
|||
|
|
runtime=json.loads((ROOT/'.local/runtime.json').read_text(encoding='utf-8-sig'))
|
|||
|
|
require(runtime['mysql']['host']=='192.168.28.10' and runtime['mysql']['database']=='am-freescan','Unexpected database')
|
|||
|
|
env=os.environ.copy()
|
|||
|
|
env.update(AM_FREESCAN_DB_USER=runtime['mysql']['user'],AM_FREESCAN_DB_PASSWORD=runtime['mysql']['password'],AM_FREESCAN_REDIS_PASSWORD=runtime['redis']['password'])
|
|||
|
|
name='scanner-workflow-backend' if supplier else 'backend-dev'
|
|||
|
|
args=[str(JAVA),'-Djdk.net.unixdomain.tmpdir='+str(ROOT/'.local/nio-tcp-fallback'),'-Dfile.encoding=UTF-8','-jar',str(JAR),
|
|||
|
|
'--spring.profiles.active=dev','--spring.data.redis.database='+str(runtime['redis']['database']),
|
|||
|
|
'--lab.artifact.nas-root='+str(ROOT/'.local/artifacts'),'--logging.file.name='+str(ROOT/'.local/logs'/f'{name}.log')]
|
|||
|
|
if supplier: args += ['--cmvr.scanner.host=127.0.0.1','--cmvr.scanner.port='+str(supplier.port),'--cmvr.scanner.api-key='+supplier.key,
|
|||
|
|
'--cmvr.scanner.robot-id='+resources.robot,'--cmvr.scanner.device-id='+resources.device,'--cmvr.scanner.poll-interval-ms=30']
|
|||
|
|
self.log=(ROOT/'.local/logs'/f'{name}-launcher.log').open('w')
|
|||
|
|
self.process=subprocess.Popen(args,cwd=ROOT,env=env,stdout=self.log,stderr=subprocess.STDOUT,creationflags=CREATE_NO_WINDOW)
|
|||
|
|
def ready():
|
|||
|
|
if self.process.poll() is not None: raise RuntimeError('Backend exited: '+name)
|
|||
|
|
with urllib.request.urlopen('http://127.0.0.1:48090/admin-api/system/tenant/get-id-by-name?name=AM%20FreeScan',timeout=2) as response:return response.status==200
|
|||
|
|
wait_for(ready,100,'backend startup')
|
|||
|
|
print('Dev backend ready ('+('localhost fixture' if supplier else 'normal configuration')+')',flush=True)
|
|||
|
|
|
|||
|
|
def stop(self):
|
|||
|
|
if self.process and self.process.poll() is None: self.process.terminate();self.process.wait(15)
|
|||
|
|
if self.log:self.log.close()
|
|||
|
|
self.process=None
|
|||
|
|
|
|||
|
|
|
|||
|
|
def main():
|
|||
|
|
parser=argparse.ArgumentParser(description=__doc__)
|
|||
|
|
parser.add_argument('--manage-dev',action='store_true',required=True)
|
|||
|
|
parser.add_argument('--review-seconds',type=int,default=0,choices=range(0,301),metavar='0..300')
|
|||
|
|
parser.add_argument('--live-review-seconds',type=int,default=0,choices=range(0,121),metavar='0..120',help='Inspect a running acquisition during a longer deterministic SLEEP node')
|
|||
|
|
parser.add_argument('--skip-build',action='store_true',help='Reuse a JAR only when newer than backend sources')
|
|||
|
|
parser.add_argument('--performance',action='store_true',help='Use a million-point PLY and 1920x1080 JPEG; probe 8 concurrent viewers')
|
|||
|
|
args=parser.parse_args()
|
|||
|
|
if args.performance:
|
|||
|
|
global PLY
|
|||
|
|
count=1000000
|
|||
|
|
header=('ply\nformat binary_little_endian 1.0\nelement vertex '+str(count)+'\nproperty float x\nproperty float y\nproperty float z\nend_header\n').encode()
|
|||
|
|
cloud=bytearray(header);cloud.extend(bytes(count*12))
|
|||
|
|
for i in range(count):struct.pack_into('<fff',cloud,len(header)+i*12,i%1000,i//1000,(i%101)/100)
|
|||
|
|
PLY=bytes(cloud)
|
|||
|
|
prefix='E2E-SCANNER-'+dt.datetime.now().strftime('%m%d%H%M%S')+'-'+uuid.uuid4().hex[:4]
|
|||
|
|
print('Regression prefix:',prefix,flush=True)
|
|||
|
|
supplier=Supplier(1920 if args.performance else 8);supplier.start()
|
|||
|
|
resources=LocalResources(prefix,supplier.port)
|
|||
|
|
backend=DevBackend();verifier=None;passed=False
|
|||
|
|
try:
|
|||
|
|
resources.provision()
|
|||
|
|
backend.stop_existing()
|
|||
|
|
if args.skip_build:
|
|||
|
|
require(JAR.exists(),'No built backend JAR')
|
|||
|
|
sources=[p for p in (ROOT/'am-backend').rglob('*') if p.is_file() and 'target' not in p.parts and p.suffix in ('.java','.yaml','.yml','.xml')]
|
|||
|
|
require(all(p.stat().st_mtime<=JAR.stat().st_mtime for p in sources),'Backend source changed; build is required')
|
|||
|
|
else:backend.build()
|
|||
|
|
backend.start(supplier,resources)
|
|||
|
|
verifier=ScannerVerifier(prefix,supplier)
|
|||
|
|
verifier.review_seconds=args.review_seconds
|
|||
|
|
verifier.live_review_seconds=args.live_review_seconds
|
|||
|
|
verifier.performance=args.performance
|
|||
|
|
verifier.run_flow()
|
|||
|
|
passed=True
|
|||
|
|
finally:
|
|||
|
|
try:
|
|||
|
|
if verifier:
|
|||
|
|
supplier.uncertain=False
|
|||
|
|
for task in verifier.active_tasks:
|
|||
|
|
state=verifier.task(task)
|
|||
|
|
if state['task']['status'] not in ('COMPLETED','CANCELLED'):
|
|||
|
|
verifier.api('POST','/lab/scan-task/cancel',dict(taskId=task,reason='LOCALHOST regression cleanup'))
|
|||
|
|
if verifier.task(task)['config'].get('stopPending'):
|
|||
|
|
verifier.api('POST','/lab/scan-task/confirm-stop',dict(taskId=task,reason='LOCALHOST regression cleanup confirmation'))
|
|||
|
|
result=cleanup([prefix],apply=True)
|
|||
|
|
require(not cleanup([prefix])['counts'],'Regression business data remains')
|
|||
|
|
verifier.report.update(passed=passed,cleanup=result,supplierPosts=len(supplier.posts))
|
|||
|
|
REPORT.write_text(json.dumps(verifier.report,ensure_ascii=False,indent=2),encoding='utf-8')
|
|||
|
|
print('Marked business data cleaned',flush=True)
|
|||
|
|
resources.close()
|
|||
|
|
finally:
|
|||
|
|
backend.stop()
|
|||
|
|
supplier.close()
|
|||
|
|
if backend.changed:backend.start()
|
|||
|
|
print(json.dumps(dict(passed=passed,checks=len(verifier.report['checks']),hardwareRequests=0,report=str(REPORT)),ensure_ascii=False))
|
|||
|
|
|
|||
|
|
|
|||
|
|
if __name__=='__main__':main()
|