mirror of
https://gitee.com/wanwujie/sub2api
synced 2026-04-06 00:10:21 +08:00
Compare commits
10 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f0e89992f7 | ||
|
|
4eaa0cf14a | ||
|
|
e9ec2280ec | ||
|
|
bb7bfb6980 | ||
|
|
b66f97c100 | ||
|
|
b51ad0d893 | ||
|
|
4eb22d8ee9 | ||
|
|
2392e7cf99 | ||
|
|
8e4bd42e8c | ||
|
|
ef3199f0ca |
3
.gitignore
vendored
3
.gitignore
vendored
@@ -91,4 +91,5 @@ backend/data/
|
||||
# ===================
|
||||
tests
|
||||
CLAUDE.md
|
||||
.claude
|
||||
.claude
|
||||
scripts
|
||||
@@ -107,7 +107,7 @@ sudo journalctl -u sub2api -f
|
||||
sudo systemctl restart sub2api
|
||||
|
||||
# Uninstall
|
||||
curl -sSL https://raw.githubusercontent.com/Wei-Shaw/sub2api/main/deploy/install.sh | sudo bash -s uninstall
|
||||
curl -sSL https://raw.githubusercontent.com/Wei-Shaw/sub2api/main/deploy/install.sh | sudo bash -s -- uninstall -y
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
@@ -107,7 +107,7 @@ sudo journalctl -u sub2api -f
|
||||
sudo systemctl restart sub2api
|
||||
|
||||
# 卸载
|
||||
curl -sSL https://raw.githubusercontent.com/Wei-Shaw/sub2api/main/deploy/install.sh | sudo bash -s uninstall
|
||||
curl -sSL https://raw.githubusercontent.com/Wei-Shaw/sub2api/main/deploy/install.sh | sudo bash -s -- uninstall -y
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
@@ -2,8 +2,10 @@ package admin
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"sub2api/internal/pkg/response"
|
||||
"sub2api/internal/pkg/sysutil"
|
||||
"sub2api/internal/service"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
@@ -72,10 +74,14 @@ func (h *SystemHandler) Rollback(c *gin.Context) {
|
||||
// RestartService restarts the systemd service
|
||||
// POST /api/v1/admin/system/restart
|
||||
func (h *SystemHandler) RestartService(c *gin.Context) {
|
||||
if err := h.updateSvc.RestartService(); err != nil {
|
||||
response.Error(c, http.StatusInternalServerError, err.Error())
|
||||
return
|
||||
}
|
||||
// Schedule service restart in background after sending response
|
||||
// This ensures the client receives the success response before the service restarts
|
||||
go func() {
|
||||
// Wait a moment to ensure the response is sent
|
||||
time.Sleep(500 * time.Millisecond)
|
||||
sysutil.RestartServiceAsync()
|
||||
}()
|
||||
|
||||
response.Success(c, gin.H{
|
||||
"message": "Service restart initiated",
|
||||
})
|
||||
|
||||
96
backend/internal/pkg/sysutil/restart.go
Normal file
96
backend/internal/pkg/sysutil/restart.go
Normal file
@@ -0,0 +1,96 @@
|
||||
package sysutil
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"log"
|
||||
"os"
|
||||
"os/exec"
|
||||
"runtime"
|
||||
)
|
||||
|
||||
const serviceName = "sub2api"
|
||||
|
||||
// findExecutable finds the full path of an executable
|
||||
// by checking common system paths
|
||||
func findExecutable(name string) string {
|
||||
// First try exec.LookPath (uses current PATH)
|
||||
if path, err := exec.LookPath(name); err == nil {
|
||||
return path
|
||||
}
|
||||
|
||||
// Fallback: check common paths
|
||||
commonPaths := []string{
|
||||
"/usr/bin/" + name,
|
||||
"/bin/" + name,
|
||||
"/usr/sbin/" + name,
|
||||
"/sbin/" + name,
|
||||
}
|
||||
|
||||
for _, path := range commonPaths {
|
||||
if _, err := os.Stat(path); err == nil {
|
||||
return path
|
||||
}
|
||||
}
|
||||
|
||||
// Return the name as-is and let exec fail with a clear error
|
||||
return name
|
||||
}
|
||||
|
||||
// RestartService triggers a service restart via systemd.
|
||||
//
|
||||
// IMPORTANT: This function initiates the restart and returns immediately.
|
||||
// The actual restart happens asynchronously - the current process will be killed
|
||||
// by systemd and a new process will be started.
|
||||
//
|
||||
// We use Start() instead of Run() because:
|
||||
// - systemctl restart will kill the current process first
|
||||
// - Run() waits for completion, but the process dies before completion
|
||||
// - Start() spawns the command independently, allowing systemd to handle the full cycle
|
||||
//
|
||||
// Prerequisites:
|
||||
// - Linux OS with systemd
|
||||
// - NOPASSWD sudo access configured (install.sh creates /etc/sudoers.d/sub2api)
|
||||
func RestartService() error {
|
||||
if runtime.GOOS != "linux" {
|
||||
return fmt.Errorf("systemd restart only available on Linux")
|
||||
}
|
||||
|
||||
log.Println("Initiating service restart...")
|
||||
|
||||
// Find full paths for sudo and systemctl
|
||||
// This ensures the commands work even if PATH is limited in systemd service
|
||||
sudoPath := findExecutable("sudo")
|
||||
systemctlPath := findExecutable("systemctl")
|
||||
|
||||
log.Printf("Using sudo: %s, systemctl: %s", sudoPath, systemctlPath)
|
||||
|
||||
// The sub2api user has NOPASSWD sudo access for systemctl commands
|
||||
// (configured by install.sh in /etc/sudoers.d/sub2api).
|
||||
// Use -n (non-interactive) to prevent sudo from waiting for password input
|
||||
//
|
||||
// Use setsid to create a new session, ensuring the child process
|
||||
// survives even if the parent process is killed by systemctl restart
|
||||
setsidPath := findExecutable("setsid")
|
||||
cmd := exec.Command(setsidPath, sudoPath, "-n", systemctlPath, "restart", serviceName)
|
||||
|
||||
// Detach from parent's stdio to ensure clean separation
|
||||
cmd.Stdin = nil
|
||||
cmd.Stdout = nil
|
||||
cmd.Stderr = nil
|
||||
|
||||
if err := cmd.Start(); err != nil {
|
||||
return fmt.Errorf("failed to initiate service restart: %w", err)
|
||||
}
|
||||
|
||||
log.Println("Service restart initiated successfully")
|
||||
return nil
|
||||
}
|
||||
|
||||
// RestartServiceAsync is a fire-and-forget version of RestartService.
|
||||
// It logs errors instead of returning them, suitable for goroutine usage.
|
||||
func RestartServiceAsync() {
|
||||
if err := RestartService(); err != nil {
|
||||
log.Printf("Service restart failed: %v", err)
|
||||
log.Println("Please restart the service manually: sudo systemctl restart sub2api")
|
||||
}
|
||||
}
|
||||
@@ -35,25 +35,25 @@ const (
|
||||
|
||||
// allowedHeaders 白名单headers(参考CRS项目)
|
||||
var allowedHeaders = map[string]bool{
|
||||
"accept": true,
|
||||
"x-stainless-retry-count": true,
|
||||
"x-stainless-timeout": true,
|
||||
"x-stainless-lang": true,
|
||||
"x-stainless-package-version": true,
|
||||
"x-stainless-os": true,
|
||||
"x-stainless-arch": true,
|
||||
"x-stainless-runtime": true,
|
||||
"x-stainless-runtime-version": true,
|
||||
"x-stainless-helper-method": true,
|
||||
"accept": true,
|
||||
"x-stainless-retry-count": true,
|
||||
"x-stainless-timeout": true,
|
||||
"x-stainless-lang": true,
|
||||
"x-stainless-package-version": true,
|
||||
"x-stainless-os": true,
|
||||
"x-stainless-arch": true,
|
||||
"x-stainless-runtime": true,
|
||||
"x-stainless-runtime-version": true,
|
||||
"x-stainless-helper-method": true,
|
||||
"anthropic-dangerous-direct-browser-access": true,
|
||||
"anthropic-version": true,
|
||||
"x-app": true,
|
||||
"anthropic-beta": true,
|
||||
"accept-language": true,
|
||||
"sec-fetch-mode": true,
|
||||
"accept-encoding": true,
|
||||
"user-agent": true,
|
||||
"content-type": true,
|
||||
"anthropic-version": true,
|
||||
"x-app": true,
|
||||
"anthropic-beta": true,
|
||||
"accept-language": true,
|
||||
"sec-fetch-mode": true,
|
||||
"accept-encoding": true,
|
||||
"user-agent": true,
|
||||
"content-type": true,
|
||||
}
|
||||
|
||||
// ClaudeUsage 表示Claude API返回的usage信息
|
||||
@@ -418,13 +418,19 @@ func (s *GatewayService) Forward(ctx context.Context, c *gin.Context, account *m
|
||||
}
|
||||
|
||||
// 构建上游请求
|
||||
upstreamReq, err := s.buildUpstreamRequest(ctx, c, account, body, token, tokenType)
|
||||
upstreamResult, err := s.buildUpstreamRequest(ctx, c, account, body, token, tokenType)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// 选择使用的client:如果有代理则使用独立的client,否则使用共享的httpClient
|
||||
httpClient := s.httpClient
|
||||
if upstreamResult.Client != nil {
|
||||
httpClient = upstreamResult.Client
|
||||
}
|
||||
|
||||
// 发送请求
|
||||
resp, err := s.httpClient.Do(upstreamReq)
|
||||
resp, err := httpClient.Do(upstreamResult.Request)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("upstream request failed: %w", err)
|
||||
}
|
||||
@@ -437,11 +443,16 @@ func (s *GatewayService) Forward(ctx context.Context, c *gin.Context, account *m
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("token refresh failed: %w", err)
|
||||
}
|
||||
upstreamReq, err = s.buildUpstreamRequest(ctx, c, account, body, token, tokenType)
|
||||
upstreamResult, err = s.buildUpstreamRequest(ctx, c, account, body, token, tokenType)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
resp, err = s.httpClient.Do(upstreamReq)
|
||||
// 重试时也需要使用正确的client
|
||||
httpClient = s.httpClient
|
||||
if upstreamResult.Client != nil {
|
||||
httpClient = upstreamResult.Client
|
||||
}
|
||||
resp, err = httpClient.Do(upstreamResult.Request)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("retry request failed: %w", err)
|
||||
}
|
||||
@@ -480,7 +491,13 @@ func (s *GatewayService) Forward(ctx context.Context, c *gin.Context, account *m
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (s *GatewayService) buildUpstreamRequest(ctx context.Context, c *gin.Context, account *model.Account, body []byte, token, tokenType string) (*http.Request, error) {
|
||||
// buildUpstreamRequestResult contains the request and optional custom client for proxy
|
||||
type buildUpstreamRequestResult struct {
|
||||
Request *http.Request
|
||||
Client *http.Client // nil means use default s.httpClient
|
||||
}
|
||||
|
||||
func (s *GatewayService) buildUpstreamRequest(ctx context.Context, c *gin.Context, account *model.Account, body []byte, token, tokenType string) (*buildUpstreamRequestResult, error) {
|
||||
// 确定目标URL
|
||||
targetURL := claudeAPIURL
|
||||
if account.Type == model.AccountTypeApiKey {
|
||||
@@ -549,7 +566,8 @@ func (s *GatewayService) buildUpstreamRequest(ctx context.Context, c *gin.Contex
|
||||
req.Header.Set("anthropic-beta", s.getBetaHeader(body, c.GetHeader("anthropic-beta")))
|
||||
}
|
||||
|
||||
// 配置代理
|
||||
// 配置代理 - 创建独立的client避免并发修改共享httpClient
|
||||
var customClient *http.Client
|
||||
if account.ProxyID != nil && account.Proxy != nil {
|
||||
proxyURL := account.Proxy.URL()
|
||||
if proxyURL != "" {
|
||||
@@ -566,12 +584,18 @@ func (s *GatewayService) buildUpstreamRequest(ctx context.Context, c *gin.Contex
|
||||
IdleConnTimeout: 90 * time.Second,
|
||||
ResponseHeaderTimeout: responseHeaderTimeout,
|
||||
}
|
||||
s.httpClient.Transport = transport
|
||||
// 创建独立的client,避免并发时修改共享的s.httpClient.Transport
|
||||
customClient = &http.Client{
|
||||
Transport: transport,
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return req, nil
|
||||
return &buildUpstreamRequestResult{
|
||||
Request: req,
|
||||
Client: customClient,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// getBetaHeader 处理anthropic-beta header
|
||||
|
||||
@@ -13,7 +13,6 @@ import (
|
||||
"net/http"
|
||||
"net/url"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"strings"
|
||||
@@ -244,23 +243,6 @@ func (s *UpdateService) Rollback() error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// RestartService triggers a service restart via systemd
|
||||
func (s *UpdateService) RestartService() error {
|
||||
if runtime.GOOS != "linux" {
|
||||
return fmt.Errorf("systemd restart only available on Linux")
|
||||
}
|
||||
|
||||
// Try direct systemctl first (works if running as root or with proper permissions)
|
||||
cmd := exec.Command("systemctl", "restart", "sub2api")
|
||||
if err := cmd.Run(); err != nil {
|
||||
// Try with sudo (requires NOPASSWD sudoers entry)
|
||||
sudoCmd := exec.Command("sudo", "systemctl", "restart", "sub2api")
|
||||
if sudoErr := sudoCmd.Run(); sudoErr != nil {
|
||||
return fmt.Errorf("systemctl restart failed: %w (sudo also failed: %v)", err, sudoErr)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *UpdateService) fetchLatestRelease(ctx context.Context) (*UpdateInfo, error) {
|
||||
url := fmt.Sprintf("https://api.github.com/repos/%s/releases/latest", githubRepo)
|
||||
|
||||
@@ -2,17 +2,15 @@ package setup
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"log"
|
||||
"net/http"
|
||||
"net/mail"
|
||||
"os/exec"
|
||||
"regexp"
|
||||
"runtime"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"sub2api/internal/pkg/response"
|
||||
"sub2api/internal/pkg/sysutil"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
@@ -346,7 +344,7 @@ func install(c *gin.Context) {
|
||||
go func() {
|
||||
// Wait a moment to ensure the response is sent
|
||||
time.Sleep(500 * time.Millisecond)
|
||||
triggerServiceRestart()
|
||||
sysutil.RestartServiceAsync()
|
||||
}()
|
||||
|
||||
response.Success(c, gin.H{
|
||||
@@ -355,27 +353,3 @@ func install(c *gin.Context) {
|
||||
})
|
||||
}
|
||||
|
||||
// triggerServiceRestart attempts to restart the service via systemd
|
||||
// This is called after setup completes to switch from setup mode to normal mode
|
||||
func triggerServiceRestart() {
|
||||
if runtime.GOOS != "linux" {
|
||||
log.Println("Service restart: not on Linux, manual restart required")
|
||||
return
|
||||
}
|
||||
|
||||
log.Println("Setup completed, triggering service restart...")
|
||||
|
||||
// Try direct systemctl first (works if running as root or with proper permissions)
|
||||
cmd := exec.Command("systemctl", "restart", "sub2api")
|
||||
if err := cmd.Run(); err != nil {
|
||||
// Try with sudo (requires NOPASSWD sudoers entry)
|
||||
sudoCmd := exec.Command("sudo", "systemctl", "restart", "sub2api")
|
||||
if sudoErr := sudoCmd.Run(); sudoErr != nil {
|
||||
log.Printf("Service restart failed: %v (sudo also failed: %v)", err, sudoErr)
|
||||
log.Println("Please restart the service manually: sudo systemctl restart sub2api")
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
log.Println("Service restart initiated successfully")
|
||||
}
|
||||
|
||||
@@ -483,9 +483,24 @@ download_and_extract() {
|
||||
create_user() {
|
||||
if id "$SERVICE_USER" &>/dev/null; then
|
||||
print_info "$(msg 'user_exists'): $SERVICE_USER"
|
||||
# Fix: Ensure existing user has /bin/sh shell for sudo to work
|
||||
# Previous versions used /bin/false which prevents sudo execution
|
||||
local current_shell
|
||||
current_shell=$(getent passwd "$SERVICE_USER" 2>/dev/null | cut -d: -f7)
|
||||
if [ "$current_shell" = "/bin/false" ] || [ "$current_shell" = "/sbin/nologin" ]; then
|
||||
print_info "Fixing user shell for sudo compatibility..."
|
||||
if usermod -s /bin/sh "$SERVICE_USER" 2>/dev/null; then
|
||||
print_success "User shell updated to /bin/sh"
|
||||
else
|
||||
print_warning "Failed to update user shell. Service restart may not work automatically."
|
||||
print_warning "Manual fix: sudo usermod -s /bin/sh $SERVICE_USER"
|
||||
fi
|
||||
fi
|
||||
else
|
||||
print_info "$(msg 'creating_user') $SERVICE_USER..."
|
||||
useradd -r -s /bin/false -d "$INSTALL_DIR" "$SERVICE_USER"
|
||||
# Use /bin/sh instead of /bin/false to allow sudo execution
|
||||
# The user still cannot login interactively (no password set)
|
||||
useradd -r -s /bin/sh -d "$INSTALL_DIR" "$SERVICE_USER"
|
||||
print_success "$(msg 'user_created')"
|
||||
fi
|
||||
}
|
||||
@@ -510,18 +525,18 @@ setup_directories() {
|
||||
setup_sudoers() {
|
||||
print_info "$(msg 'setting_up_sudoers')"
|
||||
|
||||
# Check if sudoers file exists in install dir
|
||||
if [ -f "$INSTALL_DIR/sub2api-sudoers" ]; then
|
||||
cp "$INSTALL_DIR/sub2api-sudoers" /etc/sudoers.d/sub2api
|
||||
else
|
||||
# Create sudoers file
|
||||
cat > /etc/sudoers.d/sub2api << 'EOF'
|
||||
# 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
|
||||
fi
|
||||
|
||||
# Set correct permissions (required for sudoers files)
|
||||
chmod 440 /etc/sudoers.d/sub2api
|
||||
@@ -683,7 +698,7 @@ uninstall() {
|
||||
# If not interactive (piped), require -y flag or skip confirmation
|
||||
if ! is_interactive; then
|
||||
if [ "${FORCE_YES:-}" != "true" ]; then
|
||||
print_error "Non-interactive mode detected. Use 'bash -s -- uninstall -y' to confirm."
|
||||
print_error "Non-interactive mode detected. Use 'curl ... | bash -s -- uninstall -y' to confirm."
|
||||
exit 1
|
||||
fi
|
||||
else
|
||||
|
||||
@@ -8,6 +8,10 @@
|
||||
# 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
|
||||
|
||||
Reference in New Issue
Block a user