Add v118 dashboard update confirmation and responsive spacing
This commit is contained in:
1 parent
dfa16f3772
commit
2a8b646b5c
70 files changed
+2247
-212
No files matched your search
@@ -15,7 +15,7 @@ $RemoteScript = @'
|
||||
set -eu
|
||||
stage=/tmp/__UPLOAD_NAME__
|
||||
target=/opt/owrt-remote/owrt-remote-hub.py
|
||||
backup=/opt/owrt-remote/owrt-remote-hub.py.bak-before-dashboard-layout-v117
|
||||
backup=/opt/owrt-remote/owrt-remote-hub.py.bak-before-dashboard-layout-v118
|
||||
candidate=$target.new-__UPLOAD_NAME__
|
||||
changed=0
|
||||
|
||||
@@ -106,7 +106,7 @@ if [ "$healthy" -ne 1 ]; then
|
||||
exit 1
|
||||
fi
|
||||
cmp "$source_file" "$target"
|
||||
printf '\nBackup: %s\nDASHBOARD_LAYOUT_V117_%s_OK\n' "$backup" '__ACTION__'
|
||||
printf '\nBackup: %s\nDASHBOARD_LAYOUT_V118_%s_OK\n' "$backup" '__ACTION__'
|
||||
'@
|
||||
|
||||
$RemoteScript = $RemoteScript.Replace('__UPLOAD_NAME__', $UploadName).Replace('__ACTION__', $Action)
|
||||
|
||||
@@ -0,0 +1,151 @@
|
||||
param(
|
||||
[Parameter(Mandatory = $true)][ValidateNotNullOrEmpty()][string]$Vps,
|
||||
[ValidateSet('Install', 'Rollback')][string]$Action = 'Install',
|
||||
[switch]$PrepareOnly
|
||||
)
|
||||
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$RepoRoot = Split-Path -Parent $PSScriptRoot
|
||||
$UploadName = 'owrt-dashboard-menu-' + [guid]::NewGuid().ToString('N')
|
||||
$StageRoot = Join-Path ([System.IO.Path]::GetTempPath()) $UploadName
|
||||
$Utf8 = [System.Text.UTF8Encoding]::new($false)
|
||||
|
||||
$RemoteScript = @'
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
stage=/tmp/__UPLOAD_NAME__
|
||||
target=/opt/owrt-remote/owrt-remote-hub.py
|
||||
backup=/opt/owrt-remote/owrt-remote-hub.py.bak-before-dashboard-menu-v118
|
||||
candidate=$target.new-__UPLOAD_NAME__
|
||||
changed=0
|
||||
|
||||
show_failure() {
|
||||
echo '--- owrt-remote status ---' >&2
|
||||
systemctl --no-pager -l status owrt-remote >&2 || true
|
||||
echo '--- owrt-remote journal ---' >&2
|
||||
journalctl -u owrt-remote -n 80 --no-pager -l >&2 || true
|
||||
}
|
||||
|
||||
cleanup() {
|
||||
code=$?
|
||||
trap - EXIT
|
||||
if [ "$code" -ne 0 ]; then
|
||||
echo "Remote step failed with rc=$code" >&2
|
||||
show_failure
|
||||
fi
|
||||
if [ "$code" -ne 0 ] && [ "$changed" = 1 ] && [ -s "$stage/previous.py" ]; then
|
||||
echo 'Restoring the previous Hub file...' >&2
|
||||
cp -p "$stage/previous.py" "$candidate"
|
||||
mv -f "$candidate" "$target"
|
||||
systemctl restart owrt-remote || true
|
||||
fi
|
||||
rm -f "$candidate"
|
||||
rm -rf "$stage"
|
||||
exit "$code"
|
||||
}
|
||||
trap cleanup EXIT
|
||||
|
||||
test -s "$target"
|
||||
python_bin=/opt/owrt-remote/venv/bin/python
|
||||
[ -x "$python_bin" ] || python_bin=python3
|
||||
|
||||
if [ '__ACTION__' = Install ]; then
|
||||
test -s "$stage/hub.py"
|
||||
echo 'Validating candidate...'
|
||||
"$python_bin" -m py_compile "$stage/hub.py"
|
||||
"$python_bin" - "$stage/hub.py" <<'PY'
|
||||
from pathlib import Path
|
||||
import sys
|
||||
source = Path(sys.argv[1]).read_text(encoding='utf-8')
|
||||
required = (
|
||||
"def dashboard_html(",
|
||||
"#routerUpdatesGroup .routerUpdatesLaunch{{display:flex;",
|
||||
'class="sessionBtn btn routerUpdatesLaunch"',
|
||||
"const SEASON_EFFECT_MODES = new Set(['off', 'snow', 'rain', 'cosmos', 'embers', 'orbit', 'prism', 'pulse', 'laser']);",
|
||||
)
|
||||
for mode in ('aurora', 'matrix', 'nebula', 'fireworks', 'vortex', 'comet'):
|
||||
if 'data-season-mode="' + mode + '"' in source:
|
||||
raise SystemExit('Removed effect is still offered: ' + mode)
|
||||
missing = [marker for marker in required if marker not in source]
|
||||
if missing:
|
||||
for marker in missing:
|
||||
print('Missing marker:', repr(marker), file=sys.stderr)
|
||||
raise SystemExit(1)
|
||||
print('Candidate validation OK')
|
||||
PY
|
||||
if [ ! -e "$backup" ]; then
|
||||
cp -p "$target" "$backup"
|
||||
fi
|
||||
source_file="$stage/hub.py"
|
||||
else
|
||||
test -s "$backup"
|
||||
"$python_bin" -m py_compile "$backup"
|
||||
source_file="$backup"
|
||||
fi
|
||||
|
||||
cp -p "$target" "$stage/previous.py"
|
||||
cp "$source_file" "$candidate"
|
||||
chmod 0755 "$candidate"
|
||||
changed=1
|
||||
mv -f "$candidate" "$target"
|
||||
echo 'Restarting owrt-remote...'
|
||||
if ! systemctl restart owrt-remote; then
|
||||
show_failure
|
||||
exit 1
|
||||
fi
|
||||
|
||||
healthy=0
|
||||
for attempt in 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15; do
|
||||
if systemctl is-active --quiet owrt-remote && curl -fsS --max-time 5 http://127.0.0.1:8088/health; then
|
||||
healthy=1
|
||||
break
|
||||
fi
|
||||
sleep 2
|
||||
done
|
||||
if [ "$healthy" -ne 1 ]; then
|
||||
echo 'Health check did not become ready.' >&2
|
||||
show_failure
|
||||
exit 1
|
||||
fi
|
||||
cmp "$source_file" "$target"
|
||||
printf '\nBackup: %s\nDASHBOARD_MENU_V118_%s_OK\n' "$backup" '__ACTION__'
|
||||
'@
|
||||
|
||||
$RemoteScript = $RemoteScript.Replace('__UPLOAD_NAME__', $UploadName).Replace('__ACTION__', $Action)
|
||||
|
||||
try {
|
||||
[System.IO.Directory]::CreateDirectory($StageRoot) | Out-Null
|
||||
[System.IO.File]::WriteAllText(
|
||||
(Join-Path $StageRoot 'run.sh'),
|
||||
$RemoteScript.Replace("`r`n", "`n") + "`n",
|
||||
$Utf8
|
||||
)
|
||||
|
||||
if ($Action -eq 'Install') {
|
||||
$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 "sh /tmp/$UploadName/run.sh"
|
||||
if ($LASTEXITCODE -ne 0) { throw "$Action failed. See the output above; success was not confirmed." }
|
||||
Write-Host "Dashboard menu fix $Action finished successfully."
|
||||
}
|
||||
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
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -15,7 +15,7 @@ $RemoteScript = @'
|
||||
set -eu
|
||||
stage=/tmp/__UPLOAD_NAME__
|
||||
target=/opt/owrt-remote/owrt-remote-hub.py
|
||||
backup=/opt/owrt-remote/owrt-remote-hub.py.bak-before-global-logs-ui-v117
|
||||
backup=/opt/owrt-remote/owrt-remote-hub.py.bak-before-global-logs-ui-v118
|
||||
candidate=$target.new-__UPLOAD_NAME__
|
||||
changed=0
|
||||
|
||||
@@ -107,7 +107,7 @@ if [ "$healthy" -ne 1 ]; then
|
||||
exit 1
|
||||
fi
|
||||
cmp "$source_file" "$target"
|
||||
printf '\nBackup: %s\nGLOBAL_LOGS_VPS_V117_%s_OK\n' "$backup" '__ACTION__'
|
||||
printf '\nBackup: %s\nGLOBAL_LOGS_VPS_V118_%s_OK\n' "$backup" '__ACTION__'
|
||||
'@
|
||||
|
||||
$RemoteScript = $RemoteScript.Replace('__UPLOAD_NAME__', $UploadName).Replace('__ACTION__', $Action)
|
||||
|
||||
@@ -13,7 +13,7 @@ $RemoteScript = @'
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
stage=/tmp/__UPLOAD_NAME__
|
||||
backup=/root/owrt-remote-backup-before-global-logs-stop-v117
|
||||
backup=/root/owrt-remote-backup-before-global-logs-stop-v118
|
||||
items='cgi agent init logs.sh logs-init luci'
|
||||
changed=0
|
||||
phase=preflight
|
||||
@@ -104,7 +104,7 @@ if [ '__ACTION__' = Install ]; then
|
||||
command -v base64 >/dev/null
|
||||
command -v jsonfilter >/dev/null
|
||||
grep -F -q 'globalLogsToggle' "$stage/cgi"
|
||||
for item in cgi luci; do grep -F -q 'v117' "$stage/$item"; done
|
||||
for item in cgi luci; do grep -F -q 'v118' "$stage/$item"; done
|
||||
grep -F -q 'LOG_KEEP_SECONDS=86400' "$stage/logs.sh"
|
||||
grep -F -q 'log_sync_loop' "$stage/logs.sh"
|
||||
grep -F -q 'sync_global_logs' "$stage/agent"
|
||||
|
||||
@@ -6,7 +6,7 @@ param(
|
||||
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$RepoRoot = Split-Path -Parent $PSScriptRoot
|
||||
$UploadName = 'owrt-group-colors-v117-' + [guid]::NewGuid().ToString('N')
|
||||
$UploadName = 'owrt-group-colors-v118-' + [guid]::NewGuid().ToString('N')
|
||||
$StageRoot = Join-Path ([System.IO.Path]::GetTempPath()) $UploadName
|
||||
$Utf8 = [System.Text.UTF8Encoding]::new($false)
|
||||
|
||||
@@ -15,7 +15,7 @@ $RemoteScript = @'
|
||||
set -eu
|
||||
stage=/tmp/__UPLOAD_NAME__
|
||||
target=/opt/owrt-remote/owrt-remote-hub.py
|
||||
backup=/opt/owrt-remote/owrt-remote-hub.py.bak-before-group-colors-v117
|
||||
backup=/opt/owrt-remote/owrt-remote-hub.py.bak-before-group-colors-v118
|
||||
candidate=$target.new-__UPLOAD_NAME__
|
||||
changed=0
|
||||
|
||||
@@ -57,7 +57,7 @@ if [ '__ACTION__' = Install ]; then
|
||||
from pathlib import Path
|
||||
import sys
|
||||
source = Path(sys.argv[1]).read_text(encoding='utf-8')
|
||||
required = ('v117', '#routerForm select option,#routerGroupFilter option', 'background-color:#221a34', 'id="backupDownload"', 'id="backupRestore"')
|
||||
required = ('v118', '#routerForm select option,#routerGroupFilter option', 'background-color:#221a34', 'id="backupDownload"', 'id="backupRestore"')
|
||||
if 'class="backupCmds"' in source:
|
||||
print('Old backup command instructions remain in candidate', file=sys.stderr)
|
||||
raise SystemExit(1)
|
||||
@@ -106,7 +106,7 @@ if [ "$healthy" -ne 1 ]; then
|
||||
exit 1
|
||||
fi
|
||||
cmp "$source_file" "$target"
|
||||
printf '\nBackup: %s\nGROUP_COLORS_V117_%s_OK\n' "$backup" '__ACTION__'
|
||||
printf '\nBackup: %s\nGROUP_COLORS_V118_%s_OK\n' "$backup" '__ACTION__'
|
||||
'@
|
||||
|
||||
$RemoteScript = $RemoteScript.Replace('__UPLOAD_NAME__', $UploadName).Replace('__ACTION__', $Action)
|
||||
|
||||
@@ -13,7 +13,7 @@ $RemoteScript = @'
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
stage=/tmp/__UPLOAD_NAME__
|
||||
backup=/root/owrt-remote-backup-before-heartbeat-redirect-v117
|
||||
backup=/root/owrt-remote-backup-before-heartbeat-redirect-v118
|
||||
agent=/usr/sbin/owrt-remote
|
||||
wan=/usr/lib/owrt-remote/wan.sh
|
||||
changed=0
|
||||
|
||||
@@ -17,7 +17,7 @@ $RemoteScript = @'
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
stage=/tmp/__UPLOAD_NAME__
|
||||
backup_dir=/root/owrt-remote-backup-before-heartbeat-transport-v117
|
||||
backup_dir=/root/owrt-remote-backup-before-heartbeat-transport-v118
|
||||
changed=0
|
||||
phase=preflight
|
||||
item_path() {
|
||||
|
||||
@@ -5,7 +5,7 @@ param(
|
||||
[string]$PinnedVpsHost = '193.233.82.38',
|
||||
[ValidatePattern('^[a-zA-Z0-9_-]+$')][string]$WanInterface = 'wan',
|
||||
[switch]$PreserveConnectionSettings,
|
||||
[ValidatePattern('^[a-zA-Z0-9_-]+$')][string]$BackupName = 'host-policy-v117',
|
||||
[ValidatePattern('^[a-zA-Z0-9_-]+$')][string]$BackupName = 'host-policy-v118',
|
||||
[switch]$PrepareOnly
|
||||
)
|
||||
|
||||
@@ -90,7 +90,7 @@ test -s "$config"
|
||||
if [ '__ACTION__' = Install ]; then
|
||||
for item in agent wan.sh cgi init; do test -s "$stage/$item"; sh -n "$stage/$item"; done
|
||||
test -s "$stage/luci"
|
||||
for item in cgi luci; do grep -F -q 'v117' "$stage/$item"; done
|
||||
for item in cgi luci; do grep -F -q 'v118' "$stage/$item"; done
|
||||
# curl is needed to preserve HTTPS SNI and bypass the local DNS/proxy.
|
||||
if ! command -v curl >/dev/null 2>&1; then
|
||||
if command -v opkg >/dev/null 2>&1; then opkg update && opkg install curl ca-bundle
|
||||
@@ -156,16 +156,16 @@ if [ '__ACTION__' = Install ]; then
|
||||
exit 1
|
||||
fi
|
||||
/usr/sbin/owrt-remote status
|
||||
grep -F -q 'v117' /www/cgi-bin/owrt-remote
|
||||
grep -F -q 'v117' /www/luci-static/resources/view/owrt_remote.js
|
||||
echo HOST_POLICY_ROUTER_V117_OK
|
||||
grep -F -q 'v118' /www/cgi-bin/owrt-remote
|
||||
grep -F -q 'v118' /www/luci-static/resources/view/owrt_remote.js
|
||||
echo HOST_POLICY_ROUTER_V118_OK
|
||||
else
|
||||
test -f "$backup/complete"
|
||||
save_files "$stage/previous"
|
||||
changed=1
|
||||
restore_files "$backup"
|
||||
/usr/sbin/owrt-remote status
|
||||
echo HOST_POLICY_ROUTER_V117_ROLLBACK_OK
|
||||
echo HOST_POLICY_ROUTER_V118_ROLLBACK_OK
|
||||
fi
|
||||
'@
|
||||
} else {
|
||||
@@ -180,7 +180,7 @@ fi
|
||||
set -eu
|
||||
stage=/tmp/__UPLOAD_NAME__
|
||||
target=/opt/owrt-remote/owrt-remote-hub.py
|
||||
backup=/opt/owrt-remote/owrt-remote-hub.py.bak-before-host-policy-v117
|
||||
backup=/opt/owrt-remote/owrt-remote-hub.py.bak-before-host-policy-v118
|
||||
changed=0
|
||||
cleanup() {
|
||||
code=$?
|
||||
@@ -200,7 +200,7 @@ test -s "$target"
|
||||
python_bin=/opt/owrt-remote/venv/bin/python
|
||||
[ -x "$python_bin" ] || python_bin=python3
|
||||
if [ '__ACTION__' = Install ]; then
|
||||
grep -F -q 'v117' "$stage/hub.py"
|
||||
grep -F -q 'v118' "$stage/hub.py"
|
||||
"$python_bin" -m py_compile "$stage/hub.py"
|
||||
OWRT_HOST_POLICY_HUB_SOURCE="$stage/hub.py" "$python_bin" "$stage/test_host_policy.py" HostPolicyTests -v
|
||||
OWRT_RESOURCE_HUB_SOURCE="$stage/hub.py" "$python_bin" "$stage/resources.py" -v
|
||||
@@ -226,7 +226,7 @@ for attempt in 1 2 3 4 5 6 7 8 9 10; do
|
||||
done
|
||||
test "$healthy" = 1
|
||||
cmp "$candidate" "$target"
|
||||
printf '\nHOST_POLICY_VPS_V117_%s_OK\n' '__ACTION__'
|
||||
printf '\nHOST_POLICY_VPS_V118_%s_OK\n' '__ACTION__'
|
||||
'@
|
||||
}
|
||||
|
||||
|
||||
@@ -6,7 +6,7 @@ param(
|
||||
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$RepoRoot = Split-Path -Parent $PSScriptRoot
|
||||
$UploadName = 'owrt-version-v117-' + [guid]::NewGuid().ToString('N')
|
||||
$UploadName = 'owrt-hub-self-update-' + [guid]::NewGuid().ToString('N')
|
||||
$StageRoot = Join-Path ([System.IO.Path]::GetTempPath()) $UploadName
|
||||
$Utf8 = [System.Text.UTF8Encoding]::new($false)
|
||||
|
||||
@@ -15,7 +15,7 @@ $RemoteScript = @'
|
||||
set -eu
|
||||
stage=/tmp/__UPLOAD_NAME__
|
||||
target=/opt/owrt-remote/owrt-remote-hub.py
|
||||
backup=/opt/owrt-remote/owrt-remote-hub.py.bak-before-v117
|
||||
backup=/opt/owrt-remote/owrt-remote-hub.py.bak-before-hub-self-update-v118
|
||||
candidate=$target.new-__UPLOAD_NAME__
|
||||
changed=0
|
||||
|
||||
@@ -57,10 +57,14 @@ if [ '__ACTION__' = Install ]; then
|
||||
from pathlib import Path
|
||||
import sys
|
||||
source = Path(sys.argv[1]).read_text(encoding='utf-8')
|
||||
required = ('v117',)
|
||||
if 'v' + '116' in source:
|
||||
print('Old UI version remains in candidate', file=sys.stderr)
|
||||
raise SystemExit(1)
|
||||
required = (
|
||||
"class HubUpdateManager:",
|
||||
"def run_hub_update_worker(",
|
||||
"function initHubUpdate()",
|
||||
"panel-update-worker",
|
||||
"hub_update_api",
|
||||
"X-Hub-Update-CSRF",
|
||||
)
|
||||
missing = [marker for marker in required if marker not in source]
|
||||
if missing:
|
||||
for marker in missing:
|
||||
@@ -103,7 +107,7 @@ if [ "$healthy" -ne 1 ]; then
|
||||
exit 1
|
||||
fi
|
||||
cmp "$source_file" "$target"
|
||||
printf '\nBackup: %s\nHUB_V117_%s_OK\n' "$backup" '__ACTION__'
|
||||
printf '\nBackup: %s\nHUB_SELF_UPDATE_V118_%s_OK\n' "$backup" '__ACTION__'
|
||||
'@
|
||||
|
||||
$RemoteScript = $RemoteScript.Replace('__UPLOAD_NAME__', $UploadName).Replace('__ACTION__', $Action)
|
||||
@@ -130,7 +134,7 @@ try {
|
||||
if ($LASTEXITCODE -ne 0) { throw 'Upload failed. VPS was not changed.' }
|
||||
& ssh -T -o ConnectTimeout=10 $Vps "sh /tmp/$UploadName/run.sh"
|
||||
if ($LASTEXITCODE -ne 0) { throw "$Action failed. See the output above; success was not confirmed." }
|
||||
Write-Host "Hub v117 $Action finished successfully. Refresh the Hub panel."
|
||||
Write-Host "Hub self-update feature $Action finished successfully."
|
||||
}
|
||||
finally {
|
||||
if (-not $PrepareOnly) {
|
||||
@@ -34,7 +34,7 @@ if ($Target -eq 'Router') {
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
stage=/tmp/__UPLOAD_NAME__
|
||||
backup=/root/owrt-remote-backup-before-hub-url-v117
|
||||
backup=/root/owrt-remote-backup-before-hub-url-v118
|
||||
chmod 700 "$stage"
|
||||
config=/etc/config/owrtremote
|
||||
changed=0
|
||||
@@ -99,7 +99,7 @@ if [ '__ACTION__' = Install ]; then
|
||||
grep -F -q 'heartbeat_set_url_if_changed()' "$stage/agent"
|
||||
grep -F -q 'reason=https-downgrade' "$stage/agent"
|
||||
for item in agent wan.sh; do grep -F -q -- '--post301' "$stage/$item"; done
|
||||
for item in cgi luci; do grep -F -q 'v117' "$stage/$item"; done
|
||||
for item in cgi luci; do grep -F -q 'v118' "$stage/$item"; done
|
||||
if [ ! -e "$backup" ]; then
|
||||
save_files "$stage/retained-backup"
|
||||
mv "$stage/retained-backup" "$backup"
|
||||
@@ -138,7 +138,7 @@ else
|
||||
changed=1
|
||||
restore_files "$backup"
|
||||
fi
|
||||
printf '\nBackup: %s\nHUB_URL_ROUTER_V117_%s_OK\n' "$backup" '__ACTION__'
|
||||
printf '\nBackup: %s\nHUB_URL_ROUTER_V118_%s_OK\n' "$backup" '__ACTION__'
|
||||
'@
|
||||
} else {
|
||||
$Payloads = @{
|
||||
@@ -152,7 +152,7 @@ set -eu
|
||||
stage=/tmp/__UPLOAD_NAME__
|
||||
target=/opt/owrt-remote/owrt-remote-hub.py
|
||||
chmod 700 "$stage"
|
||||
backup=/opt/owrt-remote/owrt-remote-hub.py.bak-before-hub-url-v117
|
||||
backup=/opt/owrt-remote/owrt-remote-hub.py.bak-before-hub-url-v118
|
||||
candidate=$target.new-__UPLOAD_NAME__
|
||||
changed=0
|
||||
cleanup() {
|
||||
@@ -174,7 +174,7 @@ python_bin=/opt/owrt-remote/venv/bin/python
|
||||
[ -x "$python_bin" ] || python_bin=python3
|
||||
if [ '__ACTION__' = Install ]; then
|
||||
grep -F -q 'def router_hub_origins(' "$stage/hub.py"
|
||||
grep -F -q 'v117' "$stage/hub.py"
|
||||
grep -F -q 'v118' "$stage/hub.py"
|
||||
"$python_bin" -m py_compile "$stage/hub.py"
|
||||
OWRT_HOST_POLICY_HUB_SOURCE="$stage/hub.py" "$python_bin" "$stage/host_policy.py" HostPolicyTests -v
|
||||
OWRT_RESOURCE_HUB_SOURCE="$stage/hub.py" "$python_bin" "$stage/resources.py" IntegrationTests -v
|
||||
@@ -198,7 +198,7 @@ for attempt in 1 2 3 4 5 6 7 8 9 10; do
|
||||
done
|
||||
test "$healthy" = 1
|
||||
cmp "$source_file" "$target"
|
||||
printf '\nBackup: %s\nHUB_URL_VPS_V117_%s_OK\n' "$backup" '__ACTION__'
|
||||
printf '\nBackup: %s\nHUB_URL_VPS_V118_%s_OK\n' "$backup" '__ACTION__'
|
||||
'@
|
||||
}
|
||||
$RemoteScript = $RemoteScript.Replace('__UPLOAD_NAME__', $UploadName).Replace('__ACTION__', $Action).Replace('__HUB_URL__', $HubUrl)
|
||||
|
||||
@@ -17,7 +17,7 @@ $RemoteScript = @'
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
stage=/tmp/__UPLOAD_NAME__
|
||||
backup_dir=/root/owrt-remote-backup-before-log-collector-v117
|
||||
backup_dir=/root/owrt-remote-backup-before-log-collector-v118
|
||||
changed=0
|
||||
phase=preflight
|
||||
items='logs.sh logs-init'
|
||||
|
||||
@@ -14,7 +14,7 @@ $RemoteScript = @'
|
||||
set -eu
|
||||
stage=/tmp/__UPLOAD_NAME__
|
||||
target=/opt/owrt-remote/owrt-remote-hub.py
|
||||
backup=/opt/owrt-remote/owrt-remote-hub.py.bak-before-online-status-v117
|
||||
backup=/opt/owrt-remote/owrt-remote-hub.py.bak-before-online-status-v118
|
||||
candidate=$target.new-__UPLOAD_NAME__
|
||||
changed=0
|
||||
cleanup() {
|
||||
@@ -59,7 +59,7 @@ for attempt in 1 2 3 4 5 6 7 8 9 10; do
|
||||
done
|
||||
test "$healthy" = 1
|
||||
cmp "$source_file" "$target"
|
||||
printf '\nBackup: %s\nONLINE_STATUS_V117_%s_OK\n' "$backup" '__ACTION__'
|
||||
printf '\nBackup: %s\nONLINE_STATUS_V118_%s_OK\n' "$backup" '__ACTION__'
|
||||
'@
|
||||
$RemoteScript = $RemoteScript.Replace('__UPLOAD_NAME__', $UploadName).Replace('__ACTION__', $Action)
|
||||
try {
|
||||
|
||||
@@ -15,7 +15,7 @@ $RemoteScript = @'
|
||||
set -eu
|
||||
stage=/tmp/__UPLOAD_NAME__
|
||||
target=/opt/owrt-remote/owrt-remote-hub.py
|
||||
backup=/opt/owrt-remote/owrt-remote-hub.py.bak-before-password-logout-v117
|
||||
backup=/opt/owrt-remote/owrt-remote-hub.py.bak-before-password-logout-v118
|
||||
candidate=$target.new-__UPLOAD_NAME__
|
||||
changed=0
|
||||
|
||||
@@ -105,7 +105,7 @@ if [ "$healthy" -ne 1 ]; then
|
||||
exit 1
|
||||
fi
|
||||
cmp "$source_file" "$target"
|
||||
printf '\nBackup: %s\nPASSWORD_LOGOUT_V117_%s_OK\n' "$backup" '__ACTION__'
|
||||
printf '\nBackup: %s\nPASSWORD_LOGOUT_V118_%s_OK\n' "$backup" '__ACTION__'
|
||||
'@
|
||||
|
||||
$RemoteScript = $RemoteScript.Replace('__UPLOAD_NAME__', $UploadName).Replace('__ACTION__', $Action)
|
||||
|
||||
@@ -15,7 +15,7 @@ $RemoteScript = @'
|
||||
set -eu
|
||||
stage=/tmp/__UPLOAD_NAME__
|
||||
target=/opt/owrt-remote/owrt-remote-hub.py
|
||||
backup=/opt/owrt-remote/owrt-remote-hub.py.bak-before-persistent-logs-sync-v117
|
||||
backup=/opt/owrt-remote/owrt-remote-hub.py.bak-before-persistent-logs-sync-v118
|
||||
candidate=$target.new-__UPLOAD_NAME__
|
||||
changed=0
|
||||
|
||||
@@ -144,7 +144,7 @@ if [ "$healthy" -ne 1 ]; then
|
||||
exit 1
|
||||
fi
|
||||
cmp "$source_file" "$target"
|
||||
printf '\nBackup: %s\nPERSISTENT_LOGS_VPS_V117_%s_OK\n' "$backup" '__ACTION__'
|
||||
printf '\nBackup: %s\nPERSISTENT_LOGS_VPS_V118_%s_OK\n' "$backup" '__ACTION__'
|
||||
'@
|
||||
|
||||
$RemoteScript = $RemoteScript.Replace('__UPLOAD_NAME__', $UploadName).Replace('__ACTION__', $Action)
|
||||
|
||||
@@ -13,7 +13,7 @@ $RemoteScript = @'
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
stage=/tmp/__UPLOAD_NAME__
|
||||
backup=/root/owrt-remote-backup-before-persistent-logs-v117
|
||||
backup=/root/owrt-remote-backup-before-persistent-logs-v118
|
||||
items='cgi agent logs.sh logs-init luci'
|
||||
changed=0
|
||||
phase=preflight
|
||||
@@ -106,7 +106,7 @@ if [ '__ACTION__' = Install ]; then
|
||||
exit 1
|
||||
fi
|
||||
grep -F -q 'globalLogsToggle' "$stage/cgi"
|
||||
for item in cgi luci; do grep -F -q 'v117' "$stage/$item"; done
|
||||
for item in cgi luci; do grep -F -q 'v118' "$stage/$item"; done
|
||||
grep -F -q 'LOG_BUFFER_LIMIT=16384' "$stage/logs.sh"
|
||||
grep -F -q 'LOG_KEEP_SECONDS=86400' "$stage/logs.sh"
|
||||
grep -F -q 'log_sync_loop' "$stage/logs.sh"
|
||||
|
||||
@@ -17,8 +17,8 @@ if ($Action -eq 'Install') {
|
||||
set -Eeuo pipefail
|
||||
stage=/tmp/__UPLOAD_NAME__
|
||||
target=/opt/owrt-remote/owrt-remote-hub.py
|
||||
backup=/opt/owrt-remote/owrt-remote-hub.py.bak-before-recaptcha-v3-v117
|
||||
captcha_backup=/opt/owrt-remote/captcha-before-recaptcha-v3-v117.json
|
||||
backup=/opt/owrt-remote/owrt-remote-hub.py.bak-before-recaptcha-v3-v118
|
||||
captcha_backup=/opt/owrt-remote/captcha-before-recaptcha-v3-v118.json
|
||||
candidate=$target.new-__UPLOAD_NAME__
|
||||
changed=0
|
||||
cleanup() {
|
||||
@@ -45,7 +45,7 @@ if [ ! -x "$python_bin" ]; then python_bin=python3; fi
|
||||
import ast, pathlib, sys
|
||||
source = pathlib.Path(sys.argv[1]).read_text(encoding='utf-8')
|
||||
tree = ast.parse(source)
|
||||
assert 'v117' in source
|
||||
assert 'v118' in source
|
||||
assert 'v108' not in source
|
||||
assert 'CAPTCHA_MODE_RECAPTCHA_V3' in source
|
||||
assert 'prepareLoginRecaptcha' in source
|
||||
@@ -88,7 +88,7 @@ pid=$(systemctl show owrt-remote -p MainPID --value)
|
||||
test "$pid" -gt 0
|
||||
printf 'PID=%s FD=%s\n' "$pid" "$(find /proc/$pid/fd -maxdepth 1 -type l | wc -l)"
|
||||
systemctl --no-pager --full status owrt-remote | sed -n '1,16p'
|
||||
echo RECAPTCHA_V3_V117_OK
|
||||
echo RECAPTCHA_V3_V118_OK
|
||||
'@
|
||||
} elseif ($Action -eq 'Rollback') {
|
||||
$RemoteScript = @'
|
||||
@@ -96,8 +96,8 @@ echo RECAPTCHA_V3_V117_OK
|
||||
set -Eeuo pipefail
|
||||
stage=/tmp/__UPLOAD_NAME__
|
||||
target=/opt/owrt-remote/owrt-remote-hub.py
|
||||
backup=/opt/owrt-remote/owrt-remote-hub.py.bak-before-recaptcha-v3-v117
|
||||
captcha_backup=/opt/owrt-remote/captcha-before-recaptcha-v3-v117.json
|
||||
backup=/opt/owrt-remote/owrt-remote-hub.py.bak-before-recaptcha-v3-v118
|
||||
captcha_backup=/opt/owrt-remote/captcha-before-recaptcha-v3-v118.json
|
||||
candidate=$target.rollback-__UPLOAD_NAME__
|
||||
changed=0
|
||||
restore_captcha() {
|
||||
|
||||
@@ -18,7 +18,7 @@ if ($Action -eq 'Install') {
|
||||
set -Eeuo pipefail
|
||||
stage=/tmp/__UPLOAD_NAME__
|
||||
target=/opt/owrt-remote/owrt-remote-hub.py
|
||||
backup=/opt/owrt-remote/owrt-remote-hub.py.bak-before-resource-fix-v117
|
||||
backup=/opt/owrt-remote/owrt-remote-hub.py.bak-before-resource-fix-v118
|
||||
candidate=$target.new-__UPLOAD_NAME__
|
||||
changed=0
|
||||
cleanup() {
|
||||
@@ -45,7 +45,7 @@ if [ ! -x "$python_bin" ]; then python_bin=python3; fi
|
||||
import ast, pathlib, sys
|
||||
source = pathlib.Path(sys.argv[1]).read_text(encoding='utf-8')
|
||||
tree = ast.parse(source)
|
||||
assert 'v117' in source
|
||||
assert 'v118' in source
|
||||
assert 'v108' not in source
|
||||
factory = next(node for node in tree.body if isinstance(node, ast.FunctionDef) and node.name == 'connect')
|
||||
assert any(isinstance(item, ast.Name) and item.id == 'contextmanager' for item in factory.decorator_list)
|
||||
@@ -78,7 +78,7 @@ pid=$(systemctl show owrt-remote -p MainPID --value)
|
||||
test "$pid" -gt 0
|
||||
printf 'PID=%s FD=%s\n' "$pid" "$(find /proc/$pid/fd -maxdepth 1 -type l | wc -l)"
|
||||
systemctl --no-pager --full status owrt-remote | sed -n '1,16p'
|
||||
echo RESOURCE_FIX_V117_OK
|
||||
echo RESOURCE_FIX_V118_OK
|
||||
'@
|
||||
} elseif ($Action -eq 'Rollback') {
|
||||
$RemoteScript = @'
|
||||
@@ -86,7 +86,7 @@ echo RESOURCE_FIX_V117_OK
|
||||
set -Eeuo pipefail
|
||||
stage=/tmp/__UPLOAD_NAME__
|
||||
target=/opt/owrt-remote/owrt-remote-hub.py
|
||||
backup=/opt/owrt-remote/owrt-remote-hub.py.bak-before-resource-fix-v117
|
||||
backup=/opt/owrt-remote/owrt-remote-hub.py.bak-before-resource-fix-v118
|
||||
candidate=$target.rollback-__UPLOAD_NAME__
|
||||
changed=0
|
||||
cleanup() {
|
||||
|
||||
@@ -15,7 +15,7 @@ $RemoteScript = @'
|
||||
set -eu
|
||||
stage=/tmp/__UPLOAD_NAME__
|
||||
target=/opt/owrt-remote/owrt-remote-hub.py
|
||||
backup=/opt/owrt-remote/owrt-remote-hub.py.bak-before-router-card-ui-v117
|
||||
backup=/opt/owrt-remote/owrt-remote-hub.py.bak-before-router-card-ui-v118
|
||||
candidate=$target.new-__UPLOAD_NAME__
|
||||
changed=0
|
||||
|
||||
@@ -106,7 +106,7 @@ if [ "$healthy" -ne 1 ]; then
|
||||
exit 1
|
||||
fi
|
||||
cmp "$source_file" "$target"
|
||||
printf '\nBackup: %s\nROUTER_CARD_UI_V117_%s_OK\n' "$backup" '__ACTION__'
|
||||
printf '\nBackup: %s\nROUTER_CARD_UI_V118_%s_OK\n' "$backup" '__ACTION__'
|
||||
'@
|
||||
|
||||
$RemoteScript = $RemoteScript.Replace('__UPLOAD_NAME__', $UploadName).Replace('__ACTION__', $Action)
|
||||
|
||||
@@ -15,7 +15,7 @@ $RemoteScript = @'
|
||||
set -eu
|
||||
stage=/tmp/__UPLOAD_NAME__
|
||||
target=/opt/owrt-remote/owrt-remote-hub.py
|
||||
backup=/opt/owrt-remote/owrt-remote-hub.py.bak-before-router-reboot-all-v117
|
||||
backup=/opt/owrt-remote/owrt-remote-hub.py.bak-before-router-reboot-all-v118
|
||||
candidate=$target.new-__UPLOAD_NAME__
|
||||
changed=0
|
||||
|
||||
@@ -125,7 +125,7 @@ if [ "$healthy" -ne 1 ]; then
|
||||
exit 1
|
||||
fi
|
||||
cmp "$source_file" "$target"
|
||||
printf '\nBackup: %s\nROUTER_UPDATES_V117_%s_OK\n' "$backup" '__ACTION__'
|
||||
printf '\nBackup: %s\nROUTER_UPDATES_V118_%s_OK\n' "$backup" '__ACTION__'
|
||||
'@
|
||||
|
||||
$RemoteScript = $RemoteScript.Replace('__UPLOAD_NAME__', $UploadName).Replace('__ACTION__', $Action)
|
||||
|
||||
@@ -0,0 +1,227 @@
|
||||
param(
|
||||
[Parameter(Mandatory = $true, ParameterSetName = 'Vps')][ValidateNotNullOrEmpty()][string]$Vps,
|
||||
[Parameter(Mandatory = $true, ParameterSetName = 'Router')][ValidateNotNullOrEmpty()][string]$Router,
|
||||
[ValidateSet('Install', 'Rollback')][string]$Action = 'Install',
|
||||
[switch]$PrepareOnly
|
||||
)
|
||||
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$RepoRoot = Split-Path -Parent $PSScriptRoot
|
||||
$UploadName = 'owrt-version-v118-' + [guid]::NewGuid().ToString('N')
|
||||
$StageRoot = Join-Path ([System.IO.Path]::GetTempPath()) $UploadName
|
||||
$Utf8 = [System.Text.UTF8Encoding]::new($false)
|
||||
|
||||
$RemoteScript = @'
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
stage=/tmp/__UPLOAD_NAME__
|
||||
target=/opt/owrt-remote/owrt-remote-hub.py
|
||||
backup=/opt/owrt-remote/owrt-remote-hub.py.bak-before-v118
|
||||
candidate=$target.new-__UPLOAD_NAME__
|
||||
changed=0
|
||||
|
||||
show_failure() {
|
||||
echo '--- owrt-remote status ---' >&2
|
||||
systemctl --no-pager -l status owrt-remote >&2 || true
|
||||
echo '--- owrt-remote journal ---' >&2
|
||||
journalctl -u owrt-remote -n 80 --no-pager -l >&2 || true
|
||||
}
|
||||
|
||||
cleanup() {
|
||||
code=$?
|
||||
trap - EXIT
|
||||
if [ "$code" -ne 0 ]; then
|
||||
echo "Remote step failed with rc=$code" >&2
|
||||
show_failure
|
||||
fi
|
||||
if [ "$code" -ne 0 ] && [ "$changed" = 1 ] && [ -s "$stage/previous.py" ]; then
|
||||
echo 'Restoring the previous Hub file...' >&2
|
||||
cp -p "$stage/previous.py" "$candidate"
|
||||
mv -f "$candidate" "$target"
|
||||
systemctl restart owrt-remote || true
|
||||
fi
|
||||
rm -f "$candidate"
|
||||
rm -rf "$stage"
|
||||
exit "$code"
|
||||
}
|
||||
trap cleanup EXIT
|
||||
|
||||
test -s "$target"
|
||||
python_bin=/opt/owrt-remote/venv/bin/python
|
||||
[ -x "$python_bin" ] || python_bin=python3
|
||||
|
||||
if [ '__ACTION__' = Install ]; then
|
||||
test -s "$stage/hub.py"
|
||||
echo 'Validating candidate...'
|
||||
"$python_bin" -m py_compile "$stage/hub.py"
|
||||
"$python_bin" - "$stage/hub.py" <<'PY'
|
||||
from pathlib import Path
|
||||
import sys
|
||||
source = Path(sys.argv[1]).read_text(encoding='utf-8')
|
||||
required = ('v118',)
|
||||
if 'v' + '117' in source:
|
||||
print('Old UI version remains in candidate', file=sys.stderr)
|
||||
raise SystemExit(1)
|
||||
missing = [marker for marker in required if marker not in source]
|
||||
if missing:
|
||||
for marker in missing:
|
||||
print('Missing marker:', repr(marker), file=sys.stderr)
|
||||
raise SystemExit(1)
|
||||
print('Candidate validation OK')
|
||||
PY
|
||||
if [ ! -e "$backup" ]; then
|
||||
cp -p "$target" "$backup"
|
||||
fi
|
||||
source_file="$stage/hub.py"
|
||||
else
|
||||
test -s "$backup"
|
||||
"$python_bin" -m py_compile "$backup"
|
||||
source_file="$backup"
|
||||
fi
|
||||
|
||||
cp -p "$target" "$stage/previous.py"
|
||||
cp "$source_file" "$candidate"
|
||||
chmod 0755 "$candidate"
|
||||
changed=1
|
||||
mv -f "$candidate" "$target"
|
||||
echo 'Restarting owrt-remote...'
|
||||
if ! systemctl restart owrt-remote; then
|
||||
show_failure
|
||||
exit 1
|
||||
fi
|
||||
|
||||
healthy=0
|
||||
for attempt in 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15; do
|
||||
if systemctl is-active --quiet owrt-remote && curl -fsS --max-time 5 http://127.0.0.1:8088/health; then
|
||||
healthy=1
|
||||
break
|
||||
fi
|
||||
sleep 2
|
||||
done
|
||||
if [ "$healthy" -ne 1 ]; then
|
||||
echo 'Health check did not become ready.' >&2
|
||||
show_failure
|
||||
exit 1
|
||||
fi
|
||||
cmp "$source_file" "$target"
|
||||
printf '\nBackup: %s\nHUB_V118_%s_OK\n' "$backup" '__ACTION__'
|
||||
'@
|
||||
|
||||
$RouterScript = @'
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
stage=/tmp/__UPLOAD_NAME__
|
||||
backup=/root/owrt-remote-backup-before-v118
|
||||
cgi=/www/cgi-bin/owrt-remote
|
||||
luci=/www/luci-static/resources/view/owrt_remote.js
|
||||
changed=0
|
||||
cleanup() {
|
||||
code=$?
|
||||
trap - EXIT
|
||||
if [ "$code" -ne 0 ]; then
|
||||
echo "Router version __ACTION__ failed (rc=$code)." >&2
|
||||
if [ "$changed" = 1 ]; then
|
||||
echo 'Restoring the previous router UI files...' >&2
|
||||
cp -p "$stage/previous-cgi" "$cgi.new-__UPLOAD_NAME__" && mv -f "$cgi.new-__UPLOAD_NAME__" "$cgi" || true
|
||||
cp -p "$stage/previous-luci" "$luci.new-__UPLOAD_NAME__" && mv -f "$luci.new-__UPLOAD_NAME__" "$luci" || true
|
||||
fi
|
||||
fi
|
||||
rm -f "$cgi.new-__UPLOAD_NAME__" "$luci.new-__UPLOAD_NAME__"
|
||||
rm -rf "$stage"
|
||||
exit "$code"
|
||||
}
|
||||
trap cleanup EXIT
|
||||
test -s "$cgi"
|
||||
test -s "$luci"
|
||||
if [ '__ACTION__' = Install ]; then
|
||||
sh -n "$stage/cgi"
|
||||
grep -F -q 'v118' "$stage/cgi"
|
||||
grep -F -q 'v118' "$stage/luci"
|
||||
if grep -F -q 'v''117' "$stage/cgi" "$stage/luci"; then
|
||||
echo 'Old UI version remains in candidate.' >&2
|
||||
exit 1
|
||||
fi
|
||||
if [ ! -e "$backup" ]; then
|
||||
mkdir -m 700 "$stage/retained"
|
||||
cp -p "$cgi" "$stage/retained/cgi"
|
||||
cp -p "$luci" "$stage/retained/luci"
|
||||
: >"$stage/retained/complete"
|
||||
mv "$stage/retained" "$backup"
|
||||
fi
|
||||
source_dir=$stage
|
||||
else
|
||||
source_dir=$backup
|
||||
fi
|
||||
if [ ! -f "$backup/complete" ] || [ ! -s "$backup/cgi" ] || [ ! -s "$backup/luci" ]; then
|
||||
echo "No complete backup: $backup. Nothing changed." >&2
|
||||
exit 1
|
||||
fi
|
||||
sh -n "$source_dir/cgi"
|
||||
cp -p "$cgi" "$stage/previous-cgi"
|
||||
cp -p "$luci" "$stage/previous-luci"
|
||||
cp "$source_dir/cgi" "$cgi.new-__UPLOAD_NAME__"
|
||||
chmod 0755 "$cgi.new-__UPLOAD_NAME__"
|
||||
cp "$source_dir/luci" "$luci.new-__UPLOAD_NAME__"
|
||||
chmod 0644 "$luci.new-__UPLOAD_NAME__"
|
||||
changed=1
|
||||
mv -f "$cgi.new-__UPLOAD_NAME__" "$cgi"
|
||||
mv -f "$luci.new-__UPLOAD_NAME__" "$luci"
|
||||
cmp "$source_dir/cgi" "$cgi"
|
||||
cmp "$source_dir/luci" "$luci"
|
||||
[ ! -x /etc/init.d/rpcd ] || /etc/init.d/rpcd restart || true
|
||||
[ ! -x /etc/init.d/uhttpd ] || /etc/init.d/uhttpd reload || true
|
||||
printf '\nBackup: %s\nROUTER_V118_%s_OK\n' "$backup" '__ACTION__'
|
||||
'@
|
||||
|
||||
if ($PSCmdlet.ParameterSetName -eq 'Router') {
|
||||
$RemoteScript = $RouterScript
|
||||
$TargetMachine = $Router
|
||||
}
|
||||
else {
|
||||
$TargetMachine = $Vps
|
||||
}
|
||||
$RemoteScript = $RemoteScript.Replace('__UPLOAD_NAME__', $UploadName).Replace('__ACTION__', $Action)
|
||||
|
||||
try {
|
||||
[System.IO.Directory]::CreateDirectory($StageRoot) | Out-Null
|
||||
[System.IO.File]::WriteAllText(
|
||||
(Join-Path $StageRoot 'run.sh'),
|
||||
$RemoteScript.Replace("`r`n", "`n") + "`n",
|
||||
$Utf8
|
||||
)
|
||||
|
||||
if ($Action -eq 'Install') {
|
||||
$Files = if ($PSCmdlet.ParameterSetName -eq 'Router') {
|
||||
@{ 'cgi' = 'files\www\cgi-bin\owrt-remote'; 'luci' = 'files\www\luci-static\resources\view\owrt_remote.js' }
|
||||
} else {
|
||||
@{ 'hub.py' = 'vps\owrt-remote-hub.py' }
|
||||
}
|
||||
foreach ($Name in $Files.Keys) {
|
||||
$Content = [System.IO.File]::ReadAllText((Join-Path $RepoRoot $Files[$Name])).Replace("`r`n", "`n")
|
||||
[System.IO.File]::WriteAllText((Join-Path $StageRoot $Name), $Content, $Utf8)
|
||||
}
|
||||
}
|
||||
|
||||
if ($PrepareOnly) {
|
||||
Write-Host "Prepared only: $StageRoot"
|
||||
return
|
||||
}
|
||||
|
||||
& scp -O -r -- $StageRoot "${TargetMachine}:/tmp/"
|
||||
if ($LASTEXITCODE -ne 0) { throw 'Upload failed. Target was not changed.' }
|
||||
& ssh -T -o ConnectTimeout=10 $TargetMachine "sh /tmp/$UploadName/run.sh"
|
||||
if ($LASTEXITCODE -ne 0) { throw "$Action failed. See the output above; success was not confirmed." }
|
||||
Write-Host "Version v118 $Action finished successfully. Refresh the panel."
|
||||
}
|
||||
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
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,150 @@
|
||||
param(
|
||||
[Parameter(Mandatory = $true)][ValidateNotNullOrEmpty()][string]$Vps,
|
||||
[ValidateSet('Install', 'Rollback')][string]$Action = 'Install',
|
||||
[switch]$PrepareOnly
|
||||
)
|
||||
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$RepoRoot = Split-Path -Parent $PSScriptRoot
|
||||
$UploadName = 'owrt-vps-resources-live-' + [guid]::NewGuid().ToString('N')
|
||||
$StageRoot = Join-Path ([System.IO.Path]::GetTempPath()) $UploadName
|
||||
$Utf8 = [System.Text.UTF8Encoding]::new($false)
|
||||
|
||||
$RemoteScript = @'
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
stage=/tmp/__UPLOAD_NAME__
|
||||
target=/opt/owrt-remote/owrt-remote-hub.py
|
||||
backup=/opt/owrt-remote/owrt-remote-hub.py.bak-before-vps-resources-live-v118
|
||||
candidate=$target.new-__UPLOAD_NAME__
|
||||
changed=0
|
||||
|
||||
show_failure() {
|
||||
echo '--- owrt-remote status ---' >&2
|
||||
systemctl --no-pager -l status owrt-remote >&2 || true
|
||||
echo '--- owrt-remote journal ---' >&2
|
||||
journalctl -u owrt-remote -n 80 --no-pager -l >&2 || true
|
||||
}
|
||||
|
||||
cleanup() {
|
||||
code=$?
|
||||
trap - EXIT
|
||||
if [ "$code" -ne 0 ]; then
|
||||
echo "Remote step failed with rc=$code" >&2
|
||||
show_failure
|
||||
fi
|
||||
if [ "$code" -ne 0 ] && [ "$changed" = 1 ] && [ -s "$stage/previous.py" ]; then
|
||||
echo 'Restoring the previous Hub file...' >&2
|
||||
cp -p "$stage/previous.py" "$candidate"
|
||||
mv -f "$candidate" "$target"
|
||||
systemctl restart owrt-remote || true
|
||||
fi
|
||||
rm -f "$candidate"
|
||||
rm -rf "$stage"
|
||||
exit "$code"
|
||||
}
|
||||
trap cleanup EXIT
|
||||
|
||||
test -s "$target"
|
||||
python_bin=/opt/owrt-remote/venv/bin/python
|
||||
[ -x "$python_bin" ] || python_bin=python3
|
||||
|
||||
if [ '__ACTION__' = Install ]; then
|
||||
test -s "$stage/hub.py"
|
||||
echo 'Validating candidate...'
|
||||
"$python_bin" -m py_compile "$stage/hub.py"
|
||||
"$python_bin" - "$stage/hub.py" <<'PY'
|
||||
from pathlib import Path
|
||||
import sys
|
||||
source = Path(sys.argv[1]).read_text(encoding='utf-8')
|
||||
required = (
|
||||
"def vps_resource_widgets_html(mobile=False, resources=None):",
|
||||
"vps_resources=self.app.vps_resources.snapshot(),",
|
||||
"vps_resource_widgets_html(resources=vps_resources)",
|
||||
"vps_resource_widgets_html(mobile=True, resources=vps_resources)",
|
||||
"interval = 1.0",
|
||||
"timer = setInterval(load, 1000);",
|
||||
)
|
||||
missing = [marker for marker in required if marker not in source]
|
||||
if missing:
|
||||
for marker in missing:
|
||||
print('Missing marker:', repr(marker), file=sys.stderr)
|
||||
raise SystemExit(1)
|
||||
print('Candidate validation OK')
|
||||
PY
|
||||
if [ ! -e "$backup" ]; then
|
||||
cp -p "$target" "$backup"
|
||||
fi
|
||||
source_file="$stage/hub.py"
|
||||
else
|
||||
test -s "$backup"
|
||||
"$python_bin" -m py_compile "$backup"
|
||||
source_file="$backup"
|
||||
fi
|
||||
|
||||
cp -p "$target" "$stage/previous.py"
|
||||
cp "$source_file" "$candidate"
|
||||
chmod 0755 "$candidate"
|
||||
changed=1
|
||||
mv -f "$candidate" "$target"
|
||||
echo 'Restarting owrt-remote...'
|
||||
if ! systemctl restart owrt-remote; then
|
||||
show_failure
|
||||
exit 1
|
||||
fi
|
||||
|
||||
healthy=0
|
||||
for attempt in 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15; do
|
||||
if systemctl is-active --quiet owrt-remote && curl -fsS --max-time 5 http://127.0.0.1:8088/health; then
|
||||
healthy=1
|
||||
break
|
||||
fi
|
||||
sleep 2
|
||||
done
|
||||
if [ "$healthy" -ne 1 ]; then
|
||||
echo 'Health check did not become ready.' >&2
|
||||
show_failure
|
||||
exit 1
|
||||
fi
|
||||
cmp "$source_file" "$target"
|
||||
printf '\nBackup: %s\nVPS_RESOURCES_LIVE_V118_%s_OK\n' "$backup" '__ACTION__'
|
||||
'@
|
||||
|
||||
$RemoteScript = $RemoteScript.Replace('__UPLOAD_NAME__', $UploadName).Replace('__ACTION__', $Action)
|
||||
|
||||
try {
|
||||
[System.IO.Directory]::CreateDirectory($StageRoot) | Out-Null
|
||||
[System.IO.File]::WriteAllText(
|
||||
(Join-Path $StageRoot 'run.sh'),
|
||||
$RemoteScript.Replace("`r`n", "`n") + "`n",
|
||||
$Utf8
|
||||
)
|
||||
|
||||
if ($Action -eq 'Install') {
|
||||
$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 "sh /tmp/$UploadName/run.sh"
|
||||
if ($LASTEXITCODE -ne 0) { throw "$Action failed. See the output above; success was not confirmed." }
|
||||
Write-Host "VPS resources fix $Action finished successfully."
|
||||
}
|
||||
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
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -14,7 +14,7 @@ $RemoteScript = @'
|
||||
set -eu
|
||||
stage=/tmp/__UPLOAD_NAME__
|
||||
target=/opt/owrt-remote/owrt-remote-hub.py
|
||||
backup=/opt/owrt-remote/owrt-remote-hub.py.bak-before-vps-widgets-v117
|
||||
backup=/opt/owrt-remote/owrt-remote-hub.py.bak-before-vps-widgets-v118
|
||||
candidate=$target.new-__UPLOAD_NAME__
|
||||
changed=0
|
||||
cleanup() {
|
||||
@@ -37,7 +37,7 @@ python_bin=/opt/owrt-remote/venv/bin/python
|
||||
[ -x "$python_bin" ] || python_bin=python3
|
||||
if [ '__ACTION__' = Install ]; then
|
||||
test -s "$stage/hub.py"
|
||||
grep -F -q 'v117' "$stage/hub.py"
|
||||
grep -F -q 'v118' "$stage/hub.py"
|
||||
"$python_bin" -m py_compile "$stage/hub.py"
|
||||
OWRT_VPS_WIDGETS_HUB_SOURCE="$stage/hub.py" "$python_bin" "$stage/tests.py" -v
|
||||
if [ ! -e "$backup" ]; then cp -p "$target" "$backup"; fi
|
||||
@@ -67,7 +67,7 @@ if [ '__ACTION__' = Install ]; then
|
||||
code=$(curl -sS --max-time 5 -o "$stage/response.json" -w '%{http_code}' http://127.0.0.1:8088/api/vps/resources)
|
||||
test "$code" = 401
|
||||
fi
|
||||
printf '\nVPS_WIDGETS_V117_%s_OK\n' '__ACTION__'
|
||||
printf '\nVPS_WIDGETS_V118_%s_OK\n' '__ACTION__'
|
||||
'@
|
||||
$RemoteScript = $RemoteScript.Replace('__UPLOAD_NAME__', $UploadName).Replace('__ACTION__', $Action)
|
||||
try {
|
||||
|
||||
@@ -14,7 +14,7 @@ $RemoteScript = @'
|
||||
set -eu
|
||||
stage=/tmp/__UPLOAD_NAME__
|
||||
target=/usr/lib/owrt-remote/wan.sh
|
||||
backup_dir=/root/owrt-remote-backup-before-wan-dns-v117
|
||||
backup_dir=/root/owrt-remote-backup-before-wan-dns-v118
|
||||
changed=0
|
||||
phase=preflight
|
||||
heartbeat_pid() {
|
||||
|
||||
@@ -20,7 +20,7 @@ $RemoteScript = @'
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
stage=/tmp/__UPLOAD_NAME__
|
||||
backup=/root/owrt-remote-backup-before-wan-multi-v117
|
||||
backup=/root/owrt-remote-backup-before-wan-multi-v118
|
||||
config=/etc/config/owrtremote
|
||||
changed=0
|
||||
item_path() {
|
||||
@@ -81,7 +81,7 @@ test -s "$config"
|
||||
if [ '__ACTION__' = Install ]; then
|
||||
for item in agent wan.sh cgi hotplug; do test -s "$stage/$item"; sh -n "$stage/$item"; done
|
||||
test -s "$stage/luci"
|
||||
for item in cgi luci; do grep -F -q 'v117' "$stage/$item"; done
|
||||
for item in cgi luci; do grep -F -q 'v118' "$stage/$item"; done
|
||||
grep -F -q 'wan_interface_picker' "$stage/cgi"
|
||||
grep -F -q 'wan_select_interface()' "$stage/wan.sh"
|
||||
grep -F -q 'wan_reconcile_xray()' "$stage/agent"
|
||||
|
||||
@@ -17,7 +17,7 @@ $RemoteScript = @'
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
stage=/tmp/__UPLOAD_NAME__
|
||||
backup_dir=/root/owrt-remote-backup-before-wan-recovery-v117
|
||||
backup_dir=/root/owrt-remote-backup-before-wan-recovery-v118
|
||||
changed=0
|
||||
phase=preflight
|
||||
item_path() {
|
||||
|
||||
@@ -17,7 +17,7 @@ $RemoteScript = @'
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
stage=/tmp/__UPLOAD_NAME__
|
||||
backup=/root/owrt-remote-backup-before-wan-stability-v117
|
||||
backup=/root/owrt-remote-backup-before-wan-stability-v118
|
||||
config=/etc/config/owrtremote
|
||||
changed=0
|
||||
fail() {
|
||||
|
||||
@@ -15,7 +15,7 @@ $RemoteScript = @'
|
||||
set -eu
|
||||
stage=/tmp/__UPLOAD_NAME__
|
||||
target=/opt/owrt-remote/owrt-remote-hub.py
|
||||
backup=/opt/owrt-remote/owrt-remote-hub.py.bak-before-web-push-v117
|
||||
backup=/opt/owrt-remote/owrt-remote-hub.py.bak-before-web-push-v118
|
||||
candidate=$target.new-__UPLOAD_NAME__
|
||||
changed=0
|
||||
|
||||
@@ -72,7 +72,7 @@ for attempt in 1 2 3 4 5 6 7 8 9 10; do
|
||||
done
|
||||
test "$healthy" = 1
|
||||
cmp "$source_file" "$target"
|
||||
printf '\nBackup: %s\nWEB_PUSH_V117_%s_OK\n' "$backup" '__ACTION__'
|
||||
printf '\nBackup: %s\nWEB_PUSH_V118_%s_OK\n' "$backup" '__ACTION__'
|
||||
'@
|
||||
|
||||
$RemoteScript = $RemoteScript.Replace('__UPLOAD_NAME__', $UploadName).Replace('__ACTION__', $Action)
|
||||
|
||||
@@ -14,7 +14,7 @@ $RemoteScript = @'
|
||||
set -eu
|
||||
stage=/tmp/__UPLOAD_NAME__
|
||||
target=/www/cgi-bin/owrt-remote
|
||||
backup_dir=/root/owrt-remote-backup-before-xray-apply-v117
|
||||
backup_dir=/root/owrt-remote-backup-before-xray-apply-v118
|
||||
backup=$backup_dir/owrt-remote
|
||||
candidate=$target.new-__UPLOAD_NAME__
|
||||
changed=0
|
||||
|
||||
@@ -14,7 +14,7 @@ $RemoteScript = @'
|
||||
set -eu
|
||||
stage=/tmp/__UPLOAD_NAME__
|
||||
target=/usr/sbin/owrt-remote
|
||||
backup_dir=/root/owrt-remote-backup-before-xray-boot-v117
|
||||
backup_dir=/root/owrt-remote-backup-before-xray-boot-v118
|
||||
changed=0
|
||||
phase=preflight
|
||||
heartbeat_pid() {
|
||||
|
||||
@@ -14,7 +14,7 @@ $RemoteScript = @'
|
||||
set -eu
|
||||
stage=/tmp/__UPLOAD_NAME__
|
||||
target=/www/cgi-bin/owrt-remote
|
||||
backup_dir=/root/owrt-remote-backup-before-xray-mobile-v117
|
||||
backup_dir=/root/owrt-remote-backup-before-xray-mobile-v118
|
||||
backup=$backup_dir/owrt-remote
|
||||
candidate=$target.new-__UPLOAD_NAME__
|
||||
changed=0
|
||||
|
||||
@@ -17,7 +17,7 @@ $RemoteScript = @'
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
stage=/tmp/__UPLOAD_NAME__
|
||||
backup_dir=/root/owrt-remote-backup-before-xray-validation-v117
|
||||
backup_dir=/root/owrt-remote-backup-before-xray-validation-v118
|
||||
changed=0
|
||||
phase=preflight
|
||||
item_path() {
|
||||
|
||||
+524
-53
@@ -36,6 +36,7 @@ import urllib.error
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
import uuid
|
||||
import warnings
|
||||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||
from pathlib import Path
|
||||
|
||||
@@ -72,6 +73,7 @@ except Exception:
|
||||
APP_NAME = "OpenWrt Remote Hub"
|
||||
RAW_REPO_BASE = os.environ.get("RAW_REPO_BASE", "https://raw.githubusercontent.com/kzolotarev95/luci-app-owrt-remote/main").rstrip("/")
|
||||
APP_DIR = Path(__file__).resolve().parent
|
||||
HUB_LOADED_REVISION = hashlib.sha256(Path(__file__).read_bytes()).hexdigest()
|
||||
STATIC_DIR = APP_DIR / "static"
|
||||
BRAND_THEME_COLOR = "#24192f"
|
||||
FAVICON_ICO_FILE = STATIC_DIR / "favicon.ico"
|
||||
@@ -4964,17 +4966,24 @@ def parse_resize_payload(payload):
|
||||
return message.get("rows"), message.get("cols")
|
||||
|
||||
|
||||
def vps_resource_widgets_html(mobile=False):
|
||||
def vps_resource_widgets_html(mobile=False, resources=None):
|
||||
kind = "mobile" if mobile else "desktop"
|
||||
widgets = "".join(
|
||||
f'<div class="vpsResource badge" data-vps-resource="{key}" title="{label}: ожидаем данные VPS">'
|
||||
f'<span>{label}</span><strong data-vps-resource-value>—</strong></div>'
|
||||
for key, label in (("cpu", "ЦП"), ("memory", "ОЗУ"), ("disk", "ДИСК"))
|
||||
)
|
||||
return f'<div class="vpsResources vpsResources-{kind}" role="group" aria-label="Ресурсы VPS">{widgets}</div>'
|
||||
widgets = []
|
||||
for key, label in (("cpu", "ЦП"), ("memory", "ОЗУ"), ("disk", "ДИСК")):
|
||||
metric = (resources or {}).get(key) or {}
|
||||
percent = metric.get("percent")
|
||||
valid = isinstance(percent, (int, float)) and not isinstance(percent, bool) and math.isfinite(percent)
|
||||
value = (f"{percent:.1f}".rstrip("0").rstrip(".").replace(".", ",") + "%") if valid else "—"
|
||||
title = html.escape(label + ": " + (value if valid else "данные пока недоступны"), quote=True)
|
||||
widgets.append(
|
||||
f'<div class="vpsResource badge" data-vps-resource="{key}" title="{title}" aria-label="{title}">'
|
||||
f'<span>{label}</span><strong data-vps-resource-value>{value}</strong></div>'
|
||||
)
|
||||
return f'<div class="vpsResources vpsResources-{kind}" role="group" aria-label="Ресурсы VPS">{"".join(widgets)}</div>'
|
||||
|
||||
|
||||
def dashboard_html(routers, username, sessions=None, notifications=None, auth_bootstrap=None):
|
||||
|
||||
def dashboard_html(routers, username, sessions=None, notifications=None, auth_bootstrap=None, vps_resources=None):
|
||||
routers_json = json.dumps(routers, ensure_ascii=False)
|
||||
sessions_json = json.dumps(sessions or [], ensure_ascii=False)
|
||||
notifications_json = json.dumps(notifications or [], ensure_ascii=False)
|
||||
@@ -5058,16 +5067,78 @@ input,select{{min-width:0;border:1px solid var(--line);border-radius:8px;padding
|
||||
@media(min-width:681px) and (max-width:800px){{.vpsResource.badge{{padding:8px 2px;gap:2px}}.vpsResource.badge,.vpsResource strong{{font-size:10px}}}}
|
||||
@media(max-width:680px),(max-width:1024px) and (orientation:landscape) and (pointer:coarse){{.vpsResources-mobile{{display:grid;margin:8px 0 3px}}.vpsResource.badge{{padding:8px 6px;font-size:11px}}.vpsResource strong{{font-size:11px}}}}
|
||||
@media(min-width:681px) and (max-width:1024px) and (orientation:landscape) and (pointer:coarse){{.wrap{{padding-left:max(10px,env(safe-area-inset-left,0px));padding-right:max(10px,env(safe-area-inset-right,0px))}}.cards,.routerGroupCards,.toolbar{{grid-template-columns:repeat(2,minmax(0,1fr))}}}}
|
||||
#routerUpdatesGroup .routerUpdatesLaunch{{display:flex;flex:0 1 auto;width:fit-content;min-width:0;max-width:100%;min-height:38px;margin:12px auto 0;padding:8px 14px;font-size:12px;line-height:1.3;white-space:normal;text-align:center;overflow-wrap:anywhere}}
|
||||
.desktopHeader{{--hdr-col-1:minmax(0,1fr);--hdr-col-2:minmax(0,1fr);--hdr-col-3:minmax(0,1.35fr);--hdr-col-4:minmax(0,1.25fr);--hdr-col-5:minmax(0,1fr);--hdr-col-6:minmax(0,1fr);--hdr-col-7:minmax(0,1fr);--hdr-col-8:minmax(0,1fr);width:100%;margin-left:0;grid-template-columns:minmax(0,1fr)}}
|
||||
.desktopHeaderTop,.desktopHeaderBottom{{min-width:0;max-width:100%}}
|
||||
.desktopHeaderTop>.routerSearchDock{{grid-column:4}}
|
||||
.desktopHeaderTop>.hubUpdateButton{{grid-column:3;grid-row:1}}
|
||||
#routerSearchToggle,.hubUpdateButton,#mobileRouterSearchToggle{{display:inline-flex;align-items:center;justify-content:center;gap:5px;width:100%;min-width:0;min-height:36px;margin:0;padding:8px 10px;border:1px solid var(--line);border-radius:999px;background:rgba(255,255,255,.08);box-shadow:inset 0 1px 0 rgba(255,255,255,.06);color:#f3e8ff;font-size:12px;font-weight:800;line-height:1.25;white-space:normal;overflow-wrap:anywhere;cursor:pointer}}
|
||||
#routerSearchToggle[data-active="true"],#mobileRouterSearchToggle[data-active="true"]{{border-color:var(--cyan)}}
|
||||
.hubUpdateButton[data-update-state="current"]{{border-color:rgba(34,197,94,.65);background:rgba(34,197,94,.16);color:#bbf7d0}}
|
||||
.hubUpdateButton[data-update-state="available"]{{border-color:rgba(245,158,11,.7);background:rgba(245,158,11,.18);color:#fde68a}}
|
||||
.hubUpdateButton:disabled{{cursor:wait;opacity:.75}}
|
||||
.hubUpdateButton[hidden]{{display:none!important}}
|
||||
@media(min-width:681px) and (max-width:1100px){{.desktopHeaderTop{{grid-template-columns:repeat(4,minmax(0,1fr))}}.desktopHeaderTop>#seasonDock{{grid-column:1;grid-row:2}}.desktopHeaderTop>.vpsResources-desktop{{grid-column:2/span 3;grid-row:2}}}}
|
||||
.hubUpdateNotice{{box-sizing:border-box;width:min(100%,680px);max-width:100%;min-width:0;margin:12px auto 16px;padding:10px 14px;border:1px solid rgba(255,255,255,.10);border-radius:10px;background:transparent;color:#fff;font-size:12px;line-height:1.55;text-align:center;white-space:normal;overflow-wrap:anywhere}}
|
||||
.hubUpdateConfirm[hidden]{{display:none!important}}
|
||||
.hubUpdateConfirmOpen{{overflow:hidden}}
|
||||
.hubUpdateConfirm{{position:fixed;inset:0;z-index:120;display:grid;place-items:center;padding:18px;background:rgba(7,4,15,.72);backdrop-filter:blur(8px)}}
|
||||
.hubUpdateConfirmCard{{box-sizing:border-box;width:min(100%,560px);max-height:min(88svh,620px);overflow:auto;padding:20px;border:1px solid rgba(245,158,11,.46);border-radius:18px;background:linear-gradient(180deg,rgba(255,255,255,.12),rgba(255,255,255,.055)),rgba(19,14,32,.97);box-shadow:0 24px 70px rgba(0,0,0,.48),0 0 0 1px rgba(245,158,11,.10);color:var(--text);text-align:left}}
|
||||
.hubUpdateConfirmTitle{{margin:0;color:#fde68a;font-size:18px;font-weight:900;line-height:1.25}}
|
||||
.hubUpdateConfirmLead{{margin:10px 0 0;color:#f7f2ff;font-size:14px;font-weight:750;line-height:1.45}}
|
||||
.hubUpdateConfirmMeta{{display:grid;gap:6px;margin:14px 0 0;padding:11px 12px;border:1px solid var(--line);border-radius:11px;background:rgba(0,0,0,.14);color:var(--muted);font-size:12px;line-height:1.4;overflow-wrap:anywhere}}
|
||||
.hubUpdateConfirmMeta strong{{color:#f3e8ff;font-weight:850}}
|
||||
.hubUpdateConfirmActions{{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:10px;margin-top:16px}}
|
||||
.hubUpdateConfirmActions button{{width:100%;min-width:0;min-height:42px}}
|
||||
.hubUpdateConfirmCancel{{background:rgba(255,255,255,.08);color:#f3e8ff}}
|
||||
.hubUpdateConfirmAccept{{background:var(--blue);color:#fff;box-shadow:0 10px 22px rgba(124,58,237,.24)}}
|
||||
@media(max-width:680px),(max-width:1024px) and (orientation:landscape) and (pointer:coarse){{#mobileHubUpdateDock,#mobileRouterSearchDock{{display:grid;grid-template-columns:minmax(0,1fr);gap:6px;min-width:0}}#mobileHubUpdateDock>.mobileSearchVersion{{margin:0 auto;align-self:center}}#mobileRouterSearchToggle,.hubUpdateButton{{min-height:44px;padding:8px;font-size:11px}}#mobileRouterSearchToggle{{margin-top:8px;background:var(--blue);color:#fff;box-shadow:0 10px 22px rgba(124,58,237,.22)}}#mobileSeasonDock{{display:block;width:100%;min-width:0}}#mobileSeasonToggle{{min-height:44px;margin:8px 0 0}}.vpsResources-mobile{{margin:0 0 10px}}.hubUpdateNotice{{margin:0 auto 12px;padding:10px 12px;line-height:1.5}}}}
|
||||
@media(max-width:680px),(max-width:1024px) and (orientation:landscape) and (pointer:coarse){{
|
||||
.wrap{{--mobile-control-gap:8px;display:flex;flex-direction:column;gap:var(--mobile-control-gap)}}
|
||||
.top{{grid-template-columns:minmax(0,1fr);gap:var(--mobile-control-gap);padding:6px 0 0;border-bottom:0}}
|
||||
#mobileHubUpdateDock,#mobileSeasonDock,#mobileRouterSearchDock{{display:grid;grid-template-columns:minmax(0,1fr);gap:var(--mobile-control-gap);margin:0}}
|
||||
#mobileRouterSearchToggle,#mobileSeasonToggle,#hubMenuToggle,.vpsResources-mobile{{margin:0}}
|
||||
#mobileRouterSearchPanel,#mobileSeasonPanel{{margin:0}}
|
||||
#hubMenuPanelHost{{display:contents}}
|
||||
#hubMenuPanelHost>.headerActions,#mobileOwnerTools{{grid-column:1/-1;margin:0}}
|
||||
#routerFormToggle,#routerGroupsToggle,#routerStatsToggle,#routerFormWrap,#routerGroupsPanel,#routerStats,#routerForm{{margin:0}}
|
||||
#routerFormWrap>.formMsg,#routerGroupsPanel>.formMsg{{margin:var(--mobile-control-gap) 0 0}}
|
||||
.hubUpdateNotice{{margin:0 auto 4px}}
|
||||
.hubUpdateConfirm{{padding:12px;place-items:center}}
|
||||
.hubUpdateConfirmCard{{width:100%;max-height:calc(100svh - 24px);padding:16px;border-radius:18px}}
|
||||
.hubUpdateConfirmTitle{{font-size:17px}}
|
||||
.hubUpdateConfirmLead{{font-size:14px}}
|
||||
.hubUpdateConfirmMeta{{margin-top:12px;padding:10px;font-size:11px}}
|
||||
.hubUpdateConfirmActions{{gap:8px;margin-top:14px}}
|
||||
.hubUpdateConfirmActions button{{min-height:44px;padding:9px 8px;font-size:12px}}
|
||||
}}
|
||||
</style>
|
||||
</head>
|
||||
<body class="preload-mobile-panels">
|
||||
<canvas class="seasonalFx" id="seasonalFx" aria-hidden="true" hidden></canvas>
|
||||
<main class="wrap">
|
||||
<div class="hubUpdateNotice" id="hubUpdateNotice" role="status" aria-live="polite" hidden></div>
|
||||
<div class="hubUpdateConfirm" id="hubUpdateConfirm" hidden>
|
||||
<section class="hubUpdateConfirmCard" role="dialog" aria-modal="true" aria-labelledby="hubUpdateConfirmTitle" aria-describedby="hubUpdateConfirmLead">
|
||||
<h2 class="hubUpdateConfirmTitle" id="hubUpdateConfirmTitle">Обновление панели VPS</h2>
|
||||
<p class="hubUpdateConfirmLead" id="hubUpdateConfirmLead">Действительно обновить панель до последней доступной сборки?</p>
|
||||
<div class="hubUpdateConfirmMeta">
|
||||
<div>Сборка: <strong id="hubUpdateConfirmVersion">—</strong></div>
|
||||
<div>Источник: <strong id="hubUpdateConfirmSource">—</strong></div>
|
||||
<div>После запуска Hub будет перезапущен, затем страница обновится автоматически.</div>
|
||||
</div>
|
||||
<div class="hubUpdateConfirmActions">
|
||||
<button class="hubUpdateConfirmCancel" id="hubUpdateConfirmCancel" type="button">Отмена</button>
|
||||
<button class="hubUpdateConfirmAccept primary" id="hubUpdateConfirmAccept" type="button">Обновить</button>
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
<section class="top">
|
||||
<div class="brand">
|
||||
<div class="desktopHeader">
|
||||
<div class="desktopHeaderTop">
|
||||
<h1 class="appBanner"><span>OpenWrt Remote Hub <span class="appBannerVersion">v117</span></span></h1>
|
||||
<h1 class="appBanner"><span>OpenWrt Remote Hub <span class="appBannerVersion">v118</span></span></h1>
|
||||
<button class="badge hubUpdateButton" data-hub-update type="button" {'hidden' if not is_owner else ''}>Обновление панели</button>
|
||||
<div class="routerSearchDock" id="routerSearchDock">
|
||||
<button class="routerSearchToggle" id="routerSearchToggle" type="button" aria-expanded="false" aria-controls="routerSearchPanel" data-active="false">
|
||||
<span>Поиск роутеров</span>
|
||||
@@ -5103,17 +5174,11 @@ input,select{{min-width:0;border:1px solid var(--line);border-radius:8px;padding
|
||||
<button class="seasonBtn" type="button" data-season-mode="prism" data-active="false" aria-pressed="false">Призма</button>
|
||||
<button class="seasonBtn" type="button" data-season-mode="pulse" data-active="false" aria-pressed="false">Пульс</button>
|
||||
<button class="seasonBtn" type="button" data-season-mode="laser" data-active="false" aria-pressed="false">Лучи</button>
|
||||
<button class="seasonBtn" type="button" data-season-mode="aurora" data-active="false" aria-pressed="false">Аврора</button>
|
||||
<button class="seasonBtn" type="button" data-season-mode="matrix" data-active="false" aria-pressed="false">Матрица</button>
|
||||
<button class="seasonBtn" type="button" data-season-mode="nebula" data-active="false" aria-pressed="false">Туманность</button>
|
||||
<button class="seasonBtn" type="button" data-season-mode="fireworks" data-active="false" aria-pressed="false">Фейерверк</button>
|
||||
<button class="seasonBtn" type="button" data-season-mode="vortex" data-active="false" aria-pressed="false">Вихрь</button>
|
||||
<button class="seasonBtn" type="button" data-season-mode="comet" data-active="false" aria-pressed="false">Кометы</button>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
{vps_resource_widgets_html()}
|
||||
{vps_resource_widgets_html(resources=vps_resources)}
|
||||
</div>
|
||||
<div class="desktopHeaderBottom">
|
||||
<div class="links">
|
||||
@@ -5373,7 +5438,7 @@ input,select{{min-width:0;border:1px solid var(--line);border-radius:8px;padding
|
||||
<span class="authGroupChevron" aria-hidden="true">⌄</span>
|
||||
</summary>
|
||||
<div class="authGroupBody">
|
||||
<a class="sessionBtn btn" href="/router-updates/" target="_blank" rel="noopener noreferrer">Открыть терминал обновления</a>
|
||||
<a class="sessionBtn btn routerUpdatesLaunch" href="/router-updates/" target="_blank" rel="noopener noreferrer" title="Открыть терминал обновления">Терминал обновления</a>
|
||||
</div>
|
||||
</details>
|
||||
<details class="authGroup" id="backupGroup">
|
||||
@@ -5408,24 +5473,10 @@ input,select{{min-width:0;border:1px solid var(--line);border-radius:8px;padding
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="mobileSearchDock" id="mobileRouterSearchDock">
|
||||
<span class="mobileSearchVersion">v117</span>
|
||||
<button class="routerSearchToggle mobilePanelToggle primary" id="mobileRouterSearchToggle" type="button" aria-expanded="false" aria-controls="mobileRouterSearchPanel" data-active="false">
|
||||
<span>Поиск роутеров</span>
|
||||
</button>
|
||||
<section class="routerSearchPanel" id="mobileRouterSearchPanel" aria-label="Поиск роутеров" hidden>
|
||||
<div class="routerSearchCard">
|
||||
<div class="routerSearchHead">
|
||||
<strong class="routerSearchTitle">Поиск по роутерам</strong>
|
||||
<button class="routerSearchClear" id="mobileRouterSearchClear" type="button" disabled>Очистить</button>
|
||||
</div>
|
||||
<label class="routerSearchField" for="mobileRouterSearchInput">
|
||||
<span class="routerSearchIcon" aria-hidden="true">⌕</span>
|
||||
<input id="mobileRouterSearchInput" type="search" placeholder="Имя или router id" autocomplete="off" spellcheck="false">
|
||||
</label>
|
||||
<div class="routerSearchMeta" id="mobileRouterSearchMeta">Всего роутеров: 0</div>
|
||||
</div>
|
||||
</section>
|
||||
{vps_resource_widgets_html(mobile=True, resources=vps_resources)}
|
||||
<div class="mobileSearchDock" id="mobileHubUpdateDock">
|
||||
<span class="mobileSearchVersion">v118</span>
|
||||
<button class="badge hubUpdateButton" data-hub-update type="button" {'hidden' if not is_owner else ''}>Обновление панели</button>
|
||||
</div>
|
||||
<div class="mobileSearchDock" id="mobileSeasonDock" aria-label="Зимние эффекты">
|
||||
<button class="routerSearchToggle seasonToggle mobilePanelToggle primary" id="mobileSeasonToggle" type="button" aria-expanded="false" aria-controls="mobileSeasonPanel" data-open="false">
|
||||
@@ -5444,17 +5495,28 @@ input,select{{min-width:0;border:1px solid var(--line);border-radius:8px;padding
|
||||
<button class="seasonBtn" type="button" data-season-mode="prism" data-active="false" aria-pressed="false">Призма</button>
|
||||
<button class="seasonBtn" type="button" data-season-mode="pulse" data-active="false" aria-pressed="false">Пульс</button>
|
||||
<button class="seasonBtn" type="button" data-season-mode="laser" data-active="false" aria-pressed="false">Лучи</button>
|
||||
<button class="seasonBtn" type="button" data-season-mode="aurora" data-active="false" aria-pressed="false">Аврора</button>
|
||||
<button class="seasonBtn" type="button" data-season-mode="matrix" data-active="false" aria-pressed="false">Матрица</button>
|
||||
<button class="seasonBtn" type="button" data-season-mode="nebula" data-active="false" aria-pressed="false">Туманность</button>
|
||||
<button class="seasonBtn" type="button" data-season-mode="fireworks" data-active="false" aria-pressed="false">Фейерверк</button>
|
||||
<button class="seasonBtn" type="button" data-season-mode="vortex" data-active="false" aria-pressed="false">Вихрь</button>
|
||||
<button class="seasonBtn" type="button" data-season-mode="comet" data-active="false" aria-pressed="false">Кометы</button>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
{vps_resource_widgets_html(mobile=True)}
|
||||
<div class="mobileSearchDock" id="mobileRouterSearchDock">
|
||||
<button class="routerSearchToggle mobilePanelToggle primary" id="mobileRouterSearchToggle" type="button" aria-expanded="false" aria-controls="mobileRouterSearchPanel" data-active="false">
|
||||
<span>Поиск роутеров</span>
|
||||
</button>
|
||||
<section class="routerSearchPanel" id="mobileRouterSearchPanel" aria-label="Поиск роутеров" hidden>
|
||||
<div class="routerSearchCard">
|
||||
<div class="routerSearchHead">
|
||||
<strong class="routerSearchTitle">Поиск по роутерам</strong>
|
||||
<button class="routerSearchClear" id="mobileRouterSearchClear" type="button" disabled>Очистить</button>
|
||||
</div>
|
||||
<label class="routerSearchField" for="mobileRouterSearchInput">
|
||||
<span class="routerSearchIcon" aria-hidden="true">⌕</span>
|
||||
<input id="mobileRouterSearchInput" type="search" placeholder="Имя или router id" autocomplete="off" spellcheck="false">
|
||||
</label>
|
||||
<div class="routerSearchMeta" id="mobileRouterSearchMeta">Всего роутеров: 0</div>
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
<button class="mobilePanelToggle primary" id="hubMenuToggle" type="button" hidden>Открыть меню хаба</button>
|
||||
<div id="hubMenuPanelHost"></div>
|
||||
<div class="mobileOwnerTools" id="mobileOwnerTools" hidden>
|
||||
@@ -5601,7 +5663,7 @@ const openRouterGroups = new Set(['__ungrouped__']);
|
||||
let routerGroupsPanelOpen = false;
|
||||
let lastRouterSearchTrigger = null;
|
||||
const SEASON_EFFECT_KEY = 'owrtRemote:seasonEffectMode';
|
||||
const SEASON_EFFECT_MODES = new Set(['off', 'snow', 'rain', 'cosmos', 'embers', 'orbit', 'prism', 'pulse', 'laser', 'aurora', 'matrix', 'nebula', 'fireworks', 'vortex', 'comet']);
|
||||
const SEASON_EFFECT_MODES = new Set(['off', 'snow', 'rain', 'cosmos', 'embers', 'orbit', 'prism', 'pulse', 'laser']);
|
||||
let seasonEffectMode = 'off';
|
||||
let seasonalFxCtx = null;
|
||||
let seasonalFxFrame = 0;
|
||||
@@ -11667,6 +11729,125 @@ syncRouterSearchToggleState();
|
||||
requestRouterRender();
|
||||
fillRouterForm(true);
|
||||
waitNotificationsLoop();
|
||||
function initHubUpdate() {{
|
||||
const buttons = Array.from(document.querySelectorAll('[data-hub-update]')).filter(button => !button.hidden);
|
||||
const notice = document.getElementById('hubUpdateNotice');
|
||||
if (!buttons.length || !notice) return;
|
||||
const confirmPanel = document.getElementById('hubUpdateConfirm');
|
||||
const confirmLead = document.getElementById('hubUpdateConfirmLead');
|
||||
const confirmVersion = document.getElementById('hubUpdateConfirmVersion');
|
||||
const confirmSource = document.getElementById('hubUpdateConfirmSource');
|
||||
const confirmCancel = document.getElementById('hubUpdateConfirmCancel');
|
||||
const confirmAccept = document.getElementById('hubUpdateConfirmAccept');
|
||||
let state = null, timer = null, loading = false, stopped = false, csrf = '', pending = '', deadline = 0;
|
||||
let confirmResolve = null;
|
||||
const active = job => job && ['starting', 'installing', 'restarting', 'rollback'].includes(job.status);
|
||||
try {{ pending = sessionStorage.getItem('hub-update-pending') || ''; }} catch (_) {{}}
|
||||
if (pending) deadline = Date.now() + 300000;
|
||||
const message = (text, result = '') => {{
|
||||
notice.hidden = !text; notice.textContent = text; notice.dataset.result = result;
|
||||
}};
|
||||
const closeConfirmation = (answer) => {{
|
||||
if (!confirmPanel || !confirmResolve) return;
|
||||
const resolve = confirmResolve;
|
||||
confirmResolve = null;
|
||||
confirmPanel.hidden = true;
|
||||
document.body.classList.remove('hubUpdateConfirmOpen');
|
||||
resolve(Boolean(answer));
|
||||
}};
|
||||
const askConfirmation = (candidate) => new Promise((resolve) => {{
|
||||
if (!confirmPanel || !confirmLead || !confirmVersion || !confirmSource || !confirmCancel || !confirmAccept) {{
|
||||
resolve(window.confirm('Действительно обновить панель VPS до ' + candidate.remote_version + '?'));
|
||||
return;
|
||||
}}
|
||||
closeConfirmation(false);
|
||||
confirmResolve = resolve;
|
||||
confirmLead.textContent = 'Действительно обновить панель VPS до последней доступной сборки ' + candidate.remote_version + ' (' + candidate.remote_revision.slice(0, 8) + ')?';
|
||||
confirmVersion.textContent = candidate.remote_version + ' · ' + candidate.remote_revision.slice(0, 8);
|
||||
confirmSource.textContent = candidate.source || 'источник обновления';
|
||||
confirmPanel.hidden = false;
|
||||
document.body.classList.add('hubUpdateConfirmOpen');
|
||||
confirmAccept.focus();
|
||||
}});
|
||||
if (confirmCancel) confirmCancel.addEventListener('click', () => closeConfirmation(false));
|
||||
if (confirmAccept) confirmAccept.addEventListener('click', () => closeConfirmation(true));
|
||||
if (confirmPanel) confirmPanel.addEventListener('click', (event) => {{ if (event.target === confirmPanel) closeConfirmation(false); }});
|
||||
document.addEventListener('keydown', (event) => {{ if (event.key === 'Escape') closeConfirmation(false); }});
|
||||
const remember = value => {{
|
||||
pending = value;
|
||||
try {{ if (value) sessionStorage.setItem('hub-update-pending', value); else sessionStorage.removeItem('hub-update-pending'); }} catch (_) {{}}
|
||||
}};
|
||||
const render = () => {{
|
||||
if (!state) return;
|
||||
const job = state.job || {{}}, busy = active(job);
|
||||
buttons.forEach(button => {{
|
||||
button.disabled = busy || state.checking;
|
||||
button.dataset.available = state.available ? 'true' : 'false';
|
||||
button.dataset.updateState = busy ? 'busy' : state.checking ? 'checking' : state.error ? 'error' : state.available ? 'available' : state.checked ? 'current' : 'checking';
|
||||
button.textContent = busy ? 'Обновляется…' : state.checking ? 'Проверка…' : state.available ? 'Доступно обновление' : 'Обновление панели';
|
||||
button.title = state.available ? 'Доступна сборка ' + state.remote_version + ' · ' + state.remote_revision.slice(0, 8) : state.error || 'Проверить обновление панели';
|
||||
}});
|
||||
if (busy) {{
|
||||
if (!pending) {{ remember(job.id); deadline = Date.now() + 300000; }}
|
||||
message(job.message);
|
||||
}} else if (job.id === pending && ['succeeded', 'failed'].includes(job.status)) {{
|
||||
remember('');
|
||||
message(job.message, job.status);
|
||||
if (job.status === 'succeeded') {{ stopped = true; setTimeout(() => window.location.reload(), 1500); }}
|
||||
}} else if (state.error) message(state.error, 'failed');
|
||||
else if (job.status === 'failed') message(job.message, 'failed');
|
||||
else if (state.available) message('Доступно обновление панели: ' + state.remote_version + ' · сборка ' + state.remote_revision.slice(0, 8) + '.');
|
||||
else if (state.checked && !state.checking) message('У вас последняя версия панели, обновление не требуется.', 'succeeded');
|
||||
else if (state.checking) message('Проверяется наличие обновлений панели…');
|
||||
else message('');
|
||||
}};
|
||||
const request = async (action = '', payload = {{}}) => {{
|
||||
const controller = new AbortController(), timeout = setTimeout(() => controller.abort(), 10000);
|
||||
try {{
|
||||
const options = {{cache: 'no-store', credentials: 'same-origin', signal: controller.signal}};
|
||||
if (action) Object.assign(options, {{method: 'POST', headers: {{'Content-Type': 'application/json', 'X-Hub-Update-CSRF': csrf}}, body: JSON.stringify(payload)}});
|
||||
const response = await fetch('/api/hub-update' + (action ? '/' + action : ''), options);
|
||||
if (response.status === 401 || response.status === 403) stopped = true;
|
||||
const data = await response.json();
|
||||
if (!response.ok || !data.ok) throw new Error(data.error || 'Не удалось связаться с панелью.');
|
||||
state = data; csrf = data.csrf; render();
|
||||
}} finally {{ clearTimeout(timeout); }}
|
||||
}};
|
||||
const schedule = () => {{
|
||||
clearTimeout(timer);
|
||||
if (!stopped && !document.hidden) timer = setTimeout(load, pending || state?.checking || active(state?.job) ? 2000 : 60000);
|
||||
}};
|
||||
const failure = error => {{
|
||||
if (pending && Date.now() < deadline) message('Панель перезапускается. Ожидается результат обновления…');
|
||||
else message(pending ? 'Связь с панелью не восстановилась. Результат обновления не подтверждён; проверь сервис owrt-remote на VPS.' : error.message, 'failed');
|
||||
}};
|
||||
const load = async () => {{
|
||||
if (loading || stopped || document.hidden) return;
|
||||
loading = true;
|
||||
try {{ await request(); }} catch (error) {{ failure(error); }}
|
||||
finally {{ loading = false; schedule(); }}
|
||||
}};
|
||||
buttons.forEach(button => button.addEventListener('click', async () => {{
|
||||
if (loading || active(state?.job)) return;
|
||||
loading = true;
|
||||
try {{
|
||||
if (!state) await request();
|
||||
if (state.available) {{
|
||||
if (await askConfirmation(state)) {{
|
||||
deadline = Date.now() + 300000;
|
||||
await request('start', {{revision: state.remote_revision}});
|
||||
}}
|
||||
}} else {{
|
||||
await request('check');
|
||||
}}
|
||||
}} catch (error) {{ failure(error); }}
|
||||
finally {{ loading = false; schedule(); }}
|
||||
}}));
|
||||
document.addEventListener('visibilitychange', () => {{ clearTimeout(timer); if (!document.hidden) load(); }});
|
||||
window.addEventListener('pagehide', () => clearTimeout(timer));
|
||||
window.addEventListener('pageshow', load);
|
||||
load();
|
||||
}}
|
||||
function initVpsResourceWidgets() {{
|
||||
const widgets = Array.from(document.querySelectorAll('[data-vps-resource]'));
|
||||
if (!widgets.length) return;
|
||||
@@ -11701,7 +11882,8 @@ function initVpsResourceWidgets() {{
|
||||
if (stopped || document.hidden || request) return;
|
||||
const controller = new AbortController();
|
||||
request = controller;
|
||||
const timeout = setTimeout(() => controller.abort(), 2500);
|
||||
let timedOut = false;
|
||||
const timeout = setTimeout(() => {{ timedOut = true; controller.abort(); }}, 2500);
|
||||
try {{
|
||||
const response = await fetch('/api/vps/resources', {{cache: 'no-store', signal: controller.signal}});
|
||||
if (response.status === 401 || response.status === 403) {{ stopped = true; clearInterval(timer); }}
|
||||
@@ -11710,10 +11892,10 @@ function initVpsResourceWidgets() {{
|
||||
if (!data.ok) throw new Error('Invalid VPS resources');
|
||||
if (!document.hidden && !stopped) show(data);
|
||||
}} catch (error) {{
|
||||
if (!document.hidden) show(null, true);
|
||||
if (!document.hidden && (!controller.signal.aborted || timedOut)) show(null, true);
|
||||
}} finally {{
|
||||
clearTimeout(timeout);
|
||||
request = null;
|
||||
if (request === controller) request = null;
|
||||
}}
|
||||
}};
|
||||
const pause = () => {{
|
||||
@@ -11721,10 +11903,10 @@ function initVpsResourceWidgets() {{
|
||||
if (request) request.abort();
|
||||
}};
|
||||
const resume = () => {{
|
||||
pause();
|
||||
if (stopped || document.hidden) return;
|
||||
clearInterval(timer); timer = null;
|
||||
if (stopped || document.hidden) {{ pause(); return; }}
|
||||
load();
|
||||
timer = setInterval(load, 3000);
|
||||
timer = setInterval(load, 1000);
|
||||
}};
|
||||
document.addEventListener('visibilitychange', resume);
|
||||
window.addEventListener('pagehide', pause);
|
||||
@@ -11732,6 +11914,7 @@ function initVpsResourceWidgets() {{
|
||||
resume();
|
||||
}}
|
||||
initVpsResourceWidgets();
|
||||
initHubUpdate();
|
||||
setInterval(() => {{
|
||||
loadRouters({{automatic: true}}).catch(() => {{}});
|
||||
}}, 5000);
|
||||
@@ -12944,7 +13127,7 @@ button:hover{{filter:brightness(1.06)}}
|
||||
<form class="login" method="post" action="/login">
|
||||
{error_html}
|
||||
<span class="brand">
|
||||
<h1 class="appBanner"><span>OpenWrt Remote Hub <span class="appBannerVersion">v117</span></span></h1>
|
||||
<h1 class="appBanner"><span>OpenWrt Remote Hub <span class="appBannerVersion">v118</span></span></h1>
|
||||
</span>
|
||||
<label for="hubUsername">Логин</label>
|
||||
<input id="hubUsername" name="username" autocomplete="off" autofocus required>
|
||||
@@ -13416,7 +13599,7 @@ body::after{{content:"";position:fixed;inset:0;pointer-events:none;background:li
|
||||
<circle cx="65" cy="59" r="3" fill="#E5F2FF"/>
|
||||
</svg>
|
||||
</div>
|
||||
<h2 class="brandTitle">OpenWrt Remote Hub <span class="brandVersion">v117</span></h2>
|
||||
<h2 class="brandTitle">OpenWrt Remote Hub <span class="brandVersion">v118</span></h2>
|
||||
</div>
|
||||
</div>
|
||||
<div class="brandBottom">
|
||||
@@ -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")))
|
||||
|
||||
@@ -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 }
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user