Initial LanUps implementation and native installers

This commit is contained in:
tongtong committed 2026-11-28 16:26:39 +08:00
commit 67a043c89b
66 files changed
+2870

No files matched your search

+125
View File
@@ -0,0 +1,125 @@
"""Exercise the loopback API with a simulated NUT server. Never enables real shutdown."""
import datetime
import json
import os
from pathlib import Path
import socket
import subprocess
import sys
import tempfile
import threading
import time
import urllib.error
import urllib.request
def main(*command):
mode = 'OL'
with socket.create_server(('127.0.0.1', 0)) as probe:
port = probe.getsockname()[1]
nut = socket.create_server(('127.0.0.1', 0))
def serve():
while True:
conn, _ = nut.accept()
with conn, conn.makefile('rb') as reader:
request = reader.readline()
if request == b'LIST VAR h1000m\n':
body = f'BEGIN LIST VAR h1000m\nVAR h1000m ups.status "{mode}"\nEND LIST VAR h1000m\n'
conn.sendall(b'ERR DATA-STALE\n' if mode == 'stale' else body.encode())
elif request == b'LIST UPS\n':
conn.sendall(b'BEGIN LIST UPS\nUPS h1000m "Test UPS"\nEND LIST UPS\n')
threading.Thread(target=serve, daemon=True).start()
http = urllib.request.build_opener(urllib.request.ProxyHandler({}))
with tempfile.TemporaryDirectory() as temp:
token_path = Path(temp) / 'agent.token'
env = dict(os.environ, LANUPS_AGENT_PORT=str(port), LANUPS_AGENT_TOKEN=str(token_path))
subprocess.run([*command, '--provision'], env=env, check=True)
token = token_path.read_text().strip()
def call(path, method='GET', body=None, auth=True):
headers = {'X-LanUps-Token': token} if auth else {}
data = None
if body is not None:
headers['Content-Type'] = 'application/json'
data = json.dumps(body).encode()
request = urllib.request.Request(f'http://127.0.0.1:{port}/{path}', data=data, headers=headers, method=method)
with http.open(request, timeout=2) as response:
return json.load(response)
def wait(predicate, seconds=9):
deadline = time.monotonic() + seconds
state = None
while time.monotonic() < deadline:
try:
state = call('status')
if predicate(state):
return state
except (ConnectionError, urllib.error.URLError) as error:
if isinstance(error, urllib.error.HTTPError):
raise
time.sleep(.2)
raise AssertionError(state)
def flag(state):
reading = state['update']['lastReading']
return reading and reading['values']['ups.status']
def denied(path, code, method='GET', body=None, auth=True):
try:
call(path, method, body, auth)
except urllib.error.HTTPError as error:
assert error.code == code, error.code
else:
raise AssertionError('Expected HTTP error')
def start():
return subprocess.Popen(command, env=env, stdout=subprocess.DEVNULL)
process = start()
try:
wait(lambda state: state['dryRun'])
denied('status', 401, auth=False)
endpoint = {'host': '127.0.0.1', 'port': nut.getsockname()[1], 'name': 'h1000m'}
assert call('endpoint', 'PUT', endpoint) == endpoint
assert call(f"ups?host=127.0.0.1&port={endpoint['port']}") == ['h1000m']
wait(lambda state: flag(state) == 'OL')
mode = 'stale'
wait(lambda state: state['update']['error'] and not state['pending'])
mode = 'OB FSD'
first = wait(lambda state: state['pending'])['pending']['id']
denied('endpoint', 409, 'PUT', dict(endpoint, port=1))
assert call(f'shutdown/{first}/cancel', 'POST') == 'cancel'
wait(lambda state: state['lastAction'] == '用户取消' and not state['pending'])
denied(f'shutdown/{first}/confirm', 409, 'POST')
mode = 'OL'
wait(lambda state: flag(state) == 'OL')
mode = 'OB FSD'
second = wait(lambda state: state['pending'])['pending']['id']
assert call(f'shutdown/{second}/confirm', 'POST') == 'confirm'
wait(lambda state: '已模拟关机' in (state['lastAction'] or ''))
mode = 'OL'
wait(lambda state: flag(state) == 'OL')
mode = 'OB FSD'
pending = wait(lambda state: state['pending'])['pending']
deadline = datetime.datetime.fromisoformat(pending['deadline'])
assert 56 < (deadline - datetime.datetime.now(datetime.timezone.utc)).total_seconds() <= 61
process.terminate()
process.wait()
process = start()
assert wait(lambda state: state['pending'])['pending'] == pending
print('PASS: local authorization, settings, discovery, stale data, cancel, confirm, restart recovery', flush=True)
result = wait(lambda state: (state['lastAction'] or '').startswith('60 秒内无响应'), 65)
assert result['pending'] is None and datetime.datetime.now(datetime.timezone.utc) >= deadline
print('PASS: 60-second automatic dry-run shutdown', flush=True)
finally:
process.terminate()
process.wait()
if __name__ == '__main__':
main(*sys.argv[1:])
+94
View File
@@ -0,0 +1,94 @@
"""Smoke-test a published Linux Avalonia build on a disposable Xvfb display."""
from ctypes import CDLL, POINTER, byref, c_char_p, c_int, c_uint, c_ulong, c_void_p
from datetime import datetime, timedelta, timezone
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
import json
import os
from pathlib import Path
import subprocess
import sys
import tempfile
import threading
import time
def window_titles():
x11 = CDLL('libX11.so.6')
x11.XOpenDisplay.argtypes = [c_char_p]
x11.XOpenDisplay.restype = c_void_p
x11.XDefaultRootWindow.argtypes = [c_void_p]
x11.XDefaultRootWindow.restype = c_ulong
x11.XQueryTree.argtypes = [c_void_p, c_ulong, POINTER(c_ulong), POINTER(c_ulong), POINTER(POINTER(c_ulong)), POINTER(c_uint)]
x11.XFetchName.argtypes = [c_void_p, c_ulong, POINTER(c_char_p)]
x11.XFree.argtypes = [c_void_p]
x11.XCloseDisplay.argtypes = [c_void_p]
display = x11.XOpenDisplay(None)
if not display:
raise OSError('Run this smoke test under Xvfb')
children = POINTER(c_ulong)()
count = c_uint()
titles = set()
try:
root = x11.XDefaultRootWindow(display)
x11.XQueryTree(display, root, byref(c_ulong()), byref(c_ulong()), byref(children), byref(count))
for child in children[:count.value]:
title = c_char_p()
if x11.XFetchName(display, child, byref(title)) and title.value:
titles.add(title.value.decode('utf-8', errors='replace'))
x11.XFree(title)
return titles
finally:
if children:
x11.XFree(children)
x11.XCloseDisplay(display)
def main(*command):
now = datetime.now(timezone.utc)
state = {
'dryRun': True, 'lastAction': None,
'endpoint': {'host': '127.0.0.1', 'port': 3493, 'name': 'h1000m'},
'update': {'error': None, 'newShutdownSignal': True, 'lastReading': {
'at': now.isoformat(), 'values': {'ups.status': 'OB FSD', 'battery.charge': '71'}}},
'pending': {'id': '7a581f0d-9ab1-4f81-a814-1e236e1ed309', 'deadline': (now + timedelta(minutes=1)).isoformat()},
}
observed = threading.Event()
class Handler(BaseHTTPRequestHandler):
def do_GET(self):
assert self.path == '/status' and self.headers['X-LanUps-Token'] == 'A' * 64
payload = json.dumps(state).encode()
self.send_response(200)
self.send_header('Content-Type', 'application/json')
self.send_header('Content-Length', str(len(payload)))
self.end_headers()
self.wfile.write(payload)
observed.set()
def log_message(self, *_):
pass
with ThreadingHTTPServer(('127.0.0.1', 0), Handler) as server, tempfile.TemporaryDirectory() as tmp:
threading.Thread(target=server.serve_forever, daemon=True).start()
token = Path(tmp) / 'agent.token'
token.write_text('A' * 64)
environment = dict(os.environ, LANUPS_AGENT_PORT=str(server.server_port), LANUPS_AGENT_TOKEN=str(token), XDG_DATA_HOME=tmp)
process = subprocess.Popen(command, env=environment)
try:
for _ in range(80):
if process.poll() is not None:
raise AssertionError(f'Desktop exited with code {process.returncode}')
if observed.is_set() and 'UPS 关机确认' in window_titles():
print('PASS: published Avalonia desktop read IPC state and displayed FSD confirmation', flush=True)
return
time.sleep(.2)
raise AssertionError(f'FSD dialog not found: {window_titles()}')
finally:
process.terminate()
process.wait(timeout=10)
server.shutdown()
if __name__ == '__main__':
main(*sys.argv[1:])