Fix Tachyon APK discovery and release package revision 122-r2
OpenWrt IPK and APK / Validate source and resolve stable SDKs (push) Waiting to run
OpenWrt IPK and APK / Validate source and resolve stable SDKs (push) Waiting to run
This commit is contained in:
1 parent
70a4705e67
commit
927aec8ffe
18 files changed
+496
-45
No files matched your search
@@ -51,10 +51,10 @@ jobs:
|
||||
import os, subprocess, sys
|
||||
sys.path.insert(0, 'scripts')
|
||||
import openwrt_package as p
|
||||
expected = 'v' + p.versions()[0]
|
||||
expected = p.release_tag()
|
||||
tag = os.environ['RELEASE_TAG'] or expected
|
||||
if os.environ['PUBLISH_REQUESTED'] == 'true' and tag != expected:
|
||||
raise SystemExit('Release tag must match PKG_VERSION in package/luci-app-owrt-remote/Makefile')
|
||||
raise SystemExit('Release tag must match PKG_VERSION and PKG_RELEASE (vVERSION or vVERSION-rREVISION)')
|
||||
if os.environ['MANUAL_PUBLISH'] == 'true':
|
||||
# Retry corrected build tooling without moving an existing tag.
|
||||
# Runtime files must match; packaging tools/metadata may be fixed.
|
||||
|
||||
@@ -205,6 +205,7 @@ owrt-remote status
|
||||
IPK для OpenWrt 23.05/24.10 и APK для 25.12. Пакеты
|
||||
архитектурно независимые (`all`/`noarch`): содержат тот же агент и LuCI-файлы,
|
||||
что и `install.sh`, сохраняют `/etc/config/owrtremote` и существующий Xray.
|
||||
Версия интерфейса — v122, исправленная пакетная ревизия — 122-r2.
|
||||
GitHub Actions проверяет SDK разных архитектур, установку/обновление/удаление
|
||||
в OpenWrt VM и при выпуске тега `v*` прикладывает пакеты к GitHub Release.
|
||||
Для APK в штатной LuCI нужен доверенный ключ подписи; неподписанный локальный
|
||||
|
||||
@@ -144,13 +144,17 @@ Workflow `.github/workflows/openwrt-packages.yml` запускается на т
|
||||
публикации Release, изменениях пакета в pull request и вручную. В PR и при
|
||||
обычном ручном запуске он только собирает и тестирует. Для повторной публикации
|
||||
после исправления сборочного инструмента доступен ручной запуск с
|
||||
`publish_release=true` и существующим `release_tag`, например `v122`.
|
||||
`publish_release=true` и существующим `release_tag`, например `v122-r2`.
|
||||
Он не перемещает тег и проверяет, что содержимое `files/` и установочные
|
||||
помощники совпадают с этим тегом. Рецепт и инструменты сборки могут содержать
|
||||
исправления; точный commit сборки записывается в отчёте. После проверок
|
||||
пакеты прикладываются к Release.
|
||||
Тег должен совпадать с `PKG_VERSION`: текущий пример — `v122`.
|
||||
Следующий выпуск должен получить новую версию или пакетную ревизию в Makefile.
|
||||
Первая пакетная ревизия версии использует тег `vVERSION`, следующие —
|
||||
`vVERSION-rREVISION`. Например, `PKG_VERSION=122`, `PKG_RELEASE=2` соответствуют
|
||||
тегу `v122-r2`; версия интерфейса остаётся v122. Старый тег v122 и его пакеты
|
||||
122-r1 сохраняются. Для новой версии интерфейса пакетная ревизия начинается с 1.
|
||||
При выпуске ревизии CI дополнительно скачивает предыдущий опубликованный пакет,
|
||||
проверяет его SHA256 и проверяет настоящее обновление с него на новый пакет.
|
||||
|
||||
На каждом запуске выбирается последняя стабильная patch-версия веток
|
||||
23.05, 24.10 и 25.12. Матрица `package/openwrt-targets.json` содержит 10 SDK
|
||||
|
||||
@@ -3,6 +3,74 @@
|
||||
Интеграция включена в Remote Hub v122. Обновить нужно Hub на VPS и агент
|
||||
на роутере; Tachyon устанавливается отдельно и автоматически не загружается.
|
||||
|
||||
## Исправление APK 3.0.5 в пакетах 122-r2
|
||||
|
||||
На node-12 с OpenWrt 25.12.5 команда `apk info -v tachyon` вернула описание,
|
||||
а не версию. Прежний парсер ожидал `tachyon-VERSION`, получил пустую строку
|
||||
и выбрал старую LuCI-страницу вместо самостоятельной панели на порту 1680.
|
||||
Поэтому в карточке исчезла версия, а кнопка открывала LuCI с внешней ссылкой.
|
||||
|
||||
Теперь версия читается через `apk list --installed --manifest`, с резервным
|
||||
структурированным `apk query`. Наличие самостоятельного интерфейса подтверждает
|
||||
локальный read-only API `/api/agent/v1/health`; старый номер пакета не мешает
|
||||
обнаружить работающий современный интерфейс. HTTP 403 страницы LuCI сам по себе
|
||||
не означает, что неизвестный Tachyon работает. Версия работающего приложения
|
||||
по-прежнему берётся из его OpenAPI, если он доступен.
|
||||
|
||||
Блок карточки имеет две строки: название/версия/состояние и ниже кнопка.
|
||||
Отсутствие версии больше не переносит кнопку в верхнюю строку и не меняет высоту
|
||||
обычного блока. Проверены ПК, мобильная вертикальная и горизонтальная ориентация.
|
||||
|
||||
Установить исправление интерфейса VPS из локальных исходников:
|
||||
|
||||
```powershell
|
||||
$Fix = Join-Path $env:USERPROFILE 'Documents\openwrt overlay\vps\deploy-tachyon-detection-fix.ps1'
|
||||
powershell.exe -NoProfile -ExecutionPolicy Bypass -File $Fix -Vps root@132.243.19.232 -Action Install
|
||||
```
|
||||
|
||||
Установить агент на удалённый node-12 через существующий SSH-туннель VPS:
|
||||
|
||||
```powershell
|
||||
powershell.exe -NoProfile -ExecutionPolicy Bypass -File $Fix -Vps root@132.243.19.232 -RouterId node-12 -Action Install
|
||||
```
|
||||
|
||||
SSH отдельно запрашивает пароль VPS и пароль выбранного роутера; они могут
|
||||
отличаться. Скрипт читает `ssh_entry_port` выбранного роутера из базы в режиме
|
||||
read-only и подключается через ProxyJump. Туннель не публикуется наружу.
|
||||
Перезапуск выполняет отдельный procd worker после завершения записи файлов,
|
||||
чтобы не оборвать установку вместе с SSH. После него VPS ждёт свежий Heartbeat
|
||||
и проверяет настоящий Tachyon API через обратный маршрут выбранного роутера.
|
||||
При отсутствии подтверждения выводится ошибка, успех не подставляется.
|
||||
|
||||
Проверить node-12 отдельно, без переустановки и без изменения файлов:
|
||||
|
||||
```powershell
|
||||
powershell.exe -NoProfile -ExecutionPolicy Bypass -File $Fix -Vps root@132.243.19.232 -RouterId node-12 -Action Status
|
||||
```
|
||||
|
||||
Ожидается `TACHYON_CHECK_OK: node-12`. Команда показывает версию, режим, порт,
|
||||
состояние Xray, возраст Heartbeat и результат запроса к API через туннель.
|
||||
Страница LuCI вместо JSON Tachyon не считается успешной проверкой.
|
||||
|
||||
Для обычного локального SSH:
|
||||
|
||||
```powershell
|
||||
powershell.exe -NoProfile -ExecutionPolicy Bypass -File $Fix -Router root@192.168.2.1 -Action Install
|
||||
```
|
||||
|
||||
Отдельная резервная копия на каждом устройстве:
|
||||
`/root/owrt-remote-backup-before-tachyon-detection-v122`.
|
||||
Откат удалённого роутера и затем VPS:
|
||||
|
||||
```powershell
|
||||
powershell.exe -NoProfile -ExecutionPolicy Bypass -File $Fix -Vps root@132.243.19.232 -RouterId node-12 -Action Rollback
|
||||
powershell.exe -NoProfile -ExecutionPolicy Bypass -File $Fix -Vps root@132.243.19.232 -Action Rollback
|
||||
```
|
||||
|
||||
В рамках исправления не меняются настройки и пакет самого Tachyon.
|
||||
Исправленные пакеты выпускаются с тегом v122-r2. Прежние IPK/APK 122-r1
|
||||
и тег v122 сохраняются.
|
||||
|
||||
## Обнаружение
|
||||
|
||||
Агент проверяет установленные пакеты tachyon и luci-app-tachyon через
|
||||
|
||||
@@ -9,7 +9,7 @@ tachyon_inventory_failed() {
|
||||
}
|
||||
|
||||
tachyon_json() (
|
||||
local dir package version package_version mode port service available api code pkg rc now last admin_port
|
||||
local dir package version package_version mode port service available api code pkg rc now last admin_port candidate_port probe
|
||||
umask 077
|
||||
ulimit -f 64
|
||||
mkdir -p "$TACHYON_RUNTIME" || { printf '{"checked":false}'; return; }
|
||||
@@ -29,7 +29,14 @@ tachyon_json() (
|
||||
for pkg in tachyon luci-app-tachyon; do
|
||||
grep -qx "$pkg" "$dir/package" || continue
|
||||
package="$pkg"
|
||||
version="$(apk info -v "$pkg" 2>/dev/null | sed -n "s/^$pkg-//p" | head -n 1 | awk '{print $1}')"
|
||||
# apk info -v prints the package description on OpenWrt 25.12.
|
||||
# The installed version is available through the manifest.
|
||||
version="$(apk list --installed --manifest "$pkg" 2>/dev/null | awk -v wanted="$pkg" '
|
||||
$1 == wanted && $2 != "" {print $2; exit}
|
||||
$1 ~ ("^" wanted "-") {sub("^" wanted "-", "", $1); print $1; exit}
|
||||
')"
|
||||
[ -n "$version" ] || version="$(apk query --installed --from system --fields name,version --format json "$pkg" 2>/dev/null |
|
||||
jsonfilter -e '@[0].version' 2>/dev/null)"
|
||||
break
|
||||
done
|
||||
elif command -v opkg >/dev/null 2>&1; then
|
||||
@@ -43,24 +50,33 @@ tachyon_json() (
|
||||
else
|
||||
tachyon_inventory_failed; return
|
||||
fi
|
||||
case "$version" in ''|*[!0-9a-zA-Z.+~_-]*) version='' ;; esac
|
||||
[ "${#version}" -le 80 ] || version=''
|
||||
case "$package" in tachyon|luci-app-tachyon) ;; *) package='' ;; esac
|
||||
if [ -z "$package" ]; then
|
||||
printf '{"checked":true,"installed":false}\n' >"$dir/json"
|
||||
else
|
||||
package_version="$version"
|
||||
port=0
|
||||
mode=luci
|
||||
# Older Tachyon can use listen_port for a proxy, not its web UI.
|
||||
case "$version" in 2.*|[3-9].*)
|
||||
mode=standalone
|
||||
port="$(uci -q get tachyon.settings.listen_port 2>/dev/null)"
|
||||
;;
|
||||
port=0; mode=luci; api=''
|
||||
candidate_port="$(uci -q get tachyon.settings.listen_port 2>/dev/null)"
|
||||
case "$candidate_port" in ''|*[!0-9]*) candidate_port=1680 ;; esac
|
||||
[ "${#candidate_port}" -le 5 ] || candidate_port=1680
|
||||
[ "$candidate_port" -ge 1024 ] && [ "$candidate_port" -le 65535 ] || candidate_port=1680
|
||||
candidate_port="$(printf '%s' "$candidate_port" | awk '{printf "%d", $1}')"
|
||||
# Older versions can use this port for a proxy. A real read-only
|
||||
# Tachyon API response confirms the standalone UI, even if package
|
||||
# metadata is missing or stale. An open port alone proves nothing.
|
||||
probe="$(curl -q -fsS --noproxy '*' --connect-timeout 1 --max-time 2 --max-filesize 65536 \
|
||||
"http://127.0.0.1:$candidate_port/api/agent/v1/health" 2>/dev/null |
|
||||
jsonfilter -e '@.core_running' 2>/dev/null)"
|
||||
case "$probe" in
|
||||
true|false) mode=standalone; port="$candidate_port"; api='/api/agent/v1' ;;
|
||||
*)
|
||||
# Keep v2 routed to its own port when it is temporarily down;
|
||||
# never substitute an available LuCI page for an offline UI.
|
||||
case "$version" in 2.*|[3-9].*) mode=standalone; port="$candidate_port" ;; esac
|
||||
;;
|
||||
esac
|
||||
case "$port" in ''|*[!0-9]*) port=0 ;; esac
|
||||
[ "${#port}" -le 5 ] || port=0
|
||||
[ "$port" -ge 1024 ] && [ "$port" -le 65535 ] || port=0
|
||||
port="$(printf '%s' "$port" | awk '{printf "%d", $1}')"
|
||||
[ "$mode" != standalone ] || [ "$port" != 0 ] || port=1680
|
||||
service=unknown
|
||||
for pkg in tachyon tachyon-core; do
|
||||
rc="$(ubus call service list "{\"name\":\"$pkg\"}" 2>/dev/null |
|
||||
@@ -68,7 +84,7 @@ tachyon_json() (
|
||||
if printf '%s\n' "$rc" | grep -qx true; then service=running; break; fi
|
||||
[ -z "$rc" ] || service=stopped
|
||||
done
|
||||
available=false; api=''
|
||||
available=false
|
||||
if [ "$mode" = standalone ]; then
|
||||
code="$(curl -q -s --noproxy '*' --connect-timeout 1 --max-time 2 -o /dev/null \
|
||||
-w '%{http_code}' "http://127.0.0.1:$port/" 2>/dev/null)"
|
||||
@@ -81,16 +97,11 @@ tachyon_json() (
|
||||
-w '%{http_code}' "http://127.0.0.1:$admin_port/cgi-bin/luci/admin/services/tachyon" 2>/dev/null)"
|
||||
fi
|
||||
case "$code" in 2??|3??|401|403) [ "$service" = stopped ] || available=true ;; esac
|
||||
if [ "$mode" = standalone ] && [ "$available" = true ]; then
|
||||
rc="$(curl -q -fsS --noproxy '*' --max-time 1 "http://127.0.0.1:$port/api/agent/v1/health" 2>/dev/null |
|
||||
jsonfilter -e '@.core_running' 2>/dev/null)"
|
||||
case "$rc" in true|false)
|
||||
api='/api/agent/v1'
|
||||
rc="$(curl -q -fsS --noproxy '*' --max-time 1 --max-filesize 65536 \
|
||||
"http://127.0.0.1:$port/api/agent/v1/openapi.json" 2>/dev/null | jsonfilter -e '@.info.version' 2>/dev/null)"
|
||||
case "$rc" in ''|*[!a-zA-Z0-9.+~_-]*) ;; *) [ "${#rc}" -gt 80 ] || version="$rc" ;; esac
|
||||
;;
|
||||
esac
|
||||
[ -n "$version" ] || [ "$mode" = standalone ] || available=false
|
||||
if [ "$mode" = standalone ] && [ "$available" = true ] && [ "$api" = /api/agent/v1 ]; then
|
||||
rc="$(curl -q -fsS --noproxy '*' --connect-timeout 1 --max-time 1 --max-filesize 65536 \
|
||||
"http://127.0.0.1:$port/api/agent/v1/openapi.json" 2>/dev/null | jsonfilter -e '@.info.version' 2>/dev/null)"
|
||||
case "$rc" in ''|*[!a-zA-Z0-9.+~_-]*) ;; *) [ "${#rc}" -gt 80 ] || version="$rc" ;; esac
|
||||
fi
|
||||
for pkg in tachyon-api tachyon-agent; do
|
||||
[ -z "$api" ] || break
|
||||
|
||||
@@ -2,7 +2,7 @@ include $(TOPDIR)/rules.mk
|
||||
|
||||
PKG_NAME:=luci-app-owrt-remote
|
||||
PKG_VERSION:=122
|
||||
PKG_RELEASE:=1
|
||||
PKG_RELEASE:=2
|
||||
PKG_LICENSE:=MIT
|
||||
PKG_MAINTAINER:=kzolotarev95
|
||||
PKGARCH:=all
|
||||
|
||||
@@ -60,6 +60,11 @@ def versions():
|
||||
return version, release
|
||||
|
||||
|
||||
def release_tag():
|
||||
version, revision = versions()
|
||||
return 'v' + version + (('-r' + revision) if revision != '1' else '')
|
||||
|
||||
|
||||
def latest_release(series, html):
|
||||
candidates = [link.rstrip("/") for link in Links(html).links
|
||||
if re.fullmatch(re.escape(series) + r"\.[0-9]+/", link)]
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
import argparse
|
||||
import contextlib
|
||||
import functools
|
||||
import hashlib
|
||||
import http.server
|
||||
import os
|
||||
from pathlib import Path
|
||||
@@ -54,6 +55,19 @@ def main():
|
||||
parser.error("one main package and one real upgrade fixture are required")
|
||||
candidate, fixture = candidates[0], fixtures[0]
|
||||
apk = candidate.suffix == ".apk"
|
||||
# Verify upgrades from the previously published package as well as the
|
||||
# synthetic next revision. Old Release assets/tags remain immutable.
|
||||
version, revision = package.versions()
|
||||
baseline = None
|
||||
if int(revision) > 1:
|
||||
previous = str(int(revision) - 1)
|
||||
tag = 'v' + version + (('-r' + previous) if previous != '1' else '')
|
||||
series = '.'.join(args.release.split('.')[:2])
|
||||
name = f'{package.PACKAGE}_{version}-r{previous}_openwrt-{series}_{"noarch" if apk else "all"}{candidate.suffix}'
|
||||
origin = 'https://github.com/kzolotarev95/luci-app-owrt-remote/releases/download/' + tag + '/'
|
||||
expected = package.checksum(package.get_text(origin + 'SHA256SUMS'), name)
|
||||
baseline = source / 'test-fixtures' / ('previous-release' + candidate.suffix)
|
||||
package.download(origin + name, baseline, expected)
|
||||
output = Path(args.output).resolve()
|
||||
output.mkdir(parents=True, exist_ok=True)
|
||||
port = free_port()
|
||||
@@ -141,6 +155,16 @@ def main():
|
||||
print("Testing remove, preserved state, and migration from unowned overlay files", flush=True)
|
||||
remote(remove + " " + package.PACKAGE, timeout=180)
|
||||
remote("set -e; test ! -e /usr/sbin/owrt-remote; test ! -e /www/cgi-bin/owrt-remote; test ! -e /etc/init.d/owrt-remote; sha256sum -c /tmp/remote-before.sha256")
|
||||
if baseline:
|
||||
print('Testing upgrade from the previous published Release', flush=True)
|
||||
remote('wget -qO /tmp/remote-previous' + candidate.suffix + ' ' + shlex.quote(origin + 'test-fixtures/' + baseline.name))
|
||||
baseline_install = 'apk add --allow-untrusted' if apk else 'opkg install'
|
||||
remote(baseline_install + ' /tmp/remote-previous' + candidate.suffix, timeout=300)
|
||||
remote(install + ' /tmp/remote-package' + candidate.suffix, timeout=300)
|
||||
helper = 'usr/lib/owrt-remote/tachyon.sh'
|
||||
digest = hashlib.sha256(package.payload()[helper][0]).hexdigest()
|
||||
remote('set -e; sha256sum -c /tmp/remote-before.sha256; test "$(sha256sum /' + helper + ' | cut -d\" \" -f1)" = ' + digest)
|
||||
remote(remove + ' ' + package.PACKAGE, timeout=180)
|
||||
# Configuration left by install.sh is unowned by a package manager.
|
||||
# A fresh package install must preserve it just like an upgrade.
|
||||
remote(install + " /tmp/remote-package" + candidate.suffix, timeout=300)
|
||||
|
||||
@@ -1,5 +1,9 @@
|
||||
# Версия v122
|
||||
|
||||
Исправления Tachyon для APK 3.0.5 выпускаются как пакетная ревизия 122-r2
|
||||
с тегом v122-r2. Номер интерфейсов остаётся v122; исходный тег v122 и пакеты
|
||||
122-r1 сохраняются.
|
||||
|
||||
Выпуск использует main и отдельный тег v122. GitHub Actions собирает IPK/APK,
|
||||
проверяет их и прикладывает к Releases → v122 после успешного завершения сборок
|
||||
и установки/обновления/удаления в OpenWrt VM. Выпущенная v121 сохраняется.
|
||||
|
||||
@@ -84,6 +84,11 @@ class PackageTests(unittest.TestCase):
|
||||
text = (ROOT / "files" / name).read_text(encoding="utf-8")
|
||||
self.assertIn("OpenWrt Remote Hub v" + version, text)
|
||||
|
||||
def test_package_revision_has_its_own_tag_without_renaming_the_panel(self):
|
||||
for values, expected in [(('122','1'),'v122'), (('122','2'),'v122-r2'), (('123','1'),'v123')]:
|
||||
with self.subTest(values=values), mock.patch.object(p,'versions',return_value=values):
|
||||
self.assertEqual(p.release_tag(), expected)
|
||||
|
||||
def test_package_scripts_defer_procd_lifecycle_to_openwrt_for_apk_and_ipk(self):
|
||||
script = p.package_hook("postinst")
|
||||
self.assertNotIn("configure ]", script)
|
||||
|
||||
+41
-3
@@ -137,7 +137,7 @@ curl() {
|
||||
[ "$TEST_HTTP" != fail ] || return 7
|
||||
for last do :; done
|
||||
case "$last" in
|
||||
*/api/agent/v1/health) printf '{"core_running":false}' ;;
|
||||
*/api/agent/v1/health) [ "${TEST_API:-1}" = 1 ] || return 22; printf '{"core_running":false}' ;;
|
||||
*/api/agent/v1/openapi.json) printf '{"info":{"version":"2.0.0-beta.14"}}' ;;
|
||||
*) printf '%s' "$TEST_HTTP" ;;
|
||||
esac
|
||||
@@ -180,17 +180,55 @@ print(str(value).lower() if isinstance(value,bool) else value)' "$@"
|
||||
|
||||
def test_apk_discovery_and_legacy_luci(self):
|
||||
code = r'''
|
||||
apk() { if [ "$2" = -v ]; then echo tachyon-2.0.0-r1; else printf 'base-files\ntachyon\n'; fi; }
|
||||
apk() {
|
||||
case "$1" in
|
||||
info) printf 'base-files\ntachyon\n' ;;
|
||||
list) printf 'tachyon 2.0.0-r1\n' ;;
|
||||
*) return 1 ;;
|
||||
esac
|
||||
}
|
||||
tachyon_json force
|
||||
'''
|
||||
result = self.run_shell(code)
|
||||
self.assertEqual(json.loads(result.stdout)['package_version'], '2.0.0-r1')
|
||||
with (self.root / 'uci').open('a') as config:
|
||||
config.write('tachyon.settings.listen_port=1602\n')
|
||||
result = self.harness.run_shell(self.mocks + 'tachyon_json force', TEST_VERSION='1.3.13', TEST_HTTP='403', TEST_SERVICE='true')
|
||||
result = self.harness.run_shell(self.mocks + 'tachyon_json force', TEST_VERSION='1.3.13', TEST_HTTP='403', TEST_SERVICE='true', TEST_API='0')
|
||||
self.assertEqual(json.loads(result.stdout)['mode'], 'luci')
|
||||
self.assertEqual(json.loads(result.stdout)['port'], 0)
|
||||
|
||||
def test_apk_305_description_is_not_a_version_and_manifest_selects_standalone(self):
|
||||
result = self.run_shell(r'''
|
||||
apk() {
|
||||
case "$1:$2" in
|
||||
info:) printf 'base-files\ntachyon\n' ;;
|
||||
info:-v) printf 'tachyon: Pure-Rust routing orchestrator and web panel for OpenWrt (aarch64)\ntachyon: https://github.com/Dushnilin/tachyon\ntachyon: 7136 KiB\n' ;;
|
||||
list:--installed) printf 'tachyon 2.0.0~beta.15-r1\n' ;;
|
||||
*) return 1 ;;
|
||||
esac
|
||||
}
|
||||
tachyon_json force
|
||||
''')
|
||||
status = json.loads(result.stdout)
|
||||
self.assertEqual(status['mode'], 'standalone')
|
||||
self.assertEqual(status['port'], 1680)
|
||||
self.assertEqual(status['package_version'], '2.0.0~beta.15-r1')
|
||||
self.assertTrue(status['available'])
|
||||
|
||||
def test_actual_api_recovers_missing_or_stale_package_version(self):
|
||||
for version in ('', '1.3.13'):
|
||||
result = self.harness.run_shell(self.mocks + 'tachyon_json force',
|
||||
TEST_VERSION=version, TEST_HTTP='200', TEST_SERVICE='true')
|
||||
status = json.loads(result.stdout)
|
||||
self.assertEqual(status['mode'], 'standalone')
|
||||
self.assertEqual(status['port'], 1680)
|
||||
self.assertEqual(status['version'], '2.0.0-beta.14')
|
||||
|
||||
def test_luci_login_response_is_not_proof_of_an_unknown_tachyon_ui(self):
|
||||
result = self.harness.run_shell(self.mocks + 'tachyon_json force',
|
||||
TEST_VERSION='', TEST_API='0', TEST_HTTP='403', TEST_SERVICE='true')
|
||||
self.assertFalse(json.loads(result.stdout)['available'])
|
||||
|
||||
def test_custom_web_port_and_no_reconfigure_when_manually_stopped(self):
|
||||
with (self.root / 'uci').open('a') as config:
|
||||
config.write('tachyon.settings.listen_port=1800\n')
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
// Browser regression: an absent version must not move the action into the header.
|
||||
const {chromium} = require('playwright');
|
||||
const fs = require('node:fs');
|
||||
const vm = require('node:vm');
|
||||
const assert = require('node:assert/strict');
|
||||
const source = fs.readFileSync('vps/owrt-remote-hub.py', 'utf8');
|
||||
const start = source.indexOf('function renderTachyon(router) {{');
|
||||
const end = source.indexOf('\nfunction render(list)', start);
|
||||
const escape = s => String(s).replace(/[&<>"']/g, c => ({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c]));
|
||||
const context = {escapeHtml:escape, escapeAttr:escape};
|
||||
vm.createContext(context);
|
||||
vm.runInContext(source.slice(start,end).replaceAll('{{','{').replaceAll('}}','}'), context);
|
||||
(async () => {
|
||||
const browser = await chromium.launch({headless:true, ...(process.env.OWRT_TEST_BROWSER_BIN ? {executablePath:process.env.OWRT_TEST_BROWSER_BIN} : {})});
|
||||
try {
|
||||
for (const [width,height] of [[1280,900],[390,844],[844,390]]) {
|
||||
const page = await browser.newPage({viewport:{width,height}});
|
||||
const cards = ['2.0.0-beta.15','', '2.0.0~beta.15-r1'].map(version =>
|
||||
'<section class="card">'+context.renderTachyon({permissions:{admin:true},tachyon:{installed:true,online:true,version,url:'/tachyon/test/'}})+'</section>').join('');
|
||||
await page.setContent('<style>*{box-sizing:border-box}body{margin:12px;font:13px Arial;background:#21192e;color:#fff}.cards{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:12px}.card{min-width:0}.btn{display:inline-flex;align-items:center;justify-content:center;min-height:34px;padding:8px 12px;border:1px solid #736387;border-radius:7px;background:#3b3049;color:white;text-decoration:none;font-weight:bold}@media(max-width:600px){.cards{grid-template-columns:1fr}}</style><div class="cards">'+cards+'</div>');
|
||||
const boxes = await page.locator('.tachyonIntegration').evaluateAll(items => items.map(el => {
|
||||
const box=el.getBoundingClientRect(), meta=el.querySelector('.tachyonMeta').getBoundingClientRect(), action=el.querySelector('.tachyonAction').getBoundingClientRect();
|
||||
return {height:box.height,actionTop:action.top-box.top,metaBottom:meta.bottom-box.top,overflow:el.scrollWidth>el.clientWidth,center:Math.abs((action.left+action.width/2)-(box.left+box.width/2))};
|
||||
}));
|
||||
for (const box of boxes) {
|
||||
assert(!box.overflow,`${width}: overflowing card`);
|
||||
assert(box.actionTop>=box.metaBottom+7,`${width}: action must be below metadata`);
|
||||
assert(box.center<1,`${width}: centered button`);
|
||||
assert(Math.abs(box.actionTop-boxes[0].actionTop)<1,`${width}: version changed action placement`);
|
||||
assert(Math.abs(box.height-boxes[0].height)<1,`${width}: version changed block height`);
|
||||
}
|
||||
if (process.env.OWRT_TEST_SCREENSHOT_DIR) await page.screenshot({path:process.env.OWRT_TEST_SCREENSHOT_DIR+`/tachyon-cards-${width}.png`,fullPage:true});
|
||||
await page.close();
|
||||
}
|
||||
console.log('TACHYON_CARD_LAYOUT_OK: desktop, portrait and landscape');
|
||||
} finally { await browser.close(); }
|
||||
})().catch(error => {console.error(error);process.exitCode=1;});
|
||||
@@ -5,6 +5,7 @@ import shlex
|
||||
import shutil
|
||||
import subprocess
|
||||
import tempfile
|
||||
import sys
|
||||
import unittest
|
||||
|
||||
from test_host_policy import ROOT, SH
|
||||
@@ -17,6 +18,7 @@ class DeployTests(unittest.TestCase):
|
||||
self.addCleanup(self.temp.cleanup)
|
||||
self.root = Path(self.temp.name)
|
||||
self.env = dict(os.environ)
|
||||
self.env['TEST_PYTHON'] = Path(sys.executable).as_posix()
|
||||
if os.name == 'nt':
|
||||
self.env['PATH'] = str(Path(SH).parent) + os.pathsep + self.env['PATH']
|
||||
self.targets = {name: self.root / name for name in ('agent', 'tachyon.sh')}
|
||||
@@ -29,8 +31,14 @@ class DeployTests(unittest.TestCase):
|
||||
original = {'agent': '/usr/sbin/owrt-remote', 'tachyon.sh': '/usr/lib/owrt-remote/tachyon.sh'}[name]
|
||||
self.script = self.script.replace('echo ' + original, 'echo ' + shlex.quote(target.as_posix()))
|
||||
self.script = self.script.replace('/etc/init.d/owrt-remote restart', 'test_restart')
|
||||
self.script = self.script.replace('/usr/sbin/owrt-remote tachyon-status', "printf '{\"checked\":true}'")
|
||||
mocks = '''
|
||||
ubus() { printf '{}'; }
|
||||
ubus() {
|
||||
case "$1:$2:$3" in
|
||||
call:service:add) "$TEST_PYTHON" -c 'import json,sys; data=json.loads(sys.argv[1]); assert data["instances"]["once"]["command"][0]=="/bin/sh"' "$4" ;;
|
||||
*) printf '{}' ;;
|
||||
esac
|
||||
}
|
||||
jsonfilter() { printf true; }
|
||||
timeout() { return 0; }
|
||||
busybox() { return 127; }
|
||||
@@ -39,7 +47,7 @@ sleep() { :; }
|
||||
'''
|
||||
self.script = mocks + self.script.replace('test -r /usr/lib/owrt-remote/control.sh', 'true')
|
||||
|
||||
def deploy(self, action='Install', bad=False, fail=False, no_timeout=False):
|
||||
def deploy(self, action='Install', bad=False, fail=False, no_timeout=False, deferred=False):
|
||||
stage = self.root / 'stage'
|
||||
stage.mkdir()
|
||||
for name, source in {'agent': 'files/usr/sbin/owrt-remote', 'tachyon.sh': 'files/usr/lib/owrt-remote/tachyon.sh'}.items():
|
||||
@@ -47,6 +55,7 @@ sleep() { :; }
|
||||
stage.joinpath(name).write_text(text, encoding='utf-8', newline='\n')
|
||||
script = self.script.replace('stage=/tmp/__UPLOAD_NAME__', 'stage=' + shlex.quote(stage.as_posix()))
|
||||
script = script.replace('__UPLOAD_NAME__', 'sandbox').replace('__KIND__', 'Router').replace('__ACTION__', action)
|
||||
script = script.replace('__DEFER_RESTART__', '1' if deferred else '0')
|
||||
if no_timeout:
|
||||
# Model the optional applet missing from both PATH and BusyBox.
|
||||
script = script.replace('command -v timeout >/dev/null 2>&1', 'false')
|
||||
@@ -97,6 +106,15 @@ sleep() { :; }
|
||||
self.assertNotIn('restoring files', result.stderr)
|
||||
self.assert_original()
|
||||
|
||||
def test_reverse_ssh_install_queues_independent_restart_after_file_checks(self):
|
||||
# A direct restart would close the SSH connection carrying deployment.
|
||||
# The old restart mock intentionally fails; deferred mode must skip it.
|
||||
result = self.deploy(deferred=True, fail=True)
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
self.assertIn('TACHYON_RESTART_QUEUED', result.stdout)
|
||||
self.assertNotIn('TACHYON_INTEGRATION_Router_Install_OK', result.stdout)
|
||||
self.assertNotIn('restoring files', result.stderr)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -0,0 +1,92 @@
|
||||
"""Reverse SSH verification must validate the actual router API, not the badge."""
|
||||
from contextlib import closing, redirect_stdout
|
||||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||
import io
|
||||
import json
|
||||
from pathlib import Path
|
||||
import sqlite3
|
||||
import tempfile
|
||||
import threading
|
||||
import time
|
||||
import unittest
|
||||
|
||||
|
||||
class DetectionVerificationTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.temp = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(self.temp.cleanup)
|
||||
self.db = Path(self.temp.name) / 'hub.db'
|
||||
self.body = b'{"core_running":false}'
|
||||
owner = self
|
||||
class Backend(BaseHTTPRequestHandler):
|
||||
def do_GET(self):
|
||||
self.send_response(200); self.end_headers(); self.wfile.write(owner.body)
|
||||
def log_message(self, *args): pass
|
||||
self.server = ThreadingHTTPServer(('127.0.0.1', 0), Backend)
|
||||
self.thread = threading.Thread(target=self.server.serve_forever, daemon=True)
|
||||
self.thread.start(); self.addCleanup(self.close)
|
||||
with closing(sqlite3.connect(self.db)) as db, db:
|
||||
db.execute('create table routers(id text,last_seen real,status_json text,tachyon_entry_port integer,deleted_at integer default 0)')
|
||||
db.execute('insert into routers(id,last_seen,status_json,tachyon_entry_port) values(?,?,?,?)', ('node-12', time.time(), json.dumps({
|
||||
'xray':'running', 'tachyon':{'mode':'standalone','available':True,'version':'2.0.0-beta.15'}}), self.server.server_port))
|
||||
|
||||
def close(self):
|
||||
self.server.shutdown(); self.server.server_close(); self.thread.join(timeout=3)
|
||||
|
||||
def verify(self, action='Install'):
|
||||
source = (Path(__file__).resolve().parents[1] / 'vps/deploy-tachyon-detection-fix.ps1').read_text(encoding='utf-8')
|
||||
code = source.split("$Verify = @'\n",1)[1].split("\n'@",1)[0]
|
||||
code = code.replace('/var/lib/owrt-remote/hub.db',self.db.as_posix()).replace('__ROUTER_ID__','node-12')
|
||||
code = code.replace('__SINCE__',str(int(time.time())-10)).replace('__ACTION__',action)
|
||||
code = code.replace('range(40)','range(1)').replace('time.sleep(2)','time.sleep(0)')
|
||||
output = io.StringIO()
|
||||
with redirect_stdout(output): exec(compile(code,'verification','exec'),{})
|
||||
return output.getvalue()
|
||||
|
||||
def status(self):
|
||||
source = (Path(__file__).resolve().parents[1] / 'vps/deploy-tachyon-detection-fix.ps1').read_text(encoding='utf-8')
|
||||
code = source.split("$Status = @'\n",1)[1].split("\n'@",1)[0]
|
||||
code = code.replace('/var/lib/owrt-remote/hub.db',self.db.as_posix()).replace('__ROUTER_ID__','node-12')
|
||||
output = io.StringIO()
|
||||
try:
|
||||
with redirect_stdout(output): exec(compile(code,'status','exec'),{})
|
||||
except SystemExit as result:
|
||||
return result.code, output.getvalue()
|
||||
raise AssertionError('Status must explicitly report its return code')
|
||||
|
||||
def test_standalone_route_with_stopped_core_is_still_a_working_web_api(self):
|
||||
self.assertIn('TACHYON_DETECTION_Router_Install_OK',self.verify())
|
||||
|
||||
def test_luci_html_instead_of_tachyon_is_rejected(self):
|
||||
self.body = b'<html>LuCI login</html>'
|
||||
with self.assertRaisesRegex(SystemExit,'Result not confirmed'): self.verify()
|
||||
|
||||
def test_wrong_api_field_type_is_rejected(self):
|
||||
self.body = b'{"core_running":"false"}'
|
||||
with self.assertRaisesRegex(SystemExit,'Result not confirmed'): self.verify()
|
||||
|
||||
def test_stale_heartbeat_cannot_confirm_deployment(self):
|
||||
with closing(sqlite3.connect(self.db)) as db, db: db.execute('update routers set last_seen=0')
|
||||
with self.assertRaisesRegex(SystemExit,'Result not confirmed'): self.verify()
|
||||
|
||||
def test_rollback_can_restore_legacy_detection(self):
|
||||
with closing(sqlite3.connect(self.db)) as db, db:
|
||||
db.execute('update routers set status_json=?',(json.dumps({'xray':'running','tachyon':{'mode':'luci'}}),))
|
||||
self.assertIn('TACHYON_DETECTION_Router_Rollback_OK',self.verify('Rollback'))
|
||||
|
||||
def test_status_checks_the_selected_router_without_changing_database(self):
|
||||
before = self.db.read_bytes()
|
||||
rc, output = self.status()
|
||||
self.assertEqual(rc, 0, output)
|
||||
self.assertIn('TACHYON_CHECK_OK: node-12', output)
|
||||
self.assertIn('2.0.0-beta.15', output)
|
||||
self.assertEqual(self.db.read_bytes(), before)
|
||||
|
||||
def test_status_rejects_luci_html_and_reports_failure(self):
|
||||
self.body = b'<html>LuCI</html>'
|
||||
rc, output = self.status()
|
||||
self.assertEqual(rc, 1, output)
|
||||
self.assertIn('TACHYON_CHECK_FAILED: node-12', output)
|
||||
|
||||
|
||||
if __name__ == '__main__': unittest.main()
|
||||
@@ -16,6 +16,9 @@ assert(html.includes('Открыть Tachyon'));
|
||||
assert(html.includes('target="_blank"'));
|
||||
assert(html.includes('Online'));
|
||||
assert(html.includes('href="/tachyon/a/"'));
|
||||
assert(html.includes('tachyonMeta'));
|
||||
assert(html.includes('tachyonAction'));
|
||||
assert(context.renderTachyon({permissions:{admin:true}, tachyon:{installed:true, online:true, url:'/tachyon/a/'}}).includes('Tachyon</strong>'));
|
||||
router.tachyon.online = false;
|
||||
assert(context.renderTachyon(router).includes('Offline'));
|
||||
router.permissions.admin = false;
|
||||
|
||||
@@ -0,0 +1,113 @@
|
||||
[CmdletBinding(DefaultParameterSetName = 'Router')]
|
||||
param(
|
||||
[Parameter(ParameterSetName = 'Router')][string]$Router = 'root@192.168.2.1',
|
||||
[Parameter(Mandatory = $true, ParameterSetName = 'Vps')][string]$Vps,
|
||||
[Parameter(ParameterSetName = 'Vps')][ValidatePattern('^[A-Za-z0-9_.-]+$')][string]$RouterId,
|
||||
[ValidateSet('Install', 'Rollback', 'Status')][string]$Action = 'Install',
|
||||
[switch]$PrepareOnly
|
||||
)
|
||||
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$Deploy = Join-Path $PSScriptRoot 'deploy-tachyon.ps1'
|
||||
if ($Action -eq 'Status') {
|
||||
if (-not $Vps -or -not $RouterId) { throw 'Status requires -Vps and -RouterId, for example node-12.' }
|
||||
$Status = @'
|
||||
import json, sqlite3, time, urllib.request
|
||||
from contextlib import closing
|
||||
with closing(sqlite3.connect('file:/var/lib/owrt-remote/hub.db?mode=ro', uri=True)) as db:
|
||||
row = db.execute('select last_seen,status_json,tachyon_entry_port from routers where id=? and coalesce(deleted_at,0)=0', ('__ROUTER_ID__',)).fetchone()
|
||||
if not row:
|
||||
raise SystemExit('Router __ROUTER_ID__ not found in Hub')
|
||||
status = json.loads(row[1] or '{}')
|
||||
tachyon = status.get('tachyon') or {}
|
||||
age = max(0, int(time.time() - float(row[0] or 0)))
|
||||
api_ok = False
|
||||
reason = 'standalone route unavailable'
|
||||
if tachyon.get('mode') == 'standalone' and row[2]:
|
||||
try:
|
||||
opener = urllib.request.build_opener(urllib.request.ProxyHandler({}))
|
||||
with opener.open('http://127.0.0.1:' + str(int(row[2])) + '/api/agent/v1/health', timeout=4) as response:
|
||||
health = json.loads(response.read(65536))
|
||||
api_ok = type(health.get('core_running')) is bool
|
||||
reason = 'Tachyon API confirmed through the reverse tunnel' if api_ok else 'Unexpected API response'
|
||||
except Exception as error:
|
||||
reason = 'Reverse route: ' + type(error).__name__
|
||||
print(json.dumps({'router':'__ROUTER_ID__', 'version':tachyon.get('version') or '',
|
||||
'package_version':tachyon.get('package_version') or '', 'mode':tachyon.get('mode') or 'unknown',
|
||||
'port':tachyon.get('port'), 'xray':status.get('xray'), 'heartbeat_age_seconds':age,
|
||||
'api_ok':api_ok, 'reason':reason}, ensure_ascii=True, indent=2))
|
||||
ok = age <= 120 and status.get('xray') == 'running' and tachyon.get('available') and api_ok
|
||||
print('TACHYON_CHECK_OK: __ROUTER_ID__' if ok else 'TACHYON_CHECK_FAILED: __ROUTER_ID__')
|
||||
raise SystemExit(0 if ok else 1)
|
||||
'@
|
||||
$Status = $Status.Replace('__ROUTER_ID__', $RouterId)
|
||||
$Status.Replace("`r`n", "`n") | & ssh -T -o ConnectTimeout=20 $Vps 'python3 -'
|
||||
if ($LASTEXITCODE -ne 0) { throw 'Router check failed. See mode, version and API result above. No files were changed.' }
|
||||
return
|
||||
}
|
||||
$Options = @{ Action = $Action; BackupName = 'tachyon-detection'; BackupVersion = 'v122'; PrepareOnly = $PrepareOnly }
|
||||
if ($PSCmdlet.ParameterSetName -eq 'Router') {
|
||||
& $Deploy -Router $Router @Options
|
||||
} elseif (-not $RouterId) {
|
||||
& $Deploy -Vps $Vps @Options
|
||||
} else {
|
||||
# Query only this router's loopback SSH listener. RouterId cannot contain
|
||||
# shell/SQL quoting characters, and the database is opened read-only.
|
||||
$Query = @'
|
||||
import sqlite3, time
|
||||
from contextlib import closing
|
||||
with closing(sqlite3.connect('file:/var/lib/owrt-remote/hub.db?mode=ro', uri=True)) as db:
|
||||
row = db.execute('select ssh_entry_port from routers where id=? and coalesce(deleted_at,0)=0', ('__ROUTER_ID__',)).fetchone()
|
||||
if not row or not isinstance(row[0], int) or not 1024 <= row[0] <= 65535:
|
||||
raise SystemExit('Router has no valid loopback SSH entry in Hub')
|
||||
print('TACHYON_SSH_PORT=' + str(row[0]))
|
||||
print('TACHYON_MIN_SEEN=' + str(int(time.time())))
|
||||
'@
|
||||
$Query = $Query.Replace('__ROUTER_ID__', $RouterId)
|
||||
$Output = $Query.Replace("`r`n", "`n") | & ssh -T -o ConnectTimeout=20 $Vps 'python3 -'
|
||||
if ($LASTEXITCODE -ne 0) { throw 'Cannot read the selected router SSH port. Router was not changed.' }
|
||||
$PortLine = @($Output | Where-Object { $_ -match '^TACHYON_SSH_PORT=([0-9]+)$' })
|
||||
if ($PortLine.Count -ne 1) { throw 'Hub did not return one SSH port. Router was not changed.' }
|
||||
$RouterPort = [int]($PortLine[0] -replace '^TACHYON_SSH_PORT=', '')
|
||||
if ($RouterPort -lt 1024 -or $RouterPort -gt 65535) { throw 'Invalid SSH listener port.' }
|
||||
Write-Host "Selected router: $RouterId; SSH via $Vps and loopback port $RouterPort"
|
||||
$SinceLine = @($Output | Where-Object { $_ -match '^TACHYON_MIN_SEEN=([0-9]+)$' })
|
||||
if ($SinceLine.Count -ne 1) { throw 'Hub did not return a verification timestamp.' }
|
||||
$Since = [long]($SinceLine[0] -replace '^TACHYON_MIN_SEEN=', '')
|
||||
& $Deploy -Router root@127.0.0.1 -Port $RouterPort -JumpHost $Vps -DeferRestart @Options
|
||||
if ($PrepareOnly) { return }
|
||||
# Verification uses the VPS, so a reconnecting reverse SSH tunnel does
|
||||
# not interrupt it. It also verifies the real route, not just a green card.
|
||||
$Verify = @'
|
||||
import json, sqlite3, time, urllib.request
|
||||
from contextlib import closing
|
||||
opener = urllib.request.build_opener(urllib.request.ProxyHandler({}))
|
||||
last = 'Waiting for a fresh Heartbeat and the standalone route'
|
||||
for attempt in range(40):
|
||||
with closing(sqlite3.connect('file:/var/lib/owrt-remote/hub.db?mode=ro', uri=True)) as db:
|
||||
row = db.execute('select last_seen,status_json,tachyon_entry_port from routers where id=?', ('__ROUTER_ID__',)).fetchone()
|
||||
try:
|
||||
status = json.loads(row[1] or '{}') if row else {}
|
||||
tachyon = status.get('tachyon') or {}
|
||||
fresh = row and float(row[0] or 0) >= __SINCE__
|
||||
if fresh and status.get('xray') == 'running':
|
||||
if '__ACTION__' == 'Rollback':
|
||||
print('TACHYON_DETECTION_Router_Rollback_OK: fresh Heartbeat; Xray running')
|
||||
break
|
||||
if tachyon.get('mode') == 'standalone' and tachyon.get('available') and tachyon.get('version') and row[2]:
|
||||
with opener.open('http://127.0.0.1:' + str(int(row[2])) + '/api/agent/v1/health', timeout=3) as response:
|
||||
health = json.loads(response.read(65536))
|
||||
if type(health.get('core_running')) is bool:
|
||||
print('TACHYON_DETECTION_Router_Install_OK: ' + str(tachyon.get('version')) + '; standalone API verified through the router tunnel')
|
||||
break
|
||||
last = 'Waiting for router __ROUTER_ID__: mode=' + str(tachyon.get('mode')) + '; Xray=' + str(status.get('xray'))
|
||||
except Exception as error:
|
||||
last = 'Reverse route not ready: ' + type(error).__name__
|
||||
time.sleep(2)
|
||||
else:
|
||||
raise SystemExit('Result not confirmed: ' + last + '; backup retained at /root/owrt-remote-backup-before-tachyon-detection-v122')
|
||||
'@
|
||||
$Verify = $Verify.Replace('__ROUTER_ID__', $RouterId).Replace('__SINCE__', [string]$Since).Replace('__ACTION__', $Action)
|
||||
$Verify.Replace("`r`n", "`n") | & ssh -T -o ConnectTimeout=20 -o ServerAliveInterval=15 $Vps 'python3 -'
|
||||
if ($LASTEXITCODE -ne 0) { throw 'Router result not confirmed. See diagnostic above; retained backup is available for Rollback.' }
|
||||
}
|
||||
+36
-8
@@ -2,7 +2,11 @@ param(
|
||||
[Parameter(Mandatory = $true, ParameterSetName = 'Vps')][string]$Vps,
|
||||
[Parameter(Mandatory = $true, ParameterSetName = 'Router')][string]$Router,
|
||||
[ValidateSet('Install', 'Rollback')][string]$Action = 'Install',
|
||||
[ValidateSet('tachyon-integration', 'tachyon-layout')][string]$BackupName = 'tachyon-integration',
|
||||
[ValidateSet('tachyon-integration', 'tachyon-layout', 'tachyon-detection')][string]$BackupName = 'tachyon-integration',
|
||||
[ValidateSet('v121', 'v122')][string]$BackupVersion = 'v121',
|
||||
[ValidateRange(1, 65535)][int]$Port = 22,
|
||||
[string]$JumpHost = '',
|
||||
[switch]$DeferRestart,
|
||||
[switch]$PrepareOnly
|
||||
)
|
||||
|
||||
@@ -13,6 +17,7 @@ $StageRoot = Join-Path ([System.IO.Path]::GetTempPath()) $UploadName
|
||||
$Utf8 = [System.Text.UTF8Encoding]::new($false)
|
||||
$TargetKind = $PSCmdlet.ParameterSetName
|
||||
$Destination = if ($TargetKind -eq 'Vps') { $Vps } else { $Router }
|
||||
if ($DeferRestart -and $TargetKind -ne 'Router') { throw 'Deferred restart requires a router target.' }
|
||||
|
||||
$RemoteScript = @'
|
||||
#!/bin/sh
|
||||
@@ -23,6 +28,7 @@ action=__ACTION__
|
||||
backup=/root/owrt-remote-backup-before-__BACKUP_NAME__-v121
|
||||
changed=0
|
||||
step=preflight
|
||||
defer_restart=__DEFER_RESTART__
|
||||
|
||||
if [ "$kind" = Vps ]; then
|
||||
names=hub.py
|
||||
@@ -155,8 +161,15 @@ snapshot "$stage/previous"
|
||||
changed=1
|
||||
step=apply-files
|
||||
apply_files "$source_dir"
|
||||
if [ "$kind" = Router ] && [ "$action" = Install ]; then
|
||||
step=refresh-discovery
|
||||
# Refresh the bounded RAM cache before rendering Xray, so an old LuCI
|
||||
# classification cannot keep the standalone route absent for another beat.
|
||||
/usr/sbin/owrt-remote tachyon-status >"$stage/tachyon-status"
|
||||
cat "$stage/tachyon-status"
|
||||
fi
|
||||
step=restart
|
||||
restart
|
||||
if [ "$defer_restart" != 1 ]; then restart; fi
|
||||
|
||||
step=verify-health
|
||||
if [ "$kind" = Vps ]; then
|
||||
@@ -190,12 +203,21 @@ for name in $names; do
|
||||
path="$(target "$name")"
|
||||
if [ -e "$source_dir/$name.absent" ]; then test ! -e "$path"; else cmp "$source_dir/$name" "$path"; fi
|
||||
done
|
||||
printf '\nBackup: %s\nTACHYON_INTEGRATION_%s_%s_OK\n' "$backup" "$kind" "$action"
|
||||
if [ "$defer_restart" = 1 ]; then
|
||||
step=queue-restart
|
||||
# An SSH connection through Xray must finish before Xray stops. This
|
||||
# bounded procd worker is independent of the service being restarted.
|
||||
ubus call service add '{"name":"owrt-remote-tachyon-refresh","instances":{"once":{"command":["/bin/sh","-c","sleep 3; /etc/init.d/owrt-remote restart","__UPLOAD_NAME__"],"stdout":true,"stderr":true}}}' >/dev/null
|
||||
printf '\nBackup: %s\nTACHYON_RESTART_QUEUED\n' "$backup"
|
||||
else
|
||||
printf '\nBackup: %s\nTACHYON_INTEGRATION_%s_%s_OK\n' "$backup" "$kind" "$action"
|
||||
fi
|
||||
'@
|
||||
|
||||
try {
|
||||
[System.IO.Directory]::CreateDirectory($StageRoot) | Out-Null
|
||||
$RemoteScript = $RemoteScript.Replace('__UPLOAD_NAME__', $UploadName).Replace('__KIND__', $TargetKind).Replace('__ACTION__', $Action).Replace('__BACKUP_NAME__', $BackupName)
|
||||
if ($BackupVersion -eq 'v122') { $RemoteScript = $RemoteScript.Replace('-__BACKUP_NAME__-v121', '-__BACKUP_NAME__-v122') }
|
||||
$RemoteScript = $RemoteScript.Replace('__UPLOAD_NAME__', $UploadName).Replace('__KIND__', $TargetKind).Replace('__ACTION__', $Action).Replace('__BACKUP_NAME__', $BackupName).Replace('__DEFER_RESTART__', $(if ($DeferRestart) { '1' } else { '0' }))
|
||||
[System.IO.File]::WriteAllText((Join-Path $StageRoot 'run.sh'), $RemoteScript.Replace("`r`n", "`n") + "`n", $Utf8)
|
||||
if ($Action -eq 'Install') {
|
||||
$Sources = if ($TargetKind -eq 'Vps') {
|
||||
@@ -209,11 +231,17 @@ try {
|
||||
}
|
||||
}
|
||||
if ($PrepareOnly) { Write-Host "Prepared only: $StageRoot"; return }
|
||||
& scp -O -o ConnectTimeout=20 -r -- $StageRoot "${Destination}:/tmp/"
|
||||
$JumpOptions = if ($JumpHost) { @('-o', "ProxyJump=$JumpHost") } else { @() }
|
||||
& scp -O -P $Port @JumpOptions -o ConnectTimeout=20 -r -- $StageRoot "${Destination}:/tmp/"
|
||||
if ($LASTEXITCODE -ne 0) { throw 'Upload failed. Target was not changed.' }
|
||||
& ssh -T -o ConnectTimeout=20 -o ServerAliveInterval=15 $Destination "sh /tmp/$UploadName/run.sh"
|
||||
if ($LASTEXITCODE -ne 0) { throw "$Action failed. Success was not confirmed; see output above." }
|
||||
Write-Host "Tachyon integration $TargetKind $Action finished successfully."
|
||||
$RemoteOutput = & ssh -T -p $Port @JumpOptions -o ConnectTimeout=20 -o ServerAliveInterval=15 $Destination "sh /tmp/$UploadName/run.sh"
|
||||
$RemoteCode = $LASTEXITCODE
|
||||
$RemoteOutput | Write-Output
|
||||
if ($RemoteCode -ne 0 -and -not ($DeferRestart -and $RemoteCode -eq 255 -and @($RemoteOutput) -contains 'TACHYON_RESTART_QUEUED')) {
|
||||
throw "$Action failed. Success was not confirmed; see output above."
|
||||
}
|
||||
if ($DeferRestart) { Write-Host 'Files applied; restart queued. Runtime verification follows.' }
|
||||
else { Write-Host "Tachyon integration $TargetKind $Action finished successfully." }
|
||||
} finally {
|
||||
if (-not $PrepareOnly -and (Test-Path -LiteralPath $StageRoot)) {
|
||||
$Resolved = [System.IO.Path]::GetFullPath($StageRoot)
|
||||
|
||||
@@ -8461,7 +8461,7 @@ function renderTachyon(router) {{
|
||||
const button = (router.permissions || {{}}).admin
|
||||
? `<a class="btn" href="${{escapeAttr(t.url)}}" target="_blank" rel="noopener noreferrer">Открыть Tachyon</a>`
|
||||
: '<span class="btn disabled">Открыть Tachyon</span>';
|
||||
return `<div class="tachyonIntegration" style="display:flex;flex-wrap:wrap;align-items:center;justify-content:center;gap:8px;padding:10px;margin-top:10px;border:1px solid var(--line,rgba(180,150,220,.25));border-radius:12px"><strong>Tachyon ${{escapeHtml(t.version || '')}}</strong><span style="color:${{t.online ? '#74e3ac' : '#f2bc6b'}}">${{label}}</span>${{button}}</div>`;
|
||||
return `<div class="tachyonIntegration" style="display:flex;flex-direction:column;align-items:center;justify-content:center;gap:8px;padding:10px;margin-top:10px;border:1px solid var(--line,rgba(180,150,220,.25));border-radius:12px"><div class="tachyonMeta" style="display:flex;flex-wrap:wrap;align-items:center;justify-content:center;gap:8px;min-height:24px;max-width:100%"><strong style="min-width:0;max-width:100%;overflow-wrap:anywhere;text-align:center">Tachyon${{t.version ? ' ' + escapeHtml(t.version) : ''}}</strong><span style="color:${{t.online ? '#74e3ac' : '#f2bc6b'}}">${{label}}</span></div><div class="tachyonAction">${{button}}</div></div>`;
|
||||
}}
|
||||
|
||||
function render(list) {{
|
||||
|
||||
Reference in new issue
Block a user