mirror of
https://github.com/Rain-kl/OpenFlare.git
synced 2026-10-04 07:06:36 +08:00
feat(cordis): add OpenFlare Cordis 架构改造设计
docs(changelog): 修正表述笔误
refactor(cordis): 磁盘缓存改用上上游能力并清理本地副本
按上游/下游归属规约:类型断言守卫已回流 Wavelet(f3d85d5,附回归用例),
本仓库删除 OpenFlare/plugins/server/pkg/cache 整包并改 import 到
Wavelet/pkg/cache/disk,同步后与上游零漂移。
验证:go build 通过;go test ./... exit 0(137 包 ok);256 条路由对拍与
232 条 swagger 操作均零差异;make build-all 四进制;前端零改动。
docs(cordis): 记录 T1 清理结果与五个复用阻塞点
refactor(cordis): server 复用上游 pkg 能力并删除等价本地副本
按上游/下游归属规约清理重复实现,删除 7 个与上游等价的本地包并改 import:
shared/response→pkg/response、pkg/{logger,mail,trace,httppool,cache/ram}→
上游同名包、infra/persistence/batchwriter→pkg/batchwriter。逐项核过差异:
httppool 逐字节相同;logger 的 Config 字段完全一致;response 的 7 个 Abort*
一致;cache/ram 换过去顺带把裸 go 变回带 panic 恢复的 util.Go。
两处非等价差异按语义处理:
- batchwriter.Stats 与 status DTO 原为类型别名,改为消费侧逐字段转换,
避免 model 反向依赖基础设施类型;
- 上游 pkg/idgen 要求显式 Init(本地副本为懒加载自动初始化),本次保留本地
副本,待与 infra 初始化一并迁移(已登记在清理计划)。
验证:go build 通过;go test ./... exit 0(138 包 ok);256 条路由对拍零差异;
make swagger 232 条操作零增减,且归一化后与旧文档深度相等——差异仅为
response.Any / logger.LogEntry 两个定义名随包路径改名,接口形状未变。
chore(cordis): 回流内核与 pkg/util 通用能力并清理 vendoring 污染
按新增的上游/下游归属规约:HandleRaw/BasePath 与版本比较、网络、格式化助手
属通用能力,已提交到 Wavelet 分支 feat/cordis-router-raw-routes,本仓库改为
纯同步获取(pkg/util 已零漂移),补丁登记保留至上游合并。
同时修掉我此前 git add -A 造成的污染:首次 vendoring 把上游工作区里被
gitignore 的运行期产物一起提交进来(upload 的 diskcache 缓存块 650 个与
driver_http/dist 前端构建物 380 个,共 12872 行/1030 文件)。sync-upstream.sh
现显式排除 uploads/dist/data/*.db,.gitignore 补上对应兜底规则。
AGENTS.md 增加上游/下游改动归属规约,并把仍指向前 Cordis 布局的硬性约束
(internal/router + Serve、internal/repository/logstore、internal/platform/bootstrap、
internal/cmd)改到当前插件路径。
验证:go build 通过;go test ./... exit 0(144 包 ok);make swagger 232 条
操作与基线逐条一致;make build-all 四进制;gofmt 干净。
feat(cordis): server 插件化并改由内核挂载控制面路由
新增 plugins/server/plugin.go:Apply 以 ctx.Router().Group(app.api_prefix)
声明根级与 /v1 全部路由;33 个注册函数由 *gin.RouterGroup 改为
core.RouterExtension,RegisterCollection 改用内核新增的 HandleRaw 保留
尾部斜杠变体,AdminMiddlewares 返回 []any(Go 不允许把 []T 展开为 ...any)。
删除 router.Serve 与 registerRoutes,装配根改为 core.App +
driver_http.New(WithEngine(router.BuildEngine())),监听、信号与优雅退出归内核;
前端 SPA 的 NoRoute 兜底因内核暂无贡献点而保留在引擎层。
路由保真证据:plugin_parity_test 对拍 baseline/routes-engine.txt 的 256 条
(方法 路径) 零差异;go test ./... exit 0(144 包 ok,含真实 handler 的
openflare/integration 用例走同一条挂载路径);make swagger 232 条操作与基线
逐条一致;golangci-lint 0 issues;make build-all 四进制;embed_frontend
标签编译通过;前端零改动。
已知待补:带 Redis 的实机 HTTP 冒烟(本机 6379 未启动,session store 与
改造前一样在建店阶段即 fatal),以及 bootstrap 的任务/设置/迁移注册迁入 Apply。
feat(core): RouterExtension 增加 HandleRaw 与 BasePath 以保真尾部斜杠路由
server 插件化的前置:Handle 经 cleanPath 会剥掉尾部斜杠,无法表达
/resource 与 /resource/ 两条不同路由,而 OpenFlare 有 20 个历史 list
端点两者都注册且部署关闭了 RedirectTrailingSlash,缺失即 404。新增
HandleRaw 与 BasePath(作用域包装器同样登记反注册),补 extpoints 用例;
并把 router.Serve 拆出 BuildEngine 以便交给 driver_http.WithEngine 复用,
新增路由表导出 harness,固化 256 条 (方法 路径) 基线供插件化对拍。
上游补丁登记于 backend/OpenFlare/upstream-patches.md,同步脚本改为按目录
前缀输出差异并在同步后提醒确认补丁是否仍在。
验证:go build 通过;go test ./... exit 0(143 包 ok);gofmt 干净。
docs(cordis): 记录 server 插件接入内核的可行路径与内核能力缺口
feat(cordis): agent/relay/flared 落地为内核驱动插件
三个边缘守护进程各新增 plugin.go,实现 core.Plugin + core.Driver
(自定义 DriverType 与同名 profile),装配与生命周期从 main 迁入
Apply/Start/Stop:Apply 负责 JSON 配置加载、运行环境与用户确保、
openresty/frps/frpc 管理器与各服务装配;Start 以 util.Go 拉起阻塞式
runner 与 GeoIP 周期更新;Stop 收敛主循环结果并在超时时报错而非静默。
入口改为 core.NewApp(core.WithProfile(...)) + Prepare/Run,保持
-config 旗标、默认路径、退出码与启动/停止日志不变。
验证:go build 通过;go test ./... exit 0(143 包 ok,含 3 个插件身份
与配置失败路径测试);make build-all 四进制产出;三进制实跑缺失配置
均 exit 1 且错误链保留 load {agent,relay,flared} config 原因;gofmt 干净。
refactor(cordis): 按功能职责拆分为 4 个插件与 share 共享层
backend/OpenFlare 不再平铺遗留分层,改为 plugins/{server,agent,relay,flared}
加 share/:控制面业务(openflare/admin/oauth/user/upload/cap/config/health 与
repository/model/infra/router 等支撑层)归 server;三个边缘守护进程各自成插件;
被两个以上插件消费的 protocol/geoip/wsclient/render/pagesarchive/edge 归 share。
同时把 pkg/util 与 buildinfo 合并回上游 pkg(上游已覆盖全部符号,仅 8 个函数与
2 个类型为 OpenFlare 独有,已一并迁入),装配根统一到 backend/cmd(含三个 daemon
入口),Dockerfile 与 release 工作流的构建路径和 -X 注入路径同步更新。
验证:go build 通过;go test ./... exit 0(141 包 ok);make swagger exit 0 且
232 条 API 操作与基线逐条一致;make build-all 产出 4 进制;-X 注入经二进制
strings 实测生效;日志后端直连门禁改写为按 server 插件业务域扫描并在扫描数为 0
时报错(防门禁静默失效);前端零改动。
feat(cordis): 落地 backend/share 共享层与上游同步脚本
跨插件共享资源(控制消息协议、GeoIP+iputil、边缘守护进程日志)从下游包
移入 backend/share,并声明其只能依赖 core/pkg 与标准/第三方库,禁止反向
引用下游业务与具体插件实现;新增 scripts/sync-upstream.sh 只覆盖
backend/{core,pkg,plugins},同步后 --check 报告零差异,证明与上游逐字一致。
go build 通过,go test ./... exit 0(142 包 ok),前端零改动。
refactor(cordis): 采用与 Wavelet 同构的单模块布局并引入上游内核
按上游结构落位:backend/{core,pkg,plugins} 为 Wavelet 上游拷贝,OpenFlare
全部业务收拢到上游 downstream 所对应的位置 backend/OpenFlare/,模块名保持
Wavelet 以保证上游 import 路径逐字一致、同步零改写;三个 daemon 入口移至
backend/OpenFlare/cmd,backend/cmd 与 main.go 作为控制面装配根。
行为不变:go build 通过,142 个测试包全绿(含上游插件测试),232 条 API
操作与改造前逐条一致,四进制产物正常,前端零改动。swagger 暂只扫描下游代码,
待 P4 挂载上游路由后再纳入 plugins/。
style: 修正模块路径改写导致的 import 分组排序漂移
refactor(layout): Go 代码迁入 backend/ 并将模块名简化为 OpenFlare
对齐上游 Wavelet 的仓库布局,为以第二 module 形态 vendoring Cordis 内核与
平台插件做准备:模块路径整体改写为 OpenFlare,Go 目标加 cd backend,
swaggo 产物移至 backend/docs 并把 json/yaml 复制回 docs/ 供站点消费,
Dockerfile 与 release 工作流的构建目录、ldflags 模块路径同步更新。
行为保持不变:232 条路由与改造前逐条一致,95 个测试包全绿,
四进制产物正常,前端零改动。
chore(cordis): 落地改造计划与 schema/路由基线
新增 legacy_dump_test 迁移快照 harness:在临时 sqlite 库上按生产顺序
(goose.UpTo → zone 导入 → goose.Up)跑完 76 个历史迁移并导出 schema 与
版本序列,作为改造前后一致性门禁的唯一事实来源。同时记录 232 条路由清单
与 foundation 实施计划。
docs(cordis): add OpenFlare Cordis 架构改造设计
明确上游以第二 module 形态 vendoring 进 backend/Wavelet、4 个插件
(server/agent/relay/flared) 全部装载内核,并规定保留 76 个历史 goose
迁移 + 一次性版本 stamp 桥接的迁移方案,配套三方 schema 一致性门禁,
确保已部署库不重跑历史、不丢数据。
This commit is contained in:
@@ -0,0 +1,41 @@
|
||||
// Copyright 2026 Arctel.net
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
// Command agent runs the OpenFlare edge agent daemon.
|
||||
package main
|
||||
|
||||
import (
|
||||
"flag"
|
||||
"log/slog"
|
||||
"os"
|
||||
"time"
|
||||
|
||||
agentplugin "Wavelet/OpenFlare/plugins/agent"
|
||||
"Wavelet/OpenFlare/plugins/agent/logging"
|
||||
"Wavelet/core"
|
||||
)
|
||||
|
||||
// shutdownTimeout 为 openresty 收敛与在途配置同步预留的退出窗口。
|
||||
const shutdownTimeout = 60 * time.Second
|
||||
|
||||
func main() {
|
||||
logging.Setup()
|
||||
|
||||
configPath := flag.String("config", "./agent.json", "agent config path")
|
||||
flag.Parse()
|
||||
|
||||
app := core.NewApp(
|
||||
core.WithProfile(core.Profile(agentplugin.DriverTypeAgent)),
|
||||
core.WithShutdownTimeout(shutdownTimeout),
|
||||
)
|
||||
app.Use(agentplugin.New(*configPath))
|
||||
|
||||
if err := app.Prepare(); err != nil {
|
||||
slog.Error("agent startup failed", "error", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
if err := app.Run(); err != nil {
|
||||
slog.Error("agent process exited with error", "error", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
// Copyright 2025 linux.do
|
||||
// Copyright 2026 Arctel.net
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
// Package cmd 提供 CLI 命令入口
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"log"
|
||||
"sync"
|
||||
|
||||
"Wavelet/OpenFlare/plugins/server/infra/task/scheduler"
|
||||
"Wavelet/OpenFlare/plugins/server/infra/task/worker"
|
||||
"Wavelet/OpenFlare/plugins/server/platform/bootstrap"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
var allCmd = &cobra.Command{
|
||||
Use: "all",
|
||||
Short: "以融合模式同时启动 API、Worker 和 Scheduler",
|
||||
Run: func(_ *cobra.Command, _ []string) {
|
||||
log.Println("[All] 融合模式启动")
|
||||
bootstrap.RegisterAll()
|
||||
runBootstrap(bootstrap.Options{API: true})
|
||||
|
||||
var wg sync.WaitGroup
|
||||
|
||||
// 启动 Asynq Worker 任务处理服务
|
||||
wg.Go(func() {
|
||||
log.Println("[All] 启动 Worker 服务")
|
||||
if err := worker.StartWorker(); err != nil {
|
||||
log.Printf("[All] Worker 启动失败: %v\n", err)
|
||||
}
|
||||
})
|
||||
|
||||
// 启动 Asynq 定时任务调度器
|
||||
wg.Go(func() {
|
||||
log.Println("[All] 启动 Scheduler 服务")
|
||||
if err := scheduler.StartScheduler(); err != nil {
|
||||
log.Printf("[All] Scheduler 启动失败: %v\n", err)
|
||||
}
|
||||
})
|
||||
|
||||
// API 服务持有前台阻塞与退出信号处理(runHTTPApp 返回后即已优雅退出)
|
||||
runHTTPApp("API + Worker + Scheduler")
|
||||
wg.Wait()
|
||||
},
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
// Copyright 2025 linux.do
|
||||
// Copyright 2026 Arctel.net
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"Wavelet/OpenFlare/plugins/server/platform/bootstrap"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
var apiCmd = &cobra.Command{
|
||||
Use: "api",
|
||||
Short: "wavelet API",
|
||||
Run: func(_ *cobra.Command, _ []string) {
|
||||
bootstrap.RegisterAPI()
|
||||
runBootstrap(bootstrap.Options{API: true})
|
||||
runHTTPApp("API")
|
||||
},
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
// Copyright 2026 Arctel.net
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"log"
|
||||
"runtime"
|
||||
"strings"
|
||||
|
||||
"Wavelet/OpenFlare/plugins/server/infra/config"
|
||||
"Wavelet/OpenFlare/plugins/server/infra/persistence/migrator"
|
||||
"Wavelet/pkg/buildinfo"
|
||||
)
|
||||
|
||||
type startupState struct {
|
||||
mode string
|
||||
relationalDB migrator.Report
|
||||
clickHouseDB migrator.Report
|
||||
listensForHTTP bool
|
||||
}
|
||||
|
||||
func printStartupBanner(state startupState) {
|
||||
log.Print(formatStartupBanner(state))
|
||||
}
|
||||
|
||||
func formatStartupBanner(state startupState) string {
|
||||
lines := []string{
|
||||
"",
|
||||
" ____ ________ ",
|
||||
" / __ \\____ ___ ____ / ____/ /___ _________ ",
|
||||
" / / / / __ \\/ _ \\/ __ \\/ /_ / / __ `/ ___/ _ \\",
|
||||
"/ /_/ / /_/ / __/ / / / __/ / / /_/ / / / __/",
|
||||
"\\____/ .___/\\___/_/ /_/_/ /_/\\__,_/_/ \\___/ ",
|
||||
" /_/ ",
|
||||
" OpenFlare " + buildinfo.Version,
|
||||
"",
|
||||
" Environment: " + config.Config.App.Env,
|
||||
fmt.Sprintf(" Runtime: %s/%s (%s)", runtime.GOOS, runtime.GOARCH, runtime.Version()),
|
||||
" Build time: " + buildTime(),
|
||||
" Database: " + formatMigration(state.relationalDB),
|
||||
" Analytics: " + formatMigration(state.clickHouseDB),
|
||||
}
|
||||
if state.listensForHTTP {
|
||||
lines = append(lines, " Listening: http://"+config.Config.App.Addr)
|
||||
}
|
||||
lines = append(lines, " Mode: "+state.mode, "")
|
||||
return strings.Join(lines, "\n")
|
||||
}
|
||||
|
||||
func buildTime() string {
|
||||
if buildinfo.BuildTime == "" {
|
||||
return "development build"
|
||||
}
|
||||
return buildinfo.BuildTime
|
||||
}
|
||||
|
||||
func formatMigration(report migrator.Report) string {
|
||||
if !report.Enabled {
|
||||
return "disabled"
|
||||
}
|
||||
state := "up to date"
|
||||
if report.Applied {
|
||||
state = "upgraded"
|
||||
}
|
||||
return fmt.Sprintf("%s (version %d, %s)", report.Backend, report.Version, state)
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
// Copyright 2026 Arctel.net
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"Wavelet/OpenFlare/plugins/server/infra/config"
|
||||
"Wavelet/OpenFlare/plugins/server/infra/persistence/migrator"
|
||||
"Wavelet/pkg/buildinfo"
|
||||
)
|
||||
|
||||
func TestFormatStartupBanner(t *testing.T) {
|
||||
previousVersion := buildinfo.Version
|
||||
previousBuildTime := buildinfo.BuildTime
|
||||
previousEnv := config.Config.App.Env
|
||||
previousAddr := config.Config.App.Addr
|
||||
t.Cleanup(func() {
|
||||
buildinfo.Version = previousVersion
|
||||
buildinfo.BuildTime = previousBuildTime
|
||||
config.Config.App.Env = previousEnv
|
||||
config.Config.App.Addr = previousAddr
|
||||
})
|
||||
|
||||
buildinfo.Version = "v3.2.1"
|
||||
buildinfo.BuildTime = "2026-07-13T08:00:00Z"
|
||||
config.Config.App.Env = "production"
|
||||
config.Config.App.Addr = ":3000"
|
||||
|
||||
banner := formatStartupBanner(startupState{
|
||||
mode: "API",
|
||||
relationalDB: migrator.Report{
|
||||
Backend: "PostgreSQL",
|
||||
Enabled: true,
|
||||
Version: 202607150003,
|
||||
Applied: true,
|
||||
},
|
||||
clickHouseDB: migrator.Report{Backend: "ClickHouse"},
|
||||
listensForHTTP: true,
|
||||
})
|
||||
|
||||
for _, want := range []string{
|
||||
"OpenFlare v3.2.1",
|
||||
"Environment: production",
|
||||
"Build time: 2026-07-13T08:00:00Z",
|
||||
"Database: PostgreSQL (version 202607150003, upgraded)",
|
||||
"Analytics: disabled",
|
||||
"Listening: http://:3000",
|
||||
"Mode: API",
|
||||
} {
|
||||
if !strings.Contains(banner, want) {
|
||||
t.Errorf("banner missing %q:\n%s", want, banner)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
// Copyright 2026 Arctel.net
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"Wavelet/OpenFlare/plugins/server/platform/bootstrap"
|
||||
"Wavelet/pkg/trace"
|
||||
)
|
||||
|
||||
func runBootstrap(opts bootstrap.Options) {
|
||||
ctx, span := trace.Start(context.Background(), "bootstrap.Init")
|
||||
defer span.End()
|
||||
bootstrap.Init(ctx, opts)
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
// Copyright 2026 Arctel.net
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
// Command flared runs the OpenFlare tunnel client daemon.
|
||||
package main
|
||||
|
||||
import (
|
||||
"flag"
|
||||
"log/slog"
|
||||
"os"
|
||||
"time"
|
||||
|
||||
flaredplugin "Wavelet/OpenFlare/plugins/flared"
|
||||
edgelogging "Wavelet/OpenFlare/share/edge/logging"
|
||||
"Wavelet/core"
|
||||
)
|
||||
|
||||
// shutdownTimeout 为 frpc 子进程收敛预留的退出窗口。
|
||||
const shutdownTimeout = 60 * time.Second
|
||||
|
||||
func main() {
|
||||
edgelogging.Setup(edgelogging.Options{})
|
||||
|
||||
configPath := flag.String("config", "./flared.json", "flared config path")
|
||||
flag.Parse()
|
||||
|
||||
app := core.NewApp(
|
||||
core.WithProfile(core.Profile(flaredplugin.DriverTypeFlared)),
|
||||
core.WithShutdownTimeout(shutdownTimeout),
|
||||
)
|
||||
app.Use(flaredplugin.New(*configPath))
|
||||
|
||||
if err := app.Prepare(); err != nil {
|
||||
slog.Error("flared startup failed", "error", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
if err := app.Run(); err != nil {
|
||||
slog.Error("flared process exited with error", "error", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
// Copyright 2026 Arctel.net
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"context"
|
||||
"log"
|
||||
"time"
|
||||
|
||||
"Wavelet/OpenFlare/plugins/server"
|
||||
"Wavelet/OpenFlare/plugins/server/infra/config"
|
||||
"Wavelet/OpenFlare/plugins/server/platform/bootstrap"
|
||||
"Wavelet/OpenFlare/plugins/server/router"
|
||||
"Wavelet/core"
|
||||
"Wavelet/plugins/drivers/driver_http"
|
||||
)
|
||||
|
||||
// defaultShutdownTimeout 在配置未给出优雅退出超时时兜底。
|
||||
const defaultShutdownTimeout = 10 * time.Second
|
||||
|
||||
// runHTTPApp 以 Cordis 方式启动控制面:装配根持有 gin engine(引擎级中间件与前端
|
||||
// SPA 兜底),server 插件经 ctx.Router() 声明路由,driver_http 负责监听与优雅退出。
|
||||
// 本函数阻塞至收到退出信号。
|
||||
func runHTTPApp(mode string) {
|
||||
engine := router.BuildEngine()
|
||||
timeout := shutdownTimeout()
|
||||
|
||||
app := core.NewApp(
|
||||
core.WithProfile(core.ProfileAPI),
|
||||
core.WithShutdownTimeout(timeout),
|
||||
)
|
||||
httpDriver := driver_http.New(
|
||||
driver_http.WithEngine(engine),
|
||||
driver_http.WithAddr(config.Config.App.Addr),
|
||||
)
|
||||
app.Use(server.New())
|
||||
app.Use(httpDriver)
|
||||
|
||||
if err := app.Prepare(); err != nil {
|
||||
log.Fatalf("[API] prepare failed: %v\n", err)
|
||||
}
|
||||
|
||||
printStartupBanner(startupState{
|
||||
mode: mode,
|
||||
relationalDB: latestMigrationState.relationalDB,
|
||||
clickHouseDB: latestMigrationState.clickHouseDB,
|
||||
listensForHTTP: true,
|
||||
})
|
||||
|
||||
if err := app.Run(); err != nil {
|
||||
log.Printf("[API] server failed: %v\n", err)
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), timeout)
|
||||
defer cancel()
|
||||
bootstrap.Stop(ctx)
|
||||
log.Println("[API] server exited")
|
||||
}
|
||||
|
||||
func shutdownTimeout() time.Duration {
|
||||
if config.Config.App.GracefulShutdownTimeout <= 0 {
|
||||
return defaultShutdownTimeout
|
||||
}
|
||||
return time.Duration(config.Config.App.GracefulShutdownTimeout) * time.Second
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
// Copyright 2026 Arctel.net
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
// Command relay runs the OpenFlare relay node daemon.
|
||||
package main
|
||||
|
||||
import (
|
||||
"flag"
|
||||
"log/slog"
|
||||
"os"
|
||||
"time"
|
||||
|
||||
relayplugin "Wavelet/OpenFlare/plugins/relay"
|
||||
edgelogging "Wavelet/OpenFlare/share/edge/logging"
|
||||
"Wavelet/core"
|
||||
)
|
||||
|
||||
// shutdownTimeout 为 frps 子进程收敛预留的退出窗口。
|
||||
const shutdownTimeout = 60 * time.Second
|
||||
|
||||
func main() {
|
||||
edgelogging.Setup(edgelogging.Options{})
|
||||
|
||||
configPath := flag.String("config", "./relay.json", "relay config path")
|
||||
flag.Parse()
|
||||
|
||||
app := core.NewApp(
|
||||
core.WithProfile(core.Profile(relayplugin.DriverTypeRelay)),
|
||||
core.WithShutdownTimeout(shutdownTimeout),
|
||||
)
|
||||
app.Use(relayplugin.New(*configPath))
|
||||
|
||||
if err := app.Prepare(); err != nil {
|
||||
slog.Error("relay startup failed", "error", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
if err := app.Run(); err != nil {
|
||||
slog.Error("relay process exited with error", "error", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,127 @@
|
||||
// Copyright 2026 Arctel.net
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log"
|
||||
"os"
|
||||
"strings"
|
||||
|
||||
db "Wavelet/OpenFlare/plugins/server/infra/persistence"
|
||||
"Wavelet/OpenFlare/plugins/server/infra/persistence/migrator"
|
||||
"Wavelet/OpenFlare/plugins/server/model"
|
||||
"Wavelet/OpenFlare/plugins/server/oauth"
|
||||
"Wavelet/OpenFlare/plugins/server/platform/bootstrap"
|
||||
"Wavelet/OpenFlare/plugins/server/repository"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
var (
|
||||
usernameFlag string
|
||||
passwordFlag string
|
||||
)
|
||||
|
||||
const (
|
||||
passwdCharset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*"
|
||||
defaultPasswordLength = 16
|
||||
)
|
||||
|
||||
func generateRandomPassword(length int) (string, error) {
|
||||
bytes := make([]byte, length)
|
||||
if _, err := rand.Read(bytes); err != nil {
|
||||
return "", err
|
||||
}
|
||||
for i, b := range bytes {
|
||||
bytes[i] = passwdCharset[int(b)%len(passwdCharset)]
|
||||
}
|
||||
return string(bytes), nil
|
||||
}
|
||||
|
||||
var resetPasswdCmd = &cobra.Command{
|
||||
Use: "reset-passwd",
|
||||
Short: "重置指定账号密码",
|
||||
PreRun: func(_ *cobra.Command, _ []string) {
|
||||
migrator.Migrate()
|
||||
},
|
||||
Run: func(_ *cobra.Command, _ []string) {
|
||||
ctx := context.Background()
|
||||
runBootstrap(bootstrap.Options{})
|
||||
|
||||
var username string
|
||||
if usernameFlag != "" {
|
||||
username = usernameFlag
|
||||
} else {
|
||||
fmt.Print("请输入用户名: ")
|
||||
reader := bufio.NewReader(os.Stdin)
|
||||
input, err := reader.ReadString('\n')
|
||||
if err != nil {
|
||||
log.Fatalf("读取用户名失败: %v\n", err)
|
||||
}
|
||||
username = strings.TrimSpace(input)
|
||||
if username == "" {
|
||||
log.Fatal("用户名不能为空\n")
|
||||
}
|
||||
}
|
||||
|
||||
user, err := repository.GetUserByUsername(ctx, username)
|
||||
if err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
log.Fatalf("错误: 用户 '%s' 不存在\n", username)
|
||||
}
|
||||
log.Fatalf("查询用户失败: %v\n", err)
|
||||
}
|
||||
|
||||
var password string
|
||||
if passwordFlag != "" {
|
||||
password = passwordFlag
|
||||
} else {
|
||||
password, err = generateRandomPassword(defaultPasswordLength)
|
||||
if err != nil {
|
||||
log.Fatalf("生成随机密码失败: %v\n", err)
|
||||
}
|
||||
}
|
||||
|
||||
if err := user.SetEncryptedPassword(password); err != nil {
|
||||
log.Fatalf("加密密码失败: %v\n", err)
|
||||
}
|
||||
|
||||
err = db.DB(ctx).Transaction(func(tx *gorm.DB) error {
|
||||
if err := tx.Model(&user).Update("password", user.Password).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Invalidate existing tokens
|
||||
var tokens []model.AccessToken
|
||||
if err := tx.Where("user_id = ?", user.ID).Find(&tokens).Error; err == nil {
|
||||
for _, token := range tokens {
|
||||
oauth.InvalidateCachedToken(ctx, token.TokenHash)
|
||||
}
|
||||
}
|
||||
|
||||
return tx.Where("user_id = ?", user.ID).Delete(&model.AccessToken{}).Error
|
||||
})
|
||||
if err != nil {
|
||||
log.Fatalf("重置密码失败: %v\n", err)
|
||||
}
|
||||
|
||||
oauth.InvalidateCachedUser(ctx, user.ID)
|
||||
|
||||
fmt.Println("成功重置密码!")
|
||||
fmt.Printf("用户名: %s\n", user.Username)
|
||||
fmt.Printf("新密码: %s\n", password)
|
||||
},
|
||||
}
|
||||
|
||||
func init() {
|
||||
resetPasswdCmd.Flags().StringVar(&usernameFlag, "user", "", "重置密码的目标用户名")
|
||||
resetPasswdCmd.Flags().StringVar(&passwordFlag, "password", "", "新密码(若不指定,则自动生成随机密码)")
|
||||
rootCmd.AddCommand(resetPasswdCmd)
|
||||
}
|
||||
@@ -0,0 +1,227 @@
|
||||
// Copyright 2026 Arctel.net
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"io"
|
||||
"os"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"Wavelet/OpenFlare/plugins/server/model"
|
||||
"Wavelet/OpenFlare/plugins/server/testhelper"
|
||||
)
|
||||
|
||||
func TestResetPasswdCmd_WithUserAndPassword(t *testing.T) {
|
||||
dbConn, _, cleanup := testhelper.SetupTestEnvironment(t)
|
||||
defer cleanup()
|
||||
|
||||
// Seed test user
|
||||
user := model.User{
|
||||
ID: 1001,
|
||||
Username: "testuser1",
|
||||
Nickname: "Test User 1",
|
||||
Email: "test1@example.com",
|
||||
IsActive: true,
|
||||
LastLoginAt: time.Now(),
|
||||
}
|
||||
_ = user.SetEncryptedPassword("oldpassword")
|
||||
if err := dbConn.Create(&user).Error; err != nil {
|
||||
t.Fatalf("failed to create test user: %v", err)
|
||||
}
|
||||
|
||||
// Create access token to test invalidation/deletion
|
||||
token := model.AccessToken{
|
||||
ID: 1,
|
||||
UserID: user.ID,
|
||||
Name: "testtoken",
|
||||
TokenHash: "somehash",
|
||||
MaskedToken: "some...",
|
||||
}
|
||||
if err := dbConn.Create(&token).Error; err != nil {
|
||||
t.Fatalf("failed to create access token: %v", err)
|
||||
}
|
||||
|
||||
// Override PreRun to bypass goose migrations in unit tests
|
||||
oldPreRun := resetPasswdCmd.PreRun
|
||||
resetPasswdCmd.PreRun = nil
|
||||
defer func() { resetPasswdCmd.PreRun = oldPreRun }()
|
||||
|
||||
// Execute command with args
|
||||
rootCmd.SetArgs([]string{"reset-passwd", "--user", "testuser1", "--password", "newpassword123"})
|
||||
|
||||
// Capture output
|
||||
oldStdout := os.Stdout
|
||||
r, w, _ := os.Pipe()
|
||||
os.Stdout = w
|
||||
|
||||
err := rootCmd.Execute()
|
||||
w.Close()
|
||||
os.Stdout = oldStdout
|
||||
|
||||
if err != nil {
|
||||
t.Fatalf("command execute failed: %v", err)
|
||||
}
|
||||
|
||||
var buf bytes.Buffer
|
||||
_, _ = io.Copy(&buf, r)
|
||||
output := buf.String()
|
||||
|
||||
if !bytes.Contains([]byte(output), []byte("成功重置密码!")) {
|
||||
t.Errorf("expected output to contain success message, got: %s", output)
|
||||
}
|
||||
|
||||
// Verify password in DB
|
||||
var dbUser model.User
|
||||
if err := dbConn.Where("id = ?", user.ID).First(&dbUser).Error; err != nil {
|
||||
t.Fatalf("failed to query user from DB: %v", err)
|
||||
}
|
||||
if !dbUser.CheckPassword("newpassword123") {
|
||||
t.Errorf("password was not updated correctly in DB")
|
||||
}
|
||||
|
||||
// Verify token deleted
|
||||
var count int64
|
||||
dbConn.Model(&model.AccessToken{}).Where("user_id = ?", user.ID).Count(&count)
|
||||
if count != 0 {
|
||||
t.Errorf("expected access tokens to be deleted, got %d", count)
|
||||
}
|
||||
}
|
||||
|
||||
func TestResetPasswdCmd_WithUserAndRandomPassword(t *testing.T) {
|
||||
dbConn, _, cleanup := testhelper.SetupTestEnvironment(t)
|
||||
defer cleanup()
|
||||
|
||||
// Seed test user
|
||||
user := model.User{
|
||||
ID: 1002,
|
||||
Username: "testuser2",
|
||||
Nickname: "Test User 2",
|
||||
Email: "test2@example.com",
|
||||
IsActive: true,
|
||||
LastLoginAt: time.Now(),
|
||||
}
|
||||
_ = user.SetEncryptedPassword("oldpassword")
|
||||
if err := dbConn.Create(&user).Error; err != nil {
|
||||
t.Fatalf("failed to create test user: %v", err)
|
||||
}
|
||||
|
||||
// Override PreRun
|
||||
oldPreRun := resetPasswdCmd.PreRun
|
||||
resetPasswdCmd.PreRun = nil
|
||||
defer func() { resetPasswdCmd.PreRun = oldPreRun }()
|
||||
|
||||
// Reset flags
|
||||
usernameFlag = ""
|
||||
passwordFlag = ""
|
||||
|
||||
// Execute command with args (no --password)
|
||||
rootCmd.SetArgs([]string{"reset-passwd", "--user", "testuser2"})
|
||||
|
||||
// Capture output
|
||||
oldStdout := os.Stdout
|
||||
r, w, _ := os.Pipe()
|
||||
os.Stdout = w
|
||||
|
||||
err := rootCmd.Execute()
|
||||
w.Close()
|
||||
os.Stdout = oldStdout
|
||||
|
||||
if err != nil {
|
||||
t.Fatalf("command execute failed: %v", err)
|
||||
}
|
||||
|
||||
var buf bytes.Buffer
|
||||
_, _ = io.Copy(&buf, r)
|
||||
output := buf.String()
|
||||
|
||||
if !bytes.Contains([]byte(output), []byte("成功重置密码!")) {
|
||||
t.Errorf("expected output to contain success message, got: %s", output)
|
||||
}
|
||||
|
||||
// Verify password in DB (should be updated and not equal to old one)
|
||||
var dbUser model.User
|
||||
if err := dbConn.Where("id = ?", user.ID).First(&dbUser).Error; err != nil {
|
||||
t.Fatalf("failed to query user from DB: %v", err)
|
||||
}
|
||||
if dbUser.CheckPassword("oldpassword") {
|
||||
t.Errorf("expected password to change, but it matches the old one")
|
||||
}
|
||||
}
|
||||
|
||||
func TestResetPasswdCmd_InteractiveMode(t *testing.T) {
|
||||
dbConn, _, cleanup := testhelper.SetupTestEnvironment(t)
|
||||
defer cleanup()
|
||||
|
||||
// Seed test user
|
||||
user := model.User{
|
||||
ID: 1003,
|
||||
Username: "testuser3",
|
||||
Nickname: "Test User 3",
|
||||
Email: "test3@example.com",
|
||||
IsActive: true,
|
||||
LastLoginAt: time.Now(),
|
||||
}
|
||||
_ = user.SetEncryptedPassword("oldpassword")
|
||||
if err := dbConn.Create(&user).Error; err != nil {
|
||||
t.Fatalf("failed to create test user: %v", err)
|
||||
}
|
||||
|
||||
// Override PreRun
|
||||
oldPreRun := resetPasswdCmd.PreRun
|
||||
resetPasswdCmd.PreRun = nil
|
||||
defer func() { resetPasswdCmd.PreRun = oldPreRun }()
|
||||
|
||||
// Mock stdin
|
||||
inR, inW, err := os.Pipe()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer inR.Close()
|
||||
defer inW.Close()
|
||||
|
||||
oldStdin := os.Stdin
|
||||
os.Stdin = inR
|
||||
defer func() { os.Stdin = oldStdin }()
|
||||
|
||||
// Write username to stdin
|
||||
_, _ = inW.WriteString("testuser3\n")
|
||||
inW.Close()
|
||||
|
||||
// Reset flags
|
||||
usernameFlag = ""
|
||||
passwordFlag = ""
|
||||
rootCmd.SetArgs([]string{"reset-passwd"})
|
||||
|
||||
// Capture output
|
||||
oldStdout := os.Stdout
|
||||
r, w, _ := os.Pipe()
|
||||
os.Stdout = w
|
||||
|
||||
err = rootCmd.Execute()
|
||||
w.Close()
|
||||
os.Stdout = oldStdout
|
||||
|
||||
if err != nil {
|
||||
t.Fatalf("command execute failed: %v", err)
|
||||
}
|
||||
|
||||
var buf bytes.Buffer
|
||||
_, _ = io.Copy(&buf, r)
|
||||
output := buf.String()
|
||||
|
||||
if !bytes.Contains([]byte(output), []byte("成功重置密码!")) {
|
||||
t.Errorf("expected output to contain success message, got: %s", output)
|
||||
}
|
||||
|
||||
// Verify user password changed in DB
|
||||
var dbUser model.User
|
||||
if err := dbConn.Where("id = ?", user.ID).First(&dbUser).Error; err != nil {
|
||||
t.Fatalf("failed to query user from DB: %v", err)
|
||||
}
|
||||
if dbUser.CheckPassword("oldpassword") {
|
||||
t.Errorf("expected password to change, but it matches the old one")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
// Copyright 2025 linux.do
|
||||
// Copyright 2026 Arctel.net
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"context"
|
||||
"log"
|
||||
"time"
|
||||
|
||||
"Wavelet/OpenFlare/plugins/server/infra/config"
|
||||
"Wavelet/OpenFlare/plugins/server/infra/persistence/migrator"
|
||||
"Wavelet/pkg/buildinfo"
|
||||
"Wavelet/pkg/logger"
|
||||
"Wavelet/pkg/trace"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
const traceShutdownTimeout = 10 * time.Second
|
||||
|
||||
var rootCmd = &cobra.Command{
|
||||
Use: "wavelet",
|
||||
PersistentPreRun: func(_ *cobra.Command, _ []string) {
|
||||
logger.Init(logger.Config{
|
||||
Level: config.Config.Log.Level,
|
||||
Format: config.Config.Log.Format,
|
||||
Output: config.Config.Log.Output,
|
||||
FilePath: config.Config.Log.FilePath,
|
||||
MaxSize: config.Config.Log.MaxSize,
|
||||
MaxAge: config.Config.Log.MaxAge,
|
||||
MaxBackups: config.Config.Log.MaxBackups,
|
||||
Compress: config.Config.Log.Compress,
|
||||
})
|
||||
trace.Init(trace.Config{
|
||||
AppName: config.Config.App.AppName,
|
||||
SamplingRate: config.Config.Otel.SamplingRate,
|
||||
TracerName: config.Config.Otel.TracerName,
|
||||
})
|
||||
},
|
||||
PreRun: func(_ *cobra.Command, _ []string) {
|
||||
runMigrations()
|
||||
},
|
||||
PersistentPostRun: func(_ *cobra.Command, _ []string) {
|
||||
shutdownTraceProvider()
|
||||
},
|
||||
Run: func(_ *cobra.Command, args []string) {
|
||||
// 无参数时默认以融合模式启动所有服务
|
||||
allCmd.Run(allCmd, args)
|
||||
},
|
||||
}
|
||||
|
||||
var latestMigrationState struct {
|
||||
relationalDB migrator.Report
|
||||
clickHouseDB migrator.Report
|
||||
}
|
||||
|
||||
func runMigrations() {
|
||||
latestMigrationState.relationalDB = migrator.Migrate()
|
||||
latestMigrationState.clickHouseDB = migrator.MigrateClickHouse()
|
||||
}
|
||||
|
||||
func shutdownTraceProvider() {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), traceShutdownTimeout)
|
||||
defer cancel()
|
||||
trace.Shutdown(ctx)
|
||||
}
|
||||
|
||||
func init() {
|
||||
rootCmd.Version = buildinfo.Version
|
||||
rootCmd.CompletionOptions.DisableDefaultCmd = true
|
||||
|
||||
// 1. 为需要迁移的子命令动态绑定原先 rootCmd.PreRun 拥有的数据库迁移行为
|
||||
migratePreRun := func(_ *cobra.Command, _ []string) {
|
||||
runMigrations()
|
||||
}
|
||||
allCmd.PreRun = migratePreRun
|
||||
apiCmd.PreRun = migratePreRun
|
||||
workerCmd.PreRun = migratePreRun
|
||||
schedulerCmd.PreRun = migratePreRun
|
||||
|
||||
// 2. 集中将这些命令注册为真正的子命令,以解决 Cobra 的 unknown command 校验限制
|
||||
rootCmd.AddCommand(allCmd, apiCmd, workerCmd, schedulerCmd)
|
||||
}
|
||||
|
||||
// Execute 执行根命令
|
||||
func Execute() {
|
||||
if err := rootCmd.Execute(); err != nil {
|
||||
log.Fatalf("[CMD] execute failed; %s\n", err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
// Copyright 2025 linux.do
|
||||
// Copyright 2026 Arctel.net
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"log"
|
||||
|
||||
"Wavelet/OpenFlare/plugins/server/infra/task/scheduler"
|
||||
"Wavelet/OpenFlare/plugins/server/platform/bootstrap"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
var schedulerCmd = &cobra.Command{
|
||||
Use: "scheduler",
|
||||
Short: "wavelet Scheduler",
|
||||
Run: func(_ *cobra.Command, _ []string) {
|
||||
runBootstrap(bootstrap.Options{})
|
||||
printStartupBanner(startupState{mode: "Scheduler", relationalDB: latestMigrationState.relationalDB, clickHouseDB: latestMigrationState.clickHouseDB})
|
||||
log.Println("[Scheduler] 启动定时任务调度服务")
|
||||
if err := scheduler.StartScheduler(); err != nil {
|
||||
log.Fatalf("[调度器] 启动失败: %v", err)
|
||||
}
|
||||
},
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
// Copyright 2025 linux.do
|
||||
// Copyright 2026 Arctel.net
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"log"
|
||||
|
||||
"Wavelet/OpenFlare/plugins/server/infra/task/worker"
|
||||
"Wavelet/OpenFlare/plugins/server/platform/bootstrap"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
var workerCmd = &cobra.Command{
|
||||
Use: "worker",
|
||||
Short: "wavelet Worker",
|
||||
Run: func(_ *cobra.Command, _ []string) {
|
||||
runBootstrap(bootstrap.Options{})
|
||||
printStartupBanner(startupState{mode: "Worker", relationalDB: latestMigrationState.relationalDB, clickHouseDB: latestMigrationState.clickHouseDB})
|
||||
log.Println("[Worker] 启动任务处理服务")
|
||||
if err := worker.StartWorker(); err != nil {
|
||||
log.Fatalf("[工作器] 启动失败: %v", err)
|
||||
}
|
||||
},
|
||||
}
|
||||
Reference in New Issue
Block a user