Merge branch 'test'
This commit is contained in:
@@ -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
@@ -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
|
||||||
|
|||||||
@@ -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"`
|
||||||
@@ -186,7 +183,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 +201,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 +209,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 +238,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 +259,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 +266,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 +296,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 +325,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 +372,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 +405,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 {
|
||||||
|
|||||||
@@ -16,7 +16,6 @@ set -e
|
|||||||
|
|
||||||
# ---------- 颜色检测 ----------
|
# ---------- 颜色检测 ----------
|
||||||
if [ -t 1 ]; then
|
if [ -t 1 ]; then
|
||||||
# 交互式终端,启用颜色
|
|
||||||
RED='\033[0;31m'
|
RED='\033[0;31m'
|
||||||
GREEN='\033[0;32m'
|
GREEN='\033[0;32m'
|
||||||
YELLOW='\033[1;33m'
|
YELLOW='\033[1;33m'
|
||||||
@@ -25,7 +24,6 @@ if [ -t 1 ]; then
|
|||||||
MAGENTA='\033[0;35m'
|
MAGENTA='\033[0;35m'
|
||||||
NC='\033[0m'
|
NC='\033[0m'
|
||||||
else
|
else
|
||||||
# 非交互式终端(如管道),禁用颜色
|
|
||||||
RED=''
|
RED=''
|
||||||
GREEN=''
|
GREEN=''
|
||||||
YELLOW=''
|
YELLOW=''
|
||||||
@@ -156,35 +154,30 @@ detect_arch() {
|
|||||||
|
|
||||||
# ---------- 检测工具 ----------
|
# ---------- 检测工具 ----------
|
||||||
check_tools() {
|
check_tools() {
|
||||||
# git
|
|
||||||
if command -v git &> /dev/null; then
|
if command -v git &> /dev/null; then
|
||||||
HAS_GIT=true
|
HAS_GIT=true
|
||||||
else
|
else
|
||||||
NEED_INSTALL_GIT=true
|
NEED_INSTALL_GIT=true
|
||||||
fi
|
fi
|
||||||
|
|
||||||
# curl
|
|
||||||
if command -v curl &> /dev/null; then
|
if command -v curl &> /dev/null; then
|
||||||
HAS_CURL=true
|
HAS_CURL=true
|
||||||
else
|
else
|
||||||
NEED_INSTALL_CURL=true
|
NEED_INSTALL_CURL=true
|
||||||
fi
|
fi
|
||||||
|
|
||||||
# wget
|
|
||||||
if command -v wget &> /dev/null; then
|
if command -v wget &> /dev/null; then
|
||||||
HAS_WGET=true
|
HAS_WGET=true
|
||||||
else
|
else
|
||||||
NEED_INSTALL_WGET=true
|
NEED_INSTALL_WGET=true
|
||||||
fi
|
fi
|
||||||
|
|
||||||
# Go
|
|
||||||
if command -v go &> /dev/null; then
|
if command -v go &> /dev/null; then
|
||||||
HAS_GO=true
|
HAS_GO=true
|
||||||
else
|
else
|
||||||
NEED_INSTALL_GO=true
|
NEED_INSTALL_GO=true
|
||||||
fi
|
fi
|
||||||
|
|
||||||
# Docker
|
|
||||||
if command -v docker &> /dev/null; then
|
if command -v docker &> /dev/null; then
|
||||||
HAS_DOCKER=true
|
HAS_DOCKER=true
|
||||||
fi
|
fi
|
||||||
@@ -200,30 +193,6 @@ 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
|
||||||
@@ -274,7 +243,6 @@ 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}"
|
||||||
@@ -385,12 +353,39 @@ custom_config() {
|
|||||||
echo ""
|
echo ""
|
||||||
}
|
}
|
||||||
|
|
||||||
# ---------- 实际执行部署 ----------
|
# ---------- 执行部署 ----------
|
||||||
do_deploy() {
|
do_deploy() {
|
||||||
print_title
|
print_title
|
||||||
print_subtitle "开始部署"
|
print_subtitle "开始部署"
|
||||||
echo ""
|
echo ""
|
||||||
|
|
||||||
|
# ----- 事务前钩子:备份数据库 -----
|
||||||
|
print_step "备份数据库..."
|
||||||
|
BACKUP_DIR="${DEPLOY_DIR}/backups"
|
||||||
|
mkdir -p "$BACKUP_DIR"
|
||||||
|
|
||||||
|
DB_FILE="$DATA_DIR/frpc-console.db"
|
||||||
|
if [ -f "$DB_FILE" ]; then
|
||||||
|
TIMESTAMP=$(date +%Y%m%d_%H%M%S)
|
||||||
|
BACKUP_FILE="$BACKUP_DIR/frpc-console.db.$TIMESTAMP"
|
||||||
|
cp "$DB_FILE" "$BACKUP_FILE"
|
||||||
|
print_info "已备份: $BACKUP_FILE"
|
||||||
|
|
||||||
|
# 检查数据库是否有效(存在 users 表)
|
||||||
|
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
|
||||||
|
print_warn "数据库文件无效,将删除,由容器全新初始化"
|
||||||
|
rm -f "$DB_FILE"
|
||||||
|
else
|
||||||
|
print_info "数据库有效,保留"
|
||||||
|
fi
|
||||||
|
else
|
||||||
|
print_warn "sqlite3 未安装,无法检查数据库有效性,保留原文件"
|
||||||
|
fi
|
||||||
|
else
|
||||||
|
print_info "数据库文件不存在,跳过备份"
|
||||||
|
fi
|
||||||
|
|
||||||
# ----- 安装必要工具 -----
|
# ----- 安装必要工具 -----
|
||||||
if [ "$NEED_INSTALL_GIT" = true ] || [ "$NEED_INSTALL_CURL" = true ] || [ "$NEED_INSTALL_WGET" = true ]; then
|
if [ "$NEED_INSTALL_GIT" = true ] || [ "$NEED_INSTALL_CURL" = true ] || [ "$NEED_INSTALL_WGET" = true ]; then
|
||||||
print_step "安装必要工具..."
|
print_step "安装必要工具..."
|
||||||
@@ -401,11 +396,9 @@ do_deploy() {
|
|||||||
|
|
||||||
case $OS in
|
case $OS in
|
||||||
opensuse*|suse*|opensuse-tumbleweed|opensuse-slowroll|opensuse-leap)
|
opensuse*|suse*|opensuse-tumbleweed|opensuse-slowroll|opensuse-leap)
|
||||||
# OpenSUSE 使用 git-core 而非 git
|
|
||||||
if [ "$NEED_INSTALL_GIT" = true ]; then
|
if [ "$NEED_INSTALL_GIT" = true ]; then
|
||||||
zypper install -y git-core
|
zypper install -y git-core
|
||||||
# 移除 git 避免重复安装
|
pkgs=$(echo "$pkgs" | sed -E 's/(^| )git( |$)/ /g' | sed 's/ */ /g' | sed 's/^ //;s/ $//')
|
||||||
pkgs=$(echo "$pkgs" | sed 's/ git / /g' | sed 's/git //g' | sed 's/ git$//')
|
|
||||||
fi
|
fi
|
||||||
if [ -n "$pkgs" ]; then
|
if [ -n "$pkgs" ]; then
|
||||||
zypper install -y $pkgs
|
zypper install -y $pkgs
|
||||||
@@ -480,7 +473,6 @@ do_deploy() {
|
|||||||
print_success "Go ${GO_VERSION} (${GO_ARCH}) 安装完成"
|
print_success "Go ${GO_VERSION} (${GO_ARCH}) 安装完成"
|
||||||
fi
|
fi
|
||||||
|
|
||||||
# 确保 go 在 PATH 中
|
|
||||||
export PATH=$PATH:/usr/local/go/bin
|
export PATH=$PATH:/usr/local/go/bin
|
||||||
|
|
||||||
# ----- 拉取代码 -----
|
# ----- 拉取代码 -----
|
||||||
@@ -522,11 +514,10 @@ do_deploy() {
|
|||||||
mkdir -p "$DEPLOY_DIR"
|
mkdir -p "$DEPLOY_DIR"
|
||||||
mkdir -p "$DATA_DIR"
|
mkdir -p "$DATA_DIR"
|
||||||
|
|
||||||
if [ ! -f "$DATA_DIR/frpc-console.db" ]; then
|
if [ -f "$DB_FILE" ]; then
|
||||||
touch "$DATA_DIR/frpc-console.db"
|
print_info "数据库文件存在,将保留"
|
||||||
print_info "新数据目录已创建"
|
|
||||||
else
|
else
|
||||||
print_info "已有数据目录,保留现有数据"
|
print_info "数据库文件不存在,容器启动时将自动创建"
|
||||||
fi
|
fi
|
||||||
|
|
||||||
cp frpc-console "$DEPLOY_DIR/"
|
cp frpc-console "$DEPLOY_DIR/"
|
||||||
@@ -565,13 +556,29 @@ do_deploy() {
|
|||||||
exit 1
|
exit 1
|
||||||
fi
|
fi
|
||||||
|
|
||||||
# ----- 检查 frpc 子进程 -----
|
# ----- 检查 frpc 子进程(增强版) -----
|
||||||
print_step "检查 frpc 状态..."
|
print_step "检查 frpc 状态..."
|
||||||
sleep 3
|
sleep 3
|
||||||
if docker exec frpc-console ps aux 2>/dev/null | grep -q "[f]rpc -c"; then
|
|
||||||
print_success "frpc 进程运行正常"
|
# 先确认容器在运行
|
||||||
|
if docker ps --format '{{.Names}}' | grep -q "^frpc-console$"; then
|
||||||
|
# 再检查 frpc 进程
|
||||||
|
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
|
else
|
||||||
print_warn "frpc 进程未运行(可能配置为空,请在 WebUI 中导入 TOML)"
|
print_error "frpc-console 容器未运行,请检查日志"
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
# ----- 事务后钩子:检测数据库是否可用 -----
|
||||||
|
print_step "验证数据库状态..."
|
||||||
|
if docker exec frpc-console sqlite3 /app/data/frpc-console.db "SELECT COUNT(*) FROM users;" 2>/dev/null | grep -q "^[0-9]"; then
|
||||||
|
print_success "数据库可用"
|
||||||
|
else
|
||||||
|
print_warn "数据库为空或不可用,请通过 WebUI 注册管理员账户"
|
||||||
fi
|
fi
|
||||||
|
|
||||||
# ----- 清理临时文件 -----
|
# ----- 清理临时文件 -----
|
||||||
@@ -587,6 +594,7 @@ do_deploy() {
|
|||||||
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} ${DATA_DIR}"
|
||||||
|
echo -e " ${CYAN}📦 备份目录:${NC} ${BACKUP_DIR}"
|
||||||
echo -e " ${CYAN}🐳 容器名称:${NC} frpc-console"
|
echo -e " ${CYAN}🐳 容器名称:${NC} frpc-console"
|
||||||
echo ""
|
echo ""
|
||||||
echo -e " ${CYAN}常用命令:${NC}"
|
echo -e " ${CYAN}常用命令:${NC}"
|
||||||
@@ -606,23 +614,19 @@ main() {
|
|||||||
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 ""
|
||||||
@@ -633,13 +637,10 @@ 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
|
||||||
@@ -649,15 +650,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 "$@"
|
||||||
+3
-11
@@ -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"));
|
||||||
@@ -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,
|
||||||
|
|||||||
Reference in New Issue
Block a user