feat(vmis): 租戶自動開通完整流程 + Admin Portal SSO + NC 行事曆訂閱
Backend: - schedule_tenant: NC 新容器自動 pgsql 安裝 (_nc_db_check 全新容器處理) - schedule_tenant: NC 初始化加入 Redis + APCu memcache 設定 (修正 OIDC invalid_state) - schedule_tenant: 新租戶 KC realm 自動設定 accessCodeLifespan=600s (修正 authentication_expired) - schedule_account: NC Mail 帳號自動設定 (nc_mail_result/nc_mail_done_at) - schedule_account: NC 台灣國定假日行事曆自動訂閱 (CalDAV MKCALENDAR) - nextcloud_client: 新增 subscribe_calendar() CalDAV 訂閱方法 - settings: 新增系統設定 API (site_title/version/timezone/SSO/Keycloak) - models/result: 新增 nc_mail_result, nc_mail_done_at 欄位 - alembic: 遷移 002(system_settings) 003(keycloak_admin) 004(nc_mail_result) Frontend (Admin Portal): - 新增完整管理後台 (index/tenants/accounts/servers/schedules/logs/settings/system-status) - api.js: Keycloak JS Adapter SSO 整合 (PKCE/S256, fallback KC JS 來源, 自動 token 更新) - index.html: Promise.allSettled 取代 Promise.all,防止單一 API 失敗影響整頁 - 所有頁面加入 try/catch + toast 錯誤處理 - 新增品牌 LOGO 與 favicon Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
@@ -1,6 +1,7 @@
|
||||
"""
|
||||
DockerClient — docker-py (本機 Docker socket) + paramiko SSH (遠端 docker compose)
|
||||
管理租戶的 NC / OO 容器。
|
||||
DockerClient — paramiko SSH (遠端 docker / traefik 查詢)
|
||||
所有容器都在 10.1.0.254,透過 SSH 操作。
|
||||
3-state 回傳: None=未設定(灰), True=正常(綠), False=異常(紅)
|
||||
"""
|
||||
import logging
|
||||
from typing import Optional
|
||||
@@ -12,70 +13,74 @@ logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class DockerClient:
|
||||
def __init__(self):
|
||||
self._docker = None
|
||||
|
||||
def _get_docker(self):
|
||||
if self._docker is None:
|
||||
import docker
|
||||
self._docker = docker.from_env()
|
||||
return self._docker
|
||||
def _ssh(self):
|
||||
"""建立 SSH 連線到 10.1.0.254"""
|
||||
import paramiko
|
||||
client = paramiko.SSHClient()
|
||||
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
|
||||
client.connect(
|
||||
settings.DOCKER_SSH_HOST,
|
||||
username=settings.DOCKER_SSH_USER,
|
||||
timeout=15,
|
||||
)
|
||||
return client
|
||||
|
||||
def check_traefik_route(self, domain: str) -> bool:
|
||||
def check_traefik_domain(self, domain: str) -> Optional[bool]:
|
||||
"""
|
||||
Traefik API: GET http://localhost:8080/api/http/routers
|
||||
驗證 routers 中包含 domain,且 routers 數量 > 0
|
||||
None = domain 在 Traefik 沒有路由設定(灰)
|
||||
True = 路由存在且服務存活(綠)
|
||||
False = 路由存在但服務不通(紅)
|
||||
"""
|
||||
try:
|
||||
resp = httpx.get("http://localhost:8080/api/overview", timeout=5.0)
|
||||
resp = httpx.get(f"http://{settings.DOCKER_SSH_HOST}:8080/api/http/routers", timeout=5.0)
|
||||
if resp.status_code != 200:
|
||||
return False
|
||||
data = resp.json()
|
||||
# Verify actual routes exist (functional check)
|
||||
http_count = data.get("http", {}).get("routers", {}).get("total", 0)
|
||||
if http_count == 0:
|
||||
routers = resp.json()
|
||||
route_found = any(domain in str(r.get("rule", "")) for r in routers)
|
||||
if not route_found:
|
||||
return None
|
||||
# Route exists — probe the service
|
||||
try:
|
||||
probe = httpx.get(
|
||||
f"https://{domain}",
|
||||
timeout=5.0,
|
||||
follow_redirects=True,
|
||||
)
|
||||
return probe.status_code < 500
|
||||
except Exception:
|
||||
return False
|
||||
# Check domain-specific router
|
||||
routers_resp = httpx.get("http://localhost:8080/api/http/routers", timeout=5.0)
|
||||
if routers_resp.status_code != 200:
|
||||
return False
|
||||
routers = routers_resp.json()
|
||||
return any(domain in str(r.get("rule", "")) for r in routers)
|
||||
except Exception as e:
|
||||
logger.warning(f"Traefik check failed for {domain}: {e}")
|
||||
return False
|
||||
|
||||
def ensure_container_running(self, container_name: str, tenant_code: str, realm: str) -> bool:
|
||||
"""Check container status; start if exited; deploy via SSH if not found."""
|
||||
def check_container_ssh(self, container_name: str) -> Optional[bool]:
|
||||
"""
|
||||
SSH 到 10.1.0.254 查詢容器狀態。
|
||||
None = 容器不存在(未部署)
|
||||
True = 容器正在執行
|
||||
False = 容器存在但未執行(exited/paused)
|
||||
"""
|
||||
try:
|
||||
docker_client = self._get_docker()
|
||||
container = docker_client.containers.get(container_name)
|
||||
if container.status == "running":
|
||||
return True
|
||||
elif container.status == "exited":
|
||||
container.start()
|
||||
container.reload()
|
||||
return container.status == "running"
|
||||
except Exception as e:
|
||||
if "Not Found" in str(e) or "404" in str(e):
|
||||
return self._ssh_compose_up(tenant_code, realm)
|
||||
logger.error(f"Docker check failed for {container_name}: {e}")
|
||||
return False
|
||||
return False
|
||||
|
||||
def _ssh_compose_up(self, tenant_code: str, realm: str) -> bool:
|
||||
"""SSH into 10.1.0.254 and run docker compose up -d"""
|
||||
try:
|
||||
import paramiko
|
||||
client = paramiko.SSHClient()
|
||||
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
|
||||
client.connect(
|
||||
settings.DOCKER_SSH_HOST,
|
||||
username=settings.DOCKER_SSH_USER,
|
||||
timeout=15,
|
||||
client = self._ssh()
|
||||
_, stdout, _ = client.exec_command(
|
||||
f"docker inspect --format='{{{{.State.Status}}}}' {container_name} 2>/dev/null"
|
||||
)
|
||||
output = stdout.read().decode().strip()
|
||||
client.close()
|
||||
if not output:
|
||||
return None
|
||||
return output == "running"
|
||||
except Exception as e:
|
||||
logger.error(f"SSH container check failed for {container_name}: {e}")
|
||||
return False
|
||||
|
||||
def ssh_compose_up(self, tenant_code: str) -> bool:
|
||||
"""SSH 到 10.1.0.254 執行 docker compose up -d"""
|
||||
try:
|
||||
client = self._ssh()
|
||||
deploy_dir = f"{settings.TENANT_DEPLOY_BASE}/{tenant_code}"
|
||||
stdin, stdout, stderr = client.exec_command(
|
||||
_, stdout, _ = client.exec_command(
|
||||
f"cd {deploy_dir} && docker compose up -d 2>&1"
|
||||
)
|
||||
exit_status = stdout.channel.recv_exit_status()
|
||||
@@ -84,3 +89,19 @@ class DockerClient:
|
||||
except Exception as e:
|
||||
logger.error(f"SSH compose up failed for {tenant_code}: {e}")
|
||||
return False
|
||||
|
||||
def get_oo_disk_usage_gb(self, container_name: str) -> Optional[float]:
|
||||
"""取得 OO 容器磁碟使用量(GB),容器不存在回傳 None"""
|
||||
try:
|
||||
client = self._ssh()
|
||||
_, stdout, _ = client.exec_command(
|
||||
f"docker exec {container_name} df -B1 / 2>/dev/null | awk 'NR==2 {{print $3}}'"
|
||||
)
|
||||
output = stdout.read().decode().strip()
|
||||
client.close()
|
||||
if output.isdigit():
|
||||
return round(int(output) / (1024 ** 3), 3)
|
||||
return None
|
||||
except Exception as e:
|
||||
logger.warning(f"OO disk usage check failed for {container_name}: {e}")
|
||||
return None
|
||||
|
||||
Reference in New Issue
Block a user