mirror of
https://gitee.com/wanwujie/sub2api
synced 2026-04-04 23:42:13 +08:00
Compare commits
6 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
9b4fc42457 | ||
|
|
caae7e4603 | ||
|
|
a26db8b3e2 | ||
|
|
8e81e395b3 | ||
|
|
f0e89992f7 | ||
|
|
4eaa0cf14a |
@@ -1,44 +1,39 @@
|
|||||||
package sysutil
|
package sysutil
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"fmt"
|
|
||||||
"log"
|
"log"
|
||||||
"os/exec"
|
"os"
|
||||||
"runtime"
|
"runtime"
|
||||||
|
"time"
|
||||||
)
|
)
|
||||||
|
|
||||||
const serviceName = "sub2api"
|
// RestartService triggers a service restart by gracefully exiting.
|
||||||
|
|
||||||
// RestartService triggers a service restart via systemd.
|
|
||||||
//
|
//
|
||||||
// IMPORTANT: This function initiates the restart and returns immediately.
|
// This relies on systemd's Restart=always configuration to automatically
|
||||||
// The actual restart happens asynchronously - the current process will be killed
|
// restart the service after it exits. This is the industry-standard approach:
|
||||||
// by systemd and a new process will be started.
|
// - Simple and reliable
|
||||||
//
|
// - No sudo permissions needed
|
||||||
// We use Start() instead of Run() because:
|
// - No complex process management
|
||||||
// - systemctl restart will kill the current process first
|
// - Leverages systemd's native restart capability
|
||||||
// - Run() waits for completion, but the process dies before completion
|
|
||||||
// - Start() spawns the command independently, allowing systemd to handle the full cycle
|
|
||||||
//
|
//
|
||||||
// Prerequisites:
|
// Prerequisites:
|
||||||
// - Linux OS with systemd
|
// - Linux OS with systemd
|
||||||
// - NOPASSWD sudo access configured (install.sh creates /etc/sudoers.d/sub2api)
|
// - Service configured with Restart=always in systemd unit file
|
||||||
func RestartService() error {
|
func RestartService() error {
|
||||||
if runtime.GOOS != "linux" {
|
if runtime.GOOS != "linux" {
|
||||||
return fmt.Errorf("systemd restart only available on Linux")
|
log.Println("Service restart via exit only works on Linux with systemd")
|
||||||
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
log.Println("Initiating service restart...")
|
log.Println("Initiating service restart by graceful exit...")
|
||||||
|
log.Println("systemd will automatically restart the service (Restart=always)")
|
||||||
|
|
||||||
// The sub2api user has NOPASSWD sudo access for systemctl commands
|
// Give a moment for logs to flush and response to be sent
|
||||||
// (configured by install.sh in /etc/sudoers.d/sub2api).
|
go func() {
|
||||||
// Use -n (non-interactive) to prevent sudo from waiting for password input
|
time.Sleep(100 * time.Millisecond)
|
||||||
cmd := exec.Command("sudo", "-n", "systemctl", "restart", serviceName)
|
os.Exit(0)
|
||||||
if err := cmd.Start(); err != nil {
|
}()
|
||||||
return fmt.Errorf("failed to initiate service restart: %w", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
log.Println("Service restart initiated successfully")
|
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -125,6 +125,7 @@ func (s *UpdateService) CheckUpdate(ctx context.Context, force bool) (*UpdateInf
|
|||||||
}
|
}
|
||||||
|
|
||||||
// PerformUpdate downloads and applies the update
|
// PerformUpdate downloads and applies the update
|
||||||
|
// Uses atomic file replacement pattern for safe in-place updates
|
||||||
func (s *UpdateService) PerformUpdate(ctx context.Context) error {
|
func (s *UpdateService) PerformUpdate(ctx context.Context) error {
|
||||||
info, err := s.CheckUpdate(ctx, true)
|
info, err := s.CheckUpdate(ctx, true)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -173,8 +174,11 @@ func (s *UpdateService) PerformUpdate(ctx context.Context) error {
|
|||||||
return fmt.Errorf("failed to resolve symlinks: %w", err)
|
return fmt.Errorf("failed to resolve symlinks: %w", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Create temp directory for extraction
|
exeDir := filepath.Dir(exePath)
|
||||||
tempDir, err := os.MkdirTemp("", "sub2api-update-*")
|
|
||||||
|
// Create temp directory in the SAME directory as executable
|
||||||
|
// This ensures os.Rename is atomic (same filesystem)
|
||||||
|
tempDir, err := os.MkdirTemp(exeDir, ".sub2api-update-*")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return fmt.Errorf("failed to create temp dir: %w", err)
|
return fmt.Errorf("failed to create temp dir: %w", err)
|
||||||
}
|
}
|
||||||
@@ -199,23 +203,36 @@ func (s *UpdateService) PerformUpdate(ctx context.Context) error {
|
|||||||
return fmt.Errorf("extraction failed: %w", err)
|
return fmt.Errorf("extraction failed: %w", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Backup current binary
|
// Set executable permission before replacement
|
||||||
backupFile := exePath + ".backup"
|
if err := os.Chmod(newBinaryPath, 0755); err != nil {
|
||||||
if err := os.Rename(exePath, backupFile); err != nil {
|
|
||||||
return fmt.Errorf("backup failed: %w", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Replace with new binary
|
|
||||||
if err := copyFile(newBinaryPath, exePath); err != nil {
|
|
||||||
os.Rename(backupFile, exePath)
|
|
||||||
return fmt.Errorf("replace failed: %w", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Make executable
|
|
||||||
if err := os.Chmod(exePath, 0755); err != nil {
|
|
||||||
return fmt.Errorf("chmod failed: %w", err)
|
return fmt.Errorf("chmod failed: %w", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Atomic replacement using rename pattern:
|
||||||
|
// 1. Rename current -> backup (atomic on Unix)
|
||||||
|
// 2. Rename new -> current (atomic on Unix, same filesystem)
|
||||||
|
// If step 2 fails, restore backup
|
||||||
|
backupPath := exePath + ".backup"
|
||||||
|
|
||||||
|
// Remove old backup if exists
|
||||||
|
os.Remove(backupPath)
|
||||||
|
|
||||||
|
// Step 1: Move current binary to backup
|
||||||
|
if err := os.Rename(exePath, backupPath); err != nil {
|
||||||
|
return fmt.Errorf("backup failed: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Step 2: Move new binary to target location (atomic, same filesystem)
|
||||||
|
if err := os.Rename(newBinaryPath, exePath); err != nil {
|
||||||
|
// Restore backup on failure
|
||||||
|
if restoreErr := os.Rename(backupPath, exePath); restoreErr != nil {
|
||||||
|
return fmt.Errorf("replace failed and restore failed: %w (restore error: %v)", err, restoreErr)
|
||||||
|
}
|
||||||
|
return fmt.Errorf("replace failed (restored backup): %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Success - backup file is kept for rollback capability
|
||||||
|
// It will be cleaned up on next successful update
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -515,23 +532,6 @@ func (s *UpdateService) extractBinary(archivePath, destPath string) error {
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
func copyFile(src, dst string) error {
|
|
||||||
in, err := os.Open(src)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
defer in.Close()
|
|
||||||
|
|
||||||
out, err := os.Create(dst)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
defer out.Close()
|
|
||||||
|
|
||||||
_, err = io.Copy(out, in)
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *UpdateService) getFromCache(ctx context.Context) (*UpdateInfo, error) {
|
func (s *UpdateService) getFromCache(ctx context.Context) (*UpdateInfo, error) {
|
||||||
data, err := s.rdb.Get(ctx, updateCacheKey).Result()
|
data, err := s.rdb.Get(ctx, updateCacheKey).Result()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
|||||||
@@ -73,9 +73,6 @@ declare -A MSG_ZH=(
|
|||||||
["dirs_configured"]="目录配置完成"
|
["dirs_configured"]="目录配置完成"
|
||||||
["installing_service"]="正在安装 systemd 服务..."
|
["installing_service"]="正在安装 systemd 服务..."
|
||||||
["service_installed"]="systemd 服务已安装"
|
["service_installed"]="systemd 服务已安装"
|
||||||
["setting_up_sudoers"]="正在配置 sudoers..."
|
|
||||||
["sudoers_configured"]="sudoers 配置完成"
|
|
||||||
["sudoers_failed"]="sudoers 验证失败,已移除文件"
|
|
||||||
["ready_for_setup"]="准备就绪,可以启动设置向导"
|
["ready_for_setup"]="准备就绪,可以启动设置向导"
|
||||||
|
|
||||||
# Completion
|
# Completion
|
||||||
@@ -131,6 +128,15 @@ declare -A MSG_ZH=(
|
|||||||
["server_port_hint"]="建议使用 1024-65535 之间的端口"
|
["server_port_hint"]="建议使用 1024-65535 之间的端口"
|
||||||
["server_config_summary"]="服务器配置"
|
["server_config_summary"]="服务器配置"
|
||||||
["invalid_port"]="无效端口号,请输入 1-65535 之间的数字"
|
["invalid_port"]="无效端口号,请输入 1-65535 之间的数字"
|
||||||
|
|
||||||
|
# Service management
|
||||||
|
["starting_service"]="正在启动服务..."
|
||||||
|
["service_started"]="服务已启动"
|
||||||
|
["service_start_failed"]="服务启动失败,请检查日志"
|
||||||
|
["enabling_autostart"]="正在设置开机自启..."
|
||||||
|
["autostart_enabled"]="开机自启已启用"
|
||||||
|
["getting_public_ip"]="正在获取公网 IP..."
|
||||||
|
["public_ip_failed"]="无法获取公网 IP,使用本地 IP"
|
||||||
)
|
)
|
||||||
|
|
||||||
# English strings
|
# English strings
|
||||||
@@ -173,9 +179,6 @@ declare -A MSG_EN=(
|
|||||||
["dirs_configured"]="Directories configured"
|
["dirs_configured"]="Directories configured"
|
||||||
["installing_service"]="Installing systemd service..."
|
["installing_service"]="Installing systemd service..."
|
||||||
["service_installed"]="Systemd service installed"
|
["service_installed"]="Systemd service installed"
|
||||||
["setting_up_sudoers"]="Setting up sudoers..."
|
|
||||||
["sudoers_configured"]="Sudoers configured"
|
|
||||||
["sudoers_failed"]="Sudoers validation failed, removing file"
|
|
||||||
["ready_for_setup"]="Ready for Setup Wizard"
|
["ready_for_setup"]="Ready for Setup Wizard"
|
||||||
|
|
||||||
# Completion
|
# Completion
|
||||||
@@ -231,6 +234,15 @@ declare -A MSG_EN=(
|
|||||||
["server_port_hint"]="Recommended range: 1024-65535"
|
["server_port_hint"]="Recommended range: 1024-65535"
|
||||||
["server_config_summary"]="Server configuration"
|
["server_config_summary"]="Server configuration"
|
||||||
["invalid_port"]="Invalid port number, please enter a number between 1-65535"
|
["invalid_port"]="Invalid port number, please enter a number between 1-65535"
|
||||||
|
|
||||||
|
# Service management
|
||||||
|
["starting_service"]="Starting service..."
|
||||||
|
["service_started"]="Service started"
|
||||||
|
["service_start_failed"]="Service failed to start, please check logs"
|
||||||
|
["enabling_autostart"]="Enabling auto-start on boot..."
|
||||||
|
["autostart_enabled"]="Auto-start enabled"
|
||||||
|
["getting_public_ip"]="Getting public IP..."
|
||||||
|
["public_ip_failed"]="Failed to get public IP, using local IP"
|
||||||
)
|
)
|
||||||
|
|
||||||
# Get message based on current language
|
# Get message based on current language
|
||||||
@@ -260,9 +272,11 @@ print_error() {
|
|||||||
echo -e "${RED}[$(msg 'error')]${NC} $1"
|
echo -e "${RED}[$(msg 'error')]${NC} $1"
|
||||||
}
|
}
|
||||||
|
|
||||||
# Check if running interactively (stdin is a terminal)
|
# Check if running interactively (can access terminal)
|
||||||
|
# When piped (curl | bash), stdin is not a terminal, but /dev/tty may still be available
|
||||||
is_interactive() {
|
is_interactive() {
|
||||||
[ -t 0 ]
|
# Check if /dev/tty is available (works even when piped)
|
||||||
|
[ -e /dev/tty ] && [ -r /dev/tty ] && [ -w /dev/tty ]
|
||||||
}
|
}
|
||||||
|
|
||||||
# Select language
|
# Select language
|
||||||
@@ -282,7 +296,7 @@ select_language() {
|
|||||||
echo " 2) $(msg 'lang_en')"
|
echo " 2) $(msg 'lang_en')"
|
||||||
echo ""
|
echo ""
|
||||||
|
|
||||||
read -p "$(msg 'enter_choice'): " lang_input
|
read -p "$(msg 'enter_choice'): " lang_input < /dev/tty
|
||||||
|
|
||||||
case "$lang_input" in
|
case "$lang_input" in
|
||||||
2|en|EN|english|English)
|
2|en|EN|english|English)
|
||||||
@@ -323,7 +337,7 @@ configure_server() {
|
|||||||
|
|
||||||
# Server host
|
# Server host
|
||||||
echo -e "${YELLOW}$(msg 'server_host_hint')${NC}"
|
echo -e "${YELLOW}$(msg 'server_host_hint')${NC}"
|
||||||
read -p "$(msg 'server_host_prompt') [${SERVER_HOST}]: " input_host
|
read -p "$(msg 'server_host_prompt') [${SERVER_HOST}]: " input_host < /dev/tty
|
||||||
if [ -n "$input_host" ]; then
|
if [ -n "$input_host" ]; then
|
||||||
SERVER_HOST="$input_host"
|
SERVER_HOST="$input_host"
|
||||||
fi
|
fi
|
||||||
@@ -333,7 +347,7 @@ configure_server() {
|
|||||||
# Server port
|
# Server port
|
||||||
echo -e "${YELLOW}$(msg 'server_port_hint')${NC}"
|
echo -e "${YELLOW}$(msg 'server_port_hint')${NC}"
|
||||||
while true; do
|
while true; do
|
||||||
read -p "$(msg 'server_port_prompt') [${SERVER_PORT}]: " input_port
|
read -p "$(msg 'server_port_prompt') [${SERVER_PORT}]: " input_port < /dev/tty
|
||||||
if [ -z "$input_port" ]; then
|
if [ -z "$input_port" ]; then
|
||||||
# Use default
|
# Use default
|
||||||
break
|
break
|
||||||
@@ -521,35 +535,6 @@ setup_directories() {
|
|||||||
print_success "$(msg 'dirs_configured')"
|
print_success "$(msg 'dirs_configured')"
|
||||||
}
|
}
|
||||||
|
|
||||||
# Setup sudoers for service restart
|
|
||||||
setup_sudoers() {
|
|
||||||
print_info "$(msg 'setting_up_sudoers')"
|
|
||||||
|
|
||||||
# Always generate sudoers file from script (not from tar.gz)
|
|
||||||
# This ensures the latest configuration is used even with older releases
|
|
||||||
# Support both /bin/systemctl and /usr/bin/systemctl for different distros
|
|
||||||
cat > /etc/sudoers.d/sub2api << 'EOF'
|
|
||||||
# Sudoers configuration for Sub2API
|
|
||||||
sub2api ALL=(ALL) NOPASSWD: /bin/systemctl restart sub2api
|
|
||||||
sub2api ALL=(ALL) NOPASSWD: /bin/systemctl stop sub2api
|
|
||||||
sub2api ALL=(ALL) NOPASSWD: /bin/systemctl start sub2api
|
|
||||||
sub2api ALL=(ALL) NOPASSWD: /usr/bin/systemctl restart sub2api
|
|
||||||
sub2api ALL=(ALL) NOPASSWD: /usr/bin/systemctl stop sub2api
|
|
||||||
sub2api ALL=(ALL) NOPASSWD: /usr/bin/systemctl start sub2api
|
|
||||||
EOF
|
|
||||||
|
|
||||||
# Set correct permissions (required for sudoers files)
|
|
||||||
chmod 440 /etc/sudoers.d/sub2api
|
|
||||||
|
|
||||||
# Validate sudoers file
|
|
||||||
if visudo -c -f /etc/sudoers.d/sub2api &>/dev/null; then
|
|
||||||
print_success "$(msg 'sudoers_configured')"
|
|
||||||
else
|
|
||||||
print_warning "$(msg 'sudoers_failed')"
|
|
||||||
rm -f /etc/sudoers.d/sub2api
|
|
||||||
fi
|
|
||||||
}
|
|
||||||
|
|
||||||
# Install systemd service
|
# Install systemd service
|
||||||
install_service() {
|
install_service() {
|
||||||
print_info "$(msg 'installing_service')"
|
print_info "$(msg 'installing_service')"
|
||||||
@@ -601,13 +586,61 @@ prepare_for_setup() {
|
|||||||
print_success "$(msg 'ready_for_setup')"
|
print_success "$(msg 'ready_for_setup')"
|
||||||
}
|
}
|
||||||
|
|
||||||
|
# Get public IP address
|
||||||
|
get_public_ip() {
|
||||||
|
print_info "$(msg 'getting_public_ip')"
|
||||||
|
|
||||||
|
# Try to get public IP from ipinfo.io
|
||||||
|
local response
|
||||||
|
response=$(curl -s --connect-timeout 5 --max-time 10 "https://ipinfo.io/json" 2>/dev/null)
|
||||||
|
|
||||||
|
if [ -n "$response" ]; then
|
||||||
|
# Extract IP from JSON response using grep and sed (no jq dependency)
|
||||||
|
PUBLIC_IP=$(echo "$response" | grep -o '"ip": *"[^"]*"' | sed 's/"ip": *"\([^"]*\)"/\1/')
|
||||||
|
if [ -n "$PUBLIC_IP" ]; then
|
||||||
|
print_success "Public IP: $PUBLIC_IP"
|
||||||
|
return 0
|
||||||
|
fi
|
||||||
|
fi
|
||||||
|
|
||||||
|
# Fallback to local IP
|
||||||
|
print_warning "$(msg 'public_ip_failed')"
|
||||||
|
PUBLIC_IP=$(hostname -I 2>/dev/null | awk '{print $1}' || echo "YOUR_SERVER_IP")
|
||||||
|
return 1
|
||||||
|
}
|
||||||
|
|
||||||
|
# Start service
|
||||||
|
start_service() {
|
||||||
|
print_info "$(msg 'starting_service')"
|
||||||
|
|
||||||
|
if systemctl start sub2api; then
|
||||||
|
print_success "$(msg 'service_started')"
|
||||||
|
return 0
|
||||||
|
else
|
||||||
|
print_error "$(msg 'service_start_failed')"
|
||||||
|
print_info "sudo journalctl -u sub2api -n 50"
|
||||||
|
return 1
|
||||||
|
fi
|
||||||
|
}
|
||||||
|
|
||||||
|
# Enable service auto-start
|
||||||
|
enable_autostart() {
|
||||||
|
print_info "$(msg 'enabling_autostart')"
|
||||||
|
|
||||||
|
if systemctl enable sub2api 2>/dev/null; then
|
||||||
|
print_success "$(msg 'autostart_enabled')"
|
||||||
|
return 0
|
||||||
|
else
|
||||||
|
print_warning "Failed to enable auto-start"
|
||||||
|
return 1
|
||||||
|
fi
|
||||||
|
}
|
||||||
|
|
||||||
# Print completion message
|
# Print completion message
|
||||||
print_completion() {
|
print_completion() {
|
||||||
local ip_addr
|
# Use PUBLIC_IP which was set by get_public_ip()
|
||||||
ip_addr=$(hostname -I 2>/dev/null | awk '{print $1}' || echo "YOUR_SERVER_IP")
|
|
||||||
|
|
||||||
# Determine display address
|
# Determine display address
|
||||||
local display_host="$ip_addr"
|
local display_host="${PUBLIC_IP:-YOUR_SERVER_IP}"
|
||||||
if [ "$SERVER_HOST" = "127.0.0.1" ]; then
|
if [ "$SERVER_HOST" = "127.0.0.1" ]; then
|
||||||
display_host="127.0.0.1"
|
display_host="127.0.0.1"
|
||||||
fi
|
fi
|
||||||
@@ -621,21 +654,9 @@ print_completion() {
|
|||||||
echo "$(msg 'server_config_summary'): ${SERVER_HOST}:${SERVER_PORT}"
|
echo "$(msg 'server_config_summary'): ${SERVER_HOST}:${SERVER_PORT}"
|
||||||
echo ""
|
echo ""
|
||||||
echo "=============================================="
|
echo "=============================================="
|
||||||
echo " $(msg 'next_steps')"
|
echo " $(msg 'step4_open_wizard')"
|
||||||
echo "=============================================="
|
echo "=============================================="
|
||||||
echo ""
|
echo ""
|
||||||
echo " 1. $(msg 'step1_check_services')"
|
|
||||||
echo " sudo systemctl status postgresql"
|
|
||||||
echo " sudo systemctl status redis"
|
|
||||||
echo ""
|
|
||||||
echo " 2. $(msg 'step2_start_service')"
|
|
||||||
echo " sudo systemctl start sub2api"
|
|
||||||
echo ""
|
|
||||||
echo " 3. $(msg 'step3_enable_autostart')"
|
|
||||||
echo " sudo systemctl enable sub2api"
|
|
||||||
echo ""
|
|
||||||
echo " 4. $(msg 'step4_open_wizard')"
|
|
||||||
echo ""
|
|
||||||
print_info " http://${display_host}:${SERVER_PORT}"
|
print_info " http://${display_host}:${SERVER_PORT}"
|
||||||
echo ""
|
echo ""
|
||||||
echo " $(msg 'wizard_guide')"
|
echo " $(msg 'wizard_guide')"
|
||||||
@@ -702,7 +723,7 @@ uninstall() {
|
|||||||
exit 1
|
exit 1
|
||||||
fi
|
fi
|
||||||
else
|
else
|
||||||
read -p "$(msg 'are_you_sure') " -n 1 -r
|
read -p "$(msg 'are_you_sure') " -n 1 -r < /dev/tty
|
||||||
echo
|
echo
|
||||||
if [[ ! $REPLY =~ ^[Yy]$ ]]; then
|
if [[ ! $REPLY =~ ^[Yy]$ ]]; then
|
||||||
print_info "$(msg 'uninstall_cancelled')"
|
print_info "$(msg 'uninstall_cancelled')"
|
||||||
@@ -716,7 +737,6 @@ uninstall() {
|
|||||||
|
|
||||||
print_info "$(msg 'removing_files')"
|
print_info "$(msg 'removing_files')"
|
||||||
rm -f /etc/systemd/system/sub2api.service
|
rm -f /etc/systemd/system/sub2api.service
|
||||||
rm -f /etc/sudoers.d/sub2api
|
|
||||||
systemctl daemon-reload
|
systemctl daemon-reload
|
||||||
|
|
||||||
print_info "$(msg 'removing_install_dir')"
|
print_info "$(msg 'removing_install_dir')"
|
||||||
@@ -787,8 +807,10 @@ main() {
|
|||||||
create_user
|
create_user
|
||||||
setup_directories
|
setup_directories
|
||||||
install_service
|
install_service
|
||||||
setup_sudoers
|
|
||||||
prepare_for_setup
|
prepare_for_setup
|
||||||
|
get_public_ip
|
||||||
|
start_service
|
||||||
|
enable_autostart
|
||||||
print_completion
|
print_completion
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,17 +0,0 @@
|
|||||||
# Sudoers configuration for Sub2API
|
|
||||||
# This file allows the sub2api service user to restart the service without password
|
|
||||||
#
|
|
||||||
# Installation:
|
|
||||||
# sudo cp sub2api-sudoers /etc/sudoers.d/sub2api
|
|
||||||
# sudo chmod 440 /etc/sudoers.d/sub2api
|
|
||||||
#
|
|
||||||
# SECURITY NOTE: This grants limited sudo access only for service management
|
|
||||||
|
|
||||||
# Allow sub2api user to restart the service without password
|
|
||||||
# Support both /bin/systemctl (Debian/Ubuntu) and /usr/bin/systemctl (RHEL/CentOS)
|
|
||||||
sub2api ALL=(ALL) NOPASSWD: /bin/systemctl restart sub2api
|
|
||||||
sub2api ALL=(ALL) NOPASSWD: /bin/systemctl stop sub2api
|
|
||||||
sub2api ALL=(ALL) NOPASSWD: /bin/systemctl start sub2api
|
|
||||||
sub2api ALL=(ALL) NOPASSWD: /usr/bin/systemctl restart sub2api
|
|
||||||
sub2api ALL=(ALL) NOPASSWD: /usr/bin/systemctl stop sub2api
|
|
||||||
sub2api ALL=(ALL) NOPASSWD: /usr/bin/systemctl start sub2api
|
|
||||||
@@ -40,9 +40,42 @@ export async function checkUpdates(force = false): Promise<VersionInfo> {
|
|||||||
return data;
|
return data;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export interface UpdateResult {
|
||||||
|
message: string;
|
||||||
|
need_restart: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Perform system update
|
||||||
|
* Downloads and applies the latest version
|
||||||
|
*/
|
||||||
|
export async function performUpdate(): Promise<UpdateResult> {
|
||||||
|
const { data } = await apiClient.post<UpdateResult>('/admin/system/update');
|
||||||
|
return data;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Rollback to previous version
|
||||||
|
*/
|
||||||
|
export async function rollback(): Promise<UpdateResult> {
|
||||||
|
const { data } = await apiClient.post<UpdateResult>('/admin/system/rollback');
|
||||||
|
return data;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Restart the service
|
||||||
|
*/
|
||||||
|
export async function restartService(): Promise<{ message: string }> {
|
||||||
|
const { data } = await apiClient.post<{ message: string }>('/admin/system/restart');
|
||||||
|
return data;
|
||||||
|
}
|
||||||
|
|
||||||
export const systemAPI = {
|
export const systemAPI = {
|
||||||
getVersion,
|
getVersion,
|
||||||
checkUpdates,
|
checkUpdates,
|
||||||
|
performUpdate,
|
||||||
|
rollback,
|
||||||
|
restartService,
|
||||||
};
|
};
|
||||||
|
|
||||||
export default systemAPI;
|
export default systemAPI;
|
||||||
|
|||||||
@@ -69,8 +69,63 @@
|
|||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<!-- Update available for source build - show git pull hint -->
|
<!-- Priority 1: Update error (must check before hasUpdate) -->
|
||||||
<div v-if="hasUpdate && !isReleaseBuild" class="space-y-2">
|
<div v-if="updateError" class="space-y-2">
|
||||||
|
<div class="flex items-center gap-3 p-3 rounded-lg bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800/50">
|
||||||
|
<div class="flex-shrink-0 w-8 h-8 rounded-full bg-red-100 dark:bg-red-900/50 flex items-center justify-center">
|
||||||
|
<svg class="w-4 h-4 text-red-600 dark:text-red-400" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
|
||||||
|
<path stroke-linecap="round" stroke-linejoin="round" d="M6 18L18 6M6 6l12 12" />
|
||||||
|
</svg>
|
||||||
|
</div>
|
||||||
|
<div class="flex-1 min-w-0">
|
||||||
|
<p class="text-sm font-medium text-red-700 dark:text-red-300">{{ t('version.updateFailed') }}</p>
|
||||||
|
<p class="text-xs text-red-600/70 dark:text-red-400/70 truncate">{{ updateError }}</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- Retry button -->
|
||||||
|
<button
|
||||||
|
@click="handleUpdate"
|
||||||
|
:disabled="updating"
|
||||||
|
class="w-full flex items-center justify-center gap-2 px-4 py-2 rounded-lg text-sm font-medium text-white bg-red-500 hover:bg-red-600 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
|
||||||
|
>
|
||||||
|
{{ t('version.retry') }}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- Priority 2: Update success - need restart -->
|
||||||
|
<div v-else-if="updateSuccess && needRestart" class="space-y-2">
|
||||||
|
<div class="flex items-center gap-3 p-3 rounded-lg bg-green-50 dark:bg-green-900/20 border border-green-200 dark:border-green-800/50">
|
||||||
|
<div class="flex-shrink-0 w-8 h-8 rounded-full bg-green-100 dark:bg-green-900/50 flex items-center justify-center">
|
||||||
|
<svg class="w-4 h-4 text-green-600 dark:text-green-400" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
|
||||||
|
<path stroke-linecap="round" stroke-linejoin="round" d="M5 13l4 4L19 7" />
|
||||||
|
</svg>
|
||||||
|
</div>
|
||||||
|
<div class="flex-1 min-w-0">
|
||||||
|
<p class="text-sm font-medium text-green-700 dark:text-green-300">{{ t('version.updateComplete') }}</p>
|
||||||
|
<p class="text-xs text-green-600/70 dark:text-green-400/70">{{ t('version.restartRequired') }}</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- Restart button -->
|
||||||
|
<button
|
||||||
|
@click="handleRestart"
|
||||||
|
:disabled="restarting"
|
||||||
|
class="w-full flex items-center justify-center gap-2 px-4 py-2 rounded-lg text-sm font-medium text-white bg-green-500 hover:bg-green-600 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
|
||||||
|
>
|
||||||
|
<svg v-if="restarting" class="animate-spin h-4 w-4" fill="none" viewBox="0 0 24 24">
|
||||||
|
<circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
|
||||||
|
<path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
|
||||||
|
</svg>
|
||||||
|
<svg v-else class="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
|
||||||
|
<path stroke-linecap="round" stroke-linejoin="round" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15" />
|
||||||
|
</svg>
|
||||||
|
{{ restarting ? t('version.restarting') : t('version.restartNow') }}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- Priority 3: Update available for source build - show git pull hint -->
|
||||||
|
<div v-else-if="hasUpdate && !isReleaseBuild" class="space-y-2">
|
||||||
<a
|
<a
|
||||||
v-if="releaseInfo?.html_url && releaseInfo.html_url !== '#'"
|
v-if="releaseInfo?.html_url && releaseInfo.html_url !== '#'"
|
||||||
:href="releaseInfo.html_url"
|
:href="releaseInfo.html_url"
|
||||||
@@ -100,29 +155,53 @@
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<!-- Update available for release build - show download link -->
|
<!-- Priority 4: Update available for release build - show update button -->
|
||||||
<a
|
<div v-else-if="hasUpdate && isReleaseBuild" class="space-y-2">
|
||||||
v-else-if="hasUpdate && isReleaseBuild && releaseInfo?.html_url && releaseInfo.html_url !== '#'"
|
<!-- Update info card -->
|
||||||
:href="releaseInfo.html_url"
|
<div class="flex items-center gap-3 p-3 rounded-lg bg-amber-50 dark:bg-amber-900/20 border border-amber-200 dark:border-amber-800/50">
|
||||||
target="_blank"
|
<div class="flex-shrink-0 w-8 h-8 rounded-full bg-amber-100 dark:bg-amber-900/50 flex items-center justify-center">
|
||||||
rel="noopener noreferrer"
|
<svg class="w-4 h-4 text-amber-600 dark:text-amber-400" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
|
||||||
class="flex items-center gap-3 p-3 rounded-lg bg-amber-50 dark:bg-amber-900/20 border border-amber-200 dark:border-amber-800/50 hover:bg-amber-100 dark:hover:bg-amber-900/30 transition-colors group"
|
<path stroke-linecap="round" stroke-linejoin="round" d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4" />
|
||||||
>
|
</svg>
|
||||||
<div class="flex-shrink-0 w-8 h-8 rounded-full bg-amber-100 dark:bg-amber-900/50 flex items-center justify-center">
|
</div>
|
||||||
<svg class="w-4 h-4 text-amber-600 dark:text-amber-400" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
|
<div class="flex-1 min-w-0">
|
||||||
|
<p class="text-sm font-medium text-amber-700 dark:text-amber-300">{{ t('version.updateAvailable') }}</p>
|
||||||
|
<p class="text-xs text-amber-600/70 dark:text-amber-400/70">v{{ latestVersion }}</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- Update button -->
|
||||||
|
<button
|
||||||
|
@click="handleUpdate"
|
||||||
|
:disabled="updating"
|
||||||
|
class="w-full flex items-center justify-center gap-2 px-4 py-2 rounded-lg text-sm font-medium text-white bg-primary-500 hover:bg-primary-600 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
|
||||||
|
>
|
||||||
|
<svg v-if="updating" class="animate-spin h-4 w-4" fill="none" viewBox="0 0 24 24">
|
||||||
|
<circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
|
||||||
|
<path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
|
||||||
|
</svg>
|
||||||
|
<svg v-else class="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
|
||||||
<path stroke-linecap="round" stroke-linejoin="round" d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4" />
|
<path stroke-linecap="round" stroke-linejoin="round" d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4" />
|
||||||
</svg>
|
</svg>
|
||||||
</div>
|
{{ updating ? t('version.updating') : t('version.updateNow') }}
|
||||||
<div class="flex-1 min-w-0">
|
</button>
|
||||||
<p class="text-sm font-medium text-amber-700 dark:text-amber-300">{{ t('version.updateAvailable') }}</p>
|
|
||||||
<p class="text-xs text-amber-600/70 dark:text-amber-400/70">v{{ latestVersion }}</p>
|
|
||||||
</div>
|
|
||||||
<svg class="w-4 h-4 text-amber-500 dark:text-amber-400 group-hover:translate-x-0.5 transition-transform" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
|
|
||||||
<path stroke-linecap="round" stroke-linejoin="round" d="M9 5l7 7-7 7" />
|
|
||||||
</svg>
|
|
||||||
</a>
|
|
||||||
|
|
||||||
<!-- GitHub link when up to date -->
|
<!-- View release link -->
|
||||||
|
<a
|
||||||
|
v-if="releaseInfo?.html_url && releaseInfo.html_url !== '#'"
|
||||||
|
:href="releaseInfo.html_url"
|
||||||
|
target="_blank"
|
||||||
|
rel="noopener noreferrer"
|
||||||
|
class="flex items-center justify-center gap-1 text-xs text-gray-500 dark:text-dark-400 hover:text-gray-700 dark:hover:text-dark-200 transition-colors"
|
||||||
|
>
|
||||||
|
{{ t('version.viewChangelog') }}
|
||||||
|
<svg class="w-3 h-3" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
|
||||||
|
<path stroke-linecap="round" stroke-linejoin="round" d="M10 6H6a2 2 0 00-2 2v10a2 2 0 002 2h10a2 2 0 002-2v-4M14 4h6m0 0v6m0-6L10 14" />
|
||||||
|
</svg>
|
||||||
|
</a>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- Priority 5: Up to date - show GitHub link -->
|
||||||
<a
|
<a
|
||||||
v-else-if="releaseInfo?.html_url && releaseInfo.html_url !== '#'"
|
v-else-if="releaseInfo?.html_url && releaseInfo.html_url !== '#'"
|
||||||
:href="releaseInfo.html_url"
|
:href="releaseInfo.html_url"
|
||||||
@@ -155,7 +234,7 @@
|
|||||||
import { ref, computed, onMounted, onBeforeUnmount } from 'vue';
|
import { ref, computed, onMounted, onBeforeUnmount } from 'vue';
|
||||||
import { useI18n } from 'vue-i18n';
|
import { useI18n } from 'vue-i18n';
|
||||||
import { useAuthStore } from '@/stores';
|
import { useAuthStore } from '@/stores';
|
||||||
import { checkUpdates, type VersionInfo, type ReleaseInfo } from '@/api/admin/system';
|
import { checkUpdates, performUpdate, restartService, type VersionInfo, type ReleaseInfo } from '@/api/admin/system';
|
||||||
|
|
||||||
const { t } = useI18n();
|
const { t } = useI18n();
|
||||||
|
|
||||||
@@ -177,6 +256,13 @@ const hasUpdate = ref(false);
|
|||||||
const releaseInfo = ref<ReleaseInfo | null>(null);
|
const releaseInfo = ref<ReleaseInfo | null>(null);
|
||||||
const buildType = ref('source'); // "source" or "release"
|
const buildType = ref('source'); // "source" or "release"
|
||||||
|
|
||||||
|
// Update process states
|
||||||
|
const updating = ref(false);
|
||||||
|
const restarting = ref(false);
|
||||||
|
const needRestart = ref(false);
|
||||||
|
const updateError = ref('');
|
||||||
|
const updateSuccess = ref(false);
|
||||||
|
|
||||||
// Only show update check for release builds (binary/docker deployment)
|
// Only show update check for release builds (binary/docker deployment)
|
||||||
const isReleaseBuild = computed(() => buildType.value === 'release');
|
const isReleaseBuild = computed(() => buildType.value === 'release');
|
||||||
|
|
||||||
@@ -200,6 +286,10 @@ async function refreshVersion(force = true) {
|
|||||||
// Show update indicator for all build types
|
// Show update indicator for all build types
|
||||||
hasUpdate.value = data.has_update;
|
hasUpdate.value = data.has_update;
|
||||||
releaseInfo.value = data.release_info || null;
|
releaseInfo.value = data.release_info || null;
|
||||||
|
// Reset update states when refreshing
|
||||||
|
updateError.value = '';
|
||||||
|
updateSuccess.value = false;
|
||||||
|
needRestart.value = false;
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Failed to check updates:', error);
|
console.error('Failed to check updates:', error);
|
||||||
} finally {
|
} finally {
|
||||||
@@ -207,6 +297,45 @@ async function refreshVersion(force = true) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async function handleUpdate() {
|
||||||
|
if (updating.value) return;
|
||||||
|
|
||||||
|
updating.value = true;
|
||||||
|
updateError.value = '';
|
||||||
|
updateSuccess.value = false;
|
||||||
|
|
||||||
|
try {
|
||||||
|
const result = await performUpdate();
|
||||||
|
updateSuccess.value = true;
|
||||||
|
needRestart.value = result.need_restart;
|
||||||
|
hasUpdate.value = false;
|
||||||
|
} catch (error: unknown) {
|
||||||
|
const err = error as { response?: { data?: { message?: string } }; message?: string };
|
||||||
|
updateError.value = err.response?.data?.message || err.message || t('version.updateFailed');
|
||||||
|
} finally {
|
||||||
|
updating.value = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function handleRestart() {
|
||||||
|
if (restarting.value) return;
|
||||||
|
|
||||||
|
restarting.value = true;
|
||||||
|
|
||||||
|
try {
|
||||||
|
await restartService();
|
||||||
|
// Service will restart, page will reload automatically or show disconnected
|
||||||
|
} catch (error) {
|
||||||
|
// Expected - connection will be lost during restart
|
||||||
|
console.log('Service restarting...');
|
||||||
|
}
|
||||||
|
|
||||||
|
// Show restarting state for a while, then reload
|
||||||
|
setTimeout(() => {
|
||||||
|
window.location.reload();
|
||||||
|
}, 3000);
|
||||||
|
}
|
||||||
|
|
||||||
function handleClickOutside(event: MouseEvent) {
|
function handleClickOutside(event: MouseEvent) {
|
||||||
const target = event.target as Node;
|
const target = event.target as Node;
|
||||||
const button = (event.target as Element).closest('button');
|
const button = (event.target as Element).closest('button');
|
||||||
|
|||||||
@@ -1023,9 +1023,18 @@ export default {
|
|||||||
noReleaseNotes: 'No release notes',
|
noReleaseNotes: 'No release notes',
|
||||||
viewUpdate: 'View Update',
|
viewUpdate: 'View Update',
|
||||||
viewRelease: 'View Release',
|
viewRelease: 'View Release',
|
||||||
|
viewChangelog: 'View Changelog',
|
||||||
refresh: 'Refresh',
|
refresh: 'Refresh',
|
||||||
sourceMode: 'Source Build',
|
sourceMode: 'Source Build',
|
||||||
sourceModeHint: 'Update detection is disabled for source builds. Use git pull to update.',
|
sourceModeHint: 'Source build, use git pull to update',
|
||||||
|
updateNow: 'Update Now',
|
||||||
|
updating: 'Updating...',
|
||||||
|
updateComplete: 'Update Complete',
|
||||||
|
updateFailed: 'Update Failed',
|
||||||
|
restartRequired: 'Please restart the service to apply the update',
|
||||||
|
restartNow: 'Restart Now',
|
||||||
|
restarting: 'Restarting...',
|
||||||
|
retry: 'Retry',
|
||||||
},
|
},
|
||||||
|
|
||||||
// User Subscriptions Page
|
// User Subscriptions Page
|
||||||
|
|||||||
@@ -1202,9 +1202,18 @@ export default {
|
|||||||
noReleaseNotes: '暂无更新日志',
|
noReleaseNotes: '暂无更新日志',
|
||||||
viewUpdate: '查看更新',
|
viewUpdate: '查看更新',
|
||||||
viewRelease: '查看发布',
|
viewRelease: '查看发布',
|
||||||
|
viewChangelog: '查看更新日志',
|
||||||
refresh: '刷新',
|
refresh: '刷新',
|
||||||
sourceMode: '源码构建',
|
sourceMode: '源码构建',
|
||||||
sourceModeHint: '源码构建模式不支持更新检测,请使用 git pull 更新代码。',
|
sourceModeHint: '源码构建请使用 git pull 更新',
|
||||||
|
updateNow: '立即更新',
|
||||||
|
updating: '正在更新...',
|
||||||
|
updateComplete: '更新完成',
|
||||||
|
updateFailed: '更新失败',
|
||||||
|
restartRequired: '请重启服务以应用更新',
|
||||||
|
restartNow: '立即重启',
|
||||||
|
restarting: '正在重启...',
|
||||||
|
retry: '重试',
|
||||||
},
|
},
|
||||||
|
|
||||||
// User Subscriptions Page
|
// User Subscriptions Page
|
||||||
|
|||||||
@@ -9,4 +9,8 @@ const app = createApp(App)
|
|||||||
app.use(createPinia())
|
app.use(createPinia())
|
||||||
app.use(router)
|
app.use(router)
|
||||||
app.use(i18n)
|
app.use(i18n)
|
||||||
app.mount('#app')
|
|
||||||
|
// 等待路由器完成初始导航后再挂载,避免竞态条件导致的空白渲染
|
||||||
|
router.isReady().then(() => {
|
||||||
|
app.mount('#app')
|
||||||
|
})
|
||||||
|
|||||||
Reference in New Issue
Block a user