From 2a8b646b5cee2f46ab465e73bbb4cd953371fd4f Mon Sep 17 00:00:00 2001 From: kzolotarev95 Date: Tue, 20 Oct 2026 01:03:23 +0400 Subject: [PATCH] Add v118 dashboard update confirmation and responsive spacing --- files/www/cgi-bin/owrt-remote | 4 +- .../luci-static/resources/view/owrt_remote.js | 4 +- tests/HEARTBEAT_TRANSPORT.md | 4 +- tests/HOST_POLICY.md | 24 +- tests/HUB_UPDATE.md | 170 ++++++ tests/LOG_COLLECTOR.md | 4 +- tests/PERSISTENT_LOGS.md | 2 +- tests/RECAPTCHA_V3.md | 6 +- tests/RESOURCE_AUDIT.md | 6 +- tests/ROUTER_UPDATES.md | 4 +- tests/VERSION.md | 39 ++ tests/VPS_WIDGETS.md | 24 +- tests/WAN_DNS.md | 4 +- tests/WAN_INTERFACE_PICKER.md | 4 +- tests/WAN_RECOVERY.md | 4 +- tests/WAN_STABILITY.md | 6 +- tests/XRAY_APPLY.md | 12 +- tests/XRAY_BOOT.md | 4 +- tests/test_global_logs_deploy.py | 6 +- tests/test_global_logs_vps_deploy.py | 4 +- tests/test_heartbeat_transport_deploy.py | 2 +- tests/test_hub_self_update_local.py | 178 ++++++ tests/test_hub_update.py | 212 +++++++ tests/test_hub_update_ui.cjs | 150 +++++ tests/test_log_collector_deploy.py | 2 +- tests/test_persistent_logs_deploy.py | 6 +- tests/test_persistent_logs_vps_deploy.py | 4 +- tests/test_resource_lifecycle.py | 2 +- tests/test_router_updates_deploy.py | 4 +- tests/test_vps_resources.py | 38 +- tests/test_vps_resources_ui.cjs | 21 +- tests/test_wan_dns_deploy.py | 2 +- tests/test_wan_recovery_deploy.py | 2 +- tests/test_wan_stability_deploy.py | 2 +- tests/test_xray_boot_deploy.py | 2 +- tests/test_xray_mobile_deploy.py | 2 +- tests/test_xray_validation_deploy.py | 2 +- vps/deploy-dashboard-layout-fix.ps1 | 4 +- vps/deploy-dashboard-menu-fix.ps1 | 151 +++++ vps/deploy-global-logs-vps.ps1 | 4 +- vps/deploy-global-logs.ps1 | 4 +- vps/deploy-group-colors-fix.ps1 | 8 +- vps/deploy-heartbeat-redirect.ps1 | 2 +- vps/deploy-heartbeat-transport-fix.ps1 | 2 +- vps/deploy-host-policy.ps1 | 18 +- ...on-v117.ps1 => deploy-hub-self-update.ps1} | 20 +- vps/deploy-hub-url-fix.ps1 | 12 +- vps/deploy-log-collector-fix.ps1 | 2 +- vps/deploy-online-status-fix.ps1 | 4 +- vps/deploy-password-logout-fix.ps1 | 4 +- vps/deploy-persistent-logs-vps.ps1 | 4 +- vps/deploy-persistent-logs.ps1 | 4 +- vps/deploy-recaptcha-v3.ps1 | 12 +- vps/deploy-resource-fix.ps1 | 8 +- vps/deploy-router-card-ui-fix.ps1 | 4 +- vps/deploy-router-updates.ps1 | 4 +- vps/deploy-version-v118.ps1 | 227 +++++++ vps/deploy-vps-resources-fix.ps1 | 150 +++++ vps/deploy-vps-widgets.ps1 | 6 +- vps/deploy-wan-dns-fix.ps1 | 2 +- vps/deploy-wan-multi.ps1 | 4 +- vps/deploy-wan-recovery-fix.ps1 | 2 +- vps/deploy-wan-stability-fix.ps1 | 2 +- vps/deploy-web-push-fix.ps1 | 4 +- vps/deploy-xray-apply-fix.ps1 | 2 +- vps/deploy-xray-boot-fix.ps1 | 2 +- vps/deploy-xray-mobile-fix.ps1 | 2 +- vps/deploy-xray-validation-fix.ps1 | 2 +- vps/owrt-remote-hub.py | 577 ++++++++++++++++-- vps/test-hub-self-update.ps1 | 240 ++++++++ 70 files changed, 2247 insertions(+), 212 deletions(-) create mode 100644 tests/HUB_UPDATE.md create mode 100644 tests/VERSION.md create mode 100644 tests/test_hub_self_update_local.py create mode 100644 tests/test_hub_update.py create mode 100644 tests/test_hub_update_ui.cjs create mode 100644 vps/deploy-dashboard-menu-fix.ps1 rename vps/{deploy-version-v117.ps1 => deploy-hub-self-update.ps1} (89%) create mode 100644 vps/deploy-version-v118.ps1 create mode 100644 vps/deploy-vps-resources-fix.ps1 create mode 100644 vps/test-hub-self-update.ps1 diff --git a/files/www/cgi-bin/owrt-remote b/files/www/cgi-bin/owrt-remote index ba1e1c1..61c5af4 100644 --- a/files/www/cgi-bin/owrt-remote +++ b/files/www/cgi-bin/owrt-remote @@ -505,7 +505,7 @@ render_page() { -OpenWrt Remote Hub v117 +OpenWrt Remote Hub v118
+ +
-

OpenWrt Remote Hub v117

+

OpenWrt Remote Hub v118

+
- - - - - -
- {vps_resource_widgets_html()} + {vps_resource_widgets_html(resources=vps_resources)}
-
- v117 - - + {vps_resource_widgets_html(mobile=True, resources=vps_resources)} +
+ v118 +
- - - - - -
- {vps_resource_widgets_html(mobile=True)} +
+ + +
-

OpenWrt Remote Hub v117

+

OpenWrt Remote Hub v118

@@ -14357,7 +14540,7 @@ def login_html(error=""): class VpsResourceMonitor: """Shared, nonblocking Linux samples; never spawn commands per browser poll.""" - interval = 3.0 + interval = 1.0 def __init__(self, proc_dir="/proc", disk_path="/"): self.proc_dir = Path(proc_dir) @@ -15169,6 +15352,243 @@ class RouterUpdateManager: thread.join(timeout=25) +HUB_UPDATE_LIMIT = 4 * 1024 * 1024 +HUB_UPDATE_ACTIVE = {'starting', 'installing', 'restarting', 'rollback'} + + +def hub_update_write(path, data, mode=0o600): + """One durable atomic replacement; never truncate a running Hub or its state.""" + path = Path(path) + path.parent.mkdir(mode=0o700, parents=True, exist_ok=True) + fd, name = tempfile.mkstemp(prefix='.' + path.name + '-', dir=path.parent) + try: + with os.fdopen(fd, 'wb') as stream: + stream.write(data) + stream.flush() + os.fsync(stream.fileno()) + os.chmod(name, mode) + os.replace(name, path) + finally: + Path(name).unlink(missing_ok=True) + + +def hub_update_state(directory, value=None): + path = Path(directory) / 'job.json' + if value is not None: + hub_update_write(path, json.dumps(value, ensure_ascii=False).encode('utf-8')) + return value + try: + with path.open('rb') as stream: + raw = stream.read(16385) + data = json.loads(raw) if len(raw) <= 16384 else {} + return data if isinstance(data, dict) else {} + except (OSError, ValueError): + return {} + + +@contextmanager +def hub_update_lock(directory, blocking=False): + # The worker survives Hub restarts; the kernel releases this lock on a crash. + import fcntl + Path(directory).mkdir(mode=0o700, parents=True, exist_ok=True) + with (Path(directory) / 'worker.lock').open('a') as stream: + try: + fcntl.flock(stream, fcntl.LOCK_EX | (0 if blocking else fcntl.LOCK_NB)) + except BlockingIOError: + raise RuntimeError('Обновление панели уже выполняется.') + try: + yield + finally: + fcntl.flock(stream, fcntl.LOCK_UN) + + +def hub_update_validate(data): + if not 50000 <= len(data) <= HUB_UPDATE_LIMIT: + raise ValueError('Некорректный размер файла обновления панели.') + source = data.decode('utf-8') + if not all(marker in source for marker in ('class App:', 'class Handler(', 'def dashboard_html(', 'def main():')): + raise ValueError('Источник вернул файл, не похожий на панель Hub.') + if not all(marker in source for marker in ('class HubUpdateManager:', 'panel-update-worker', 'HUB_LOADED_REVISION')): + raise ValueError('Сборка в источнике ещё не поддерживает проверяемое обновление из панели.') + with warnings.catch_warnings(): + warnings.simplefilter('ignore', SyntaxWarning) + compile(source, 'owrt-remote-hub.py', 'exec', dont_inherit=True) + return data + + +def hub_update_version(data): + match = re.search(rb'appBannerVersion[^>]*>(v[0-9]+)', data) + return match[1].decode('ascii') if match else 'последняя сборка' + + +def hub_update_health(url, revision, attempts=30): + for _ in range(attempts): + try: + with urllib.request.urlopen(url + '?panel-update=1', timeout=2) as response: + data = json.loads(response.read(4096)) + if data.get('ok') and data.get('revision') == revision: + return True + except (OSError, ValueError): + pass + time.sleep(2) + return False + + +def run_hub_update_worker(job_id, directory=None, target=None): + directory = Path(directory or STATE_DIR / 'panel-update') + target = Path(target or Path(__file__).resolve()) + with hub_update_lock(directory, blocking=True): + job = hub_update_state(directory) + if job.get('id') != job_id or job.get('status') != 'starting': + raise RuntimeError('Задача обновления устарела или уже запущена.') + changed = False + previous = None + candidate = directory / 'candidate.py' + def report(status, message): + job.update(status=status, message=message, updated_at=time.time()) + hub_update_state(directory, job) + try: + time.sleep(2) # Give the initiating HTTP request time to return its job id. + data = hub_update_validate(candidate.read_bytes()) + if hashlib.sha256(data).hexdigest() != job.get('revision'): + raise RuntimeError('Контрольная сумма обновления не совпала; файл не заменён.') + previous = target.read_bytes() + if hashlib.sha256(previous).hexdigest() != job.get('previous_revision'): + raise RuntimeError('Файл Hub изменился после подтверждения; обнови страницу.') + hub_update_write(directory / 'previous.py', previous, 0o700) + report('installing', 'Устанавливается новая сборка панели…') + hub_update_write(target, data, 0o755) + changed = True + report('restarting', 'Панель перезапускается; ожидается проверка новой сборки…') + subprocess.run(['systemctl', 'restart', 'owrt-remote'], check=True, capture_output=True, timeout=35) + if not hub_update_health(job['health_url'], job['revision']): + raise RuntimeError('Новая сборка не прошла проверку работоспособности.') + report('succeeded', 'Панель успешно обновлена. Страница будет перезагружена.') + return 0 + except Exception as exc: + reason = str(exc)[:500] + if changed and previous is not None: + try: + report('rollback', 'Ошибка обновления; восстанавливается предыдущая сборка…') + except OSError: + pass # A full state disk must not prevent recovery of the Hub file. + try: + hub_update_write(target, previous, 0o755) + subprocess.run(['systemctl', 'restart', 'owrt-remote'], check=True, capture_output=True, timeout=35) + restored = hub_update_health(job['health_url'], job['previous_revision'], attempts=15) + reason += ' Предыдущий файл восстановлен.' + ('' if restored else ' Работоспособность сервиса не подтверждена; проверь журнал owrt-remote на VPS.') + except Exception as rollback_exc: + reason += ' Не удалось завершить откат: ' + str(rollback_exc)[:300] + report('failed', 'Обновление не выполнено: ' + reason) + return 1 + finally: + candidate.unlink(missing_ok=True) + + +class HubUpdateManager: + check_interval = 300 + + def __init__(self, target=None, directory=None, source=None): + self.target = Path(target or Path(__file__).resolve()) + self.directory = Path(directory or STATE_DIR / 'panel-update') + self.source = (source or RAW_REPO_BASE).rstrip('/') + self.csrf = secrets.token_urlsafe(32) + self.lock = threading.Lock() + self.checked_at = 0 + self.checking = False + self.error = '' + self.candidate = None + self.remote_revision = '' + self.remote_version = '' + self.health_url = 'http://127.0.0.1:8088/health' + + def check(self, force=False): + with self.lock: + job = hub_update_state(self.directory) + if self.checking or job.get('status') in HUB_UPDATE_ACTIVE: + return + if self.checked_at and time.monotonic() - self.checked_at < (15 if force else self.check_interval): + return + self.checking = True + try: + threading.Thread(target=self._check, name='owrt-panel-update-check', daemon=True).start() + except Exception: + with self.lock: + self.checking = False + raise + + def fetch_candidate(self): + if urllib.parse.urlsplit(self.source).scheme != 'https': + raise ValueError('Источник обновления должен использовать HTTPS.') + request = urllib.request.Request(self.source + '/vps/owrt-remote-hub.py', headers={ + 'User-Agent': 'OpenWrt-Remote-Hub-Updater', 'Cache-Control': 'no-cache'}) + with urllib.request.urlopen(request, timeout=15) as response: + if urllib.parse.urlsplit(response.geturl()).scheme != 'https': + raise ValueError('Источник обновления должен использовать HTTPS.') + return response.read(HUB_UPDATE_LIMIT + 1) + + def _check(self): + data, error = None, '' + try: + data = self.fetch_candidate() + hub_update_validate(data) + except Exception as exc: + error = 'Не удалось проверить обновление: ' + str(exc)[:300] + with self.lock: + self.checked_at = time.monotonic() + self.error = error + self.candidate = data if not error else None + self.remote_revision = hashlib.sha256(data).hexdigest() if not error else '' + self.remote_version = hub_update_version(data) if not error else '' + self.checking = False + + def snapshot(self): + with self.lock: + job = hub_update_state(self.directory) + if job.get('status') in HUB_UPDATE_ACTIVE and time.time() - job.get('started_at', 0) > 420: + job.update(status='failed', message='Процесс обновления прерван. Итог не подтверждён; проверь сервис owrt-remote на VPS.') + hub_update_state(self.directory, job) + revision = HUB_LOADED_REVISION + return {'checking': self.checking, 'error': self.error, 'source': self.source, + 'current_revision': revision, 'remote_revision': self.remote_revision, + 'remote_version': self.remote_version, 'checked': bool(self.checked_at), + 'available': bool(self.remote_revision and self.remote_revision != revision), + 'job': job, 'csrf': self.csrf} + + def start(self, revision): + with self.lock: + with hub_update_lock(self.directory): + job = hub_update_state(self.directory) + if job.get('status') in HUB_UPDATE_ACTIVE: + raise RuntimeError('Обновление панели уже выполняется.') + if not revision or revision != self.remote_revision or not self.candidate or self.error or self.checking: + raise ValueError('Результат проверки устарел. Проверь обновление ещё раз.') + if revision == HUB_LOADED_REVISION: + raise ValueError('Эта сборка панели уже установлена.') + hub_update_validate(self.candidate) + if shutil.disk_usage(self.target.parent).free < HUB_UPDATE_LIMIT * 3: + raise RuntimeError('Недостаточно свободного места для обновления и резервной копии.') + if shutil.disk_usage(self.directory).free < HUB_UPDATE_LIMIT * 3: + raise RuntimeError('Недостаточно свободного места для резервной копии панели.') + job = {'id': secrets.token_hex(16), 'status': 'starting', 'started_at': time.time(), + 'message': 'Запускается обновление панели…', 'revision': revision, + 'version': self.remote_version, 'previous_revision': HUB_LOADED_REVISION, + 'health_url': self.health_url} + hub_update_write(self.directory / 'candidate.py', self.candidate) + hub_update_state(self.directory, job) + try: + subprocess.run(['systemd-run', '--unit=owrt-remote-panel-update-' + job['id'], '--collect', + '--property=RuntimeMaxSec=360', '--setenv=OWRT_REMOTE_STATE_DIR=' + str(STATE_DIR), + sys.executable, str(self.target), 'panel-update-worker', '--job-id', job['id']], + check=True, capture_output=True, timeout=15) + except Exception as exc: + job.update(status='failed', message='Не удалось запустить обновление через systemd: ' + str(exc)[:300]) + hub_update_state(self.directory, job) + (self.directory / 'candidate.py').unlink(missing_ok=True) + raise RuntimeError(job['message']) + return job + + class App: def __init__(self, db_path, session, agent, public_url): self.db_path = Path(db_path) @@ -15181,6 +15601,7 @@ class App: self.router_monitor_thread = None self.vps_resources = VpsResourceMonitor() self.router_updates = RouterUpdateManager(self) + self.hub_update = HubUpdateManager() @contextmanager def conn(self): @@ -16869,6 +17290,40 @@ a{{display:inline-flex;margin-top:18px;color:#93c5fd}} return self.send_bytes(200, router_updates_html(self.app.router_updates.csrf).encode('utf-8'), 'text/html; charset=utf-8') + def hub_update_api(self, action=''): + if not self.require_owner(json_mode=True): + return + manager = self.app.hub_update + if action: + if not secrets.compare_digest(self.headers.get('X-Hub-Update-CSRF', ''), manager.csrf): + self.send_json(403, {'ok': False, 'error': 'Обнови страницу панели и повтори.'}) + return + if self.headers.get('Origin') and self.headers['Origin'] != self.request_origin(): + self.send_json(403, {'ok': False, 'error': 'Недопустимый источник запроса.'}) + return + length = self.headers.get('Content-Length', '') + if (self.headers.get('Transfer-Encoding') or not length.isdigit() or int(length) > 2048 + or 'application/json' not in self.headers.get('Content-Type', '')): + self.send_json(400, {'ok': False, 'error': 'Ожидается небольшой запрос JSON.'}) + return + try: + payload = self.read_payload() + if not isinstance(payload, dict): + raise ValueError('Ожидается объект JSON.') + if action == 'start': + manager.start(payload.get('revision')) + else: + manager.check(force=True) + except ValueError as exc: + self.send_json(400, {'ok': False, 'error': str(exc)}) + return + except (RuntimeError, OSError) as exc: + self.send_json(409, {'ok': False, 'error': str(exc)}) + return + else: + manager.check() + self.send_json(200, {'ok': True, **manager.snapshot()}) + def router_updates_api(self, action=''): if not self.require_owner(json_mode=True): return @@ -18251,7 +18706,13 @@ exit 127 def do_GET(self): path = self.parsed().path if path == "/health": - self.send_json(200, {"ok": True}) + result = {"ok": True} + if self.query().get('panel-update') == ['1']: + result['revision'] = HUB_LOADED_REVISION + self.send_json(200, result) + return + if path == '/api/hub-update': + self.hub_update_api() return if path == "/api/vps/resources": if not self.admin_ok(): @@ -18382,6 +18843,7 @@ exit 127 "is_owner": bool(profile and profile.get("is_owner")), "can_add_router": bool(profile and account_can_add_router(profile)), }, + vps_resources=self.app.vps_resources.snapshot(), ).encode("utf-8"), "text/html; charset=utf-8", extra_headers, @@ -18502,6 +18964,9 @@ exit 127 def do_POST(self): path = self.parsed().path + if path in {'/api/hub-update/check', '/api/hub-update/start'}: + self.hub_update_api(path.rsplit('/', 1)[-1]) + return if path in {'/api/router-updates/start', '/api/router-updates/reboot', '/api/router-updates/cancel', '/api/router-updates/refresh'}: self.router_updates_api(path.rsplit('/', 1)[-1]) return @@ -19840,6 +20305,8 @@ def make_http_server(app, host, port, tls_cert="", tls_key=""): def cmd_serve(args): app = App(args.db, session_token(), agent_token(), args.public_url) + health_host = args.host if args.host not in {'', '0.0.0.0', '::'} else ('::1' if args.host == '::' else '127.0.0.1') + app.hub_update.health_url = 'http://' + ('[' + health_host + ']' if ':' in health_host else health_host) + ':' + str(args.port) + '/health' with app.conn(): pass record_hub_start_event() @@ -19974,6 +20441,10 @@ def parser(): ) rewrite.set_defaults(func=cmd_rewrite_endpoints) + update_worker = sub.add_parser('panel-update-worker', help=argparse.SUPPRESS) + update_worker.add_argument('--job-id', required=True) + update_worker.set_defaults(func=lambda args: sys.exit(run_hub_update_worker(args.job_id))) + serve = sub.add_parser("serve", help="run web dashboard") serve.add_argument("--host", default=os.environ.get("OWRT_REMOTE_BIND", "0.0.0.0")) serve.add_argument("--port", type=int, default=int(os.environ.get("OWRT_REMOTE_PORT", "8088"))) diff --git a/vps/test-hub-self-update.ps1 b/vps/test-hub-self-update.ps1 new file mode 100644 index 0000000..8bbcbbc --- /dev/null +++ b/vps/test-hub-self-update.ps1 @@ -0,0 +1,240 @@ +param( + [Parameter(Mandatory = $true)][ValidateNotNullOrEmpty()][string]$Vps, + [ValidateSet('Prepare', 'Retest', 'Status', 'Restore')][string]$Action = 'Prepare', + [switch]$PrepareOnly +) + +$ErrorActionPreference = 'Stop' +$RepoRoot = Split-Path -Parent $PSScriptRoot +$UploadName = 'owrt-hub-update-test-' + [guid]::NewGuid().ToString('N') +$StageRoot = Join-Path ([System.IO.Path]::GetTempPath()) $UploadName +$Utf8 = [System.Text.UTF8Encoding]::new($false) +$RemoteTool = @' +import hashlib +import json +import os +from pathlib import Path +import re +import shutil +import subprocess +import sys +import tempfile +import time +import urllib.request +import uuid +import warnings + +STAGE = Path(__file__).resolve().parent +TARGET = Path('/opt/owrt-remote/owrt-remote-hub.py') +ROOT = TARGET.parent / 'self-update-local-test' +HEALTH = 'http://127.0.0.1:8088/health?panel-update=1' + +def digest(data): + return hashlib.sha256(data).hexdigest() + +def atomic(path, data, mode=0o600): + fd, name = tempfile.mkstemp(prefix='.' + path.name + '-', dir=path.parent) + try: + with os.fdopen(fd, 'wb') as stream: + stream.write(data) + stream.flush() + os.fsync(stream.fileno()) + os.chmod(name, mode) + os.replace(name, path) + finally: + Path(name).unlink(missing_ok=True) + +def read_json(path): + try: + with path.open('rb') as stream: + data = stream.read(16385) + return json.loads(data) if len(data) <= 16384 else {} + except (OSError, ValueError): + return {} + +def read_health(): + try: + with urllib.request.urlopen(HEALTH, timeout=3) as response: + data = json.loads(response.read(4096)) + return data if isinstance(data, dict) else {} + except (OSError, ValueError): + return {} + +def healthy(revision='', attempts=20): + for _ in range(attempts): + data = read_health() + if data.get('ok') and (not revision or data.get('revision') == revision): + return True + time.sleep(2) + return False + +def idle(): + result = subprocess.run(['systemctl', 'list-units', '--state=active', '--no-legend', + '--plain', 'owrt-remote-panel-update-*'], + capture_output=True, text=True, check=True, timeout=15) + if result.stdout.strip(): + raise RuntimeError('A panel update is running. Wait for its result before preparing or restoring the test.') + +def restart(): + subprocess.run(['systemctl', 'restart', 'owrt-remote'], check=True, timeout=45) + +def cleanup_test(): + if ROOT.resolve() != TARGET.resolve().parent / 'self-update-local-test': + raise RuntimeError('Unsafe test cleanup path.') + job_directory = ROOT / 'job' + if job_directory.exists(): + for name in ('candidate.py', 'previous.py', 'job.json', 'worker.lock'): + (job_directory / name).unlink(missing_ok=True) + job_directory.rmdir() + for name in ('candidate.py', 'before.py', 'test.json'): + (ROOT / name).unlink(missing_ok=True) + ROOT.rmdir() + +def builds(source, candidate_path, token): + anchor = '\nif __name__ == "__main__":\n main()' + if source.count(anchor) != 1 or ' def fetch_candidate(self):' not in source: + raise RuntimeError('Local source does not contain the testable self-update feature.') + # Only these disposable builds read a local file. The repository source, + # RAW_REPO_BASE, router installers and regular HTTPS checks are unchanged. + patch = ''' +# LOCAL SELF-UPDATE TEST: remove with test-hub-self-update.ps1 -Action Restore. +def _owrt_local_test_fetch(self): + self.source = "\\u041b\\u043e\\u043a\\u0430\\u043b\\u044c\\u043d\\u044b\\u0439 \\u0442\\u0435\\u0441\\u0442 \\u043d\\u0430 VPS (\\u0431\\u0435\\u0437 GitHub)" + with Path(__CANDIDATE__).open('rb') as stream: + return stream.read(HUB_UPDATE_LIMIT + 1) +HubUpdateManager.fetch_candidate = _owrt_local_test_fetch + +_owrt_local_original_init = HubUpdateManager.__init__ +def _owrt_local_test_init(self, *args, **kwargs): + _owrt_local_original_init(self, *args, **kwargs) + self.directory = Path(__JOB_DIRECTORY__) +HubUpdateManager.__init__ = _owrt_local_test_init + +_owrt_local_original_worker = run_hub_update_worker +def run_hub_update_worker(job_id, directory=None, target=None): + return _owrt_local_original_worker(job_id, directory or Path(__JOB_DIRECTORY__), target) +'''.replace('__CANDIDATE__', repr(str(candidate_path))).replace( + '__JOB_DIRECTORY__', repr(str(candidate_path.parent / 'job'))) + source = source.replace(anchor, '\n' + patch + anchor) + baseline = (source + '\n# LOCAL TEST BASELINE ' + token + '\n').encode('utf-8') + candidate = (source + '\n# LOCAL TEST UPDATED ' + token + '\n').encode('utf-8') + with warnings.catch_warnings(): + warnings.simplefilter('ignore', SyntaxWarning) + compile(baseline, 'local-test-baseline.py', 'exec') + compile(candidate, 'local-test-candidate.py', 'exec') + return baseline, candidate + +def prepare(): + idle() + if ROOT.exists(): + raise RuntimeError('A local test already exists. Use -Action Status or -Action Restore first.') + original = TARGET.read_bytes() + source = (STAGE / 'hub.py').read_text(encoding='utf-8') + baseline, candidate = builds(source, ROOT / 'candidate.py', uuid.uuid4().hex) + ROOT.mkdir(mode=0o700) + changed = False + try: + atomic(ROOT / 'before.py', original, 0o700) + atomic(ROOT / 'candidate.py', candidate, 0o700) + metadata = {'baseline': digest(baseline), 'candidate': digest(candidate), + 'before': digest(original), 'created_at': time.time()} + atomic(ROOT / 'test.json', json.dumps(metadata).encode('ascii')) + atomic(TARGET, baseline, 0o755) + changed = True + restart() + if not healthy(metadata['baseline']): + raise RuntimeError('Test baseline did not become healthy.') + except Exception: + if changed: + atomic(TARGET, original, 0o755) + restart() + revision = digest(original) if b'HUB_LOADED_REVISION =' in original else '' + if not healthy(revision): + raise RuntimeError('Previous file restored but service health is not confirmed. Backup: ' + str(ROOT / 'before.py')) + cleanup_test() + raise + print('SELF_UPDATE_LOCAL_TEST_READY') + print('Open the Hub, press Ctrl+F5, wait for the YELLOW update button, then confirm the update.') + print('After success and the automatic reload, the update button must turn GREEN.') + print('No GitHub/GitVerse push or installation link changes were made.') + print('Backup: ' + str(ROOT / 'before.py')) + +def status(): + metadata = read_json(ROOT / 'test.json') + current = digest(TARGET.read_bytes()) + job = read_json(ROOT / 'job/job.json') + service = subprocess.run(['systemctl', 'is-active', '--quiet', 'owrt-remote'], timeout=10).returncode == 0 + health = read_health() + loaded = health.get('revision', '') + build = ('baseline' if current == metadata.get('baseline') else + 'candidate' if current == metadata.get('candidate') else 'other') + passed = (bool(metadata) and build == 'candidate' and service and health.get('ok') + and loaded == metadata['candidate'] and job.get('status') == 'succeeded' + and job.get('revision') == metadata['candidate']) + print('SELF_UPDATE_LOCAL_TEST_NOT_PREPARED' if not metadata else + 'SELF_UPDATE_LOCAL_TEST_PASSED' if passed else 'SELF_UPDATE_LOCAL_TEST_WAITING') + print(json.dumps({'service_active': service, 'job_status': job.get('status', 'not started'), + 'test_prepared': bool(metadata), 'installed_build': build, + 'running_installed_file': bool(health.get('ok') and loaded == current), + 'installed_test_candidate': build == 'candidate', + 'candidate_revision': metadata.get('candidate', ''), + 'installed_revision': current, 'loaded_revision': loaded}, indent=2)) + if not metadata or build == 'other': + print('The disposable local test build is not installed. Its local source is not active.') + elif loaded != current: + print('The running Hub does not match the installed test file. Check the owrt-remote service.') + else: + print('The local test build is running on this VPS. If the browser reports a GitHub error, verify that its domain points to this VPS.') + +def restore(): + idle() + metadata = read_json(ROOT / 'test.json') + original = (ROOT / 'before.py').read_bytes() + if not metadata or digest(original) != metadata.get('before'): + raise RuntimeError('Test backup validation failed. Nothing changed.') + atomic(TARGET, original, 0o755) + restart() + revision = digest(original) if b'HUB_LOADED_REVISION =' in original else '' + if not healthy(revision): + raise RuntimeError('Previous file restored but service health is not confirmed. Backup was kept.') + cleanup_test() + print('SELF_UPDATE_LOCAL_TEST_RESTORED') + print('The previous Hub file and its usual update source are restored. Press Ctrl+F5.') + +def retest(): + if ROOT.exists(): + restore() + prepare() + +if __name__ == '__main__': + try: + {'Prepare': prepare, 'Retest': retest, 'Status': status, 'Restore': restore}[sys.argv[1]]() + finally: + if STAGE.parent == Path('/tmp') and re.fullmatch(r'owrt-hub-update-test-[0-9a-f]{32}', STAGE.name): + shutil.rmtree(STAGE) +'@ + +try { + [System.IO.Directory]::CreateDirectory($StageRoot) | Out-Null + [System.IO.File]::WriteAllText((Join-Path $StageRoot 'run.py'), $RemoteTool.Replace("`r`n", "`n") + "`n", $Utf8) + if ($Action -in @('Prepare', 'Retest')) { + $Content = [System.IO.File]::ReadAllText((Join-Path $RepoRoot 'vps\owrt-remote-hub.py')).Replace("`r`n", "`n") + [System.IO.File]::WriteAllText((Join-Path $StageRoot 'hub.py'), $Content, $Utf8) + } + if ($PrepareOnly) { + Write-Host "Prepared only: $StageRoot" + return + } + & scp -O -r -- $StageRoot "${Vps}:/tmp/" + if ($LASTEXITCODE -ne 0) { throw 'Upload failed. VPS was not changed.' } + & ssh -T -o ConnectTimeout=10 $Vps "if [ -x /opt/owrt-remote/venv/bin/python ]; then /opt/owrt-remote/venv/bin/python /tmp/$UploadName/run.py $Action; else python3 /tmp/$UploadName/run.py $Action; fi" + if ($LASTEXITCODE -ne 0) { throw "$Action failed. See the output above; success was not confirmed." } +} +finally { + if (-not $PrepareOnly) { + $Resolved = [System.IO.Path]::GetFullPath($StageRoot) + $Expected = [System.IO.Path]::GetFullPath((Join-Path ([System.IO.Path]::GetTempPath()) $UploadName)) + if ($Resolved -ne $Expected -or (Split-Path -Leaf $Resolved) -ne $UploadName) { throw 'Unsafe staging cleanup path.' } + if (Test-Path -LiteralPath $Resolved) { Remove-Item -LiteralPath $Resolved -Recurse -Force } + } +}