Compare commits
8
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
94bd61daa1 | ||
|
|
948aef0fe4 | ||
|
|
c340e3934c | ||
|
|
ef6c75aef9 | ||
|
|
6904e4993f | ||
|
|
babfdee02b | ||
|
|
aaac3fc791 | ||
|
|
c2516dc8ff |
@@ -6,11 +6,13 @@ import (
|
||||
"fmt"
|
||||
"io"
|
||||
"io/fs"
|
||||
"net"
|
||||
"net/http"
|
||||
"os"
|
||||
"strconv"
|
||||
"strings"
|
||||
"text/template"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
@@ -43,10 +45,13 @@ func SetupRouter() *gin.Engine {
|
||||
|
||||
api := r.Group("/api")
|
||||
{
|
||||
// ---- 公开路由(不需要认证) ----
|
||||
api.GET("/check/users", checkUsersHandler)
|
||||
api.POST("/register", registerHandler)
|
||||
api.POST("/login", loginHandler)
|
||||
api.GET("/ping", pingHandler)
|
||||
|
||||
// ---- 需要认证的路由 ----
|
||||
auth := api.Group("/")
|
||||
auth.Use(AuthMiddleware())
|
||||
{
|
||||
@@ -75,7 +80,7 @@ func SetupRouter() *gin.Engine {
|
||||
return r
|
||||
}
|
||||
|
||||
// ========== 所有 Handler ==========
|
||||
// ========== 认证 Handler ==========
|
||||
|
||||
func checkUsersHandler(c *gin.Context) {
|
||||
count, err := CountUsers()
|
||||
@@ -223,6 +228,8 @@ func changePasswordHandler(c *gin.Context) {
|
||||
c.JSON(http.StatusOK, gin.H{"code": 0, "msg": "密码修改成功"})
|
||||
}
|
||||
|
||||
// ========== 配置 Handler ==========
|
||||
|
||||
func getConfigHandler(c *gin.Context) {
|
||||
cfg, err := GetGlobalConfig()
|
||||
if err != nil {
|
||||
@@ -258,6 +265,8 @@ func updateConfigHandler(c *gin.Context) {
|
||||
c.JSON(http.StatusOK, gin.H{"code": 0, "msg": "配置更新成功"})
|
||||
}
|
||||
|
||||
// ========== 隧道 Handler ==========
|
||||
|
||||
func getProxiesHandler(c *gin.Context) {
|
||||
proxies, err := GetProxies()
|
||||
if err != nil {
|
||||
@@ -348,6 +357,8 @@ func deleteProxyHandler(c *gin.Context) {
|
||||
c.JSON(http.StatusOK, gin.H{"code": 0, "msg": "隧道删除成功"})
|
||||
}
|
||||
|
||||
// ========== frpc 进程管理 Handler ==========
|
||||
|
||||
func reloadFrpcHandler(c *gin.Context) {
|
||||
if err := GenerateFrpcConfig(); err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"code": 2, "msg": "生成配置失败: " + err.Error()})
|
||||
@@ -385,6 +396,144 @@ func getFrpcStatusHandler(c *gin.Context) {
|
||||
c.JSON(http.StatusOK, gin.H{"code": 0, "data": gin.H{"running": running}})
|
||||
}
|
||||
|
||||
// ========== 日志 Handler ==========
|
||||
|
||||
func getFrpcLogHandler(c *gin.Context) {
|
||||
lines, err := readTailLog("./frpc.log", 200)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"code": 0,
|
||||
"data": gin.H{
|
||||
"lines": []string{},
|
||||
"total": 0,
|
||||
"error": err.Error(),
|
||||
},
|
||||
})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"code": 0,
|
||||
"data": gin.H{
|
||||
"lines": lines,
|
||||
"total": len(lines),
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
// readTailLog 读取文件末尾 n 行(倒序读取,返回正序)
|
||||
func readTailLog(filePath string, n int) ([]string, error) {
|
||||
file, err := os.Open(filePath)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer file.Close()
|
||||
|
||||
// 获取文件大小
|
||||
info, err := file.Stat()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
fileSize := info.Size()
|
||||
if fileSize == 0 {
|
||||
return []string{}, nil
|
||||
}
|
||||
|
||||
// 从末尾开始读
|
||||
const chunkSize = 4096
|
||||
var lines []string
|
||||
var leftover []byte
|
||||
offset := fileSize
|
||||
|
||||
for len(lines) < n && offset > 0 {
|
||||
// 计算读取起点
|
||||
readSize := chunkSize
|
||||
if offset < int64(chunkSize) {
|
||||
readSize = int(offset)
|
||||
}
|
||||
offset -= int64(readSize)
|
||||
|
||||
// 读取这一块
|
||||
buf := make([]byte, readSize)
|
||||
_, err := file.ReadAt(buf, offset)
|
||||
if err != nil && err != io.EOF {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// 将当前块与之前剩下的拼接
|
||||
data := append(buf, leftover...)
|
||||
leftover = nil
|
||||
|
||||
// 按行分割(从后往前)
|
||||
start := 0
|
||||
for i := len(data) - 1; i >= 0; i-- {
|
||||
if data[i] == '\n' {
|
||||
if i+1 < len(data) {
|
||||
line := string(data[i+1:])
|
||||
if line != "" {
|
||||
lines = append([]string{line}, lines...)
|
||||
if len(lines) >= n {
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
start = i
|
||||
}
|
||||
}
|
||||
|
||||
// 如果还没凑够,把未处理的部分留到下一轮
|
||||
if len(lines) < n && start > 0 {
|
||||
leftover = data[:start]
|
||||
}
|
||||
}
|
||||
|
||||
// 处理最后剩余部分(文件开头)
|
||||
if len(lines) < n && len(leftover) > 0 {
|
||||
parts := strings.Split(string(leftover), "\n")
|
||||
for i := len(parts) - 1; i >= 0; i-- {
|
||||
if parts[i] != "" {
|
||||
lines = append([]string{parts[i]}, lines...)
|
||||
if len(lines) >= n {
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return lines, nil
|
||||
}
|
||||
|
||||
// ========== Ping Handler ==========
|
||||
|
||||
func pingHandler(c *gin.Context) {
|
||||
target := c.Query("target")
|
||||
if target == "" {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"code": 1, "msg": "缺少 target 参数"})
|
||||
return
|
||||
}
|
||||
|
||||
cfg, err := GetGlobalConfig()
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"code": 2, "msg": "读取配置失败"})
|
||||
return
|
||||
}
|
||||
|
||||
port := cfg.ServerPort
|
||||
address := net.JoinHostPort(target, strconv.Itoa(port))
|
||||
|
||||
start := time.Now()
|
||||
conn, err := net.DialTimeout("tcp", address, 5*time.Second)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusOK, gin.H{"code": 1, "msg": "ping 失败", "latency": -1})
|
||||
return
|
||||
}
|
||||
conn.Close()
|
||||
|
||||
latency := time.Since(start).Milliseconds()
|
||||
c.JSON(http.StatusOK, gin.H{"code": 0, "latency": latency})
|
||||
}
|
||||
|
||||
// ========== 导入/导出 TOML ==========
|
||||
|
||||
func importTomlHandler(c *gin.Context) {
|
||||
file, err := c.FormFile("file")
|
||||
if err != nil {
|
||||
@@ -470,14 +619,22 @@ func ExportTomlHandler(c *gin.Context) {
|
||||
}
|
||||
}
|
||||
|
||||
// 构建与 GenerateFrpcConfig 一致的数据结构
|
||||
data := struct {
|
||||
*GlobalConfig
|
||||
Proxies []Proxy
|
||||
WireProtocolLine string
|
||||
}{
|
||||
GlobalConfig: cfg,
|
||||
Proxies: activeProxies,
|
||||
}
|
||||
|
||||
if cfg.WireProtocolV2 {
|
||||
data.WireProtocolLine = `wireProtocol = "v2"`
|
||||
} else {
|
||||
data.WireProtocolLine = ""
|
||||
}
|
||||
|
||||
tmpl, err := template.New("frpc").Parse(FrpcTemplateContent)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"code": 2, "msg": "解析模板失败: " + err.Error()})
|
||||
@@ -495,114 +652,6 @@ func ExportTomlHandler(c *gin.Context) {
|
||||
c.String(http.StatusOK, buf.String())
|
||||
}
|
||||
|
||||
// ========== 日志读取 ==========
|
||||
|
||||
func getFrpcLogHandler(c *gin.Context) {
|
||||
// 读取 ./frpc.log,最多返回 200 行(最新的 200 行)
|
||||
lines, err := readTailLog("./frpc.log", 200)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"code": 0,
|
||||
"data": gin.H{
|
||||
"lines": []string{},
|
||||
"total": 0,
|
||||
"error": err.Error(),
|
||||
},
|
||||
})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"code": 0,
|
||||
"data": gin.H{
|
||||
"lines": lines,
|
||||
"total": len(lines),
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
// readTailLog 读取文件末尾 n 行(倒序读取,返回正序)
|
||||
func readTailLog(filePath string, n int) ([]string, error) {
|
||||
file, err := os.Open(filePath)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer file.Close()
|
||||
|
||||
// 获取文件大小
|
||||
info, err := file.Stat()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
fileSize := info.Size()
|
||||
if fileSize == 0 {
|
||||
return []string{}, nil
|
||||
}
|
||||
|
||||
// 从末尾开始读
|
||||
const chunkSize = 4096
|
||||
var lines []string
|
||||
var leftover []byte
|
||||
offset := fileSize
|
||||
|
||||
for len(lines) < n && offset > 0 {
|
||||
// 计算读取起点
|
||||
readSize := chunkSize
|
||||
if offset < int64(chunkSize) {
|
||||
readSize = int(offset)
|
||||
}
|
||||
offset -= int64(readSize)
|
||||
|
||||
// 读取这一块
|
||||
buf := make([]byte, readSize)
|
||||
_, err := file.ReadAt(buf, offset)
|
||||
if err != nil && err != io.EOF {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// 将当前块与之前剩下的拼接
|
||||
data := append(buf, leftover...)
|
||||
leftover = nil
|
||||
|
||||
// 按行分割
|
||||
start := 0
|
||||
for i := len(data) - 1; i >= 0; i-- {
|
||||
if data[i] == '\n' {
|
||||
if i+1 < len(data) {
|
||||
line := string(data[i+1:])
|
||||
if line != "" {
|
||||
lines = append([]string{line}, lines...)
|
||||
if len(lines) >= n {
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
start = i
|
||||
}
|
||||
}
|
||||
|
||||
// 如果还没凑够,把未处理的部分留到下一轮
|
||||
if len(lines) < n && start > 0 {
|
||||
leftover = data[:start]
|
||||
}
|
||||
}
|
||||
|
||||
// 处理最后剩余部分(文件开头)
|
||||
if len(lines) < n && len(leftover) > 0 {
|
||||
// 从 leftover 中提取行
|
||||
parts := strings.Split(string(leftover), "\n")
|
||||
for i := len(parts) - 1; i >= 0; i-- {
|
||||
if parts[i] != "" {
|
||||
lines = append([]string{parts[i]}, lines...)
|
||||
if len(lines) >= n {
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return lines, nil
|
||||
}
|
||||
|
||||
func generateAndReload() error {
|
||||
if err := GenerateFrpcConfig(); err != nil {
|
||||
return err
|
||||
|
||||
@@ -0,0 +1,91 @@
|
||||
package main
|
||||
|
||||
// ============================================================
|
||||
// db-history.go - Schema 版本声明与字段映射
|
||||
// ============================================================
|
||||
|
||||
type SchemaVersionDef struct {
|
||||
Version string
|
||||
TableName string
|
||||
Columns map[string]ColumnDef
|
||||
}
|
||||
|
||||
type ColumnDef struct {
|
||||
Type string
|
||||
NotNull bool
|
||||
Default string
|
||||
Primary bool
|
||||
}
|
||||
|
||||
var schemaHistory = []SchemaVersionDef{
|
||||
// v1:初始版本
|
||||
{
|
||||
Version: "v1",
|
||||
TableName: "proxies",
|
||||
Columns: map[string]ColumnDef{
|
||||
"id": {Type: "INTEGER", Primary: true},
|
||||
"name": {Type: "TEXT", NotNull: true},
|
||||
"type": {Type: "TEXT", NotNull: true, Default: "'tcp'"},
|
||||
"local_ip": {Type: "TEXT", NotNull: true},
|
||||
"local_port": {Type: "INTEGER", NotNull: true},
|
||||
"remote_port": {Type: "INTEGER", NotNull: true},
|
||||
"enabled": {Type: "INTEGER", NotNull: true, Default: "1"},
|
||||
"created_at": {Type: "DATETIME", Default: "CURRENT_TIMESTAMP"},
|
||||
"updated_at": {Type: "DATETIME", Default: "CURRENT_TIMESTAMP"},
|
||||
},
|
||||
},
|
||||
// v2:当前版本(frpc-console 2.0 LTS)
|
||||
{
|
||||
Version: "v2",
|
||||
TableName: "proxies",
|
||||
Columns: map[string]ColumnDef{
|
||||
"id": {Type: "INTEGER", Primary: true},
|
||||
"name": {Type: "TEXT", NotNull: true},
|
||||
"type": {Type: "TEXT", NotNull: true, Default: "'tcp'"},
|
||||
"local_ip": {Type: "TEXT", NotNull: true},
|
||||
"local_port": {Type: "INTEGER", NotNull: true},
|
||||
"remote_port": {Type: "INTEGER", NotNull: true},
|
||||
"enabled": {Type: "INTEGER", NotNull: true, Default: "1"},
|
||||
"created_at": {Type: "DATETIME", Default: "CURRENT_TIMESTAMP"},
|
||||
"updated_at": {Type: "DATETIME", Default: "CURRENT_TIMESTAMP"},
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
func getSchemaDef(version string) *SchemaVersionDef {
|
||||
for _, def := range schemaHistory {
|
||||
if def.Version == version {
|
||||
return &def
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func getLatestSchemaDef() *SchemaVersionDef {
|
||||
if len(schemaHistory) == 0 {
|
||||
return nil
|
||||
}
|
||||
return &schemaHistory[len(schemaHistory)-1]
|
||||
}
|
||||
|
||||
func schemaVersionsEqual(v1, v2 *SchemaVersionDef) bool {
|
||||
if v1 == nil || v2 == nil {
|
||||
return false
|
||||
}
|
||||
if v1.TableName != v2.TableName {
|
||||
return false
|
||||
}
|
||||
if len(v1.Columns) != len(v2.Columns) {
|
||||
return false
|
||||
}
|
||||
for name, col1 := range v1.Columns {
|
||||
col2, ok := v2.Columns[name]
|
||||
if !ok {
|
||||
return false
|
||||
}
|
||||
if col1.Type != col2.Type || col1.NotNull != col2.NotNull || col1.Default != col2.Default {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
@@ -8,6 +8,7 @@ import (
|
||||
"io"
|
||||
"log"
|
||||
"os"
|
||||
"sort"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
@@ -21,14 +22,13 @@ var DB *sql.DB
|
||||
// ============================================================
|
||||
|
||||
const (
|
||||
SchemaVersion = "2.0.0" // 当前数据库 Schema 版本,与项目版本同步
|
||||
SchemaVersion = "v2" // 当前数据库 Schema 版本
|
||||
)
|
||||
|
||||
// ============================================================
|
||||
// 数据模型
|
||||
// ============================================================
|
||||
|
||||
// GlobalConfig 全局配置表
|
||||
type GlobalConfig struct {
|
||||
ID int `json:"id"`
|
||||
ServerAddr string `json:"serverAddr"`
|
||||
@@ -41,10 +41,9 @@ type GlobalConfig struct {
|
||||
HeartbeatInterval int `json:"heartbeatInterval"`
|
||||
HeartbeatTimeout int `json:"heartbeatTimeout"`
|
||||
PoolCount int `json:"poolCount"`
|
||||
WireProtocolV2 bool `json:"wireProtocolV2"` // v2.0 正式启用
|
||||
WireProtocolV2 bool `json:"wireProtocolV2"`
|
||||
}
|
||||
|
||||
// Proxy 隧道表
|
||||
type Proxy struct {
|
||||
ID int `json:"id"`
|
||||
Name string `json:"name"`
|
||||
@@ -55,7 +54,6 @@ type Proxy struct {
|
||||
Enabled bool `json:"enabled"`
|
||||
}
|
||||
|
||||
// User 用户表
|
||||
type User struct {
|
||||
ID int `json:"id"`
|
||||
Username string `json:"username"`
|
||||
@@ -68,28 +66,31 @@ type User struct {
|
||||
// ============================================================
|
||||
|
||||
func InitDB() error {
|
||||
// 确保 data 目录存在
|
||||
if err := os.MkdirAll("./data", 0755); err != nil {
|
||||
return fmt.Errorf("创建数据目录失败: %w", err)
|
||||
}
|
||||
|
||||
dbPath := "./data/frpc-console.db"
|
||||
var err error
|
||||
DB, err = sql.Open("sqlite", "./frpc-console.db")
|
||||
DB, err = sql.Open("sqlite", dbPath)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// ---- 创建所有表 ----
|
||||
if err := createTables(); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// ---- 执行版本迁移 ----
|
||||
if err := runMigrations(); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// ---- 确保 JWT 密钥存在 ----
|
||||
if err := ensureJwtSecret(); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
log.Println("✅ 数据库初始化完成 (Schema v" + SchemaVersion + ")")
|
||||
log.Println("✅ 数据库初始化完成 (Schema " + SchemaVersion + ")")
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -152,7 +153,7 @@ func createTables() error {
|
||||
return err
|
||||
}
|
||||
|
||||
// 应用配置表(存储 JWT 密钥、Schema 版本等)
|
||||
// 应用配置表
|
||||
_, err = DB.Exec(`
|
||||
CREATE TABLE IF NOT EXISTS app_config (
|
||||
key TEXT PRIMARY KEY,
|
||||
@@ -164,7 +165,7 @@ func createTables() error {
|
||||
return err
|
||||
}
|
||||
|
||||
// 初始化默认配置(仅当表为空时)
|
||||
// 初始化默认配置
|
||||
var count int
|
||||
DB.QueryRow("SELECT COUNT(*) FROM global_config").Scan(&count)
|
||||
if count == 0 {
|
||||
@@ -188,30 +189,24 @@ func createTables() error {
|
||||
// 迁移引擎
|
||||
// ============================================================
|
||||
|
||||
// getSchemaVersion 读取当前数据库的 Schema 版本
|
||||
func getSchemaVersion() string {
|
||||
func getCurrentSchemaVersion() string {
|
||||
var version string
|
||||
err := DB.QueryRow("SELECT value FROM app_config WHERE key = 'schema_version'").Scan(&version)
|
||||
if err != nil {
|
||||
if err == sql.ErrNoRows {
|
||||
// 没有版本记录 → 首次启动或 v1.x 升级
|
||||
// 检查是否已有数据(通过 users 表判断)
|
||||
var count int
|
||||
DB.QueryRow("SELECT COUNT(*) FROM users").Scan(&count)
|
||||
if count > 0 {
|
||||
// 有用户数据 → 这是 v1.x 升级,标记为 1.5
|
||||
return "1.5.0"
|
||||
return "v1"
|
||||
}
|
||||
// 全新安装 → 直接标记为当前版本
|
||||
return SchemaVersion
|
||||
}
|
||||
log.Printf("⚠️ 读取 Schema 版本失败: %v", err)
|
||||
return "1.5.0" // 保守降级
|
||||
return "v1"
|
||||
}
|
||||
return version
|
||||
}
|
||||
|
||||
// setSchemaVersion 更新 Schema 版本
|
||||
func setSchemaVersion(version string) error {
|
||||
_, err := DB.Exec(`
|
||||
INSERT INTO app_config (key, value) VALUES ('schema_version', ?)
|
||||
@@ -220,15 +215,14 @@ func setSchemaVersion(version string) error {
|
||||
return err
|
||||
}
|
||||
|
||||
// backupDatabase 备份数据库文件
|
||||
func backupDatabase() (string, error) {
|
||||
src := "./frpc-console.db"
|
||||
src := "./data/frpc-console.db"
|
||||
if _, err := os.Stat(src); os.IsNotExist(err) {
|
||||
return "", nil // 数据库不存在,无需备份
|
||||
return "", nil
|
||||
}
|
||||
|
||||
timestamp := time.Now().Format("20060102_150405")
|
||||
dst := fmt.Sprintf("./frpc-console.db.pre-v%s.%s", SchemaVersion, timestamp)
|
||||
dst := fmt.Sprintf("./data/frpc-console.db.pre-%s.%s", SchemaVersion, timestamp)
|
||||
|
||||
srcFile, err := os.Open(src)
|
||||
if err != nil {
|
||||
@@ -250,69 +244,6 @@ func backupDatabase() (string, error) {
|
||||
return dst, nil
|
||||
}
|
||||
|
||||
// runMigrations 执行版本迁移
|
||||
func runMigrations() error {
|
||||
currentVersion := getSchemaVersion()
|
||||
log.Printf("📌 当前数据库 Schema: %s, 目标版本: %s", currentVersion, SchemaVersion)
|
||||
|
||||
if currentVersion == SchemaVersion {
|
||||
log.Println("✅ Schema 已是最新,无需迁移")
|
||||
return nil
|
||||
}
|
||||
|
||||
log.Printf("🔄 检测到版本变更 (%s → %s),开始迁移...", currentVersion, SchemaVersion)
|
||||
|
||||
// ---- 1. 备份数据库 ----
|
||||
backupPath, err := backupDatabase()
|
||||
if err != nil {
|
||||
return fmt.Errorf("备份数据库失败: %w", err)
|
||||
}
|
||||
if backupPath != "" {
|
||||
log.Printf("📦 备份文件: %s", backupPath)
|
||||
} else {
|
||||
log.Println("📦 数据库为空,跳过备份")
|
||||
}
|
||||
|
||||
// ---- 2. 执行迁移 ----
|
||||
// 按照版本号逐个升级
|
||||
migrations := []struct {
|
||||
from string
|
||||
upgrade func() error
|
||||
}{
|
||||
{"1.5.0", migrateFrom1_5_0},
|
||||
{"2.0.0", migrateFrom2_0_0}, // 预留,实际无操作
|
||||
}
|
||||
|
||||
applied := 0
|
||||
for _, m := range migrations {
|
||||
if currentVersion == m.from {
|
||||
log.Printf(" 执行迁移: %s → %s", m.from, SchemaVersion)
|
||||
if err := m.upgrade(); err != nil {
|
||||
// 迁移失败,尝试恢复备份
|
||||
if backupPath != "" {
|
||||
log.Printf("❌ 迁移失败,尝试恢复备份: %s", backupPath)
|
||||
if restoreErr := restoreDatabase(backupPath); restoreErr != nil {
|
||||
log.Printf("⚠️ 恢复备份失败: %v", restoreErr)
|
||||
}
|
||||
}
|
||||
return fmt.Errorf("迁移失败: %w", err)
|
||||
}
|
||||
applied++
|
||||
currentVersion = SchemaVersion
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
// ---- 3. 更新 Schema 版本 ----
|
||||
if err := setSchemaVersion(SchemaVersion); err != nil {
|
||||
return fmt.Errorf("更新 Schema 版本失败: %w", err)
|
||||
}
|
||||
|
||||
log.Printf("✅ 迁移完成,应用了 %d 个迁移", applied)
|
||||
return nil
|
||||
}
|
||||
|
||||
// restoreDatabase 从备份恢复数据库
|
||||
func restoreDatabase(backupPath string) error {
|
||||
srcFile, err := os.Open(backupPath)
|
||||
if err != nil {
|
||||
@@ -320,7 +251,7 @@ func restoreDatabase(backupPath string) error {
|
||||
}
|
||||
defer srcFile.Close()
|
||||
|
||||
dstFile, err := os.Create("./frpc-console.db")
|
||||
dstFile, err := os.Create("./data/frpc-console.db")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -334,76 +265,187 @@ func restoreDatabase(backupPath string) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// 迁移函数(各版本)
|
||||
// ============================================================
|
||||
func runMigrations() error {
|
||||
currentVer := getCurrentSchemaVersion()
|
||||
targetVer := SchemaVersion
|
||||
|
||||
// migrateFrom1_5_0: v1.5 → v2.0
|
||||
// v1.5 已经有 wire_protocol_v2 字段(灰标占位),v2.0 无需新增字段
|
||||
// 但需要确保字段存在(兼容从 v1.0 直接升级的场景)
|
||||
func migrateFrom1_5_0() error {
|
||||
log.Println(" 迁移: v1.5.0 → v2.0.0")
|
||||
log.Printf("📌 当前数据库 Schema: %s, 目标版本: %s", currentVer, targetVer)
|
||||
|
||||
// 检查并补全 wire_protocol_v2 字段(兼容从 v1.0 直接升级的场景)
|
||||
cols, err := getCurrentColumns("global_config")
|
||||
if err != nil {
|
||||
return fmt.Errorf("获取列信息失败: %w", err)
|
||||
if currentVer == targetVer {
|
||||
// 检查数据库是否包含有效数据
|
||||
var userCount int
|
||||
err := DB.QueryRow("SELECT COUNT(*) FROM users").Scan(&userCount)
|
||||
if err != nil || userCount == 0 {
|
||||
log.Println(" 数据库为空或无效,无需迁移,直接初始化")
|
||||
return nil
|
||||
}
|
||||
|
||||
if !contains(cols, "wire_protocol_v2") {
|
||||
log.Println(" 添加字段: wire_protocol_v2")
|
||||
_, err := DB.Exec("ALTER TABLE global_config ADD COLUMN wire_protocol_v2 INTEGER NOT NULL DEFAULT 0")
|
||||
if err != nil {
|
||||
return fmt.Errorf("添加 wire_protocol_v2 字段失败: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
log.Println(" ✅ v1.5.0 → v2.0.0 迁移完成")
|
||||
log.Println("✅ Schema 已是最新,数据库有效")
|
||||
return nil
|
||||
}
|
||||
|
||||
// migrateFrom2_0_0: 预留,v2.0 → 未来版本
|
||||
func migrateFrom2_0_0() error {
|
||||
log.Println(" v2.0.0 已是当前版本,无需迁移")
|
||||
log.Printf("🔄 检测到版本变更 (%s → %s),开始迁移...", currentVer, targetVer)
|
||||
|
||||
backupPath, err := backupDatabase()
|
||||
if err != nil {
|
||||
return fmt.Errorf("备份数据库失败: %w", err)
|
||||
}
|
||||
if backupPath != "" {
|
||||
log.Printf("📦 备份文件: %s", backupPath)
|
||||
}
|
||||
|
||||
currentSchema := getSchemaDef(currentVer)
|
||||
targetSchema := getSchemaDef(targetVer)
|
||||
|
||||
if targetSchema == nil {
|
||||
return fmt.Errorf("目标 Schema 版本 %s 未在 schemaHistory 中定义", targetVer)
|
||||
}
|
||||
|
||||
if currentSchema == nil || schemaVersionsEqual(currentSchema, targetSchema) {
|
||||
log.Println(" 迁移类型: 轻量复制(Schema 无变更)")
|
||||
// 验证数据库是否有效
|
||||
var userCount int
|
||||
err := DB.QueryRow("SELECT COUNT(*) FROM users").Scan(&userCount)
|
||||
if err != nil || userCount == 0 {
|
||||
log.Println(" 数据库为空或无效,跳过迁移,直接初始化")
|
||||
return nil
|
||||
}
|
||||
log.Println(" 数据库有效,继续使用")
|
||||
} else {
|
||||
log.Println(" 迁移类型: 重型迁移(Schema 有变更,新建表 + 搬数据)")
|
||||
if err := heavyMigration(currentSchema, targetSchema); err != nil {
|
||||
if backupPath != "" {
|
||||
log.Printf("❌ 迁移失败,尝试恢复备份: %s", backupPath)
|
||||
if restoreErr := restoreDatabase(backupPath); restoreErr != nil {
|
||||
log.Printf("⚠️ 恢复备份失败: %v", restoreErr)
|
||||
}
|
||||
}
|
||||
return fmt.Errorf("重型迁移失败: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
if err := setSchemaVersion(targetVer); err != nil {
|
||||
return fmt.Errorf("更新 Schema 版本失败: %w", err)
|
||||
}
|
||||
|
||||
log.Printf("✅ 迁移完成,当前 Schema: %s", targetVer)
|
||||
return nil
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// 辅助函数
|
||||
// ============================================================
|
||||
|
||||
func getCurrentColumns(tableName string) ([]string, error) {
|
||||
rows, err := DB.Query("PRAGMA table_info(" + tableName + ")")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
func heavyMigration(oldDef, newDef *SchemaVersionDef) error {
|
||||
if oldDef == nil {
|
||||
return fmt.Errorf("旧 Schema 定义为空,无法执行重型迁移")
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
oldTable := oldDef.TableName
|
||||
newTable := oldTable + "_new"
|
||||
|
||||
createSQL := buildCreateTableSQL(newTable, newDef)
|
||||
log.Printf(" 创建新表: %s", newTable)
|
||||
if _, err := DB.Exec(createSQL); err != nil {
|
||||
return fmt.Errorf("创建新表失败: %w", err)
|
||||
}
|
||||
|
||||
insertSQL, err := buildInsertSQL(oldTable, newTable, oldDef, newDef)
|
||||
if err != nil {
|
||||
return fmt.Errorf("构建数据迁移 SQL 失败: %w", err)
|
||||
}
|
||||
log.Printf(" 迁移数据: %s → %s", oldTable, newTable)
|
||||
if _, err := DB.Exec(insertSQL); err != nil {
|
||||
return fmt.Errorf("数据迁移失败: %w", err)
|
||||
}
|
||||
|
||||
var oldCount, newCount int
|
||||
DB.QueryRow(fmt.Sprintf("SELECT COUNT(*) FROM %s", oldTable)).Scan(&oldCount)
|
||||
DB.QueryRow(fmt.Sprintf("SELECT COUNT(*) FROM %s", newTable)).Scan(&newCount)
|
||||
if oldCount != newCount {
|
||||
return fmt.Errorf("数据迁移不完整: 旧表 %d 行,新表 %d 行", oldCount, newCount)
|
||||
}
|
||||
log.Printf(" 数据迁移验证通过: %d 行", newCount)
|
||||
|
||||
tempTable := oldTable + "_old_temp"
|
||||
if _, err := DB.Exec(fmt.Sprintf("ALTER TABLE %s RENAME TO %s", oldTable, tempTable)); err != nil {
|
||||
return fmt.Errorf("重命名旧表失败: %w", err)
|
||||
}
|
||||
if _, err := DB.Exec(fmt.Sprintf("ALTER TABLE %s RENAME TO %s", newTable, oldTable)); err != nil {
|
||||
DB.Exec(fmt.Sprintf("ALTER TABLE %s RENAME TO %s", tempTable, oldTable))
|
||||
return fmt.Errorf("重命名新表失败: %w", err)
|
||||
}
|
||||
if _, err := DB.Exec(fmt.Sprintf("DROP TABLE %s", tempTable)); err != nil {
|
||||
log.Printf("⚠️ 删除临时表失败(不影响使用): %v", err)
|
||||
}
|
||||
|
||||
log.Printf(" 表交换完成: %s (新表已生效)", oldTable)
|
||||
return nil
|
||||
}
|
||||
|
||||
func buildCreateTableSQL(tableName string, def *SchemaVersionDef) string {
|
||||
var cols []string
|
||||
for rows.Next() {
|
||||
var (
|
||||
cid int
|
||||
name string
|
||||
typ string
|
||||
notNull int
|
||||
dfltVal sql.NullString
|
||||
pk int
|
||||
)
|
||||
if err := rows.Scan(&cid, &name, &typ, ¬Null, &dfltVal, &pk); err != nil {
|
||||
return nil, err
|
||||
var primaryKey string
|
||||
|
||||
names := make([]string, 0, len(def.Columns))
|
||||
for name := range def.Columns {
|
||||
names = append(names, name)
|
||||
}
|
||||
cols = append(cols, name)
|
||||
sort.Strings(names)
|
||||
|
||||
for _, name := range names {
|
||||
col := def.Columns[name]
|
||||
parts := []string{name, col.Type}
|
||||
if col.NotNull {
|
||||
parts = append(parts, "NOT NULL")
|
||||
}
|
||||
if col.Default != "" {
|
||||
parts = append(parts, "DEFAULT "+col.Default)
|
||||
}
|
||||
if col.Primary {
|
||||
primaryKey = "PRIMARY KEY (" + name + ")"
|
||||
} else {
|
||||
cols = append(cols, strings.Join(parts, " "))
|
||||
}
|
||||
return cols, rows.Err()
|
||||
}
|
||||
|
||||
func contains(slice []string, item string) bool {
|
||||
for _, s := range slice {
|
||||
if strings.EqualFold(s, item) {
|
||||
return true
|
||||
if primaryKey != "" {
|
||||
cols = append(cols, primaryKey)
|
||||
}
|
||||
|
||||
return fmt.Sprintf("CREATE TABLE %s (\n %s\n)", tableName, strings.Join(cols, ",\n "))
|
||||
}
|
||||
|
||||
func buildInsertSQL(oldTable, newTable string, oldDef, newDef *SchemaVersionDef) (string, error) {
|
||||
newCols := make([]string, 0, len(newDef.Columns))
|
||||
for name := range newDef.Columns {
|
||||
newCols = append(newCols, name)
|
||||
}
|
||||
sort.Strings(newCols)
|
||||
|
||||
var selectParts []string
|
||||
var colNames []string
|
||||
|
||||
for _, name := range newCols {
|
||||
colNames = append(colNames, name)
|
||||
if _, ok := oldDef.Columns[name]; ok {
|
||||
selectParts = append(selectParts, name)
|
||||
} else {
|
||||
colDef := newDef.Columns[name]
|
||||
if colDef.Default != "" {
|
||||
selectParts = append(selectParts, colDef.Default+" AS "+name)
|
||||
} else if colDef.Type == "INTEGER" {
|
||||
selectParts = append(selectParts, "0 AS "+name)
|
||||
} else if colDef.Type == "TEXT" {
|
||||
selectParts = append(selectParts, "'' AS "+name)
|
||||
} else {
|
||||
selectParts = append(selectParts, "NULL AS "+name)
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
return fmt.Sprintf(
|
||||
"INSERT INTO %s (%s) SELECT %s FROM %s",
|
||||
newTable,
|
||||
strings.Join(colNames, ", "),
|
||||
strings.Join(selectParts, ", "),
|
||||
oldTable,
|
||||
), nil
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
@@ -504,10 +546,7 @@ func GetProxies() ([]Proxy, error) {
|
||||
}
|
||||
proxies = append(proxies, p)
|
||||
}
|
||||
if err = rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return proxies, nil
|
||||
return proxies, rows.Err()
|
||||
}
|
||||
|
||||
func GetProxy(id int) (*Proxy, error) {
|
||||
|
||||
@@ -1,20 +1,22 @@
|
||||
#!/bin/bash
|
||||
|
||||
# ============================================================
|
||||
# frpc-console 一键部署脚本
|
||||
# frpc-console 一键部署脚本 (Docker 优先)
|
||||
# 支持:Linux x86_64 / ARM64 / ARMv7
|
||||
# 自动安装:git / curl / wget / Go / Docker
|
||||
# 自动安装:git / curl / wget / Docker
|
||||
#
|
||||
# 用法:
|
||||
# ./deploy.sh # 完整交互流程
|
||||
# ./deploy.sh --yes # 跳过确认,直接执行
|
||||
# ./deploy.sh --check # 只检测环境,不执行
|
||||
# ./deploy.sh --dry-run # 显示将执行的操作,不实际执行
|
||||
# ./deploy.sh # 交互式选择通道
|
||||
# ./deploy.sh --channel lts # 指定 LTS 通道
|
||||
# ./deploy.sh --channel preview # 指定 Preview 通道
|
||||
# ./deploy.sh --yes # 跳过确认
|
||||
# ./deploy.sh --check # 只检测环境
|
||||
# ============================================================
|
||||
|
||||
set -e
|
||||
|
||||
# ---------- 颜色输出 ----------
|
||||
# ---------- 颜色检测 ----------
|
||||
if [ -t 1 ]; then
|
||||
RED='\033[0;31m'
|
||||
GREEN='\033[0;32m'
|
||||
YELLOW='\033[1;33m'
|
||||
@@ -22,6 +24,15 @@ BLUE='\033[0;34m'
|
||||
CYAN='\033[0;36m'
|
||||
MAGENTA='\033[0;35m'
|
||||
NC='\033[0m'
|
||||
else
|
||||
RED=''
|
||||
GREEN=''
|
||||
YELLOW=''
|
||||
BLUE=''
|
||||
CYAN=''
|
||||
MAGENTA=''
|
||||
NC=''
|
||||
fi
|
||||
|
||||
# ---------- 配置 ----------
|
||||
REPO_URL="https://git.whitetop.xyz/lxh2875931338/frpc-console.git"
|
||||
@@ -30,22 +41,18 @@ WORK_DIR="/tmp/frpc-console-build"
|
||||
DEFAULT_PORT=9300
|
||||
DEFAULT_DEPLOY_DIR="/opt/frpc-console"
|
||||
IMAGE_NAME="frpc-console"
|
||||
GO_VERSION="1.25.0"
|
||||
|
||||
# ---------- 状态变量 ----------
|
||||
OS=""
|
||||
OS_VERSION=""
|
||||
ARCH=""
|
||||
GO_ARCH=""
|
||||
HAS_GIT=false
|
||||
HAS_CURL=false
|
||||
HAS_WGET=false
|
||||
HAS_GO=false
|
||||
HAS_DOCKER=false
|
||||
NEED_INSTALL_GIT=false
|
||||
NEED_INSTALL_CURL=false
|
||||
NEED_INSTALL_WGET=false
|
||||
NEED_INSTALL_GO=false
|
||||
PORT=${DEFAULT_PORT}
|
||||
DEPLOY_DIR=${DEFAULT_DEPLOY_DIR}
|
||||
DATA_DIR="${DEPLOY_DIR}/data"
|
||||
@@ -54,6 +61,10 @@ CONTAINER_RUNNING=false
|
||||
SKIP_CONFIRM=false
|
||||
CHECK_ONLY=false
|
||||
DRY_RUN=false
|
||||
CHANNEL=""
|
||||
CURRENT_VERSION=""
|
||||
TARGET_VERSION=""
|
||||
IMAGE_TAG=""
|
||||
|
||||
# ---------- 打印函数 ----------
|
||||
print_info() { echo -e "${BLUE}[INFO]${NC} $1"; }
|
||||
@@ -77,19 +88,28 @@ parse_args() {
|
||||
--dry-run)
|
||||
DRY_RUN=true
|
||||
;;
|
||||
--channel)
|
||||
shift
|
||||
CHANNEL="$1"
|
||||
;;
|
||||
--channel=*)
|
||||
CHANNEL="${arg#*=}"
|
||||
;;
|
||||
--help|-h)
|
||||
echo "用法: ./deploy.sh [选项]"
|
||||
echo ""
|
||||
echo "选项:"
|
||||
echo " --yes, -y 跳过所有确认提示,直接执行"
|
||||
echo " --channel lts 使用 LTS 通道"
|
||||
echo " --channel preview 使用 Preview 通道"
|
||||
echo " --yes, -y 跳过所有确认提示"
|
||||
echo " --check 只检测环境,不执行部署"
|
||||
echo " --dry-run 显示将执行的操作,不实际执行"
|
||||
echo " --help, -h 显示帮助信息"
|
||||
echo ""
|
||||
echo "示例:"
|
||||
echo " ./deploy.sh # 完整交互流程"
|
||||
echo " ./deploy.sh # 交互式选择通道"
|
||||
echo " ./deploy.sh --channel lts # 部署 LTS 版本"
|
||||
echo " ./deploy.sh --yes # 无人值守部署"
|
||||
echo " ./deploy.sh --check # 只检测环境"
|
||||
exit 0
|
||||
;;
|
||||
*)
|
||||
@@ -126,14 +146,8 @@ detect_os() {
|
||||
detect_arch() {
|
||||
ARCH=$(uname -m)
|
||||
case $ARCH in
|
||||
x86_64|amd64)
|
||||
GO_ARCH="amd64"
|
||||
;;
|
||||
aarch64|arm64)
|
||||
GO_ARCH="arm64"
|
||||
;;
|
||||
armv7l|armhf)
|
||||
GO_ARCH="armv6l"
|
||||
x86_64|amd64|aarch64|arm64|armv7l|armhf)
|
||||
print_success "CPU 架构: $ARCH"
|
||||
;;
|
||||
*)
|
||||
print_error "不支持的 CPU 架构: $ARCH"
|
||||
@@ -144,38 +158,10 @@ detect_arch() {
|
||||
|
||||
# ---------- 检测工具 ----------
|
||||
check_tools() {
|
||||
# git
|
||||
if command -v git &> /dev/null; then
|
||||
HAS_GIT=true
|
||||
else
|
||||
NEED_INSTALL_GIT=true
|
||||
fi
|
||||
|
||||
# curl
|
||||
if command -v curl &> /dev/null; then
|
||||
HAS_CURL=true
|
||||
else
|
||||
NEED_INSTALL_CURL=true
|
||||
fi
|
||||
|
||||
# wget
|
||||
if command -v wget &> /dev/null; then
|
||||
HAS_WGET=true
|
||||
else
|
||||
NEED_INSTALL_WGET=true
|
||||
fi
|
||||
|
||||
# Go
|
||||
if command -v go &> /dev/null; then
|
||||
HAS_GO=true
|
||||
else
|
||||
NEED_INSTALL_GO=true
|
||||
fi
|
||||
|
||||
# Docker
|
||||
if command -v docker &> /dev/null; then
|
||||
HAS_DOCKER=true
|
||||
fi
|
||||
command -v git &> /dev/null && HAS_GIT=true || NEED_INSTALL_GIT=true
|
||||
command -v curl &> /dev/null && HAS_CURL=true || NEED_INSTALL_CURL=true
|
||||
command -v wget &> /dev/null && HAS_WGET=true || NEED_INSTALL_WGET=true
|
||||
command -v docker &> /dev/null && HAS_DOCKER=true
|
||||
}
|
||||
|
||||
# ---------- 检查容器状态 ----------
|
||||
@@ -188,27 +174,149 @@ check_container() {
|
||||
fi
|
||||
}
|
||||
|
||||
# ---------- 获取系统包管理器 ----------
|
||||
get_package_manager() {
|
||||
case $OS in
|
||||
opensuse*|suse*|opensuse-tumbleweed|opensuse-slowroll|opensuse-leap)
|
||||
echo "zypper"
|
||||
;;
|
||||
ubuntu|debian|linuxmint)
|
||||
echo "apt"
|
||||
;;
|
||||
centos|rhel|fedora|rocky|almalinux)
|
||||
echo "yum"
|
||||
;;
|
||||
alpine)
|
||||
echo "apk"
|
||||
;;
|
||||
arch|manjaro|endeavouros)
|
||||
echo "pacman"
|
||||
;;
|
||||
*)
|
||||
echo "unknown"
|
||||
;;
|
||||
# ---------- 版本管理函数 ----------
|
||||
|
||||
# read_version_file 读取仓库的 VERSION.ini 文件
|
||||
read_version_file() {
|
||||
local version_file="./VERSION.ini"
|
||||
if [ ! -f "$version_file" ]; then
|
||||
print_error "VERSION.ini 文件不存在: $version_file"
|
||||
return 1
|
||||
fi
|
||||
# 去掉注释行(以 ; 或 # 开头),读取第一列为语义版本
|
||||
SEMVER=$(grep -v "^[;#]" "$version_file" | head -1 | awk '{print $1}')
|
||||
LTS_DATE=$(grep -v "^[;#]" "$version_file" | head -1 | awk '{print $2}')
|
||||
echo "$SEMVER $LTS_DATE"
|
||||
}
|
||||
|
||||
# get_version_type 判断版本类型
|
||||
get_version_type() {
|
||||
local semver="$1"
|
||||
local minor="${semver#*.}"
|
||||
if [ "$minor" = "0" ] || [ "$minor" = "5" ]; then
|
||||
echo "lts"
|
||||
else
|
||||
echo "preview"
|
||||
fi
|
||||
}
|
||||
|
||||
# generate_target_version 生成目标版本字符串
|
||||
generate_target_version() {
|
||||
local channel="$1"
|
||||
local semver_lts_date
|
||||
semver_lts_date=$(read_version_file)
|
||||
SEMVER=$(echo "$semver_lts_date" | awk '{print $1}')
|
||||
LTS_DATE=$(echo "$semver_lts_date" | awk '{print $2}')
|
||||
|
||||
if [ -z "$SEMVER" ]; then
|
||||
print_error "无法从 VERSION.ini 读取语义版本"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
local vtype
|
||||
vtype=$(get_version_type "$SEMVER")
|
||||
|
||||
if [ "$channel" = "lts" ] || [ "$vtype" = "lts" ]; then
|
||||
# LTS 版本必须有日期
|
||||
if [ -z "$LTS_DATE" ]; then
|
||||
LTS_DATE=$(date +%Y%m%d)
|
||||
print_warn "LTS 版本未指定日期,使用今天: $LTS_DATE"
|
||||
fi
|
||||
TARGET_VERSION="${SEMVER}-lts-${LTS_DATE}"
|
||||
IMAGE_TAG="${SEMVER}-lts-${LTS_DATE}"
|
||||
else
|
||||
# Preview 版本使用编译时间戳
|
||||
TIMESTAMP=$(date +%Y%m%d-%H%M%S)
|
||||
TARGET_VERSION="${SEMVER}-preview-${TIMESTAMP}"
|
||||
IMAGE_TAG="preview-${TIMESTAMP}"
|
||||
fi
|
||||
echo "$TARGET_VERSION $IMAGE_TAG"
|
||||
}
|
||||
|
||||
# get_current_version 获取当前运行的版本
|
||||
get_current_version() {
|
||||
local version_file="${DEPLOY_DIR}/VERSION.ini"
|
||||
if [ -f "$version_file" ]; then
|
||||
# 去掉注释行,读取第一行内容
|
||||
grep -v "^[;#]" "$version_file" | head -1 | tr -d '\n'
|
||||
else
|
||||
# 兼容旧版本
|
||||
if [ "$CONTAINER_EXISTS" = true ]; then
|
||||
docker exec frpc-console cat /app/VERSION.ini 2>/dev/null | grep -v "^[;#]" | head -1 | tr -d '\n' || echo "0.0.0-dev"
|
||||
else
|
||||
echo "0.0.0-dev"
|
||||
fi
|
||||
fi
|
||||
}
|
||||
|
||||
# extract_semver 提取语义版本
|
||||
extract_semver() {
|
||||
local version="$1"
|
||||
echo "$version" | sed -E 's/^([0-9]+\.[0-9]+).*$/\1/'
|
||||
}
|
||||
|
||||
# extract_timestamp 提取时间戳
|
||||
extract_timestamp() {
|
||||
local version="$1"
|
||||
echo "$version" | sed -E 's/^[0-9]+\.[0-9]+-(lts|preview)-//'
|
||||
}
|
||||
|
||||
# compare_version 比较两个版本
|
||||
# 返回: 0=相等, 1=目标更新, 2=目标更旧
|
||||
compare_version() {
|
||||
local current="$1"
|
||||
local target="$2"
|
||||
|
||||
local cur_semver=$(extract_semver "$current")
|
||||
local tgt_semver=$(extract_semver "$target")
|
||||
|
||||
if [ "$tgt_semver" -gt "$cur_semver" ] 2>/dev/null; then
|
||||
return 1
|
||||
fi
|
||||
if [ "$tgt_semver" -lt "$cur_semver" ] 2>/dev/null; then
|
||||
return 2
|
||||
fi
|
||||
|
||||
local cur_ts=$(extract_timestamp "$current")
|
||||
local tgt_ts=$(extract_timestamp "$target")
|
||||
|
||||
if [ -z "$cur_ts" ]; then
|
||||
cur_ts="0"
|
||||
fi
|
||||
if [ -z "$tgt_ts" ]; then
|
||||
tgt_ts="0"
|
||||
fi
|
||||
|
||||
if [ "$tgt_ts" -gt "$cur_ts" ] 2>/dev/null; then
|
||||
return 1
|
||||
elif [ "$tgt_ts" -eq "$cur_ts" ] 2>/dev/null; then
|
||||
return 0
|
||||
else
|
||||
return 2
|
||||
fi
|
||||
}
|
||||
|
||||
# ---------- 通道选择 ----------
|
||||
select_channel() {
|
||||
if [ -n "$CHANNEL" ]; then
|
||||
if [ "$CHANNEL" != "lts" ] && [ "$CHANNEL" != "preview" ]; then
|
||||
print_error "无效通道: $CHANNEL (仅支持 lts / preview)"
|
||||
exit 1
|
||||
fi
|
||||
return
|
||||
fi
|
||||
|
||||
echo ""
|
||||
echo -e "${CYAN}请选择部署通道:${NC}"
|
||||
echo " 1. LTS (稳定版,生产推荐) [默认]"
|
||||
echo " 2. Preview (技术预览版,包含新特性)"
|
||||
echo ""
|
||||
read -p "请选择 [1]: " CHANNEL_INPUT </dev/tty
|
||||
CHANNEL_INPUT=${CHANNEL_INPUT:-1}
|
||||
case $CHANNEL_INPUT in
|
||||
1|"") CHANNEL="lts" ;;
|
||||
2) CHANNEL="preview" ;;
|
||||
*) print_error "无效选择"; exit 1 ;;
|
||||
esac
|
||||
}
|
||||
|
||||
@@ -219,14 +327,14 @@ print_environment_summary() {
|
||||
echo ""
|
||||
|
||||
echo -e " ${CYAN}操作系统:${NC} $OS $OS_VERSION"
|
||||
echo -e " ${CYAN}CPU 架构:${NC} $ARCH → Go 架构: $GO_ARCH"
|
||||
echo -e " ${CYAN}CPU 架构:${NC} $ARCH"
|
||||
echo ""
|
||||
|
||||
echo " ${CYAN}必要工具:${NC}"
|
||||
if [ "$HAS_GIT" = true ]; then
|
||||
echo -e " git ✅ 已安装 ($(git --version | awk '{print $3}'))"
|
||||
else
|
||||
echo -e " git ❌ 未安装 (将自动安装)"
|
||||
echo " git ❌ 未安装 (将自动安装)"
|
||||
fi
|
||||
if [ "$HAS_CURL" = true ]; then
|
||||
echo " curl ✅ 已安装"
|
||||
@@ -239,14 +347,6 @@ print_environment_summary() {
|
||||
echo " wget ❌ 未安装 (将自动安装)"
|
||||
fi
|
||||
|
||||
echo ""
|
||||
echo " ${CYAN}Go 环境:${NC}"
|
||||
if [ "$HAS_GO" = true ]; then
|
||||
echo -e " go ✅ 已安装 ($(go version | awk '{print $3}'))"
|
||||
else
|
||||
echo " go ❌ 未安装 (将自动安装 Go ${GO_VERSION})"
|
||||
fi
|
||||
|
||||
echo ""
|
||||
echo " ${CYAN}Docker 环境:${NC}"
|
||||
if [ "$HAS_DOCKER" = true ]; then
|
||||
@@ -262,15 +362,16 @@ print_environment_summary() {
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# 容器状态
|
||||
if [ "$CONTAINER_EXISTS" = true ]; then
|
||||
echo ""
|
||||
echo " ${CYAN}容器状态:${NC}"
|
||||
if [ "$CONTAINER_RUNNING" = true ]; then
|
||||
echo -e " frpc-console ✅ 运行中"
|
||||
else
|
||||
echo -e " frpc-console ⏸️ 已存在但未运行"
|
||||
echo -e " frpc-console ⏸️ 已停止"
|
||||
fi
|
||||
CURRENT_VERSION=$(get_current_version)
|
||||
echo -e " ${CYAN}当前版本:${NC} $CURRENT_VERSION"
|
||||
fi
|
||||
|
||||
echo ""
|
||||
@@ -286,16 +387,13 @@ generate_plan() {
|
||||
[ "$NEED_INSTALL_WGET" = true ] && pkgs="${pkgs} wget"
|
||||
PLAN="${PLAN} • 安装必要工具:${pkgs}\n"
|
||||
fi
|
||||
if [ "$NEED_INSTALL_GO" = true ]; then
|
||||
PLAN="${PLAN} • 安装 Go ${GO_VERSION}\n"
|
||||
fi
|
||||
PLAN="${PLAN} • 拉取 frpc-console 源码 (${BRANCH} 分支)\n"
|
||||
PLAN="${PLAN} • 编译 frpc-console 二进制\n"
|
||||
PLAN="${PLAN} • 构建 Docker 镜像\n"
|
||||
PLAN="${PLAN} • 构建 Docker 镜像: ${IMAGE_NAME}:${IMAGE_TAG}\n"
|
||||
PLAN="${PLAN} • 目标版本: ${TARGET_VERSION}\n"
|
||||
if [ "$CONTAINER_EXISTS" = true ]; then
|
||||
PLAN="${PLAN} • 停止并删除旧容器\n"
|
||||
fi
|
||||
PLAN="${PLAN} • 启动 frpc-console 容器"
|
||||
PLAN="${PLAN} • 启动 frpc-console 容器 (端口 ${PORT})"
|
||||
}
|
||||
|
||||
# ---------- 展示部署计划 ----------
|
||||
@@ -312,18 +410,15 @@ print_deployment_plan() {
|
||||
echo -e " ────────────────────────────────────"
|
||||
echo -e " 监听端口 : ${PORT}"
|
||||
echo -e " 部署目录 : ${DEPLOY_DIR}"
|
||||
echo -e " 数据目录 : ${DATA_DIR}"
|
||||
echo -e " 目标版本 : ${TARGET_VERSION}"
|
||||
echo -e " 镜像标签 : ${IMAGE_TAG}"
|
||||
echo -e " ────────────────────────────────────"
|
||||
|
||||
if [ "$CONTAINER_EXISTS" = true ]; then
|
||||
echo ""
|
||||
echo -e " ${YELLOW}⚠ 检测到已存在的 frpc-console 容器${NC}"
|
||||
if [ "$CONTAINER_RUNNING" = true ]; then
|
||||
echo -e " 状态: 运行中 → 将被停止并重新创建"
|
||||
else
|
||||
echo -e " 状态: 已停止 → 将被删除并重新创建"
|
||||
fi
|
||||
echo -e " ${YELLOW}数据目录中的数据库文件将被保留${NC}"
|
||||
echo -e " 当前版本: ${CURRENT_VERSION}"
|
||||
echo -e " 目标版本: ${TARGET_VERSION}"
|
||||
fi
|
||||
|
||||
echo ""
|
||||
@@ -335,9 +430,10 @@ confirm_deploy() {
|
||||
echo -e "${GREEN}▶ 已启用 --yes,自动确认${NC}"
|
||||
return 0
|
||||
fi
|
||||
|
||||
echo -e -n "${CYAN}确认执行? 输入 Y 继续,输入 n 自定义配置 [Y/n]: ${NC}"
|
||||
# 强制从 /dev/tty 读取,而不是继承 stdin
|
||||
read -r CONFIRM </dev/tty
|
||||
|
||||
case $CONFIRM in
|
||||
n|N) return 1 ;;
|
||||
*) return 0 ;;
|
||||
@@ -367,12 +463,47 @@ custom_config() {
|
||||
echo ""
|
||||
}
|
||||
|
||||
# ---------- 实际执行部署 ----------
|
||||
# ---------- 执行部署 ----------
|
||||
do_deploy() {
|
||||
print_title
|
||||
print_subtitle "开始部署"
|
||||
echo ""
|
||||
|
||||
# ----- 事务前钩子:备份数据库(仅降级时备份) -----
|
||||
BACKUP_DIR=""
|
||||
if [ -n "$CURRENT_VERSION" ] && [ "$CURRENT_VERSION" != "0.0.0-dev" ]; then
|
||||
compare_version "$CURRENT_VERSION" "$TARGET_VERSION"
|
||||
COMPARE_RESULT=$?
|
||||
if [ $COMPARE_RESULT -eq 2 ]; then
|
||||
print_warn "检测到降级操作: $CURRENT_VERSION → $TARGET_VERSION"
|
||||
echo ""
|
||||
echo -e "${YELLOW}⚠ 降级可能导致数据不兼容${NC}"
|
||||
echo " 当前版本: $CURRENT_VERSION"
|
||||
echo " 目标版本: $TARGET_VERSION"
|
||||
echo ""
|
||||
echo -e "${CYAN}将备份完整数据目录到:${NC}"
|
||||
TIMESTAMP=$(date +%Y%m%d_%H%M%S)
|
||||
BACKUP_DIR="/opt/frpc-console-backups/${TIMESTAMP}_${CHANNEL}"
|
||||
echo " $BACKUP_DIR"
|
||||
echo ""
|
||||
|
||||
read -p "确认执行降级? [y/N]: " CONFIRM_DOWNGRADE </dev/tty
|
||||
if [[ ! "$CONFIRM_DOWNGRADE" =~ ^[Yy]$ ]]; then
|
||||
print_info "已取消降级操作"
|
||||
exit 0
|
||||
fi
|
||||
|
||||
print_step "执行降级前备份..."
|
||||
mkdir -p "$BACKUP_DIR"
|
||||
if [ -d "$DEPLOY_DIR" ]; then
|
||||
cp -r "$DEPLOY_DIR" "$BACKUP_DIR/frpc-console"
|
||||
print_success "备份完成: $BACKUP_DIR"
|
||||
else
|
||||
print_warn "部署目录不存在,跳过备份"
|
||||
fi
|
||||
fi
|
||||
fi
|
||||
|
||||
# ----- 安装必要工具 -----
|
||||
if [ "$NEED_INSTALL_GIT" = true ] || [ "$NEED_INSTALL_CURL" = true ] || [ "$NEED_INSTALL_WGET" = true ]; then
|
||||
print_step "安装必要工具..."
|
||||
@@ -383,7 +514,13 @@ do_deploy() {
|
||||
|
||||
case $OS in
|
||||
opensuse*|suse*|opensuse-tumbleweed|opensuse-slowroll|opensuse-leap)
|
||||
zypper install -y $pkgs-core
|
||||
if [ "$NEED_INSTALL_GIT" = true ]; then
|
||||
zypper install -y git-core
|
||||
pkgs=$(echo "$pkgs" | sed -E 's/(^| )git( |$)/ /g' | sed 's/ */ /g' | sed 's/^ //;s/ $//')
|
||||
fi
|
||||
if [ -n "$pkgs" ]; then
|
||||
zypper install -y $pkgs
|
||||
fi
|
||||
;;
|
||||
ubuntu|debian|linuxmint)
|
||||
apt update -qq && apt install -y $pkgs
|
||||
@@ -405,58 +542,6 @@ do_deploy() {
|
||||
print_success "必要工具安装完成"
|
||||
fi
|
||||
|
||||
# ----- 安装 Go -----
|
||||
if [ "$NEED_INSTALL_GO" = true ]; then
|
||||
print_step "安装 Go ${GO_VERSION} (${GO_ARCH})..."
|
||||
|
||||
GO_TMP="/tmp/go${GO_VERSION}.linux-${GO_ARCH}.tar.gz"
|
||||
|
||||
if [ -f "$GO_TMP" ]; then
|
||||
print_info "使用缓存: $GO_TMP"
|
||||
else
|
||||
print_info "正在下载..."
|
||||
MIRRORS=(
|
||||
"https://mirrors.aliyun.com/golang/go${GO_VERSION}.linux-${GO_ARCH}.tar.gz"
|
||||
"https://mirrors.tuna.tsinghua.edu.cn/golang/go${GO_VERSION}.linux-${GO_ARCH}.tar.gz"
|
||||
"https://golang.google.cn/dl/go${GO_VERSION}.linux-${GO_ARCH}.tar.gz"
|
||||
"https://dl.google.com/go/go${GO_VERSION}.linux-${GO_ARCH}.tar.gz"
|
||||
)
|
||||
|
||||
DOWNLOADED=false
|
||||
for MIRROR in "${MIRRORS[@]}"; do
|
||||
print_info "尝试: $MIRROR"
|
||||
if curl -# -f -L -o "$GO_TMP" "$MIRROR"; then
|
||||
print_success "下载成功"
|
||||
DOWNLOADED=true
|
||||
break
|
||||
else
|
||||
print_warn "失败,尝试下一个镜像..."
|
||||
rm -f "$GO_TMP"
|
||||
fi
|
||||
done
|
||||
|
||||
if [ "$DOWNLOADED" = false ]; then
|
||||
print_error "所有镜像源均下载失败"
|
||||
exit 1
|
||||
fi
|
||||
fi
|
||||
|
||||
rm -rf /usr/local/go
|
||||
tar -C /usr/local -xzf "$GO_TMP"
|
||||
export PATH=$PATH:/usr/local/go/bin
|
||||
if [ ! -f /etc/profile.d/go.sh ]; then
|
||||
echo 'export PATH=$PATH:/usr/local/go/bin' > /etc/profile.d/go.sh
|
||||
fi
|
||||
|
||||
/usr/local/go/bin/go env -w GOPROXY=https://goproxy.cn,direct
|
||||
/usr/local/go/bin/go env -w GOPRIVATE=git.whitetop.xyz
|
||||
|
||||
print_success "Go ${GO_VERSION} (${GO_ARCH}) 安装完成"
|
||||
fi
|
||||
|
||||
# 确保 go 在 PATH 中
|
||||
export PATH=$PATH:/usr/local/go/bin
|
||||
|
||||
# ----- 拉取代码 -----
|
||||
print_step "拉取代码..."
|
||||
rm -rf "$WORK_DIR"
|
||||
@@ -465,30 +550,14 @@ do_deploy() {
|
||||
mkdir -p bin static
|
||||
print_success "代码拉取完成"
|
||||
|
||||
# ----- 修复 go.mod -----
|
||||
print_step "检查 go.mod..."
|
||||
if grep -q "go 1.2[6-9]" go.mod 2>/dev/null; then
|
||||
print_warn "检测到 go.mod 版本过高,自动降级到 go 1.21"
|
||||
sed -i 's/go 1.2[6-9].*/go 1.21/' go.mod
|
||||
# ----- 停止旧容器(拉取代码之后)-----
|
||||
if [ "$CONTAINER_EXISTS" = true ]; then
|
||||
print_step "停止旧容器..."
|
||||
if [ "$CONTAINER_RUNNING" = true ]; then
|
||||
docker stop frpc-console 2>/dev/null || true
|
||||
fi
|
||||
|
||||
# ----- 下载依赖 -----
|
||||
print_step "下载 Go 依赖..."
|
||||
go mod download
|
||||
print_success "依赖下载完成"
|
||||
|
||||
# ----- 编译 -----
|
||||
print_step "编译 frpc-console..."
|
||||
CGO_ENABLED=0 GOOS=linux go build \
|
||||
-ldflags="-s -w" \
|
||||
-o frpc-console .
|
||||
|
||||
if [ -f "frpc-console" ]; then
|
||||
SIZE=$(du -h frpc-console | cut -f1)
|
||||
print_success "编译完成 ($SIZE)"
|
||||
else
|
||||
print_error "编译失败"
|
||||
exit 1
|
||||
docker rm frpc-console 2>/dev/null || true
|
||||
print_success "旧容器已清理"
|
||||
fi
|
||||
|
||||
# ----- 准备部署目录 -----
|
||||
@@ -496,29 +565,21 @@ do_deploy() {
|
||||
mkdir -p "$DEPLOY_DIR"
|
||||
mkdir -p "$DATA_DIR"
|
||||
|
||||
if [ ! -f "$DATA_DIR/frpc-console.db" ]; then
|
||||
touch "$DATA_DIR/frpc-console.db"
|
||||
print_info "新数据目录已创建"
|
||||
else
|
||||
print_info "已有数据目录,保留现有数据"
|
||||
fi
|
||||
|
||||
cp frpc-console "$DEPLOY_DIR/"
|
||||
print_success "二进制已复制到 $DEPLOY_DIR"
|
||||
|
||||
# ----- 构建 Docker 镜像 -----
|
||||
print_step "构建 Docker 镜像..."
|
||||
docker build -t "${IMAGE_NAME}:latest" .
|
||||
print_success "Docker 镜像构建完成: ${IMAGE_NAME}:latest"
|
||||
docker build -t "${IMAGE_NAME}:${IMAGE_TAG}" \
|
||||
--build-arg VERSION="${TARGET_VERSION}" \
|
||||
--build-arg IMAGE_TAG="${IMAGE_TAG}" \
|
||||
.
|
||||
|
||||
# ----- 停止旧容器 -----
|
||||
if [ "$CONTAINER_EXISTS" = true ]; then
|
||||
print_step "处理旧容器..."
|
||||
if [ "$CONTAINER_RUNNING" = true ]; then
|
||||
docker stop frpc-console 2>/dev/null || true
|
||||
fi
|
||||
docker rm frpc-console 2>/dev/null || true
|
||||
print_success "旧容器已清理"
|
||||
print_success "Docker 镜像构建完成: ${IMAGE_NAME}:${IMAGE_TAG}"
|
||||
|
||||
if [ "$CHANNEL" = "lts" ]; then
|
||||
docker tag "${IMAGE_NAME}:${IMAGE_TAG}" "${IMAGE_NAME}:lts"
|
||||
print_info "已标记 ${IMAGE_NAME}:lts"
|
||||
else
|
||||
docker tag "${IMAGE_NAME}:${IMAGE_TAG}" "${IMAGE_NAME}:preview"
|
||||
print_info "已标记 ${IMAGE_NAME}:preview"
|
||||
fi
|
||||
|
||||
# ----- 启动新容器 -----
|
||||
@@ -527,10 +588,10 @@ do_deploy() {
|
||||
--name frpc-console \
|
||||
--restart=always \
|
||||
--network host \
|
||||
-v ${DATA_DIR}:/app/data \
|
||||
-v ${DEPLOY_DIR}:/app \
|
||||
-e PORT=${PORT} \
|
||||
-e TZ=Asia/Shanghai \
|
||||
${IMAGE_NAME}:latest
|
||||
${IMAGE_NAME}:${IMAGE_TAG}
|
||||
|
||||
if docker ps | grep -q frpc-console; then
|
||||
print_success "容器启动成功!"
|
||||
@@ -542,11 +603,43 @@ do_deploy() {
|
||||
# ----- 检查 frpc 子进程 -----
|
||||
print_step "检查 frpc 状态..."
|
||||
sleep 3
|
||||
|
||||
if docker ps --format '{{.Names}}' | grep -q "^frpc-console$"; then
|
||||
if docker exec frpc-console ps aux 2>/dev/null | grep -q "[f]rpc -c"; then
|
||||
print_success "frpc 进程运行正常"
|
||||
else
|
||||
print_warn "frpc 进程未运行(可能配置为空,请在 WebUI 中导入 TOML)"
|
||||
fi
|
||||
else
|
||||
print_error "frpc-console 容器未运行,请检查日志"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# ----- 事务后钩子:检测数据库 -----
|
||||
print_step "验证数据库状态..."
|
||||
if docker exec frpc-console sqlite3 /app/frpc-console.db "SELECT COUNT(*) FROM users;" 2>/dev/null | grep -q "^[0-9]"; then
|
||||
print_success "数据库可用"
|
||||
else
|
||||
print_warn "数据库为空或不可用,请通过 WebUI 注册管理员账户"
|
||||
fi
|
||||
|
||||
# ----- 验证版本写入 -----
|
||||
print_step "验证版本..."
|
||||
sleep 1
|
||||
CONTAINER_VERSION=$(docker exec frpc-console cat /app/VERSION.ini 2>/dev/null | grep -v "^[;#]" | head -1 | tr -d '\n' || echo "unknown")
|
||||
echo -e " 容器版本: ${CONTAINER_VERSION}"
|
||||
echo -e " 目标版本: ${TARGET_VERSION}"
|
||||
if [ "$CONTAINER_VERSION" = "$TARGET_VERSION" ]; then
|
||||
print_success "版本写入成功"
|
||||
else
|
||||
print_warn "版本不匹配,请检查"
|
||||
fi
|
||||
|
||||
if [ -n "$BACKUP_DIR" ]; then
|
||||
echo ""
|
||||
print_warn "降级前数据已备份到: $BACKUP_DIR"
|
||||
echo " 如需回退,请恢复: cp -r $BACKUP_DIR/frpc-console/* $DEPLOY_DIR/"
|
||||
fi
|
||||
|
||||
# ----- 清理临时文件 -----
|
||||
print_step "清理临时文件..."
|
||||
@@ -560,46 +653,52 @@ do_deploy() {
|
||||
|
||||
echo ""
|
||||
echo -e " ${CYAN}📍 访问地址:${NC} http://$(hostname -I | awk '{print $1}'):${PORT}"
|
||||
echo -e " ${CYAN}📂 数据目录:${NC} ${DATA_DIR}"
|
||||
echo -e " ${CYAN}📂 数据目录:${NC} ${DEPLOY_DIR}"
|
||||
echo -e " ${CYAN}📦 备份目录:${NC} /tmp/frpc-console/db-backups"
|
||||
echo -e " ${CYAN}🐳 容器名称:${NC} frpc-console"
|
||||
echo -e " ${CYAN}🏷️ 版本:${NC} ${TARGET_VERSION}"
|
||||
echo ""
|
||||
echo -e " ${CYAN}常用命令:${NC}"
|
||||
echo " docker logs frpc-console # 查看日志"
|
||||
echo " docker restart frpc-console # 重启服务"
|
||||
echo " docker stop frpc-console # 停止服务"
|
||||
echo " docker start frpc-console # 启动服务"
|
||||
echo " cat ${DEPLOY_DIR}/VERSION.ini # 查看当前版本"
|
||||
echo ""
|
||||
echo -e " ${YELLOW}首次访问需要注册管理员账户${NC}"
|
||||
echo ""
|
||||
print_title
|
||||
}
|
||||
|
||||
# ---------- 主流程 ----------
|
||||
# ---------- 主流程 ----------
|
||||
main() {
|
||||
# 清屏,让输出从头开始
|
||||
clear 2>/dev/null || true
|
||||
|
||||
parse_args "$@"
|
||||
check_root
|
||||
|
||||
# ---- 环境检测 ----
|
||||
print_step "正在检测环境..."
|
||||
print_step "检测环境..."
|
||||
detect_os
|
||||
detect_arch
|
||||
check_tools
|
||||
check_container
|
||||
|
||||
# ---- 展示检测结果 ----
|
||||
select_channel
|
||||
|
||||
generate_target_version "$CHANNEL"
|
||||
|
||||
if [ "$CONTAINER_EXISTS" = true ]; then
|
||||
CURRENT_VERSION=$(get_current_version)
|
||||
else
|
||||
CURRENT_VERSION="(首次部署)"
|
||||
fi
|
||||
|
||||
print_environment_summary
|
||||
|
||||
# ---- 如果只检测 ----
|
||||
if [ "$CHECK_ONLY" = true ]; then
|
||||
print_info "环境检测完成(--check 模式,不执行部署)"
|
||||
exit 0
|
||||
fi
|
||||
|
||||
# ---- 如果 Docker 未安装 ----
|
||||
if [ "$HAS_DOCKER" = false ]; then
|
||||
print_error "Docker 未安装,请先安装 Docker"
|
||||
echo ""
|
||||
@@ -610,15 +709,12 @@ main() {
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# ---- 生成部署计划 ----
|
||||
generate_plan
|
||||
|
||||
# ---- 展示部署计划 ----
|
||||
print_deployment_plan
|
||||
|
||||
# ---- 确认或自定义 ----
|
||||
if ! confirm_deploy; then
|
||||
custom_config
|
||||
generate_plan
|
||||
print_deployment_plan
|
||||
if ! confirm_deploy; then
|
||||
print_info "已取消部署"
|
||||
@@ -626,15 +722,12 @@ main() {
|
||||
fi
|
||||
fi
|
||||
|
||||
# ---- 如果只是演练 ----
|
||||
if [ "$DRY_RUN" = true ]; then
|
||||
print_info "演练模式(--dry-run),不实际执行部署"
|
||||
exit 0
|
||||
fi
|
||||
|
||||
# ---- 执行部署 ----
|
||||
do_deploy
|
||||
}
|
||||
|
||||
# ---------- 入口 ----------
|
||||
main "$@"
|
||||
@@ -2,15 +2,29 @@ package main
|
||||
|
||||
import (
|
||||
"log"
|
||||
"os"
|
||||
"time"
|
||||
)
|
||||
|
||||
// 由 build.go 通过 -ldflags 注入
|
||||
var (
|
||||
buildVersion = "0.0.0-dev"
|
||||
buildImageTag = "dev"
|
||||
buildTime = "unknown"
|
||||
)
|
||||
|
||||
func main() {
|
||||
// ---- 写入 VERSION.ini 文件到持久化目录 ----
|
||||
if err := os.WriteFile("./VERSION.ini", []byte(buildVersion+"\n"), 0644); err != nil {
|
||||
log.Printf("⚠️ 写入 VERSION.ini 文件失败: %v", err)
|
||||
} else {
|
||||
log.Printf("📌 版本: %s", buildVersion)
|
||||
}
|
||||
|
||||
if err := InitDB(); err != nil {
|
||||
log.Fatal("❌ 数据库初始化失败:", err)
|
||||
}
|
||||
|
||||
// 启动时生成配置并启动 frpc
|
||||
if err := GenerateFrpcConfig(); err != nil {
|
||||
log.Println("⚠️ 生成配置文件失败:", err)
|
||||
}
|
||||
@@ -19,7 +33,6 @@ func main() {
|
||||
log.Println("⚠️ 启动 frpc 失败:", err)
|
||||
}
|
||||
|
||||
// ✅ 启动 Watchdog:每 30 秒检查一次 frpc 状态,挂了自动重启
|
||||
go startWatchdog()
|
||||
|
||||
r := SetupRouter()
|
||||
@@ -32,7 +45,6 @@ func main() {
|
||||
}
|
||||
}
|
||||
|
||||
// Watchdog 协程:定期检查 frpc 是否存活
|
||||
func startWatchdog() {
|
||||
ticker := time.NewTicker(30 * time.Second)
|
||||
defer ticker.Stop()
|
||||
|
||||
@@ -142,7 +142,14 @@ go build -ldflags="-s -w" -o frpc-console .
|
||||
|
||||
#### Q: frpc 启动失败怎么办?
|
||||
|
||||
检查 frpc.toml 配置是否正确,或查看 ./frpc.log 日志文件。
|
||||
如果是首次启动,console 会自动生成一份符合官方规范的 `frps.toml` 配置文件,通常不需要额外操作。
|
||||
|
||||
如果在使用过程中遇到启动失败,可以按以下步骤排查:
|
||||
|
||||
1. **检查配置是否正确** —— 在「全局配置」页面重新配置一次服务端参数,或导入已有的 `frpc.toml` 配置文件,console 会自动应用并尝试重启
|
||||
2. **查看日志定位问题** —— 若上述操作后仍然失败,请查看 `./frpc.log` 日志文件,定位具体报错原因
|
||||
|
||||
> 日志文件的位置:与 `frpc-console` 二进制同级目录下的 `frpc.log`。Docker 部署时,可通过 `docker logs frpc-console` 查看容器输出。
|
||||
|
||||
#### Q: 支持哪些 frp 版本?
|
||||
|
||||
@@ -289,7 +296,7 @@ frpc-console 遵循 **“够用就好”** 的原则:
|
||||
|
||||
## 📄 许可证
|
||||
|
||||
MIT License © 2026 Gitea:lxh2875931338/Github:XHLiang0
|
||||
MIT License © 2026 lxh2875931338(XHLiang0)
|
||||
|
||||
---
|
||||
|
||||
|
||||
+119
-10
@@ -9,6 +9,7 @@ import (
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
type Platform struct {
|
||||
@@ -22,15 +23,99 @@ var platforms = []Platform{
|
||||
{"windows", "amd64", "Windows x86-64", ".exe"},
|
||||
{"linux", "amd64", "Linux x86-64", ""},
|
||||
{"linux", "arm64", "Linux ARM64", ""},
|
||||
{"linux", "arm", "Linux ARMv7l", ""}, // GOARCH=arm, GOARM=7
|
||||
{"linux", "arm", "Linux ARMv7l", ""},
|
||||
}
|
||||
|
||||
const (
|
||||
Version = "2.0.0"
|
||||
BuildTime = "2026-07-26"
|
||||
BuildTime = "2026-07-29"
|
||||
Binary = "frpc-console"
|
||||
)
|
||||
|
||||
// ============================================================
|
||||
// 版本管理核心
|
||||
// ============================================================
|
||||
|
||||
// readVersion 读取仓库根目录的 VERSION.ini 文件
|
||||
// Preview 格式: "2.4"
|
||||
// LTS 格式: "2.5 20260729"
|
||||
func readVersion() (semver string, ltsDate string) {
|
||||
data, err := os.ReadFile("./VERSION.ini")
|
||||
if err != nil {
|
||||
return "0.0.0", ""
|
||||
}
|
||||
// 去掉注释行(以 ; 或 # 开头)
|
||||
lines := strings.Split(string(data), "\n")
|
||||
var content string
|
||||
for _, line := range lines {
|
||||
line = strings.TrimSpace(line)
|
||||
if line == "" || strings.HasPrefix(line, ";") || strings.HasPrefix(line, "#") {
|
||||
continue
|
||||
}
|
||||
content = line
|
||||
break
|
||||
}
|
||||
parts := strings.Fields(content)
|
||||
if len(parts) < 1 {
|
||||
return "0.0.0", ""
|
||||
}
|
||||
semver = parts[0]
|
||||
if len(parts) > 1 {
|
||||
ltsDate = parts[1]
|
||||
}
|
||||
return semver, ltsDate
|
||||
}
|
||||
|
||||
// getVersionType 判断版本类型
|
||||
// 规则: X.0 或 X.5 → LTS,其他 → Preview
|
||||
func getVersionType(semver string) string {
|
||||
parts := strings.Split(semver, ".")
|
||||
if len(parts) < 2 {
|
||||
return "preview"
|
||||
}
|
||||
minor := parts[1]
|
||||
if minor == "0" || minor == "5" {
|
||||
return "lts"
|
||||
}
|
||||
return "preview"
|
||||
}
|
||||
|
||||
// getFullVersion 生成完整版本字符串
|
||||
// LTS (X.0/X.5): {semver}-lts-{ltsDate} (必须有日期)
|
||||
// Preview (其他): {semver}-preview-{buildTimestamp}
|
||||
func getFullVersion() string {
|
||||
semver, ltsDate := readVersion()
|
||||
vType := getVersionType(semver)
|
||||
|
||||
switch vType {
|
||||
case "lts":
|
||||
if ltsDate == "" {
|
||||
ltsDate = time.Now().Format("20060102")
|
||||
}
|
||||
return semver + "-lts-" + ltsDate
|
||||
default:
|
||||
timestamp := time.Now().Format("20060102-150405")
|
||||
return semver + "-preview-" + timestamp
|
||||
}
|
||||
}
|
||||
|
||||
// getImageTag 生成镜像标签
|
||||
// LTS: {semver}-lts-{ltsDate}
|
||||
// Preview: preview-{buildTimestamp}
|
||||
func getImageTag() string {
|
||||
semver, ltsDate := readVersion()
|
||||
vType := getVersionType(semver)
|
||||
|
||||
switch vType {
|
||||
case "lts":
|
||||
if ltsDate == "" {
|
||||
ltsDate = time.Now().Format("20060102")
|
||||
}
|
||||
return semver + "-lts-" + ltsDate
|
||||
default:
|
||||
return "preview-" + time.Now().Format("20060102-150405")
|
||||
}
|
||||
}
|
||||
|
||||
func main() {
|
||||
if len(os.Args) > 1 {
|
||||
target := os.Args[1]
|
||||
@@ -44,6 +129,12 @@ func main() {
|
||||
case "list":
|
||||
listPlatforms()
|
||||
return
|
||||
case "version":
|
||||
fmt.Println(getFullVersion())
|
||||
return
|
||||
case "image-tag":
|
||||
fmt.Println(getImageTag())
|
||||
return
|
||||
}
|
||||
for _, p := range platforms {
|
||||
if target == p.OS+"/"+p.Arch {
|
||||
@@ -52,13 +143,17 @@ func main() {
|
||||
}
|
||||
}
|
||||
fmt.Println("❌ 不支持的平台:", target)
|
||||
fmt.Println(" 可用: windows/amd64, linux/amd64, linux/arm64, linux/armv7")
|
||||
fmt.Println(" 或: all, list, clean")
|
||||
fmt.Println(" 可用: windows/amd64, linux/amd64, linux/arm64, linux/arm")
|
||||
fmt.Println(" 或: all, list, clean, version, image-tag")
|
||||
return
|
||||
}
|
||||
interactiveMenu()
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// 构建函数
|
||||
// ============================================================
|
||||
|
||||
func listPlatforms() {
|
||||
fmt.Println("可用平台:")
|
||||
for i, p := range platforms {
|
||||
@@ -68,15 +163,19 @@ func listPlatforms() {
|
||||
|
||||
func interactiveMenu() {
|
||||
fmt.Println("========================================")
|
||||
fmt.Println(" frpc-console 多平台构建工具 v" + Version)
|
||||
fmt.Println(" frpc-console 多平台构建工具")
|
||||
fmt.Println("========================================")
|
||||
fmt.Println()
|
||||
fmt.Println(" 当前版本:", getFullVersion())
|
||||
fmt.Println(" 镜像标签:", getImageTag())
|
||||
fmt.Println()
|
||||
|
||||
for i, p := range platforms {
|
||||
fmt.Printf(" %d. %s (%s/%s)\n", i+1, p.Name, p.OS, p.Arch)
|
||||
}
|
||||
fmt.Println(" a. 全部构建")
|
||||
fmt.Println(" c. 清理构建产物")
|
||||
fmt.Println(" v. 显示版本信息")
|
||||
fmt.Println(" q. 退出")
|
||||
fmt.Println()
|
||||
|
||||
@@ -96,6 +195,10 @@ func interactiveMenu() {
|
||||
case "a":
|
||||
buildAll()
|
||||
return
|
||||
case "v":
|
||||
fmt.Println("版本:", getFullVersion())
|
||||
fmt.Println("镜像标签:", getImageTag())
|
||||
return
|
||||
default:
|
||||
var idx int
|
||||
if n, err := fmt.Sscanf(input, "%d", &idx); n == 1 && err == nil && idx >= 1 && idx <= len(platforms) {
|
||||
@@ -125,16 +228,22 @@ func build(p Platform, silent bool) {
|
||||
return
|
||||
}
|
||||
|
||||
// 构建输出文件名
|
||||
fullVersion := getFullVersion()
|
||||
imageTag := getImageTag()
|
||||
|
||||
outName := Binary + "-" + p.OS + "-" + p.Arch
|
||||
if p.Arch == "arm" {
|
||||
outName += "v7" // 标注 ARMv7 版本
|
||||
outName += "v7"
|
||||
}
|
||||
outName += p.Ext
|
||||
outPath := filepath.Join(outDir, outName)
|
||||
|
||||
cmd := exec.Command("go", "build",
|
||||
"-ldflags=-s -w -X main.version="+Version,
|
||||
"-ldflags="+
|
||||
"-s -w "+
|
||||
"-X main.buildVersion="+fullVersion+" "+
|
||||
"-X main.buildImageTag="+imageTag+" "+
|
||||
"-X main.buildTime="+BuildTime,
|
||||
"-o", outPath,
|
||||
".",
|
||||
)
|
||||
@@ -144,7 +253,6 @@ func build(p Platform, silent bool) {
|
||||
"CGO_ENABLED=0",
|
||||
)
|
||||
|
||||
// ARM 架构指定 GOARM=7
|
||||
if p.Arch == "arm" {
|
||||
cmd.Env = append(cmd.Env, "GOARM=7")
|
||||
}
|
||||
@@ -159,6 +267,7 @@ func build(p Platform, silent bool) {
|
||||
|
||||
if !silent {
|
||||
fmt.Printf("✅ 构建完成: %s\n", outPath)
|
||||
fmt.Printf(" 版本: %s\n", fullVersion)
|
||||
if info, err := os.Stat(outPath); err == nil {
|
||||
size := float64(info.Size()) / 1024 / 1024
|
||||
fmt.Printf(" 📦 %.2f MB\n", size)
|
||||
|
||||
+107
-6
@@ -28,6 +28,13 @@ async function apiFetch(endpoint, options = {}) {
|
||||
...options,
|
||||
headers: { ...headers, ...(options.headers || {}) },
|
||||
});
|
||||
|
||||
if (res.status === 401) {
|
||||
clearAuthState();
|
||||
window.dispatchEvent(new CustomEvent("auth:expired"));
|
||||
return { code: 401, msg: "认证已过期,请重新登录" };
|
||||
}
|
||||
|
||||
return res.json();
|
||||
}
|
||||
|
||||
@@ -163,7 +170,7 @@ function filterProxies(list, keyword) {
|
||||
(p) =>
|
||||
p.name.toLowerCase().includes(kw) ||
|
||||
p.localIP.includes(kw) ||
|
||||
String(p.remotePort).includes(kw)
|
||||
String(p.remotePort).includes(kw),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -189,7 +196,11 @@ async function fetchLogsApi() {
|
||||
try {
|
||||
const data = await apiFetch("/frpc/log");
|
||||
if (data.code === 0) {
|
||||
return { lines: data.data.lines || [], total: data.data.total || 0, error: data.data.error || "" };
|
||||
return {
|
||||
lines: data.data.lines || [],
|
||||
total: data.data.total || 0,
|
||||
error: data.data.error || "",
|
||||
};
|
||||
}
|
||||
return { lines: [], total: 0, error: "加载失败" };
|
||||
} catch (e) {
|
||||
@@ -286,8 +297,83 @@ const app = createApp({
|
||||
let logTimer = null;
|
||||
let logFetching = false;
|
||||
|
||||
// ---- Ping 延迟检测 ----
|
||||
const pingLatency = ref(null);
|
||||
let pingTimer = null;
|
||||
const PING_INTERVAL_MS = 30000;
|
||||
const PING_TIMEOUT_MS = 5000;
|
||||
|
||||
const pingStatusClass = computed(() => {
|
||||
if (pingLatency.value === null) return "ping-fail";
|
||||
if (pingLatency.value < 1000) return "ping-good";
|
||||
if (pingLatency.value < 5000) return "ping-slow";
|
||||
return "ping-fail";
|
||||
});
|
||||
|
||||
const pingIcon = computed(() => {
|
||||
if (pingLatency.value === null) {
|
||||
return `<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 256 256">
|
||||
<path d="M0 0h256v256H0z" fill="none"/>
|
||||
<g fill="currentColor">
|
||||
<path d="m224.39 104.34-90.24 108.78a8 8 0 0 1-12.3 0L17.8 87.69a7.79 7.79 0 0 1 1.31-11.21A179.58 179.58 0 0 1 128 40a182 182 0 0 1 33.06 3a7.94 7.94 0 0 1 4.17 2.21L224 104Z" opacity=".2"/>
|
||||
<path d="M229.66 98.34a8 8 0 0 1-11.32 11.32L200 91.31l-18.34 18.35a8 8 0 0 1-11.32-11.32L188.69 80l-18.35-18.34a8 8 0 0 1 11.32-11.32L200 68.69l18.34-18.35a8 8 0 0 1 11.32 11.32L211.31 80Zm-33.06 39.5a8 8 0 0 0-11.27 1L128 208L24.09 82.74A170.76 170.76 0 0 1 128 48c2.54 0 5.11.06 7.65.17a8 8 0 0 0 .7-16c-2.77-.12-5.58-.18-8.35-.18A186.67 186.67 0 0 0 14.28 70.1a15.93 15.93 0 0 0-6.17 10.81a15.65 15.65 0 0 0 3.54 11.89l104 125.43A15.93 15.93 0 0 0 128 224a15.93 15.93 0 0 0 12.31-5.77l57.34-69.12a8 8 0 0 0-1.05-11.27"/>
|
||||
</g>
|
||||
</svg>`;
|
||||
}
|
||||
if (pingLatency.value < 1000) {
|
||||
return `<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 25 24">
|
||||
<path d="M0 0h25v24H0z" fill="none"/>
|
||||
<path fill="currentColor" d="M2.046 6.725c6.192-4.967 15.05-4.967 21.243 0l.779.625l-11.4 14.25L1.265 7.35z"/>
|
||||
</svg>`;
|
||||
}
|
||||
return `<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24">
|
||||
<path d="M0 0h24v24H0z" fill="none"/>
|
||||
<path fill="none" stroke="currentColor" stroke-width="2" d="M21.996 7.505L12 20L2.004 7.505c5.827-4.673 14.165-4.673 19.992 0Z"/>
|
||||
</svg>`;
|
||||
});
|
||||
|
||||
async function doPing() {
|
||||
if (!frpcRunning.value) {
|
||||
pingLatency.value = null;
|
||||
return;
|
||||
}
|
||||
const addr = globalConfig.serverAddr || "frp.example.com";
|
||||
const start = performance.now();
|
||||
try {
|
||||
const res = await fetch(
|
||||
`/api/ping?target=${encodeURIComponent(addr)}`,
|
||||
{ signal: AbortSignal.timeout(PING_TIMEOUT_MS) },
|
||||
);
|
||||
if (!res.ok) throw new Error("Ping failed");
|
||||
const end = performance.now();
|
||||
pingLatency.value = Math.round(end - start);
|
||||
} catch {
|
||||
pingLatency.value = null;
|
||||
}
|
||||
}
|
||||
|
||||
function startPingPolling() {
|
||||
if (pingTimer) return;
|
||||
doPing();
|
||||
pingTimer = setInterval(doPing, PING_INTERVAL_MS);
|
||||
}
|
||||
|
||||
function stopPingPolling() {
|
||||
if (pingTimer) {
|
||||
clearInterval(pingTimer);
|
||||
pingTimer = null;
|
||||
}
|
||||
}
|
||||
|
||||
// ---- 认证过期处理 ----
|
||||
const handleAuthExpired = () => {
|
||||
doLogout();
|
||||
};
|
||||
|
||||
// ---- 初始化 ----
|
||||
onMounted(() => {
|
||||
window.addEventListener("auth:expired", handleAuthExpired);
|
||||
|
||||
const saved = loadAuthState();
|
||||
if (saved.valid) {
|
||||
token.value = saved.token;
|
||||
@@ -312,6 +398,15 @@ const app = createApp({
|
||||
}
|
||||
});
|
||||
|
||||
watch(frpcRunning, (running) => {
|
||||
if (!running) {
|
||||
stopPingPolling();
|
||||
pingLatency.value = null;
|
||||
} else if (loggedIn.value) {
|
||||
startPingPolling();
|
||||
}
|
||||
});
|
||||
|
||||
async function checkUsers() {
|
||||
try {
|
||||
const res = await fetch("/api/check/users");
|
||||
@@ -351,6 +446,10 @@ const app = createApp({
|
||||
logFetching = true;
|
||||
try {
|
||||
const result = await fetchLogsApi();
|
||||
if (result.code === 401) {
|
||||
logFetching = false;
|
||||
return;
|
||||
}
|
||||
logLines.value = result.lines;
|
||||
logTotal.value = result.total;
|
||||
logError.value = result.error;
|
||||
@@ -478,6 +577,7 @@ const app = createApp({
|
||||
const doLogout = () => {
|
||||
if (expireTimer) clearInterval(expireTimer);
|
||||
stopLogPolling();
|
||||
stopPingPolling();
|
||||
contentVisible.value = false;
|
||||
loggedIn.value = false;
|
||||
token.value = "";
|
||||
@@ -637,11 +737,10 @@ const app = createApp({
|
||||
|
||||
// ---- 计算属性 ----
|
||||
const filteredProxies = computed(() =>
|
||||
filterProxies(proxies.value, searchKeyword.value)
|
||||
filterProxies(proxies.value, searchKeyword.value),
|
||||
);
|
||||
|
||||
const showDefaultTip = computed(() => {
|
||||
// 如果 serverAddr 还是默认值,或者为空,显示警告
|
||||
const addr = globalConfig.serverAddr;
|
||||
return !addr || addr === "frp.example.com" || addr.trim() === "";
|
||||
});
|
||||
@@ -694,7 +793,6 @@ const app = createApp({
|
||||
|
||||
showDefaultTip,
|
||||
|
||||
// 日志相关
|
||||
logLines,
|
||||
logTotal,
|
||||
logError,
|
||||
@@ -703,8 +801,11 @@ const app = createApp({
|
||||
refreshLogs,
|
||||
scrollLogToBottom,
|
||||
|
||||
// Token 显示切换
|
||||
showToken,
|
||||
|
||||
pingLatency,
|
||||
pingStatusClass,
|
||||
pingIcon,
|
||||
};
|
||||
},
|
||||
});
|
||||
|
||||
+50
-47
@@ -97,11 +97,15 @@
|
||||
<span class="status-wrapper">
|
||||
<span class="status-dot" :class="{ active: frpcRunning }"></span>
|
||||
<span class="status-text">{{ frpcRunning ? 'frpc 运行中' : 'frpc 已停止' }}</span>
|
||||
<!-- Ping 延迟显示 -->
|
||||
<span class="ping-display" :class="pingStatusClass">
|
||||
<span class="ping-icon" v-html="pingIcon"></span>
|
||||
<span class="ping-value">{{ pingLatency !== null ? pingLatency + 'ms' : '--ms' }}</span>
|
||||
</span>
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="top-right">
|
||||
<span class="user-name">{{ loginForm.username }}</span>
|
||||
<button class="logout-btn" @click="doLogout">退出</button>
|
||||
</div>
|
||||
</div>
|
||||
@@ -114,6 +118,8 @@
|
||||
@click="activeTab = 'config'">全局配置信息</span>
|
||||
<span class="tab-item" :class="{ active: activeTab === 'logs' }"
|
||||
@click="activeTab = 'logs'">运行日志</span>
|
||||
<span class="tab-item" :class="{ active: activeTab === 'user' }"
|
||||
@click="activeTab = 'user'">用户配置:{{loginForm.username }}</span>
|
||||
</div>
|
||||
|
||||
<!-- 内容区 -->
|
||||
@@ -159,48 +165,18 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- ====== 全局配置信息 ====== -->
|
||||
<!-- ====== 全局配置信息 ====== -->
|
||||
<div v-if="activeTab === 'config'" class="tab-content config-tab-content">
|
||||
<!-- 页面标题 -->
|
||||
<div class="config-page-header">
|
||||
<h2>全局配置信息</h2>
|
||||
<p class="config-subtitle">管理 frpc 连接参数与传输设置</p>
|
||||
</div>
|
||||
|
||||
<!-- 首次使用提示 -->
|
||||
<div v-if="showDefaultTip" class="config-tip">
|
||||
首次使用请修改「服务器地址」和「认证令牌」为您的真实 frpc 配置
|
||||
首次使用请修改「服务器地址」和「认证令牌」为您的真实 frps 配置
|
||||
</div>
|
||||
|
||||
<!-- ===== 账户管理 ===== -->
|
||||
<div class="profile-section">
|
||||
<div class="profile-header">
|
||||
<span>账户管理</span>
|
||||
<span class="profile-username">{{ loginForm.username }}</span>
|
||||
</div>
|
||||
<div class="profile-form">
|
||||
<div class="form-row">
|
||||
<label>当前密码</label>
|
||||
<input v-model="passwordChange.oldPassword" type="password" placeholder="输入当前密码" />
|
||||
</div>
|
||||
<div class="form-row">
|
||||
<label>新密码</label>
|
||||
<input v-model="passwordChange.newPassword" type="password"
|
||||
placeholder="至少8位,含大小写/数字/特殊字符" />
|
||||
</div>
|
||||
<div class="form-row">
|
||||
<label>确认新密码</label>
|
||||
<input v-model="passwordChange.confirmPassword" type="password"
|
||||
placeholder="再次输入新密码" />
|
||||
</div>
|
||||
<button class="save-btn" @click="changePassword">修改密码</button>
|
||||
<p v-if="passwordChangeError" class="login-error">{{ passwordChangeError }}</p>
|
||||
<p v-if="passwordChangeSuccess" class="login-success">{{ passwordChangeSuccess }}</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- ===== 卡片1: 服务器连接 ===== -->
|
||||
<!-- 卡片1: 服务器连接 -->
|
||||
<div class="config-card">
|
||||
<div class="config-card-header">
|
||||
<span class="card-title">服务器连接</span>
|
||||
@@ -227,13 +203,12 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- ===== 卡片2: 传输配置 ===== -->
|
||||
<!-- 卡片2: 传输配置 -->
|
||||
<div class="config-card">
|
||||
<div class="config-card-header">
|
||||
<span class="card-title">传输配置</span>
|
||||
</div>
|
||||
<div class="config-card-body">
|
||||
<!-- TCP 多路复用(只读,占满一行) -->
|
||||
<div class="form-row" style="grid-column: 1 / -1;">
|
||||
<label>TCP 多路复用</label>
|
||||
<div class="readonly-value">
|
||||
@@ -242,31 +217,26 @@
|
||||
<span class="hint-text">优化连接性能,减少延迟,frp 官方推荐开启</span>
|
||||
</div>
|
||||
</div>
|
||||
<!-- 保活间隔 -->
|
||||
<div class="form-row">
|
||||
<label>保活间隔(秒)</label>
|
||||
<input type="number" v-model="globalConfig.tcpMuxKeepalive" />
|
||||
</div>
|
||||
<!-- 心跳间隔 -->
|
||||
<div class="form-row">
|
||||
<label>心跳间隔(秒)</label>
|
||||
<input type="number" v-model="globalConfig.heartbeatInterval" />
|
||||
</div>
|
||||
<!-- 心跳超时 -->
|
||||
<div class="form-row">
|
||||
<label>心跳超时(秒)</label>
|
||||
<input type="number" v-model="globalConfig.heartbeatTimeout" />
|
||||
</div>
|
||||
<!-- 连接池大小 -->
|
||||
<div class="form-row">
|
||||
<label>连接池大小(个)</label>
|
||||
<input type="number" v-model="globalConfig.poolCount" />
|
||||
</div>
|
||||
<!-- v2 协议开关(v1.5 灰标禁用) -->
|
||||
<div class="form-row v2-switch-row">
|
||||
<label>frp v2 隧道支持</label>
|
||||
<div class="v2-switch-wrapper">
|
||||
<label class="switch disabled">
|
||||
<label class="switch">
|
||||
<input type="checkbox" v-model="globalConfig.wireProtocolV2" />
|
||||
<span class="slider"></span>
|
||||
</label>
|
||||
@@ -278,7 +248,7 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- ===== 卡片3: 日志配置 ===== -->
|
||||
<!-- 卡片3: 日志配置 -->
|
||||
<div class="config-card">
|
||||
<div class="config-card-header">
|
||||
<span class="card-title">日志配置</span>
|
||||
@@ -301,12 +271,11 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 保存按钮 -->
|
||||
<button class="save-config-btn" @click="saveConfig">保存配置并热加载</button>
|
||||
</div>
|
||||
|
||||
<!-- ====== 运行日志 ====== -->
|
||||
<div v-else-if="activeTab === 'logs'" class="tab-content log-tab-content">
|
||||
<!-- 工具栏 -->
|
||||
<div class="log-toolbar">
|
||||
<div class="log-toolbar-left">
|
||||
<span class="log-info-badge">共 {{ logTotal }} 行</span>
|
||||
@@ -322,7 +291,6 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 日志显示区域 -->
|
||||
<div class="log-terminal" id="logContainer">
|
||||
<div v-if="logLines.length === 0 && !logError" class="log-empty">
|
||||
暂无日志,frpc 尚未产生输出
|
||||
@@ -332,17 +300,48 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 底部状态 -->
|
||||
<div class="log-footer">
|
||||
<span>上次更新: {{ logLastUpdate || '--:--:--' }}</span>
|
||||
<span class="log-polling-status">自动刷新中 (8s)</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- ====== 用户配置 ====== -->
|
||||
<div v-if="activeTab === 'user'" class="tab-content config-tab-content">
|
||||
<div class="config-page-header">
|
||||
<h2>用户配置:{{ loginForm.username }}</h2>
|
||||
<p class="config-subtitle">修改当前账户的登录密码</p>
|
||||
</div>
|
||||
|
||||
<div class="profile-section">
|
||||
<div class="profile-header">
|
||||
<span>账户管理</span>
|
||||
<span class="profile-username">{{ loginForm.username }}</span>
|
||||
</div>
|
||||
<div class="profile-form">
|
||||
<div class="form-row">
|
||||
<label>当前密码</label>
|
||||
<input v-model="passwordChange.oldPassword" type="password" placeholder="输入当前密码" />
|
||||
</div>
|
||||
<div class="form-row">
|
||||
<label>新密码</label>
|
||||
<input v-model="passwordChange.newPassword" type="password"
|
||||
placeholder="至少8位,含大小写/数字/特殊字符" />
|
||||
</div>
|
||||
<div class="form-row">
|
||||
<label>确认新密码</label>
|
||||
<input v-model="passwordChange.confirmPassword" type="password"
|
||||
placeholder="再次输入新密码" />
|
||||
</div>
|
||||
<button class="save-btn" @click="changePassword">修改密码</button>
|
||||
<p v-if="passwordChangeError" class="login-error">{{ passwordChangeError }}</p>
|
||||
<p v-if="passwordChangeSuccess" class="login-success">{{ passwordChangeSuccess }}</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
</div> <!-- /content-area -->
|
||||
|
||||
<!-- ====== 弹窗 ====== -->
|
||||
<Transition name="dialog">
|
||||
<div v-if="dialogVisible" class="dialog-overlay" @click.self="dialogVisible = false">
|
||||
@@ -373,9 +372,13 @@
|
||||
</div>
|
||||
</Transition>
|
||||
|
||||
</div> <!-- /main-panel -->
|
||||
</div> <!-- /app-container -->
|
||||
|
||||
<!-- 隐藏文件选择器 -->
|
||||
<input type="file" id="tomlFileInput" accept=".toml" style="display:none" @change="handleImport" />
|
||||
</div>
|
||||
|
||||
</div> <!-- /#app -->
|
||||
|
||||
<script src="/static/app.js"></script>
|
||||
</body>
|
||||
|
||||
@@ -735,3 +735,69 @@ select:disabled {
|
||||
padding: 20px;
|
||||
}
|
||||
}
|
||||
|
||||
/* ---------- Ping 延迟显示 ---------- */
|
||||
.status-wrapper {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
.ping-display {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 4px;
|
||||
font-size: 12px;
|
||||
font-weight: 500;
|
||||
padding: 2px 8px 2px 4px;
|
||||
border-radius: 12px;
|
||||
background: rgba(255, 255, 255, 0.04);
|
||||
transition: background 0.3s;
|
||||
}
|
||||
|
||||
.ping-display .ping-icon {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
width: 16px;
|
||||
height: 16px;
|
||||
}
|
||||
|
||||
.ping-display .ping-icon svg {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
}
|
||||
|
||||
/* 状态颜色 */
|
||||
.ping-good .ping-icon {
|
||||
color: #63e2b7;
|
||||
}
|
||||
.ping-good .ping-value {
|
||||
color: #63e2b7;
|
||||
}
|
||||
|
||||
.ping-slow .ping-icon {
|
||||
color: #f0c040;
|
||||
}
|
||||
.ping-slow .ping-value {
|
||||
color: #f0c040;
|
||||
}
|
||||
|
||||
.ping-fail .ping-icon {
|
||||
color: #f87171;
|
||||
}
|
||||
.ping-fail .ping-value {
|
||||
color: #f87171;
|
||||
}
|
||||
|
||||
/* 响应式调整 */
|
||||
@media (max-width: 768px) {
|
||||
.ping-display {
|
||||
font-size: 11px;
|
||||
padding: 1px 6px 1px 2px;
|
||||
}
|
||||
.ping-display .ping-icon {
|
||||
width: 14px;
|
||||
height: 14px;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
; frpc-console 版本声明文件
|
||||
; 格式: {语义版本号} [{LTS发布日期}]
|
||||
; 示例:
|
||||
; 2.4 # Preview 版本,无日期
|
||||
; 2.5 20260729 # LTS 版本,带发布日期
|
||||
2.4
|
||||
Reference in New Issue
Block a user