Template
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
2808a49fa5 |
+1
-1
@@ -21,6 +21,6 @@ COPY . .
|
||||
EXPOSE 5000
|
||||
|
||||
HEALTHCHECK --interval=30s --timeout=10s --start-period=40s --retries=3 \
|
||||
CMD curl -fsS "http://127.0.0.1:${APP_PORT}/docs" >/dev/null || exit 1
|
||||
CMD curl -fsS "http://127.0.0.1:${APP_PORT}/health" >/dev/null || exit 1
|
||||
|
||||
CMD ["python3", "app.py"]
|
||||
|
||||
@@ -228,6 +228,9 @@ GitHub Actions workflows in `.github/workflows/`:
|
||||
|
||||
## 📋 Fix / changelog (this fork)
|
||||
|
||||
### v2.5.5
|
||||
* **Fix 404 after panel update** — correct tunnel/local port when `APP_PORT` is set (Docker), health check before reload, auto-restart quick tunnels after reboot, reliable archive download URLs.
|
||||
|
||||
### v2.5.4
|
||||
* **Move connections between servers** — on a server page, select configs and move them to another server (recreates peers, keeps user links).
|
||||
|
||||
|
||||
@@ -102,7 +102,7 @@ else:
|
||||
application_path = os.path.dirname(__file__)
|
||||
|
||||
DATA_FILE = os.path.join(application_path, 'data.json') # legacy JSON; used only for one-shot import / export
|
||||
CURRENT_VERSION = "v2.5.4"
|
||||
CURRENT_VERSION = "v2.5.5"
|
||||
RELEASES_REPO_URL = repo_url()
|
||||
RELEASES_API_LATEST = api_latest_url()
|
||||
BIN_DIR = os.environ.get('TUNNEL_BIN_DIR', os.path.join(application_path, 'bin'))
|
||||
@@ -224,12 +224,46 @@ def tpl(request, template, **kwargs):
|
||||
return templates.TemplateResponse(template, ctx)
|
||||
|
||||
|
||||
def get_panel_listen_port(data: Optional[dict] = None) -> int:
|
||||
try:
|
||||
env_port = int(os.environ.get('APP_PORT', '0') or '0')
|
||||
except ValueError:
|
||||
env_port = 0
|
||||
if env_port:
|
||||
return env_port
|
||||
if data is None:
|
||||
data = load_data()
|
||||
ssl_conf = data.get('settings', {}).get('ssl', {}) or {}
|
||||
try:
|
||||
return int(ssl_conf.get('panel_port', 5000) or 5000)
|
||||
except (TypeError, ValueError):
|
||||
return 5000
|
||||
|
||||
|
||||
def panel_ssl_active(data: Optional[dict] = None) -> bool:
|
||||
if data is None:
|
||||
data = load_data()
|
||||
ssl_conf = data.get('settings', {}).get('ssl', {}) or {}
|
||||
if not ssl_conf.get('enabled'):
|
||||
return False
|
||||
# Docker/compose usually terminates TLS outside the app and serves plain HTTP inside.
|
||||
if os.environ.get('APP_PORT'):
|
||||
return False
|
||||
cert_path = ssl_conf.get('cert_path')
|
||||
key_path = ssl_conf.get('key_path')
|
||||
if ssl_conf.get('cert_text') or ssl_conf.get('key_text'):
|
||||
return True
|
||||
return bool(
|
||||
cert_path and key_path
|
||||
and os.path.exists(cert_path) and os.path.exists(key_path)
|
||||
)
|
||||
|
||||
|
||||
def get_panel_local_url(request: Optional[Request] = None):
|
||||
data = load_data()
|
||||
ssl_conf = data.get('settings', {}).get('ssl', {})
|
||||
scheme = 'https' if ssl_conf.get('enabled') else 'http'
|
||||
scheme = 'https' if panel_ssl_active(data) else 'http'
|
||||
host = '127.0.0.1'
|
||||
port = ssl_conf.get('panel_port', 5000) or 5000
|
||||
port = get_panel_listen_port(data)
|
||||
if request:
|
||||
scheme = request.url.scheme or scheme
|
||||
host = request.url.hostname or host
|
||||
@@ -239,12 +273,17 @@ def get_panel_local_url(request: Optional[Request] = None):
|
||||
|
||||
def get_panel_tunnel_target_url():
|
||||
data = load_data()
|
||||
ssl_conf = data.get('settings', {}).get('ssl', {})
|
||||
scheme = 'https' if ssl_conf.get('enabled') else 'http'
|
||||
port = ssl_conf.get('panel_port', 5000) or 5000
|
||||
scheme = 'https' if panel_ssl_active(data) else 'http'
|
||||
port = get_panel_listen_port(data)
|
||||
return f"{scheme}://127.0.0.1:{port}"
|
||||
|
||||
|
||||
@app.get('/health', include_in_schema=False)
|
||||
@app.get('/api/health', include_in_schema=False)
|
||||
async def health_check():
|
||||
return {'status': 'ok', 'version': CURRENT_VERSION}
|
||||
|
||||
|
||||
def get_warp_cli_binary():
|
||||
found = shutil.which(WARP_CLI_COMMAND)
|
||||
if found:
|
||||
@@ -2436,6 +2475,24 @@ async def startup():
|
||||
logger.info("Starting Telegram bot from saved settings...")
|
||||
tg_bot.launch_bot(tg_cfg['token'], load_data, generate_vpn_link, save_data)
|
||||
|
||||
# Reattach quick tunnels after panel restart so public URLs keep working.
|
||||
try:
|
||||
tunnel_state = await asyncio.to_thread(load_tunnel_state)
|
||||
local_url = get_panel_tunnel_target_url()
|
||||
for provider in ('cloudflare', 'ngrok'):
|
||||
state = tunnel_state.get(provider) or {}
|
||||
if not (state.get('public_url') or state.get('pid') or state.get('started_at')):
|
||||
continue
|
||||
if state.get('pid') and pid_is_running(state.get('pid')):
|
||||
continue
|
||||
try:
|
||||
await asyncio.to_thread(start_tunnel, provider, local_url)
|
||||
logger.info('Restarted %s tunnel after panel boot -> %s', provider, local_url)
|
||||
except Exception as exc:
|
||||
logger.warning('Could not restart %s tunnel after panel boot: %s', provider, exc)
|
||||
except Exception as exc:
|
||||
logger.warning('Tunnel auto-restart skipped: %s', exc)
|
||||
|
||||
|
||||
def _scrape_server_traffic(server, sid, my_conns):
|
||||
server_updates = []
|
||||
@@ -5843,11 +5900,11 @@ async def api_my_connection_config(request: Request, connection_id: str):
|
||||
return JSONResponse({'error': str(e)}, status_code=500)
|
||||
|
||||
|
||||
@app.get('/settings', tags=["System Templates"])
|
||||
@app.get('/settings', response_class=HTMLResponse, tags=["System Templates"])
|
||||
async def settings_page(request: Request):
|
||||
user = _check_admin(request)
|
||||
if not user:
|
||||
return RedirectResponse('/login')
|
||||
return RedirectResponse('/login', status_code=302)
|
||||
data = load_data()
|
||||
from managers.xui_servers import list_xui_servers, public_server_view, ensure_xui_servers
|
||||
settings = data.setdefault('settings', {})
|
||||
@@ -5951,7 +6008,7 @@ async def api_apply_update(request: Request, req: ApplyUpdateRequest):
|
||||
return JSONResponse({'error': result.get('message') or 'Update failed', **result}, status_code=status_code)
|
||||
|
||||
if result.get('restart'):
|
||||
UpdateManager.schedule_restart(1.5)
|
||||
UpdateManager.schedule_restart(application_path, 1.5)
|
||||
return result
|
||||
|
||||
|
||||
@@ -5989,7 +6046,7 @@ async def api_upgrade_panel(request: Request):
|
||||
if result.get('status') != 'success':
|
||||
return JSONResponse({'error': result.get('message') or 'Update failed', **result}, status_code=500)
|
||||
if result.get('restart'):
|
||||
UpdateManager.schedule_restart(1.5)
|
||||
UpdateManager.schedule_restart(application_path, 1.5)
|
||||
result['up_to_date'] = False
|
||||
result['previous_version'] = CURRENT_VERSION
|
||||
return result
|
||||
@@ -6564,10 +6621,10 @@ if __name__ == '__main__':
|
||||
uvicorn_kwargs = {
|
||||
"app": app,
|
||||
"host": "0.0.0.0",
|
||||
"port": env_port or ssl_conf.get('panel_port', 5000) or 5000,
|
||||
"port": env_port or get_panel_listen_port(data),
|
||||
}
|
||||
|
||||
if ssl_conf.get('enabled') and cert_file and key_file:
|
||||
if panel_ssl_active(data) and cert_file and key_file:
|
||||
if os.path.exists(cert_file) and os.path.exists(key_file):
|
||||
logger.info(f"Starting panel with HTTPS enabled on domain: {ssl_conf.get('domain')} at port {uvicorn_kwargs['port']}")
|
||||
uvicorn_kwargs["ssl_certfile"] = cert_file
|
||||
|
||||
+1
-1
@@ -37,7 +37,7 @@ services:
|
||||
- amnezia_data:/app/data
|
||||
restart: unless-stopped
|
||||
healthcheck:
|
||||
test: ["CMD-SHELL", "curl -fsS http://127.0.0.1:5000/docs >/dev/null || exit 1"]
|
||||
test: ["CMD-SHELL", "curl -fsS http://127.0.0.1:5000/health >/dev/null || exit 1"]
|
||||
interval: 30s
|
||||
timeout: 10s
|
||||
retries: 3
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import re
|
||||
@@ -278,12 +279,33 @@ class UpdateManager:
|
||||
}
|
||||
|
||||
def _archive_urls(self, tag: str) -> list[str]:
|
||||
urls: list[str] = []
|
||||
api_base = api_latest_url().rsplit('/releases/latest', 1)[0]
|
||||
for endpoint in (f'{api_base}/releases/tags/{tag}', api_latest_url()):
|
||||
try:
|
||||
req = urllib.request.Request(
|
||||
endpoint,
|
||||
headers={'Accept': 'application/json', 'User-Agent': 'Amnezia-Web-Panel-Updater'},
|
||||
)
|
||||
with urllib.request.urlopen(req, timeout=30) as resp:
|
||||
payload = json.loads(resp.read().decode('utf-8', errors='replace') or '{}')
|
||||
zipball = (payload.get('zipball_url') or '').strip()
|
||||
if zipball:
|
||||
urls.append(zipball)
|
||||
except Exception:
|
||||
pass
|
||||
base = repo_url()
|
||||
return [
|
||||
urls.extend([
|
||||
f'{base}/archive/{tag}.zip',
|
||||
f'{base}/archive/{tag.lstrip("v")}.zip',
|
||||
f'{api_latest_url().rsplit("/releases/latest", 1)[0]}/archive/{tag}.zip',
|
||||
]
|
||||
f'{api_base}/archive/{tag}.zip',
|
||||
])
|
||||
seen = set()
|
||||
ordered: list[str] = []
|
||||
for url in urls:
|
||||
if url and url not in seen:
|
||||
seen.add(url)
|
||||
ordered.append(url)
|
||||
return ordered
|
||||
|
||||
def _download_archive(self, tag: str, dest_path: str) -> None:
|
||||
last_err = 'unknown error'
|
||||
@@ -383,15 +405,26 @@ class UpdateManager:
|
||||
return {'status': 'error', 'message': hint, 'mode': mode}
|
||||
|
||||
@staticmethod
|
||||
def schedule_restart(delay_sec: float = 1.5) -> None:
|
||||
def schedule_restart(app_root: str, delay_sec: float = 1.5) -> None:
|
||||
def _restart():
|
||||
time.sleep(max(0.5, float(delay_sec)))
|
||||
argv = [sys.executable] + sys.argv
|
||||
cwd = os.path.abspath(app_root or os.getcwd())
|
||||
logger.info('Restarting panel after update: %s (cwd=%s)', argv, cwd)
|
||||
try:
|
||||
argv = [sys.executable] + sys.argv
|
||||
logger.info('Restarting panel after update: %s', argv)
|
||||
os.chdir(cwd)
|
||||
os.execv(sys.executable, argv)
|
||||
except Exception:
|
||||
logger.exception('Failed to restart after update; exiting')
|
||||
logger.exception('execv restart failed; trying subprocess fallback')
|
||||
try:
|
||||
subprocess.Popen(
|
||||
argv,
|
||||
cwd=cwd,
|
||||
close_fds=True,
|
||||
start_new_session=True,
|
||||
)
|
||||
except Exception:
|
||||
logger.exception('Failed to restart after update')
|
||||
os._exit(0)
|
||||
|
||||
threading.Thread(target=_restart, name='panel-update-restart', daemon=False).start()
|
||||
|
||||
+35
-8
@@ -1718,6 +1718,22 @@
|
||||
}
|
||||
}
|
||||
|
||||
async function waitForPanelRestart(timeoutMs = 90000) {
|
||||
const started = Date.now();
|
||||
while (Date.now() - started < timeoutMs) {
|
||||
try {
|
||||
const res = await fetch('/api/health', { cache: 'no-store' });
|
||||
if (res.ok) {
|
||||
window.location.reload();
|
||||
return true;
|
||||
}
|
||||
} catch (_) {}
|
||||
await new Promise((resolve) => setTimeout(resolve, 1500));
|
||||
}
|
||||
showToast("{{ _('update_restart_timeout')|default('Panel did not come back in time. Refresh the page manually.') }}", 'error');
|
||||
return false;
|
||||
}
|
||||
|
||||
async function applyPanelUpdate() {
|
||||
const applyBtn = document.getElementById('applyUpdateBtn');
|
||||
const applyText = document.getElementById('applyUpdateBtnText');
|
||||
@@ -1733,18 +1749,24 @@
|
||||
applyBtn.disabled = true;
|
||||
applyText.textContent = "{{ _('applying_update')|default('Updating…') }}";
|
||||
applySpinner.classList.remove('hidden');
|
||||
let restarting = false;
|
||||
try {
|
||||
const data = await apiCall('/api/settings/apply_update', 'POST', {
|
||||
target_version: target,
|
||||
allow_dirty: true,
|
||||
});
|
||||
showToast(data.message || "{{ _('update_restarting')|default('Updated. Restarting…') }}", 'success');
|
||||
setTimeout(() => { window.location.reload(); }, 3500);
|
||||
restarting = true;
|
||||
applyText.textContent = "{{ _('update_waiting_restart')|default('Waiting for panel…') }}";
|
||||
await waitForPanelRestart();
|
||||
} catch (err) {
|
||||
showToast(_('error') + ': ' + err.message, 'error');
|
||||
applyBtn.disabled = false;
|
||||
applyText.textContent = "⬆ {{ _('apply_update')|default('Install update') }}";
|
||||
applySpinner.classList.add('hidden');
|
||||
} finally {
|
||||
if (!restarting) {
|
||||
applyBtn.disabled = false;
|
||||
applyText.textContent = "⬆ {{ _('apply_update')|default('Install update') }}";
|
||||
applySpinner.classList.add('hidden');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1761,6 +1783,7 @@
|
||||
btn.disabled = true;
|
||||
spinner.classList.remove('hidden');
|
||||
text.textContent = "{{ _('upgrade_panel_working')|default('Updating panel…') }}";
|
||||
let restarting = false;
|
||||
try {
|
||||
const data = await apiCall('/api/settings/upgrade_panel', 'POST', {});
|
||||
if (data.up_to_date) {
|
||||
@@ -1769,14 +1792,18 @@
|
||||
return;
|
||||
}
|
||||
showToast(data.message || "{{ _('update_restarting')|default('Updated. Restarting…') }}", 'success');
|
||||
setTimeout(() => { window.location.reload(); }, 4000);
|
||||
restarting = true;
|
||||
text.textContent = "{{ _('update_waiting_restart')|default('Waiting for panel…') }}";
|
||||
await waitForPanelRestart();
|
||||
} catch (err) {
|
||||
showToast(_('error') + ': ' + err.message, 'error');
|
||||
await checkForUpdates(true);
|
||||
} finally {
|
||||
btn.disabled = false;
|
||||
spinner.classList.add('hidden');
|
||||
text.textContent = "⬆ {{ _('upgrade_panel')|default('Update panel') }}";
|
||||
if (!restarting) {
|
||||
btn.disabled = false;
|
||||
spinner.classList.add('hidden');
|
||||
text.textContent = "⬆ {{ _('upgrade_panel')|default('Update panel') }}";
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -505,6 +505,8 @@
|
||||
"applying_update": "Updating…",
|
||||
"apply_update_confirm": "Install update from git.evilfox.cc and restart the panel?",
|
||||
"update_restarting": "Updated. Restarting panel…",
|
||||
"update_waiting_restart": "Waiting for panel to restart…",
|
||||
"update_restart_timeout": "Panel did not come back in time. Refresh the page manually.",
|
||||
"update_no_target": "No target version. Check for updates first.",
|
||||
"auto_update_hint": "Auto-update pulls the release tag from git.evilfox.cc (git checkout required).",
|
||||
"auto_update_ready": "Git auto-update is available for this install.",
|
||||
|
||||
@@ -505,6 +505,8 @@
|
||||
"applying_update": "Обновление…",
|
||||
"apply_update_confirm": "Установить обновление с git.evilfox.cc и перезапустить панель?",
|
||||
"update_restarting": "Обновлено. Перезапуск панели…",
|
||||
"update_waiting_restart": "Ожидание перезапуска панели…",
|
||||
"update_restart_timeout": "Панель не ответила вовремя. Обновите страницу вручную.",
|
||||
"update_no_target": "Нет целевой версии. Сначала проверьте обновления.",
|
||||
"auto_update_hint": "Автообновление тянет тег релиза с git.evilfox.cc (нужен git clone панели).",
|
||||
"auto_update_ready": "Для этой установки доступно автообновление через git.",
|
||||
|
||||
Reference in New Issue
Block a user