19 Commits
Author SHA1 Message Date
lxh2875931338 e1cf6f4f47 推送新的日志 2026-07-28 23:14:39 +08:00
lxh2875931338 a5c33580e2 调整部分部署逻辑 2026-07-28 22:56:45 +08:00
lxh2875931338 f2af48f8d0 调整部分部署逻辑 2026-07-28 22:50:17 +08:00
lxh2875931338 2663e71b4f 调整部分部署逻辑 2026-07-28 22:35:48 +08:00
lxh2875931338 bf24d3cb00 调整部分部署逻辑 2026-07-28 22:29:42 +08:00
lxh2875931338 00f2b9fd14 重新设计新的部署逻辑,去掉本机自己的go build,合并到docker多阶段构建部分进行 2026-07-28 22:23:39 +08:00
lxh2875931338 76ac9503c6 调整部分部署逻辑 2026-07-28 21:58:12 +08:00
lxh2875931338 04851d244f 调整部分部署逻辑 2026-07-28 21:55:33 +08:00
lxh2875931338 a2f4326882 确认部分逻辑 2026-07-28 21:50:04 +08:00
lxh2875931338 4cd438ed3e Merge branch 'test' 2026-07-28 21:24:54 +08:00
lxh2875931338 c340e3934c 更新部署逻辑 2026-07-28 21:22:31 +08:00
lxh2875931338 ef6c75aef9 需要测试相关功能 2026-07-28 20:47:41 +08:00
lxh2875931338 6904e4993f 延迟监测逻辑更新 2026-07-28 20:38:21 +08:00
lxh2875931338 1bfa2383c1 docker脚本部分逻辑更新 2026-07-28 20:21:01 +08:00
lxh2875931338 b13f2d5047 指南更新 2026-07-28 20:13:14 +08:00
lxh2875931338 7a2737bc83 指南更新 2026-07-28 20:11:53 +08:00
lxh2875931338 1fd845a981 readme更新 2026-07-28 20:09:34 +08:00
lxh2875931338 f9a97a0af5 版本更新说明 2026-07-28 20:06:14 +08:00
lxh2875931338 ab73a38f06 直接更新 2026-07-28 20:03:20 +08:00
9 changed files with 329 additions and 501 deletions
+1 -1
View File
@@ -24,7 +24,7 @@ RUN CGO_ENABLED=0 GOOS=linux go build \
FROM alpine:latest FROM alpine:latest
# 安装 ca-certificates 和 tzdata(确保 HTTPS 和时区正常) # 安装 ca-certificates 和 tzdata(确保 HTTPS 和时区正常)
RUN apk --no-cache add ca-certificates tzdata RUN apk add --no-cache ca-certificates sqlite tzdata
WORKDIR /app WORKDIR /app
+157 -140
View File
@@ -45,10 +45,13 @@ func SetupRouter() *gin.Engine {
api := r.Group("/api") api := r.Group("/api")
{ {
// ---- 公开路由(不需要认证) ----
api.GET("/check/users", checkUsersHandler) api.GET("/check/users", checkUsersHandler)
api.POST("/register", registerHandler) api.POST("/register", registerHandler)
api.POST("/login", loginHandler) api.POST("/login", loginHandler)
api.GET("/ping", pingHandler)
// ---- 需要认证的路由 ----
auth := api.Group("/") auth := api.Group("/")
auth.Use(AuthMiddleware()) auth.Use(AuthMiddleware())
{ {
@@ -66,7 +69,7 @@ func SetupRouter() *gin.Engine {
auth.POST("/frpc/stop", stopFrpcHandler) auth.POST("/frpc/stop", stopFrpcHandler)
auth.GET("/frpc/status", getFrpcStatusHandler) auth.GET("/frpc/status", getFrpcStatusHandler)
auth.GET("/frpc/log", getFrpcLogHandler) auth.GET("/frpc/log", getFrpcLogHandler)
auth.GET("/ping", pingHandler)
auth.POST("/import/toml", importTomlHandler) auth.POST("/import/toml", importTomlHandler)
auth.GET("/export/toml", ExportTomlHandler) auth.GET("/export/toml", ExportTomlHandler)
@@ -77,7 +80,7 @@ func SetupRouter() *gin.Engine {
return r return r
} }
// ========== 所有 Handler ========== // ========== 认证 Handler ==========
func checkUsersHandler(c *gin.Context) { func checkUsersHandler(c *gin.Context) {
count, err := CountUsers() count, err := CountUsers()
@@ -145,36 +148,6 @@ func registerHandler(c *gin.Context) {
}) })
} }
// Ping 延迟检测
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})
}
func loginHandler(c *gin.Context) { func loginHandler(c *gin.Context) {
var req struct { var req struct {
Username string `json:"username"` Username string `json:"username"`
@@ -255,6 +228,8 @@ func changePasswordHandler(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{"code": 0, "msg": "密码修改成功"}) c.JSON(http.StatusOK, gin.H{"code": 0, "msg": "密码修改成功"})
} }
// ========== 配置 Handler ==========
func getConfigHandler(c *gin.Context) { func getConfigHandler(c *gin.Context) {
cfg, err := GetGlobalConfig() cfg, err := GetGlobalConfig()
if err != nil { if err != nil {
@@ -290,6 +265,8 @@ func updateConfigHandler(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{"code": 0, "msg": "配置更新成功"}) c.JSON(http.StatusOK, gin.H{"code": 0, "msg": "配置更新成功"})
} }
// ========== 隧道 Handler ==========
func getProxiesHandler(c *gin.Context) { func getProxiesHandler(c *gin.Context) {
proxies, err := GetProxies() proxies, err := GetProxies()
if err != nil { if err != nil {
@@ -380,6 +357,8 @@ func deleteProxyHandler(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{"code": 0, "msg": "隧道删除成功"}) c.JSON(http.StatusOK, gin.H{"code": 0, "msg": "隧道删除成功"})
} }
// ========== frpc 进程管理 Handler ==========
func reloadFrpcHandler(c *gin.Context) { func reloadFrpcHandler(c *gin.Context) {
if err := GenerateFrpcConfig(); err != nil { if err := GenerateFrpcConfig(); err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"code": 2, "msg": "生成配置失败: " + err.Error()}) c.JSON(http.StatusInternalServerError, gin.H{"code": 2, "msg": "生成配置失败: " + err.Error()})
@@ -417,6 +396,144 @@ func getFrpcStatusHandler(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{"code": 0, "data": gin.H{"running": running}}) 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) { func importTomlHandler(c *gin.Context) {
file, err := c.FormFile("file") file, err := c.FormFile("file")
if err != nil { if err != nil {
@@ -502,14 +619,22 @@ func ExportTomlHandler(c *gin.Context) {
} }
} }
// 构建与 GenerateFrpcConfig 一致的数据结构
data := struct { data := struct {
*GlobalConfig *GlobalConfig
Proxies []Proxy Proxies []Proxy
WireProtocolLine string
}{ }{
GlobalConfig: cfg, GlobalConfig: cfg,
Proxies: activeProxies, Proxies: activeProxies,
} }
if cfg.WireProtocolV2 {
data.WireProtocolLine = `wireProtocol = "v2"`
} else {
data.WireProtocolLine = ""
}
tmpl, err := template.New("frpc").Parse(FrpcTemplateContent) tmpl, err := template.New("frpc").Parse(FrpcTemplateContent)
if err != nil { if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"code": 2, "msg": "解析模板失败: " + err.Error()}) c.JSON(http.StatusInternalServerError, gin.H{"code": 2, "msg": "解析模板失败: " + err.Error()})
@@ -527,114 +652,6 @@ func ExportTomlHandler(c *gin.Context) {
c.String(http.StatusOK, buf.String()) 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 { func generateAndReload() error {
if err := GenerateFrpcConfig(); err != nil { if err := GenerateFrpcConfig(); err != nil {
return err return err
+8 -28
View File
@@ -2,30 +2,23 @@ package main
// ============================================================ // ============================================================
// db-history.go - Schema 版本声明与字段映射 // db-history.go - Schema 版本声明与字段映射
// 这是整个迁移引擎的“数据源”,记录每个版本的完整 Schema 定义。
// 迁移工具通过对比当前 Schema 与目标 Schema 的差异来决定迁移路径。
// ============================================================ // ============================================================
// SchemaVersionDef 记录一个 Schema 版本的完整字段定义
type SchemaVersionDef struct { type SchemaVersionDef struct {
Version string // 如 "v1", "v2", "v3" Version string
TableName string // 表名,如 "proxies" TableName string
Columns map[string]ColumnDef // 字段名 → 字段定义 Columns map[string]ColumnDef
} }
// ColumnDef 描述一个字段的结构
type ColumnDef struct { type ColumnDef struct {
Type string // 如 "INTEGER", "TEXT", "BOOLEAN" Type string
NotNull bool // 是否 NOT NULL NotNull bool
Default string // 默认值表达式(如 "0"、"'CHANGE_ME'" Default string
Primary bool // 是否主键 Primary bool
} }
// schemaHistory 存储所有已知的 Schema 版本(从旧到新排列)
// 每个版本记录的是“完整的表结构”,而不是增量变更。
// 新增版本时,在这里追加一条记录即可。
var schemaHistory = []SchemaVersionDef{ var schemaHistory = []SchemaVersionDef{
// v1:初始版本frpc-console 1.0 // v1:初始版本
{ {
Version: "v1", Version: "v1",
TableName: "proxies", TableName: "proxies",
@@ -42,7 +35,6 @@ var schemaHistory = []SchemaVersionDef{
}, },
}, },
// v2:当前版本(frpc-console 2.0 LTS // v2:当前版本(frpc-console 2.0 LTS
// 注意:wire_protocol_v2 是全局配置(global_config),不在 proxies 表中
{ {
Version: "v2", Version: "v2",
TableName: "proxies", TableName: "proxies",
@@ -58,18 +50,8 @@ var schemaHistory = []SchemaVersionDef{
"updated_at": {Type: "DATETIME", Default: "CURRENT_TIMESTAMP"}, "updated_at": {Type: "DATETIME", Default: "CURRENT_TIMESTAMP"},
}, },
}, },
// v3:未来版本(规划中)
// 示例:新增隧道分组、流量统计等字段
// {
// Version: "v3",
// TableName: "proxies",
// Columns: map[string]ColumnDef{
// // ... 完整字段定义
// },
// },
} }
// getSchemaDef 根据版本号获取 Schema 定义
func getSchemaDef(version string) *SchemaVersionDef { func getSchemaDef(version string) *SchemaVersionDef {
for _, def := range schemaHistory { for _, def := range schemaHistory {
if def.Version == version { if def.Version == version {
@@ -79,7 +61,6 @@ func getSchemaDef(version string) *SchemaVersionDef {
return nil return nil
} }
// getLatestSchemaDef 获取最新的 Schema 版本定义
func getLatestSchemaDef() *SchemaVersionDef { func getLatestSchemaDef() *SchemaVersionDef {
if len(schemaHistory) == 0 { if len(schemaHistory) == 0 {
return nil return nil
@@ -87,7 +68,6 @@ func getLatestSchemaDef() *SchemaVersionDef {
return &schemaHistory[len(schemaHistory)-1] return &schemaHistory[len(schemaHistory)-1]
} }
// schemaVersionsEqual 判断两个 Schema 版本是否完全相同
func schemaVersionsEqual(v1, v2 *SchemaVersionDef) bool { func schemaVersionsEqual(v1, v2 *SchemaVersionDef) bool {
if v1 == nil || v2 == nil { if v1 == nil || v2 == nil {
return false return false
+18 -15
View File
@@ -22,14 +22,13 @@ var DB *sql.DB
// ============================================================ // ============================================================
const ( const (
SchemaVersion = "v2" // 当前数据库 Schema 版本(与 schemaHistory 中的版本对应) SchemaVersion = "v2" // 当前数据库 Schema 版本
) )
// ============================================================ // ============================================================
// 数据模型 // 数据模型
// ============================================================ // ============================================================
// GlobalConfig 全局配置表
type GlobalConfig struct { type GlobalConfig struct {
ID int `json:"id"` ID int `json:"id"`
ServerAddr string `json:"serverAddr"` ServerAddr string `json:"serverAddr"`
@@ -42,10 +41,9 @@ type GlobalConfig struct {
HeartbeatInterval int `json:"heartbeatInterval"` HeartbeatInterval int `json:"heartbeatInterval"`
HeartbeatTimeout int `json:"heartbeatTimeout"` HeartbeatTimeout int `json:"heartbeatTimeout"`
PoolCount int `json:"poolCount"` PoolCount int `json:"poolCount"`
WireProtocolV2 bool `json:"wireProtocolV2"` // v2 协议全局开关 WireProtocolV2 bool `json:"wireProtocolV2"`
} }
// Proxy 隧道表(不含 wire_protocol_v2
type Proxy struct { type Proxy struct {
ID int `json:"id"` ID int `json:"id"`
Name string `json:"name"` Name string `json:"name"`
@@ -56,7 +54,6 @@ type Proxy struct {
Enabled bool `json:"enabled"` Enabled bool `json:"enabled"`
} }
// User 用户表
type User struct { type User struct {
ID int `json:"id"` ID int `json:"id"`
Username string `json:"username"` Username string `json:"username"`
@@ -66,7 +63,6 @@ type User struct {
// ============================================================ // ============================================================
// 数据库初始化 // 数据库初始化
// ============================================================
func InitDB() error { func InitDB() error {
var err error var err error
@@ -186,7 +182,6 @@ func createTables() error {
// 迁移引擎 // 迁移引擎
// ============================================================ // ============================================================
// getCurrentSchemaVersion 读取当前数据库的 Schema 版本
func getCurrentSchemaVersion() string { func getCurrentSchemaVersion() string {
var version string var version string
err := DB.QueryRow("SELECT value FROM app_config WHERE key = 'schema_version'").Scan(&version) err := DB.QueryRow("SELECT value FROM app_config WHERE key = 'schema_version'").Scan(&version)
@@ -205,7 +200,6 @@ func getCurrentSchemaVersion() string {
return version return version
} }
// setSchemaVersion 更新 Schema 版本
func setSchemaVersion(version string) error { func setSchemaVersion(version string) error {
_, err := DB.Exec(` _, err := DB.Exec(`
INSERT INTO app_config (key, value) VALUES ('schema_version', ?) INSERT INTO app_config (key, value) VALUES ('schema_version', ?)
@@ -214,7 +208,6 @@ func setSchemaVersion(version string) error {
return err return err
} }
// backupDatabase 备份数据库文件
func backupDatabase() (string, error) { func backupDatabase() (string, error) {
src := "./frpc-console.db" src := "./frpc-console.db"
if _, err := os.Stat(src); os.IsNotExist(err) { if _, err := os.Stat(src); os.IsNotExist(err) {
@@ -244,7 +237,6 @@ func backupDatabase() (string, error) {
return dst, nil return dst, nil
} }
// restoreDatabase 从备份恢复数据库
func restoreDatabase(backupPath string) error { func restoreDatabase(backupPath string) error {
srcFile, err := os.Open(backupPath) srcFile, err := os.Open(backupPath)
if err != nil { if err != nil {
@@ -266,7 +258,6 @@ func restoreDatabase(backupPath string) error {
return nil return nil
} }
// runMigrations 执行迁移
func runMigrations() error { func runMigrations() error {
currentVer := getCurrentSchemaVersion() currentVer := getCurrentSchemaVersion()
targetVer := SchemaVersion targetVer := SchemaVersion
@@ -274,7 +265,14 @@ func runMigrations() error {
log.Printf("📌 当前数据库 Schema: %s, 目标版本: %s", currentVer, targetVer) log.Printf("📌 当前数据库 Schema: %s, 目标版本: %s", currentVer, targetVer)
if currentVer == targetVer { if currentVer == targetVer {
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("✅ Schema 已是最新,数据库有效")
return nil return nil
} }
@@ -297,6 +295,14 @@ func runMigrations() error {
if currentSchema == nil || schemaVersionsEqual(currentSchema, targetSchema) { if currentSchema == nil || schemaVersionsEqual(currentSchema, targetSchema) {
log.Println(" 迁移类型: 轻量复制(Schema 无变更)") 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 { } else {
log.Println(" 迁移类型: 重型迁移(Schema 有变更,新建表 + 搬数据)") log.Println(" 迁移类型: 重型迁移(Schema 有变更,新建表 + 搬数据)")
if err := heavyMigration(currentSchema, targetSchema); err != nil { if err := heavyMigration(currentSchema, targetSchema); err != nil {
@@ -318,7 +324,6 @@ func runMigrations() error {
return nil return nil
} }
// heavyMigration 重型迁移
func heavyMigration(oldDef, newDef *SchemaVersionDef) error { func heavyMigration(oldDef, newDef *SchemaVersionDef) error {
if oldDef == nil { if oldDef == nil {
return fmt.Errorf("旧 Schema 定义为空,无法执行重型迁移") return fmt.Errorf("旧 Schema 定义为空,无法执行重型迁移")
@@ -366,7 +371,6 @@ func heavyMigration(oldDef, newDef *SchemaVersionDef) error {
return nil return nil
} }
// buildCreateTableSQL 根据 Schema 定义生成 CREATE TABLE 语句
func buildCreateTableSQL(tableName string, def *SchemaVersionDef) string { func buildCreateTableSQL(tableName string, def *SchemaVersionDef) string {
var cols []string var cols []string
var primaryKey string var primaryKey string
@@ -400,7 +404,6 @@ func buildCreateTableSQL(tableName string, def *SchemaVersionDef) string {
return fmt.Sprintf("CREATE TABLE %s (\n %s\n)", tableName, strings.Join(cols, ",\n ")) return fmt.Sprintf("CREATE TABLE %s (\n %s\n)", tableName, strings.Join(cols, ",\n "))
} }
// buildInsertSQL 构建 INSERT INTO new_table SELECT ... FROM old_table
func buildInsertSQL(oldTable, newTable string, oldDef, newDef *SchemaVersionDef) (string, error) { func buildInsertSQL(oldTable, newTable string, oldDef, newDef *SchemaVersionDef) (string, error) {
newCols := make([]string, 0, len(newDef.Columns)) newCols := make([]string, 0, len(newDef.Columns))
for name := range newDef.Columns { for name := range newDef.Columns {
+89 -262
View File
@@ -1,9 +1,9 @@
#!/bin/bash #!/bin/bash
# ============================================================ # ============================================================
# frpc-console 一键部署脚本 # frpc-console 一键部署脚本Docker 优先)
# 支持:Linux x86_64 / ARM64 / ARMv7 # 支持:Linux x86_64 / ARM64 / ARMv7
# 自动安装:git / curl / wget / Go / Docker # 自动安装:git / curl / wget / Docker
# #
# 用法: # 用法:
# ./deploy.sh # 完整交互流程 # ./deploy.sh # 完整交互流程
@@ -14,14 +14,24 @@
set -e set -e
# ---------- 颜色输出 ---------- # ---------- 颜色检测 ----------
RED='\033[0;31m' if [ -t 1 ]; then
GREEN='\033[0;32m' RED='\033[0;31m'
YELLOW='\033[1;33m' GREEN='\033[0;32m'
BLUE='\033[0;34m' YELLOW='\033[1;33m'
CYAN='\033[0;36m' BLUE='\033[0;34m'
MAGENTA='\033[0;35m' CYAN='\033[0;36m'
NC='\033[0m' 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" REPO_URL="https://git.whitetop.xyz/lxh2875931338/frpc-console.git"
@@ -30,22 +40,18 @@ WORK_DIR="/tmp/frpc-console-build"
DEFAULT_PORT=9300 DEFAULT_PORT=9300
DEFAULT_DEPLOY_DIR="/opt/frpc-console" DEFAULT_DEPLOY_DIR="/opt/frpc-console"
IMAGE_NAME="frpc-console" IMAGE_NAME="frpc-console"
GO_VERSION="1.25.0"
# ---------- 状态变量 ---------- # ---------- 状态变量 ----------
OS="" OS=""
OS_VERSION="" OS_VERSION=""
ARCH="" ARCH=""
GO_ARCH=""
HAS_GIT=false HAS_GIT=false
HAS_CURL=false HAS_CURL=false
HAS_WGET=false HAS_WGET=false
HAS_GO=false
HAS_DOCKER=false HAS_DOCKER=false
NEED_INSTALL_GIT=false NEED_INSTALL_GIT=false
NEED_INSTALL_CURL=false NEED_INSTALL_CURL=false
NEED_INSTALL_WGET=false NEED_INSTALL_WGET=false
NEED_INSTALL_GO=false
PORT=${DEFAULT_PORT} PORT=${DEFAULT_PORT}
DEPLOY_DIR=${DEFAULT_DEPLOY_DIR} DEPLOY_DIR=${DEFAULT_DEPLOY_DIR}
DATA_DIR="${DEPLOY_DIR}/data" DATA_DIR="${DEPLOY_DIR}/data"
@@ -68,15 +74,9 @@ print_subtitle() { echo -e "${MAGENTA} $1${NC}"; }
parse_args() { parse_args() {
for arg in "$@"; do for arg in "$@"; do
case $arg in case $arg in
--yes|-y) --yes|-y) SKIP_CONFIRM=true ;;
SKIP_CONFIRM=true --check) CHECK_ONLY=true ;;
;; --dry-run) DRY_RUN=true ;;
--check)
CHECK_ONLY=true
;;
--dry-run)
DRY_RUN=true
;;
--help|-h) --help|-h)
echo "用法: ./deploy.sh [选项]" echo "用法: ./deploy.sh [选项]"
echo "" echo ""
@@ -126,14 +126,8 @@ detect_os() {
detect_arch() { detect_arch() {
ARCH=$(uname -m) ARCH=$(uname -m)
case $ARCH in case $ARCH in
x86_64|amd64) x86_64|amd64|aarch64|arm64|armv7l|armhf)
GO_ARCH="amd64" print_success "CPU 架构: $ARCH"
;;
aarch64|arm64)
GO_ARCH="arm64"
;;
armv7l|armhf)
GO_ARCH="armv6l"
;; ;;
*) *)
print_error "不支持的 CPU 架构: $ARCH" print_error "不支持的 CPU 架构: $ARCH"
@@ -144,38 +138,10 @@ detect_arch() {
# ---------- 检测工具 ---------- # ---------- 检测工具 ----------
check_tools() { check_tools() {
# git command -v git &> /dev/null && HAS_GIT=true || NEED_INSTALL_GIT=true
if command -v git &> /dev/null; then command -v curl &> /dev/null && HAS_CURL=true || NEED_INSTALL_CURL=true
HAS_GIT=true command -v wget &> /dev/null && HAS_WGET=true || NEED_INSTALL_WGET=true
else command -v docker &> /dev/null && HAS_DOCKER=true
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
} }
# ---------- 检查容器状态 ---------- # ---------- 检查容器状态 ----------
@@ -188,45 +154,19 @@ check_container() {
fi 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"
;;
esac
}
# ---------- 检测结果汇总 ---------- # ---------- 检测结果汇总 ----------
print_environment_summary() { print_environment_summary() {
print_title print_title
print_subtitle "环境检测结果" print_subtitle "环境检测结果"
echo "" echo ""
echo -e " ${CYAN}操作系统:${NC} $OS $OS_VERSION" echo -e " ${CYAN}操作系统:${NC} $OS $OS_VERSION"
echo -e " ${CYAN}CPU 架构:${NC} $ARCH → Go 架构: $GO_ARCH" echo -e " ${CYAN}CPU 架构:${NC} $ARCH"
echo "" echo ""
echo " ${CYAN}必要工具:${NC}" echo " ${CYAN}必要工具:${NC}"
if [ "$HAS_GIT" = true ]; then if [ "$HAS_GIT" = true ]; then
echo -e " git ✅ 已安装 ($(git --version | awk '{print $3}'))" echo -e " git ✅ 已安装 ($(git --version | awk '{print $3}'))"
else else
echo -e " git ❌ 未安装 (将自动安装)" echo " git ❌ 未安装 (将自动安装)"
fi fi
if [ "$HAS_CURL" = true ]; then if [ "$HAS_CURL" = true ]; then
echo " curl ✅ 已安装" echo " curl ✅ 已安装"
@@ -238,15 +178,6 @@ print_environment_summary() {
else else
echo " wget ❌ 未安装 (将自动安装)" echo " wget ❌ 未安装 (将自动安装)"
fi 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 ""
echo " ${CYAN}Docker 环境:${NC}" echo " ${CYAN}Docker 环境:${NC}"
if [ "$HAS_DOCKER" = true ]; then if [ "$HAS_DOCKER" = true ]; then
@@ -262,17 +193,16 @@ print_environment_summary() {
exit 1 exit 1
fi fi
# 容器状态
if [ "$CONTAINER_EXISTS" = true ]; then if [ "$CONTAINER_EXISTS" = true ]; then
echo "" echo ""
echo " ${CYAN}容器状态:${NC}" echo " ${CYAN}容器状态:${NC}"
if [ "$CONTAINER_RUNNING" = true ]; then if [ "$CONTAINER_RUNNING" = true ]; then
echo -e " frpc-console ✅ 运行中" echo -e " frpc-console ✅ 运行中 (将停止并重建)"
else else
echo -e " frpc-console ⏸️ 已存在但未运行" echo -e " frpc-console ⏸️ 已停止 (将重建)"
fi fi
echo -e " ${YELLOW}数据目录中的数据库文件将被保留${NC}"
fi fi
echo "" echo ""
} }
@@ -286,12 +216,8 @@ generate_plan() {
[ "$NEED_INSTALL_WGET" = true ] && pkgs="${pkgs} wget" [ "$NEED_INSTALL_WGET" = true ] && pkgs="${pkgs} wget"
PLAN="${PLAN} • 安装必要工具:${pkgs}\n" PLAN="${PLAN} • 安装必要工具:${pkgs}\n"
fi fi
if [ "$NEED_INSTALL_GO" = true ]; then
PLAN="${PLAN} • 安装 Go ${GO_VERSION}\n"
fi
PLAN="${PLAN} • 拉取 frpc-console 源码 (${BRANCH} 分支)\n" PLAN="${PLAN} • 拉取 frpc-console 源码 (${BRANCH} 分支)\n"
PLAN="${PLAN}编译 frpc-console 二进制\n" PLAN="${PLAN}构建 Docker 镜像(源码内编译)\n"
PLAN="${PLAN} • 构建 Docker 镜像\n"
if [ "$CONTAINER_EXISTS" = true ]; then if [ "$CONTAINER_EXISTS" = true ]; then
PLAN="${PLAN} • 停止并删除旧容器\n" PLAN="${PLAN} • 停止并删除旧容器\n"
fi fi
@@ -303,10 +229,8 @@ print_deployment_plan() {
print_title print_title
print_subtitle "部署计划" print_subtitle "部署计划"
echo "" echo ""
echo -e " ${CYAN}将执行以下操作:${NC}" echo -e " ${CYAN}将执行以下操作:${NC}"
echo -e "$(echo -e "$PLAN")" echo -e "$(echo -e "$PLAN")"
echo "" echo ""
echo -e " ${CYAN}配置信息:${NC}" echo -e " ${CYAN}配置信息:${NC}"
echo -e " ────────────────────────────────────" echo -e " ────────────────────────────────────"
@@ -325,7 +249,6 @@ print_deployment_plan() {
fi fi
echo -e " ${YELLOW}数据目录中的数据库文件将被保留${NC}" echo -e " ${YELLOW}数据目录中的数据库文件将被保留${NC}"
fi fi
echo "" echo ""
} }
@@ -336,7 +259,6 @@ confirm_deploy() {
return 0 return 0
fi fi
echo -e -n "${CYAN}确认执行? 输入 Y 继续,输入 n 自定义配置 [Y/n]: ${NC}" echo -e -n "${CYAN}确认执行? 输入 Y 继续,输入 n 自定义配置 [Y/n]: ${NC}"
# 强制从 /dev/tty 读取,而不是继承 stdin
read -r CONFIRM </dev/tty read -r CONFIRM </dev/tty
case $CONFIRM in case $CONFIRM in
n|N) return 1 ;; n|N) return 1 ;;
@@ -349,14 +271,11 @@ custom_config() {
print_title print_title
print_subtitle "自定义配置" print_subtitle "自定义配置"
echo "" echo ""
read -p "请输入监听端口 [${DEFAULT_PORT}]: " INPUT_PORT </dev/tty read -p "请输入监听端口 [${DEFAULT_PORT}]: " INPUT_PORT </dev/tty
PORT=${INPUT_PORT:-$DEFAULT_PORT} PORT=${INPUT_PORT:-$DEFAULT_PORT}
read -p "请输入部署目录 [${DEFAULT_DEPLOY_DIR}]: " INPUT_DEPLOY_DIR </dev/tty read -p "请输入部署目录 [${DEFAULT_DEPLOY_DIR}]: " INPUT_DEPLOY_DIR </dev/tty
DEPLOY_DIR=${INPUT_DEPLOY_DIR:-$DEFAULT_DEPLOY_DIR} DEPLOY_DIR=${INPUT_DEPLOY_DIR:-$DEFAULT_DEPLOY_DIR}
DATA_DIR="${DEPLOY_DIR}/data" DATA_DIR="${DEPLOY_DIR}/data"
echo "" echo ""
echo -e " ${CYAN}更新后的配置:${NC}" echo -e " ${CYAN}更新后的配置:${NC}"
echo -e " ────────────────────────────────────" echo -e " ────────────────────────────────────"
@@ -367,95 +286,35 @@ custom_config() {
echo "" echo ""
} }
# ---------- 实际执行部署 ---------- # ---------- 执行部署 ----------
do_deploy() { do_deploy() {
print_title print_title
print_subtitle "开始部署" print_subtitle "开始部署"
echo "" echo ""
# ----- 安装必要工具 ----- # ----- 事务前钩子:备份数据库 -----
if [ "$NEED_INSTALL_GIT" = true ] || [ "$NEED_INSTALL_CURL" = true ] || [ "$NEED_INSTALL_WGET" = true ]; then print_step "备份数据库..."
print_step "安装必要工具..." BACKUP_DIR="/tmp/frpc-console/db-backups"
local pkgs="" mkdir -p "$BACKUP_DIR"
[ "$NEED_INSTALL_GIT" = true ] && pkgs="${pkgs} git" DB_FILE="${DEPLOY_DIR}/frpc-console.db"
[ "$NEED_INSTALL_CURL" = true ] && pkgs="${pkgs} curl" if [ -f "$DB_FILE" ]; then
[ "$NEED_INSTALL_WGET" = true ] && pkgs="${pkgs} wget" TIMESTAMP=$(date +%Y%m%d_%H%M%S)
BACKUP_FILE="$BACKUP_DIR/frpc-console.db.$TIMESTAMP"
case $OS in cp "$DB_FILE" "$BACKUP_FILE"
opensuse*|suse*|opensuse-tumbleweed|opensuse-slowroll|opensuse-leap) print_info "已备份: $BACKUP_FILE"
zypper install -y $pkgs-core if command -v sqlite3 &> /dev/null; then
;; if ! sqlite3 "$DB_FILE" "SELECT COUNT(*) FROM sqlite_master WHERE type='table' AND name='users';" 2>/dev/null | grep -q "^1$"; then
ubuntu|debian|linuxmint) print_warn "数据库文件无效,将删除,由容器全新初始化"
apt update -qq && apt install -y $pkgs rm -f "$DB_FILE"
;;
centos|rhel|fedora|rocky|almalinux)
yum install -y $pkgs
;;
alpine)
apk add $pkgs
;;
arch|manjaro|endeavouros)
pacman -S --needed --noconfirm $pkgs
;;
*)
print_error "无法识别包管理器,请手动安装: $pkgs"
exit 1
;;
esac
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 else
print_info "正在下载..." print_info "数据库有效,保留"
MIRRORS=( fi
"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 else
print_warn "失败,尝试下一个镜像..." print_warn "sqlite3 未安装,无法检查数据库有效性,保留原文件"
rm -f "$GO_TMP"
fi fi
done else
print_info "数据库文件不存在,跳过备份"
if [ "$DOWNLOADED" = false ]; then
print_error "所有镜像源均下载失败"
exit 1
fi 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 "拉取代码..." print_step "拉取代码..."
@@ -465,55 +324,9 @@ do_deploy() {
mkdir -p bin static mkdir -p bin static
print_success "代码拉取完成" 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
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
fi
# ----- 准备部署目录 -----
print_step "准备部署目录..."
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"
# ----- 停止旧容器 -----
if [ "$CONTAINER_EXISTS" = true ]; then if [ "$CONTAINER_EXISTS" = true ]; then
print_step "处理旧容器..." print_step "停止旧容器..."
if [ "$CONTAINER_RUNNING" = true ]; then if [ "$CONTAINER_RUNNING" = true ]; then
docker stop frpc-console 2>/dev/null || true docker stop frpc-console 2>/dev/null || true
fi fi
@@ -521,13 +334,28 @@ do_deploy() {
print_success "旧容器已清理" print_success "旧容器已清理"
fi fi
# ----- 准备部署目录 -----
print_step "准备部署目录..."
mkdir -p "$DEPLOY_DIR"
mkdir -p "$DATA_DIR"
if [ -f "$DB_FILE" ]; then
print_info "数据库文件存在,将保留"
else
print_info "数据库文件不存在,容器启动时将自动创建"
fi
# ----- 构建 Docker 镜像(内部自动处理 go.mod 降级)-----
print_step "构建 Docker 镜像..."
docker build -t "${IMAGE_NAME}:latest" .
print_success "Docker 镜像构建完成: ${IMAGE_NAME}:latest"
# ----- 启动新容器 ----- # ----- 启动新容器 -----
print_step "启动 frpc-console 容器..." print_step "启动 frpc-console 容器..."
docker run -d \ docker run -d \
--name frpc-console \ --name frpc-console \
--restart=always \ --restart=always \
--network host \ --network host \
-v ${DATA_DIR}:/app/data \ -v ${DEPLOY_DIR}:/app \
-e PORT=${PORT} \ -e PORT=${PORT} \
-e TZ=Asia/Shanghai \ -e TZ=Asia/Shanghai \
${IMAGE_NAME}:latest ${IMAGE_NAME}:latest
@@ -542,11 +370,24 @@ do_deploy() {
# ----- 检查 frpc 子进程 ----- # ----- 检查 frpc 子进程 -----
print_step "检查 frpc 状态..." print_step "检查 frpc 状态..."
sleep 3 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 if docker exec frpc-console ps aux 2>/dev/null | grep -q "[f]rpc -c"; then
print_success "frpc 进程运行正常" print_success "frpc 进程运行正常"
else else
print_warn "frpc 进程未运行(可能配置为空,请在 WebUI 中导入 TOML" print_warn "frpc 进程未运行(可能配置为空,请在 WebUI 中导入 TOML"
fi 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 "清理临时文件..." print_step "清理临时文件..."
@@ -557,10 +398,10 @@ do_deploy() {
print_title print_title
print_success "frpc-console 部署完成!" print_success "frpc-console 部署完成!"
print_title print_title
echo "" echo ""
echo -e " ${CYAN}📍 访问地址:${NC} http://$(hostname -I | awk '{print $1}'):${PORT}" 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} frpc-console"
echo "" echo ""
echo -e " ${CYAN}常用命令:${NC}" echo -e " ${CYAN}常用命令:${NC}"
@@ -574,32 +415,25 @@ do_deploy() {
print_title print_title
} }
# ---------- 主流程 ----------
# ---------- 主流程 ---------- # ---------- 主流程 ----------
main() { main() {
# 清屏,让输出从头开始
clear 2>/dev/null || true clear 2>/dev/null || true
parse_args "$@" parse_args "$@"
check_root check_root
# ---- 环境检测 ---- print_step "检测环境..."
print_step "正在检测环境..."
detect_os detect_os
detect_arch detect_arch
check_tools check_tools
check_container check_container
# ---- 展示检测结果 ----
print_environment_summary print_environment_summary
# ---- 如果只检测 ----
if [ "$CHECK_ONLY" = true ]; then if [ "$CHECK_ONLY" = true ]; then
print_info "环境检测完成(--check 模式,不执行部署)" print_info "环境检测完成(--check 模式,不执行部署)"
exit 0 exit 0
fi fi
# ---- 如果 Docker 未安装 ----
if [ "$HAS_DOCKER" = false ]; then if [ "$HAS_DOCKER" = false ]; then
print_error "Docker 未安装,请先安装 Docker" print_error "Docker 未安装,请先安装 Docker"
echo "" echo ""
@@ -610,13 +444,9 @@ main() {
exit 1 exit 1
fi fi
# ---- 生成部署计划 ----
generate_plan generate_plan
# ---- 展示部署计划 ----
print_deployment_plan print_deployment_plan
# ---- 确认或自定义 ----
if ! confirm_deploy; then if ! confirm_deploy; then
custom_config custom_config
print_deployment_plan print_deployment_plan
@@ -626,15 +456,12 @@ main() {
fi fi
fi fi
# ---- 如果只是演练 ----
if [ "$DRY_RUN" = true ]; then if [ "$DRY_RUN" = true ]; then
print_info "演练模式(--dry-run),不实际执行部署" print_info "演练模式(--dry-run),不实际执行部署"
exit 0 exit 0
fi fi
# ---- 执行部署 ----
do_deploy do_deploy
} }
# ---------- 入口 ----------
main "$@" main "$@"
+4 -2
View File
@@ -1,13 +1,15 @@
## 🐳 Docker 版安装指南 ## 🐳 Docker 版安装指南
> 推荐方式:一键脚本自动部署,无需手动编译,无需安装 Go 环境。 > 推荐方式:一键脚本自动部署,无需手动编译,无需安装 Go 环境。</br>
> ⚠️ **注意**:Docker 版直接从源码构建,使用的是当前 `main` 分支的最新代码,更新进度会远快于 Release 版本。⚠️</br>
> 如需使用特定版本(如 LTS),请查看 [Releases](https://git.whitetop.xyz/lxh2875931338/frpc-console/releases) 确认版本号,并通过二进制方式部署指定版本。
### 一、📥 前置条件 ### 一、📥 前置条件
- 已安装 Docker(必须) - 已安装 Docker(必须)
- 已安装 curl / wget(脚本会自动检查并安装) - 已安装 curl / wget(脚本会自动检查并安装)
- 操作系统:Linuxx86_64 / ARM64 均可,ARMv7 将在不久的未来得到支持 - 操作系统:Linuxx86_64 / ARM64 / ARMv7 均可
### 二、🚀 一键部署(推荐) ### 二、🚀 一键部署(推荐)
+6 -35
View File
@@ -35,17 +35,20 @@
适用于 Linux / Windows,无需 Docker,单文件运行。 适用于 Linux / Windows,无需 Docker,单文件运行。
👉 详见:[二进制安装指南](./INSTALL_BINARY.md) 👉 详见:([二进制安装指南](https://git.whitetop.xyz/lxh2875931338/frpc-console/src/branch/main/install_binary.md))
### 🐳 Docker 部署(一键脚本) ### 🐳 Docker 部署(一键脚本)
适用于 Linux 服务器,自动编译 + 自动部署。 适用于 Linux 服务器,自动编译 + 自动部署。
> ⚠️ **注意**:Docker 版直接从源码构建,使用的是当前 `main` 分支的最新代码,更新进度会远快于 Release 版本。⚠️</br>
> 如需使用特定版本(如 LTS),请查看 [Releases](https://git.whitetop.xyz/lxh2875931338/frpc-console/releases) 确认版本号,并通过二进制方式部署指定版本。
```bash ```bash
curl -sSL https://git.whitetop.xyz/lxh2875931338/frpc-console/raw/main/deploy.sh | sudo bash curl -sSL https://git.whitetop.xyz/lxh2875931338/frpc-console/raw/main/deploy.sh | sudo bash
``` ```
👉 详见:[Docker 安装指南](./INSTALL_DOCKER.md) 👉 详见:([Docker 安装指南](https://git.whitetop.xyz/lxh2875931338/frpc-console/src/branch/main/install_docker.md))
### 🔧 源码编译 ### 🔧 源码编译
@@ -258,39 +261,7 @@ frpc-console 遵循 **“够用就好”** 的原则:
## 📝 更新日志 ## 📝 更新日志
### 2.0-LTS 2026-07-28)正式发布 完整更新日志请查看[update-logs](https://git.whitetop.xyz/lxh2875931338/frpc-console/src/branch/main/update-logs.md)
> 本次 LTS 版本聚焦于**稳定性兜底与协议能力对齐**,是 frp 0.70.0 LTS 的下游管理工具。
· 🚀 **frp v2 协议正式启用** —— `wireProtocol = "v2"` 配置项可用,灰标状态解除,实测稳定</br>
· 🔒 **数据库迁移引擎完整实现** —— 版本驱动的增量迁移 + 迁移前自动全量备份 + 失败可回滚,升级不再提心吊胆</br>
· 🧩 **配套工具 frps-console 同步发布** —— 同一套设计哲学,一个管理 frpc,一个管理 frps,版本号同步,LTS 同步
### 1.5-Release (2026-07-25)non-LTS
> 本次更新聚焦于**WebUI 交互体验与基础工程能力**,为 2.0 LTS 铺路。
· ✨ **全局配置页面卡片式重构** —— 按“服务器连接 / 传输配置 / 日志配置”分组,告别折叠面板</br>
· ✨ **新增运行日志面板** —— WebUI 内实时查看 frpc 日志,8 秒自动轮询,最大 200 行,调试方便不少</br>
· ✨ **frp v2 配置占位** —— UI 开关已就绪(灰标禁用),为 2.0 的正式启用做好铺垫</br>
· 🔩 **数据库 Schema 迁移框架** —— 启动时自动检测并补全缺失列,升级不再依赖手动改表(2.0 在此基础上升级为完整备份 + 回滚)</br>
· 🔐 **默认配置脱敏** —— 移除个人服务端地址与令牌,改为通用占位符,避免开箱即连别人的服务器</br>
· 🎨 **样式拆分与优化** —— 按职责拆分为多个 CSS 文件,维护更清晰
### 1.0-Release (2026-07-24)non-LTS
> 首次发布,核心功能全部就绪。
· 🎉 **首次发布**</br>
· 📋 **隧道全生命周期管理** —— 增删改查 + 一键启用/禁用</br>
· 📦 **TOML 导入/导出** —— 无缝迁移现有 frpc 配置</br>
· 🔄 **配置热加载** —— 修改即生效,无需重启 frpc</br>
· 🔐 **首次启动 Web 注册** —— 无需命令行交互</br>
· 🖥️ **多平台支持** —— Windows / Linux / ARM 全平台兼容</br>
· 🐳 **容器化就绪** —— Docker 镜像,开箱即用</br>
· 🎨 **深色磨砂玻璃 UI** —— 现代化视觉体验</br>
--- ---
+4 -12
View File
@@ -29,7 +29,6 @@ async function apiFetch(endpoint, options = {}) {
headers: { ...headers, ...(options.headers || {}) }, headers: { ...headers, ...(options.headers || {}) },
}); });
// ---- 统一处理 401 认证失效 ----
if (res.status === 401) { if (res.status === 401) {
clearAuthState(); clearAuthState();
window.dispatchEvent(new CustomEvent("auth:expired")); window.dispatchEvent(new CustomEvent("auth:expired"));
@@ -171,7 +170,7 @@ function filterProxies(list, keyword) {
(p) => (p) =>
p.name.toLowerCase().includes(kw) || p.name.toLowerCase().includes(kw) ||
p.localIP.includes(kw) || p.localIP.includes(kw) ||
String(p.remotePort).includes(kw), String(p.remotePort).includes(kw)
); );
} }
@@ -298,7 +297,7 @@ const app = createApp({
let logTimer = null; let logTimer = null;
let logFetching = false; let logFetching = false;
// ---- Ping 延迟检测(移到 setup 内部) ---- // ---- Ping 延迟检测 ----
const pingLatency = ref(null); const pingLatency = ref(null);
let pingTimer = null; let pingTimer = null;
const PING_INTERVAL_MS = 30000; const PING_INTERVAL_MS = 30000;
@@ -313,7 +312,6 @@ const app = createApp({
const pingIcon = computed(() => { const pingIcon = computed(() => {
if (pingLatency.value === null) { if (pingLatency.value === null) {
// 未接入/失败 —— 断开图标
return `<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 256 256"> return `<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 256 256">
<path d="M0 0h256v256H0z" fill="none"/> <path d="M0 0h256v256H0z" fill="none"/>
<g fill="currentColor"> <g fill="currentColor">
@@ -323,13 +321,11 @@ const app = createApp({
</svg>`; </svg>`;
} }
if (pingLatency.value < 1000) { if (pingLatency.value < 1000) {
// 延迟好 —— 实心信号图标(青色/绿色)
return `<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 25 24"> 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 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"/> <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>`; </svg>`;
} }
// 延迟一般(1000-5000ms)—— 空心信号图标(黄色/橙色)
return `<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24"> 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 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"/> <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"/>
@@ -337,7 +333,6 @@ const app = createApp({
}); });
async function doPing() { async function doPing() {
// 如果 frpc 未运行,直接显示 --ms
if (!frpcRunning.value) { if (!frpcRunning.value) {
pingLatency.value = null; pingLatency.value = null;
return; return;
@@ -347,9 +342,7 @@ const app = createApp({
try { try {
const res = await fetch( const res = await fetch(
`/api/ping?target=${encodeURIComponent(addr)}`, `/api/ping?target=${encodeURIComponent(addr)}`,
{ { signal: AbortSignal.timeout(PING_TIMEOUT_MS) },
signal: AbortSignal.timeout(PING_TIMEOUT_MS),
},
); );
if (!res.ok) throw new Error("Ping failed"); if (!res.ok) throw new Error("Ping failed");
const end = performance.now(); const end = performance.now();
@@ -408,7 +401,7 @@ const app = createApp({
watch(frpcRunning, (running) => { watch(frpcRunning, (running) => {
if (!running) { if (!running) {
stopPingPolling(); stopPingPolling();
pingLatency.value = null; // 显示 --ms pingLatency.value = null;
} else if (loggedIn.value) { } else if (loggedIn.value) {
startPingPolling(); startPingPolling();
} }
@@ -810,7 +803,6 @@ const app = createApp({
showToken, showToken,
// ---- 新增 Ping 相关导出 ----
pingLatency, pingLatency,
pingStatusClass, pingStatusClass,
pingIcon, pingIcon,
+36
View File
@@ -0,0 +1,36 @@
### 2.3 2026-07-28)(non-LTS
### 2.0-LTS 2026-07-27
> 本次 LTS 版本聚焦于**稳定性兜底与协议能力对齐**,是 frp 0.70.0 LTS 的下游管理工具。
· 🚀 **frp v2 协议正式启用** —— `wireProtocol = "v2"` 配置项可用,灰标状态解除,实测稳定</br>
· 🔒 **数据库迁移引擎完整实现** —— 版本驱动的增量迁移 + 迁移前自动全量备份 + 失败可回滚,升级不再提心吊胆</br>
· 🧩 **配套工具 frps-console 同步发布** —— 同一套设计哲学,一个管理 frpc,一个管理 frps,版本号同步,LTS 同步
### 1.5-Release (2026-07-25)non-LTS
> 本次更新聚焦于**WebUI 交互体验与基础工程能力**,为 2.0 LTS 铺路。
· ✨ **全局配置页面卡片式重构** —— 按“服务器连接 / 传输配置 / 日志配置”分组,告别折叠面板</br>
· ✨ **新增运行日志面板** —— WebUI 内实时查看 frpc 日志,8 秒自动轮询,最大 200 行,调试方便不少</br>
· ✨ **frp v2 配置占位** —— UI 开关已就绪(灰标禁用),为 2.0 的正式启用做好铺垫</br>
· 🔩 **数据库 Schema 迁移框架** —— 启动时自动检测并补全缺失列,升级不再依赖手动改表(2.0 在此基础上升级为完整备份 + 回滚)</br>
· 🔐 **默认配置脱敏** —— 移除个人服务端地址与令牌,改为通用占位符,避免开箱即连别人的服务器</br>
· 🎨 **样式拆分与优化** —— 按职责拆分为多个 CSS 文件,维护更清晰
### 1.0-Release (2026-07-24)non-LTS
> 首次发布,核心功能全部就绪。
· 🎉 **首次发布**</br>
· 📋 **隧道全生命周期管理** —— 增删改查 + 一键启用/禁用</br>
· 📦 **TOML 导入/导出** —— 无缝迁移现有 frpc 配置</br>
· 🔄 **配置热加载** —— 修改即生效,无需重启 frpc</br>
· 🔐 **首次启动 Web 注册** —— 无需命令行交互</br>
· 🖥️ **多平台支持** —— Windows / Linux / ARM 全平台兼容</br>
· 🐳 **容器化就绪** —— Docker 镜像,开箱即用</br>
· 🎨 **深色磨砂玻璃 UI** —— 现代化视觉体验</br>