237 lines
11 KiB
Python
237 lines
11 KiB
Python
"""Real controller/agent regression with a controllable ADB smart socket server."""
|
|
import argparse
|
|
import json
|
|
import os
|
|
from pathlib import Path
|
|
import secrets
|
|
import socket
|
|
import socketserver
|
|
import subprocess
|
|
import threading
|
|
import time
|
|
import urllib.request
|
|
import uuid
|
|
|
|
from e2e import ROOT, free_port, wait_until, Echo, Phone
|
|
|
|
|
|
def receive(stream, size):
|
|
data = b''
|
|
while len(data) < size:
|
|
chunk = stream.recv(size-len(data))
|
|
if not chunk:
|
|
raise EOFError('ADB socket closed')
|
|
data += chunk
|
|
return data
|
|
|
|
|
|
class AdbHandler(socketserver.BaseRequestHandler):
|
|
def handle(self):
|
|
try:
|
|
self.request.settimeout(15)
|
|
service = receive(self.request, int(receive(self.request, 4), 16)).decode()
|
|
with self.server.lock:
|
|
available = self.server.available
|
|
devices = dict(self.server.devices)
|
|
if service == 'host:devices-l':
|
|
self.server.queries += 1
|
|
delay = self.server.delay
|
|
self.server.queried.set()
|
|
else:
|
|
delay = 0
|
|
if not available:
|
|
return
|
|
if delay:
|
|
time.sleep(delay)
|
|
if service == 'host:devices-l':
|
|
text = ''.join(f'{serial}\t{state} product:test\n' for serial, state in devices.items()).encode()
|
|
self.request.sendall(b'OKAY'+f'{len(text):04x}'.encode()+text)
|
|
return
|
|
serial = service.removeprefix('host:transport:')
|
|
if not service.startswith('host:transport:') or devices.get(serial) != 'device':
|
|
self.request.sendall(b'FAIL0007offline')
|
|
return
|
|
self.request.sendall(b'OKAY')
|
|
service = receive(self.request, int(receive(self.request, 4), 16))
|
|
if service != b'tcp:5555':
|
|
return
|
|
self.request.sendall(b'OKAY')
|
|
while data := self.request.recv(65536):
|
|
self.request.sendall(data)
|
|
except (OSError, EOFError, ValueError):
|
|
pass
|
|
|
|
|
|
class Adb(socketserver.ThreadingTCPServer):
|
|
allow_reuse_address = True
|
|
daemon_threads = True
|
|
block_on_close = False
|
|
|
|
def __init__(self):
|
|
super().__init__(('127.0.0.1', 0), AdbHandler)
|
|
self.lock = threading.Lock()
|
|
self.devices = {}
|
|
self.available = True
|
|
self.delay = 0
|
|
self.queries = 0
|
|
self.queried = threading.Event()
|
|
|
|
def set(self, devices=None, available=None, delay=None):
|
|
with self.lock:
|
|
if devices is not None:
|
|
self.devices = devices
|
|
if available is not None:
|
|
self.available = available
|
|
if delay is not None:
|
|
self.delay = delay
|
|
|
|
|
|
def main():
|
|
parser = argparse.ArgumentParser(description=__doc__)
|
|
parser.add_argument('--rust-dir', type=Path, default=ROOT/'target/debug')
|
|
parser.add_argument('--bin-dir', type=Path, default=ROOT/'bin')
|
|
args = parser.parse_args()
|
|
suffix = '.exe' if os.name == 'nt' else ''
|
|
folder = ROOT/'work/agent-adb-presence'/uuid.uuid4().hex
|
|
folder.mkdir(parents=True, mode=0o700)
|
|
config = folder/'agent.json'
|
|
tokens = {key: secrets.token_hex(32) for key in ('ADS_AGENT_TOKEN', 'ADS_CLIENT_TOKEN', 'ADS_ADMIN_TOKEN')}
|
|
port = free_port()
|
|
url = f'ws://127.0.0.1:{port}'
|
|
processes, logs = [], []
|
|
|
|
def environment(*roles):
|
|
result = dict(os.environ)
|
|
for key in (*tokens, 'ADS_CONNECT_ADDRESS'):
|
|
result.pop(key, None)
|
|
result.update({key: tokens[key] for key in roles})
|
|
result['RUST_LOG'] = 'ads_agent=info,ads_core=info,warn'
|
|
return result
|
|
|
|
def launch(name, command, *roles):
|
|
output = open(folder/(name+'.log'), 'wb')
|
|
logs.append(output)
|
|
process = subprocess.Popen(list(map(str, command)), env=environment(*roles), stdout=output, stderr=output,
|
|
creationflags=subprocess.CREATE_NO_WINDOW if os.name == 'nt' else 0)
|
|
processes.append(process)
|
|
return process
|
|
|
|
def get(path, role='ADS_CLIENT_TOKEN'):
|
|
request = urllib.request.Request(url.replace('ws:', 'http:')+path, headers={'Authorization':'Bearer '+tokens[role]})
|
|
with urllib.request.urlopen(request, timeout=3) as response:
|
|
return json.load(response)
|
|
|
|
def cli(*commands):
|
|
result = subprocess.run([str(args.rust_dir/('adsctl'+suffix)), '--json', '--config', str(config), *commands],
|
|
env=environment(), capture_output=True, text=True, encoding='utf-8', timeout=8)
|
|
assert result.returncode == 0, result.stderr
|
|
return json.loads(result.stdout)
|
|
|
|
def listed():
|
|
return {device['id'] for device in get('/v1/devices')}
|
|
|
|
with Adb() as adb, Phone(('127.0.0.1', 0), Echo) as direct:
|
|
for server in (adb, direct):
|
|
threading.Thread(target=server.serve_forever, daemon=True).start()
|
|
try:
|
|
config.write_text(json.dumps({'version':1, 'id':'presence-test', 'name':'ADB presence test', 'server':url,
|
|
'allow_insecure':True, 'adb_server':f'127.0.0.1:{adb.server_address[1]}', 'devices':[
|
|
{'id':'phone-a', 'adb_serial':'USB-A'}, {'id':'phone-b', 'adb_serial':'USB-B'},
|
|
{'id':'direct-phone', 'target':f'127.0.0.1:{direct.server_address[1]}'}]}, indent=2), encoding='utf-8')
|
|
config.chmod(0o600)
|
|
original = config.read_bytes()
|
|
launch('controller', [args.bin_dir/('ads-server'+suffix), '--listen', f'127.0.0.1:{port}'], *tokens)
|
|
wait_until(lambda: get('/v1/devices') == [], 'controller startup')
|
|
started = time.monotonic()
|
|
launch('agent', [args.rust_dir/('ads-agent'+suffix), '--config', config], 'ADS_AGENT_TOKEN')
|
|
wait_until(lambda: listed() == {'direct-phone'}, 'initial missing ADB devices are not registered')
|
|
pid = cli('status')['pid']
|
|
adb.set({'USB-A':'device', 'USB-B':'unauthorized'})
|
|
wait_until(lambda: listed() == {'direct-phone', 'phone-a'}, 'only authorized device registered')
|
|
status = cli('status')
|
|
assert any(d['id']=='phone-b' and not d['connected'] and '未授权' in d['last_error'] for d in status['devices'])
|
|
adb.set({'USB-A':'device', 'USB-B':'device'})
|
|
wait_until(lambda: len(listed()) == 3, 'second device authorized')
|
|
|
|
client_port = free_port()
|
|
launch('client', [args.rust_dir/('ads-client'+suffix), '--server', url, '--allow-insecure', '--device', 'phone-a',
|
|
'--listen', f'127.0.0.1:{client_port}', '--transport', 'relay', '--no-auto-connect'], 'ADS_CLIENT_TOKEN')
|
|
wait_until(lambda: any(d['id']=='phone-a' and d['busy'] for d in get('/v1/devices')), 'client lease')
|
|
with socket.create_connection(('127.0.0.1', client_port), timeout=5) as stream:
|
|
stream.settimeout(8)
|
|
stream.sendall(b'before')
|
|
assert receive(stream, 6) == b'before'
|
|
adb.set({'USB-A':'device'})
|
|
wait_until(lambda: listed() == {'direct-phone', 'phone-a'}, 'unplug removes only second device')
|
|
stream.sendall(b'after')
|
|
assert receive(stream, 5) == b'after'
|
|
adb.set({'USB-A':'offline', 'USB-B':'device'})
|
|
wait_until(lambda: listed() == {'direct-phone', 'phone-b'}, 'offline state unregisters first device')
|
|
try:
|
|
assert stream.recv(1) == b'', 'offline upstream connection was retained'
|
|
except ConnectionResetError:
|
|
pass
|
|
assert cli('status')['pid'] == pid
|
|
assert config.read_bytes() == original, 'monitor rewrote configuration or IDs'
|
|
adb.set(available=False)
|
|
wait_until(lambda: listed() == {'direct-phone'}, 'ADB server failure withdraws all serial devices')
|
|
assert any(a['online'] for a in get('/v3/agents', 'ADS_ADMIN_TOKEN')), 'Agent management went offline'
|
|
adb.set({'USB-A':'device', 'USB-B':'device'}, available=True)
|
|
wait_until(lambda: len(listed()) == 3, 'ADB server recovery restores original IDs')
|
|
def recovered_stream():
|
|
try:
|
|
with socket.create_connection(('127.0.0.1', client_port), timeout=2) as stream:
|
|
stream.settimeout(2)
|
|
stream.sendall(b'recovered')
|
|
return receive(stream, 9) == b'recovered'
|
|
except (OSError, EOFError):
|
|
return False
|
|
wait_until(recovered_stream, 'client reacquires lease and forwards after recovery')
|
|
elapsed = time.monotonic()-started
|
|
assert adb.queries <= elapsed/2+3, 'ADB polling was duplicated per phone'
|
|
cli('devices', 'disable', 'phone-b')
|
|
wait_until(lambda: listed() == {'direct-phone', 'phone-a'}, 'disabled device withdrawn')
|
|
time.sleep(2.5)
|
|
assert 'phone-b' not in listed(), 'monitor re-enabled a disabled device'
|
|
adb.queried.clear()
|
|
adb.set(delay=8)
|
|
assert adb.queried.wait(4), 'delayed ADB query did not start'
|
|
request_started = time.monotonic()
|
|
assert cli('status')['pid'] == pid
|
|
assert time.monotonic()-request_started < 3, 'ADB query blocked management IPC'
|
|
wait_until(lambda: listed() == {'direct-phone'}, 'hung ADB query expires')
|
|
adb.set(delay=0)
|
|
wait_until(lambda: listed() == {'direct-phone', 'phone-a'}, 'query timeout recovery respects disabled device')
|
|
# Policy operations use existing ConfigGet/Set so older controllers need no protocol upgrade.
|
|
assert cli('config', 'get')['auto_register_usb'] is False
|
|
cli('devices', 'auto-usb', 'on')
|
|
assert cli('config', 'get')['auto_register_usb'] is True
|
|
cli('devices', 'remove', 'phone-b')
|
|
saved = cli('config', 'get')
|
|
assert 'USB-B' in saved['ignored_usb_serials']
|
|
cli('devices', 'unignore', 'USB-B')
|
|
assert 'USB-B' not in cli('config', 'get')['ignored_usb_serials']
|
|
stale = cli('config', 'get')
|
|
cli('devices', 'auto-usb', 'off')
|
|
conflict = subprocess.run([str(args.rust_dir/('adsctl'+suffix)), '--json', '--config', str(config), 'request'],
|
|
input=json.dumps({'op':'config_set','config':stale,'expected_config':stale}),
|
|
env=environment(), capture_output=True, text=True, encoding='utf-8', timeout=8)
|
|
assert conflict.returncode != 0, 'stale policy overwrote a concurrent configuration change'
|
|
assert cli('config', 'get')['auto_register_usb'] is False
|
|
print('PASS: USB policy defaults off; removal persists ignore; CLI can unignore and disable')
|
|
print('PASS: missing/offline/unauthorized/server failure withdraw registration; recovery preserves IDs and PID')
|
|
print('PASS: one poll per ADB server; other phone stream stays live; old stream closes and reconnects; disabled stays disabled')
|
|
finally:
|
|
for process in reversed(processes):
|
|
if process.poll() is None:
|
|
process.terminate()
|
|
process.wait(timeout=10)
|
|
for output in logs:
|
|
output.close()
|
|
adb.shutdown()
|
|
direct.shutdown()
|
|
|
|
|
|
if __name__ == '__main__':
|
|
main()
|