mirror of
https://github.com/tnb-labs/panel.git
synced 2026-09-21 13:20:10 +08:00
依赖注入:
- 移除 google/wire(含 wire.go/wire_gen.go 与全部 ProviderSet),
改用 samber/do v2 单注入器 + 双入口惰性构建
- 贡献模型替代命令式注册:路由 routes:、命令 commands:、
任务 jobs: 前缀经 internal/registry 收集与校验
- 构造函数统一 func NewXxx(i do.Injector) (T, error)
三层架构:
- 补全用例层:每个 biz.XxxRepo 配 XxxUsecase,
service/command/job 表现层只依赖用例,不再直接引用仓储
路由与文档:
- route/http.go 按域拆为声明式 Endpoint 贡献,
Endpoint 承载登录白名单与端点限流语义
- 调试模式下提供 OpenAPI 3.1 文档:/openapi.json 与 /docs(Scalar),
从 validate 标签生成
目录与依赖:
- internal/http/{middleware,request,rule} 拍平至 internal/*
- CLI 命令拆至 internal/command
- 日志轮转 timberjack 换为 libtnb/logrotate
- 升级 validator/cron/sessions/gormstore/sqlite/securecookie
- 数据库迁移保持 gormigrate 不变
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
262 lines
7.9 KiB
Go
262 lines
7.9 KiB
Go
package redis
|
|
|
|
import (
|
|
"fmt"
|
|
"net/http"
|
|
"regexp"
|
|
"strings"
|
|
|
|
"github.com/go-chi/chi/v5"
|
|
"github.com/leonelquinteros/gotext"
|
|
"github.com/samber/do/v2"
|
|
"github.com/samber/lo"
|
|
|
|
"github.com/acepanel/panel/v3/internal/app"
|
|
"github.com/acepanel/panel/v3/internal/biz"
|
|
"github.com/acepanel/panel/v3/internal/service"
|
|
"github.com/acepanel/panel/v3/pkg/io"
|
|
"github.com/acepanel/panel/v3/pkg/shell"
|
|
"github.com/acepanel/panel/v3/pkg/systemctl"
|
|
"github.com/acepanel/panel/v3/pkg/types"
|
|
)
|
|
|
|
type App struct {
|
|
t *gotext.Locale
|
|
databaseServerRepo biz.DatabaseServerRepo
|
|
}
|
|
|
|
func NewApp(i do.Injector) (*App, error) {
|
|
t := do.MustInvoke[*gotext.Locale](i)
|
|
databaseServer := do.MustInvoke[biz.DatabaseServerRepo](i)
|
|
return &App{
|
|
t: t,
|
|
databaseServerRepo: databaseServer,
|
|
}, nil
|
|
}
|
|
|
|
func (s *App) Route(r chi.Router) {
|
|
r.Get("/load", s.Load)
|
|
r.Get("/config", s.GetConfig)
|
|
r.Post("/config", s.UpdateConfig)
|
|
r.Get("/config_tune", s.GetConfigTune)
|
|
r.Post("/config_tune", s.UpdateConfigTune)
|
|
}
|
|
|
|
func (s *App) Status() string {
|
|
ok, _ := systemctl.Status("redis")
|
|
return types.AggregateAppStatus(ok)
|
|
}
|
|
|
|
func (s *App) Load(w http.ResponseWriter, r *http.Request) {
|
|
status, err := systemctl.Status("redis")
|
|
if err != nil {
|
|
service.Error(w, http.StatusInternalServerError, s.t.Get("failed to get redis status: %v", err))
|
|
return
|
|
}
|
|
if !status {
|
|
service.Success(w, []types.NV{})
|
|
return
|
|
}
|
|
|
|
// 检查 Redis 密码
|
|
withPassword := ""
|
|
config, err := io.Read(fmt.Sprintf("%s/server/redis/redis.conf", app.Root))
|
|
if err != nil {
|
|
service.Error(w, http.StatusInternalServerError, "%v", err)
|
|
return
|
|
}
|
|
re := regexp.MustCompile(`(?m)^requirepass\s+(.+)`)
|
|
matches := re.FindStringSubmatch(config)
|
|
if len(matches) == 2 {
|
|
withPassword = " -a " + matches[1]
|
|
}
|
|
|
|
raw, err := shell.Execf("redis-cli%s info", withPassword)
|
|
if err != nil {
|
|
service.Error(w, http.StatusInternalServerError, s.t.Get("failed to get redis info: %v", err))
|
|
return
|
|
}
|
|
|
|
dataRaw := lo.SliceToMap(strings.Split(raw, "\n"), func(item string) (string, string) {
|
|
parts := strings.Split(item, ":")
|
|
if len(parts) != 2 {
|
|
return "", ""
|
|
}
|
|
return strings.TrimSpace(parts[0]), strings.TrimSpace(parts[1])
|
|
})
|
|
|
|
data := []types.NV{
|
|
{Name: s.t.Get("TCP Port"), Value: dataRaw["tcp_port"]},
|
|
{Name: s.t.Get("Uptime in Days"), Value: dataRaw["uptime_in_days"]},
|
|
{Name: s.t.Get("Connected Clients"), Value: dataRaw["connected_clients"]},
|
|
{Name: s.t.Get("Total Allocated Memory"), Value: dataRaw["used_memory_human"]},
|
|
{Name: s.t.Get("Total Memory Usage"), Value: dataRaw["used_memory_rss_human"]},
|
|
{Name: s.t.Get("Peak Memory Usage"), Value: dataRaw["used_memory_peak_human"]},
|
|
{Name: s.t.Get("Memory Fragmentation Ratio"), Value: dataRaw["mem_fragmentation_ratio"]},
|
|
{Name: s.t.Get("Total Connections Received"), Value: dataRaw["total_connections_received"]},
|
|
{Name: s.t.Get("Total Commands Processed"), Value: dataRaw["total_commands_processed"]},
|
|
{Name: s.t.Get("Commands Per Second"), Value: dataRaw["instantaneous_ops_per_sec"]},
|
|
{Name: s.t.Get("Keyspace Hits"), Value: dataRaw["keyspace_hits"]},
|
|
{Name: s.t.Get("Keyspace Misses"), Value: dataRaw["keyspace_misses"]},
|
|
{Name: s.t.Get("Latest Fork Time (ms)"), Value: dataRaw["latest_fork_usec"]},
|
|
}
|
|
|
|
service.Success(w, data)
|
|
}
|
|
|
|
func (s *App) GetConfig(w http.ResponseWriter, r *http.Request) {
|
|
config, err := io.Read(fmt.Sprintf("%s/server/redis/redis.conf", app.Root))
|
|
if err != nil {
|
|
service.Error(w, http.StatusInternalServerError, "%v", err)
|
|
return
|
|
}
|
|
|
|
service.Success(w, config)
|
|
}
|
|
|
|
func (s *App) UpdateConfig(w http.ResponseWriter, r *http.Request) {
|
|
req, err := service.Bind[UpdateConfig](r)
|
|
if err != nil {
|
|
service.Error(w, http.StatusUnprocessableEntity, "%v", err)
|
|
return
|
|
}
|
|
|
|
if err = io.Write(fmt.Sprintf("%s/server/redis/redis.conf", app.Root), req.Config, 0644); err != nil {
|
|
service.Error(w, http.StatusInternalServerError, "%v", err)
|
|
return
|
|
}
|
|
|
|
if err = systemctl.Restart("redis"); err != nil {
|
|
service.Error(w, http.StatusInternalServerError, "%v", err)
|
|
return
|
|
}
|
|
|
|
service.Success(w, nil)
|
|
}
|
|
|
|
// GetConfigTune 获取 Redis 配置调整参数
|
|
func (s *App) GetConfigTune(w http.ResponseWriter, r *http.Request) {
|
|
config, err := io.Read(fmt.Sprintf("%s/server/redis/redis.conf", app.Root))
|
|
if err != nil {
|
|
service.Error(w, http.StatusInternalServerError, "%v", err)
|
|
return
|
|
}
|
|
|
|
tune := ConfigTune{
|
|
Bind: s.getRedisValue(config, "bind"),
|
|
Port: s.getRedisValue(config, "port"),
|
|
Databases: s.getRedisValue(config, "databases"),
|
|
Requirepass: s.getRedisValue(config, "requirepass"),
|
|
Timeout: s.getRedisValue(config, "timeout"),
|
|
TCPKeepalive: s.getRedisValue(config, "tcp-keepalive"),
|
|
Maxmemory: s.getRedisValue(config, "maxmemory"),
|
|
MaxmemoryPolicy: s.getRedisValue(config, "maxmemory-policy"),
|
|
Appendonly: s.getRedisValue(config, "appendonly"),
|
|
Appendfsync: s.getRedisValue(config, "appendfsync"),
|
|
}
|
|
|
|
service.Success(w, tune)
|
|
}
|
|
|
|
// UpdateConfigTune 更新 Redis 配置调整参数
|
|
func (s *App) UpdateConfigTune(w http.ResponseWriter, r *http.Request) {
|
|
req, err := service.Bind[ConfigTune](r)
|
|
if err != nil {
|
|
service.Error(w, http.StatusUnprocessableEntity, "%v", err)
|
|
return
|
|
}
|
|
|
|
confPath := fmt.Sprintf("%s/server/redis/redis.conf", app.Root)
|
|
config, err := io.Read(confPath)
|
|
if err != nil {
|
|
service.Error(w, http.StatusInternalServerError, "%v", err)
|
|
return
|
|
}
|
|
|
|
config = s.setRedisValue(config, "bind", req.Bind)
|
|
config = s.setRedisValue(config, "port", req.Port)
|
|
config = s.setRedisValue(config, "databases", req.Databases)
|
|
config = s.setRedisValue(config, "requirepass", req.Requirepass)
|
|
config = s.setRedisValue(config, "timeout", req.Timeout)
|
|
config = s.setRedisValue(config, "tcp-keepalive", req.TCPKeepalive)
|
|
config = s.setRedisValue(config, "maxmemory", req.Maxmemory)
|
|
config = s.setRedisValue(config, "maxmemory-policy", req.MaxmemoryPolicy)
|
|
config = s.setRedisValue(config, "appendonly", req.Appendonly)
|
|
config = s.setRedisValue(config, "appendfsync", req.Appendfsync)
|
|
|
|
if err = io.Write(confPath, config, 0644); err != nil {
|
|
service.Error(w, http.StatusInternalServerError, "%v", err)
|
|
return
|
|
}
|
|
|
|
if err = systemctl.Restart("redis"); err != nil {
|
|
service.Error(w, http.StatusInternalServerError, "%v", err)
|
|
return
|
|
}
|
|
|
|
// 同步密码到数据库服务器记录
|
|
_ = s.databaseServerRepo.UpdatePassword("local_redis", req.Requirepass)
|
|
|
|
service.Success(w, nil)
|
|
}
|
|
|
|
// getRedisValue 从 Redis 配置内容中获取指定键的值
|
|
func (s *App) getRedisValue(content string, key string) string {
|
|
lines := strings.SplitSeq(content, "\n")
|
|
for line := range lines {
|
|
trimmed := strings.TrimSpace(line)
|
|
if trimmed == "" || strings.HasPrefix(trimmed, "#") {
|
|
continue
|
|
}
|
|
parts := strings.Fields(trimmed)
|
|
if len(parts) >= 2 && parts[0] == key {
|
|
return strings.Join(parts[1:], " ")
|
|
}
|
|
}
|
|
return ""
|
|
}
|
|
|
|
// setRedisValue 在 Redis 配置内容中设置指定键的值
|
|
func (s *App) setRedisValue(content string, key string, value string) string {
|
|
value = strings.ReplaceAll(value, "\n", "")
|
|
value = strings.ReplaceAll(value, "\r", "")
|
|
|
|
lines := strings.Split(content, "\n")
|
|
result := make([]string, 0, len(lines))
|
|
found := false
|
|
for _, line := range lines {
|
|
trimmed := strings.TrimSpace(line)
|
|
if trimmed == "" {
|
|
result = append(result, line)
|
|
continue
|
|
}
|
|
checkLine := trimmed
|
|
if strings.HasPrefix(checkLine, "#") {
|
|
checkLine = strings.TrimSpace(checkLine[1:])
|
|
}
|
|
parts := strings.Fields(checkLine)
|
|
if len(parts) >= 1 && parts[0] == key {
|
|
if found {
|
|
continue
|
|
}
|
|
found = true
|
|
// 值为空时注释掉该配置项
|
|
if value == "" {
|
|
if !strings.HasPrefix(trimmed, "#") {
|
|
result = append(result, "# "+trimmed)
|
|
} else {
|
|
result = append(result, line)
|
|
}
|
|
continue
|
|
}
|
|
result = append(result, key+" "+value)
|
|
} else {
|
|
result = append(result, line)
|
|
}
|
|
}
|
|
if !found && value != "" {
|
|
result = append(result, key+" "+value)
|
|
}
|
|
return strings.Join(result, "\n")
|
|
}
|