From 8283cd7d0252e0a876055a84c05d77af5b51bddc Mon Sep 17 00:00:00 2001 From: ssongliu <73214554+ssongliu@users.noreply.github.com> Date: Fri, 24 Jan 2025 11:00:07 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20adjust=20internationalization=20errors?= =?UTF-8?q?=20and=20the=20positions=20of=20global=20=E2=80=A6=20(#7767)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- agent/app/api/v2/dashboard.go | 5 +- agent/app/api/v2/file.go | 18 +- agent/app/api/v2/ftp.go | 15 +- agent/app/api/v2/helper/helper.go | 36 +--- agent/app/api/v2/setting.go | 2 +- agent/app/api/v2/terminal.go | 4 +- agent/app/model/app.go | 5 +- agent/app/model/app_install.go | 5 +- agent/app/model/runtime.go | 8 +- agent/app/model/website_ssl.go | 4 +- agent/app/service/app.go | 32 ++-- agent/app/service/app_install.go | 28 +-- agent/app/service/app_utils.go | 80 ++++----- agent/app/service/backup.go | 29 ++-- agent/app/service/backup_app.go | 7 +- agent/app/service/backup_mysql.go | 7 +- agent/app/service/backup_postgresql.go | 7 +- agent/app/service/backup_record.go | 5 +- agent/app/service/backup_redis.go | 16 +- agent/app/service/backup_runtime.go | 6 +- agent/app/service/backup_website.go | 21 +-- agent/app/service/clam.go | 34 ++-- agent/app/service/compose_template.go | 15 +- agent/app/service/container.go | 22 +-- agent/app/service/container_compose.go | 15 +- agent/app/service/container_network.go | 3 +- agent/app/service/container_volume.go | 5 +- agent/app/service/cronjob.go | 23 +-- agent/app/service/cronjob_backup.go | 20 +-- agent/app/service/cronjob_helper.go | 6 +- agent/app/service/dashboard.go | 7 +- agent/app/service/database.go | 21 +-- agent/app/service/database_common.go | 20 +-- agent/app/service/database_mysql.go | 29 ++-- agent/app/service/database_postgresql.go | 26 +-- agent/app/service/database_redis.go | 10 +- agent/app/service/device.go | 16 +- agent/app/service/device_clean.go | 162 +++++++++--------- agent/app/service/favorite.go | 5 +- agent/app/service/file.go | 24 +-- agent/app/service/firewall.go | 6 +- agent/app/service/ftp.go | 13 +- agent/app/service/host_tool.go | 8 +- agent/app/service/image.go | 9 +- agent/app/service/image_repo.go | 15 +- agent/app/service/logs.go | 7 +- agent/app/service/monitor.go | 4 +- agent/app/service/nginx.go | 14 +- agent/app/service/nginx_utils.go | 3 +- agent/app/service/php_extensions.go | 3 +- agent/app/service/recycle_bin.go | 7 +- agent/app/service/runtime.go | 35 ++-- agent/app/service/runtime_utils.go | 33 ++-- agent/app/service/setting.go | 15 +- agent/app/service/snapshot.go | 19 +- agent/app/service/snapshot_create.go | 32 ++-- agent/app/service/snapshot_recover.go | 17 +- agent/app/service/snapshot_rollback.go | 13 +- agent/app/service/ssh.go | 7 +- agent/app/service/website.go | 34 ++-- agent/app/service/website_acme_account.go | 7 +- agent/app/service/website_ca.go | 15 +- agent/app/service/website_dns_account.go | 8 +- agent/app/service/website_ssl.go | 14 +- agent/app/service/website_utils.go | 19 +- agent/app/task/task.go | 5 +- agent/cmd/server/conf/app.yaml | 6 +- agent/configs/config.go | 6 - agent/configs/log.go | 9 - agent/configs/system.go | 23 --- agent/constant/dir.go | 22 --- agent/constant/errs.go | 155 ----------------- agent/global/config.go | 51 ++++++ agent/global/global.go | 14 +- agent/i18n/lang/zh.yaml | 5 +- agent/init/app/app.go | 38 ---- agent/init/db/db.go | 6 +- agent/init/dir/dir.go | 44 +++++ agent/init/hook/hook.go | 14 +- agent/init/log/log.go | 7 +- agent/init/migration/migrations/init.go | 4 +- agent/init/viper/viper.go | 25 +-- agent/middleware/certificate.go | 5 +- agent/middleware/demo_handle.go | 3 +- agent/middleware/loading.go | 7 +- agent/server/server.go | 6 +- agent/utils/cloud_storage/client/minio.go | 5 +- .../cloud_storage/cloud_storage_client.go | 3 +- agent/utils/cmd/cmd.go | 12 +- agent/utils/encrypt/encrypt.go | 12 +- agent/utils/files/archiver.go | 3 +- agent/utils/files/fileinfo.go | 7 +- agent/utils/files/zip.go | 2 +- agent/utils/firewall/client.go | 5 +- agent/utils/firewall/client/firewalld.go | 5 +- agent/utils/firewall/client/ufw.go | 5 +- agent/utils/geo/geo.go | 9 +- agent/utils/mysql/client.go | 3 +- agent/utils/mysql/client/local.go | 8 +- agent/utils/mysql/client/remote.go | 8 +- agent/utils/postgresql/client.go | 3 +- agent/utils/postgresql/client/local.go | 10 +- agent/utils/postgresql/client/remote.go | 13 +- agent/utils/xpack/xpack.go | 3 +- core/app/api/v2/app_launcher.go | 5 +- core/app/api/v2/auth.go | 4 +- core/app/api/v2/command.go | 3 +- core/app/api/v2/group.go | 3 +- core/app/api/v2/helper/helper.go | 46 ++--- core/app/api/v2/host.go | 3 +- core/app/api/v2/logs.go | 3 +- core/app/api/v2/setting.go | 52 +++--- core/app/api/v2/upgrade.go | 3 +- core/app/repo/setting.go | 9 + core/app/service/auth.go | 21 ++- core/app/service/backup.go | 31 ++-- core/app/service/command.go | 15 +- core/app/service/group.go | 16 +- core/app/service/host.go | 14 +- core/app/service/logs.go | 16 +- core/app/service/setting.go | 42 ++--- core/app/service/upgrade.go | 33 ++-- core/app/task/task.go | 2 +- core/cmd/server/cmd/restore.go | 2 +- core/cmd/server/cmd/update.go | 2 +- core/cmd/server/cmd/user-info.go | 2 +- core/cmd/server/cmd/version.go | 6 +- core/configs/config.go | 6 - core/configs/log.go | 9 - core/configs/system.go | 28 --- core/constant/errs.go | 87 ---------- core/global/config.go | 49 ++++++ core/global/global.go | 4 +- core/i18n/lang/zh.yaml | 17 +- core/init/db/db.go | 4 +- core/init/hook/hook.go | 70 ++------ core/init/lang/lang.go | 8 +- core/init/log/log.go | 5 +- core/init/migration/migrations/init.go | 16 +- core/init/router/proxy.go | 3 +- core/init/router/router.go | 2 +- core/init/session/session.go | 5 +- core/init/viper/viper.go | 55 +++--- core/middleware/bind_domain.go | 5 +- core/middleware/demo_handle.go | 3 +- core/middleware/ip_limit.go | 5 +- core/middleware/jwt.go | 6 +- core/middleware/loading.go | 5 +- core/middleware/operation.go | 6 +- core/middleware/password_expired.go | 9 +- core/middleware/session.go | 18 +- core/server/server.go | 16 +- core/utils/captcha/captcha.go | 6 +- core/utils/cloud_storage/client/minio.go | 5 +- .../cloud_storage/cloud_storage_client.go | 3 +- core/utils/cmd/cmd.go | 3 +- core/utils/encrypt/encrypt.go | 12 +- core/utils/geo/geo.go | 9 +- core/utils/jwt/jwt.go | 5 +- 159 files changed, 1110 insertions(+), 1438 deletions(-) delete mode 100644 agent/configs/config.go delete mode 100644 agent/configs/log.go delete mode 100644 agent/configs/system.go delete mode 100644 agent/constant/dir.go delete mode 100644 agent/constant/errs.go create mode 100644 agent/global/config.go create mode 100644 agent/init/dir/dir.go delete mode 100644 core/configs/config.go delete mode 100644 core/configs/log.go delete mode 100644 core/configs/system.go delete mode 100644 core/constant/errs.go create mode 100644 core/global/config.go diff --git a/agent/app/api/v2/dashboard.go b/agent/app/api/v2/dashboard.go index a5b5b04a1..be7390aed 100644 --- a/agent/app/api/v2/dashboard.go +++ b/agent/app/api/v2/dashboard.go @@ -5,7 +5,6 @@ import ( "github.com/1Panel-dev/1Panel/agent/app/api/v2/helper" "github.com/1Panel-dev/1Panel/agent/app/dto" - "github.com/1Panel-dev/1Panel/agent/constant" "github.com/gin-gonic/gin" ) @@ -35,7 +34,7 @@ func (b *BaseApi) LoadDashboardOsInfo(c *gin.Context) { func (b *BaseApi) LoadAppLauncher(c *gin.Context) { data, err := dashboardService.LoadAppLauncher() if err != nil { - helper.ErrorWithDetail(c, constant.CodeErrInternalServer, constant.ErrTypeInternalServer, err) + helper.InternalServer(c, err) return } helper.SuccessWithData(c, data) @@ -56,7 +55,7 @@ func (b *BaseApi) LoadAppLauncherOption(c *gin.Context) { } data, err := dashboardService.ListLauncherOption(req.Filter) if err != nil { - helper.ErrorWithDetail(c, constant.CodeErrInternalServer, constant.ErrTypeInternalServer, err) + helper.InternalServer(c, err) return } helper.SuccessWithData(c, data) diff --git a/agent/app/api/v2/file.go b/agent/app/api/v2/file.go index 31e184166..a3d1c151e 100644 --- a/agent/app/api/v2/file.go +++ b/agent/app/api/v2/file.go @@ -314,7 +314,7 @@ func (b *BaseApi) UploadFiles(c *gin.Context) { } if len(paths) == 0 || !strings.Contains(paths[0], "/") { - helper.ErrorWithDetail(c, constant.CodeErrBadRequest, constant.ErrTypeInvalidParams, errors.New("error paths in request")) + helper.BadRequest(c, errors.New("error paths in request")) return } dir := path.Dir(paths[0]) @@ -327,7 +327,7 @@ func (b *BaseApi) UploadFiles(c *gin.Context) { return } if err = os.MkdirAll(dir, mode); err != nil { - helper.ErrorWithDetail(c, constant.CodeErrBadRequest, constant.ErrTypeInvalidParams, fmt.Errorf("mkdir %s failed, err: %v", dir, err)) + helper.BadRequest(c, fmt.Errorf("mkdir %s failed, err: %v", dir, err)) return } } @@ -390,7 +390,7 @@ func (b *BaseApi) UploadFiles(c *gin.Context) { success++ } if success == 0 { - helper.ErrorWithDetail(c, constant.CodeErrInternalServer, constant.ErrTypeInternalServer, failures) + helper.InternalServer(c, failures) } else { helper.SuccessWithMsg(c, fmt.Sprintf("%d files upload success", success)) } @@ -518,7 +518,7 @@ func (b *BaseApi) DownloadChunkFiles(c *gin.Context) { } fileOp := files.NewFileOp() if !fileOp.Stat(req.Path) { - helper.ErrorWithDetail(c, constant.CodeErrInternalServer, constant.ErrPathNotFound, nil) + helper.ErrorWithDetail(c, http.StatusInternalServerError, "ErrPathNotFound", nil) return } filePath := req.Path @@ -533,7 +533,7 @@ func (b *BaseApi) DownloadChunkFiles(c *gin.Context) { return } if info.IsDir() { - helper.ErrorWithDetail(c, constant.CodeErrInternalServer, constant.ErrFileDownloadDir, err) + helper.ErrorWithDetail(c, http.StatusInternalServerError, "ErrFileDownloadDir", err) return } @@ -679,7 +679,7 @@ func (b *BaseApi) UploadChunkFiles(c *gin.Context) { return } fileOp := files.NewFileOp() - tmpDir := path.Join(global.CONF.System.TmpDir, "upload") + tmpDir := path.Join(global.Dir.TmpDir, "upload") if !fileOp.Stat(tmpDir) { if err := fileOp.CreateDir(tmpDir, constant.DirPerm); err != nil { helper.BadRequest(c, err) @@ -715,14 +715,14 @@ func (b *BaseApi) UploadChunkFiles(c *gin.Context) { chunkData, err = io.ReadAll(uploadFile) if err != nil { - helper.ErrorWithDetail(c, constant.CodeErrInternalServer, constant.ErrTypeInternalServer, buserr.WithMap(constant.ErrFileUpload, map[string]interface{}{"name": filename, "detail": err.Error()}, err)) + helper.InternalServer(c, buserr.WithMap("ErrFileUpload", map[string]interface{}{"name": filename, "detail": err.Error()}, err)) return } chunkPath := filepath.Join(fileDir, fmt.Sprintf("%s.%d", filename, chunkIndex)) err = os.WriteFile(chunkPath, chunkData, constant.DirPerm) if err != nil { - helper.ErrorWithDetail(c, constant.CodeErrInternalServer, constant.ErrTypeInternalServer, buserr.WithMap(constant.ErrFileUpload, map[string]interface{}{"name": filename, "detail": err.Error()}, err)) + helper.InternalServer(c, buserr.WithMap("ErrFileUpload", map[string]interface{}{"name": filename, "detail": err.Error()}, err)) return } @@ -733,7 +733,7 @@ func (b *BaseApi) UploadChunkFiles(c *gin.Context) { } err = mergeChunks(filename, fileDir, c.PostForm("path"), chunkCount, overwrite) if err != nil { - helper.ErrorWithDetail(c, constant.CodeErrInternalServer, constant.ErrTypeInternalServer, buserr.WithMap(constant.ErrFileUpload, map[string]interface{}{"name": filename, "detail": err.Error()}, err)) + helper.InternalServer(c, buserr.WithMap("ErrFileUpload", map[string]interface{}{"name": filename, "detail": err.Error()}, err)) return } helper.SuccessWithData(c, true) diff --git a/agent/app/api/v2/ftp.go b/agent/app/api/v2/ftp.go index 308f41695..a8b4deae6 100644 --- a/agent/app/api/v2/ftp.go +++ b/agent/app/api/v2/ftp.go @@ -5,7 +5,6 @@ import ( "github.com/1Panel-dev/1Panel/agent/app/api/v2/helper" "github.com/1Panel-dev/1Panel/agent/app/dto" - "github.com/1Panel-dev/1Panel/agent/constant" "github.com/gin-gonic/gin" ) @@ -41,7 +40,7 @@ func (b *BaseApi) LoadFtpLogInfo(c *gin.Context) { total, list, err := ftpService.LoadLog(req) if err != nil { - helper.ErrorWithDetail(c, constant.CodeErrInternalServer, constant.ErrTypeInternalServer, err) + helper.InternalServer(c, err) return } @@ -66,7 +65,7 @@ func (b *BaseApi) OperateFtp(c *gin.Context) { } if err := ftpService.Operate(req.Operation); err != nil { - helper.ErrorWithDetail(c, constant.CodeErrInternalServer, constant.ErrTypeInternalServer, err) + helper.InternalServer(c, err) return } @@ -89,7 +88,7 @@ func (b *BaseApi) SearchFtp(c *gin.Context) { total, list, err := ftpService.SearchWithPage(req) if err != nil { - helper.ErrorWithDetail(c, constant.CodeErrInternalServer, constant.ErrTypeInternalServer, err) + helper.InternalServer(c, err) return } @@ -123,7 +122,7 @@ func (b *BaseApi) CreateFtp(c *gin.Context) { req.Password = string(pass) } if _, err := ftpService.Create(req); err != nil { - helper.ErrorWithDetail(c, constant.CodeErrInternalServer, constant.ErrTypeInternalServer, err) + helper.InternalServer(c, err) return } helper.SuccessWithOutData(c) @@ -145,7 +144,7 @@ func (b *BaseApi) DeleteFtp(c *gin.Context) { } if err := ftpService.Delete(req); err != nil { - helper.ErrorWithDetail(c, constant.CodeErrInternalServer, constant.ErrTypeInternalServer, err) + helper.InternalServer(c, err) return } helper.SuccessWithOutData(c) @@ -162,7 +161,7 @@ func (b *BaseApi) DeleteFtp(c *gin.Context) { // @x-panel-log {"bodyKeys":[],"paramKeys":[],"BeforeFunctions":[],"formatZH":"同步 FTP 账户","formatEN":"sync FTP users"} func (b *BaseApi) SyncFtp(c *gin.Context) { if err := ftpService.Sync(); err != nil { - helper.ErrorWithDetail(c, constant.CodeErrInternalServer, constant.ErrTypeInternalServer, err) + helper.InternalServer(c, err) return } helper.SuccessWithOutData(c) @@ -192,7 +191,7 @@ func (b *BaseApi) UpdateFtp(c *gin.Context) { req.Password = string(pass) } if err := ftpService.Update(req); err != nil { - helper.ErrorWithDetail(c, constant.CodeErrInternalServer, constant.ErrTypeInternalServer, err) + helper.InternalServer(c, err) return } helper.SuccessWithOutData(c) diff --git a/agent/app/api/v2/helper/helper.go b/agent/app/api/v2/helper/helper.go index f432d87f7..de7dd2306 100644 --- a/agent/app/api/v2/helper/helper.go +++ b/agent/app/api/v2/helper/helper.go @@ -10,7 +10,6 @@ import ( "gorm.io/gorm" "github.com/1Panel-dev/1Panel/agent/app/dto" - "github.com/1Panel-dev/1Panel/agent/buserr" "github.com/1Panel-dev/1Panel/agent/constant" "github.com/1Panel-dev/1Panel/agent/i18n" "github.com/gin-gonic/gin" @@ -22,34 +21,17 @@ func ErrorWithDetail(ctx *gin.Context, code int, msgKey string, err error) { Code: code, Message: "", } - if msgKey == constant.ErrTypeInternalServer { - switch { - case errors.Is(err, constant.ErrRecordExist): - res.Message = i18n.GetMsgWithMap("ErrRecordExist", nil) - case errors.Is(constant.ErrRecordNotFound, err): - res.Message = i18n.GetMsgWithMap("ErrRecordNotFound", nil) - case errors.Is(constant.ErrInvalidParams, err): - res.Message = i18n.GetMsgWithMap("ErrInvalidParams", nil) - case errors.Is(constant.ErrStructTransform, err): - res.Message = i18n.GetMsgWithMap("ErrStructTransform", map[string]interface{}{"detail": err}) - case errors.As(err, &buserr.BusinessError{}): - res.Message = err.Error() - default: - res.Message = i18n.GetMsgWithDetail(msgKey, err.Error()) - } - } else { - res.Message = i18n.GetMsgWithDetail(msgKey, err.Error()) - } + res.Message = i18n.GetMsgWithDetail(msgKey, err.Error()) ctx.JSON(http.StatusOK, res) ctx.Abort() } func InternalServer(ctx *gin.Context, err error) { - ErrorWithDetail(ctx, constant.CodeErrInternalServer, constant.ErrTypeInternalServer, err) + ErrorWithDetail(ctx, http.StatusInternalServerError, "ErrInternalServer", err) } func BadRequest(ctx *gin.Context, err error) { - ErrorWithDetail(ctx, constant.CodeErrBadRequest, constant.ErrTypeInvalidParams, err) + ErrorWithDetail(ctx, http.StatusBadRequest, "ErrInvalidParams", err) } func SuccessWithData(ctx *gin.Context, data interface{}) { @@ -57,7 +39,7 @@ func SuccessWithData(ctx *gin.Context, data interface{}) { data = gin.H{} } res := dto.Response{ - Code: constant.CodeSuccess, + Code: http.StatusOK, Data: data, } ctx.JSON(http.StatusOK, res) @@ -66,7 +48,7 @@ func SuccessWithData(ctx *gin.Context, data interface{}) { func SuccessWithOutData(ctx *gin.Context) { res := dto.Response{ - Code: constant.CodeSuccess, + Code: http.StatusOK, Message: "success", } ctx.JSON(http.StatusOK, res) @@ -75,7 +57,7 @@ func SuccessWithOutData(ctx *gin.Context) { func SuccessWithMsg(ctx *gin.Context, msg string) { res := dto.Response{ - Code: constant.CodeSuccess, + Code: http.StatusOK, Message: msg, } ctx.JSON(http.StatusOK, res) @@ -116,11 +98,11 @@ func GetTxAndContext() (tx *gorm.DB, ctx context.Context) { func CheckBindAndValidate(req interface{}, c *gin.Context) error { if err := c.ShouldBindJSON(req); err != nil { - ErrorWithDetail(c, constant.CodeErrBadRequest, constant.ErrTypeInvalidParams, err) + ErrorWithDetail(c, http.StatusBadRequest, "ErrInvalidParams", err) return err } if err := global.VALID.Struct(req); err != nil { - ErrorWithDetail(c, constant.CodeErrBadRequest, constant.ErrTypeInvalidParams, err) + ErrorWithDetail(c, http.StatusBadRequest, "ErrInvalidParams", err) return err } return nil @@ -128,7 +110,7 @@ func CheckBindAndValidate(req interface{}, c *gin.Context) error { func CheckBind(req interface{}, c *gin.Context) error { if err := c.ShouldBindJSON(&req); err != nil { - ErrorWithDetail(c, constant.CodeErrBadRequest, constant.ErrTypeInvalidParams, err) + ErrorWithDetail(c, http.StatusBadRequest, "ErrInvalidParams", err) return err } return nil diff --git a/agent/app/api/v2/setting.go b/agent/app/api/v2/setting.go index b2613661f..c45db305e 100644 --- a/agent/app/api/v2/setting.go +++ b/agent/app/api/v2/setting.go @@ -61,7 +61,7 @@ func (b *BaseApi) UpdateSetting(c *gin.Context) { // @Security Timestamp // @Router /settings/basedir [get] func (b *BaseApi) LoadBaseDir(c *gin.Context) { - helper.SuccessWithData(c, global.CONF.System.DataDir) + helper.SuccessWithData(c, global.Dir.DataDir) } func (b *BaseApi) ReloadConn(c *gin.Context) { diff --git a/agent/app/api/v2/terminal.go b/agent/app/api/v2/terminal.go index b85ff956c..59b8149e0 100644 --- a/agent/app/api/v2/terminal.go +++ b/agent/app/api/v2/terminal.go @@ -26,7 +26,7 @@ func (b *BaseApi) RedisWsSsh(c *gin.Context) { } defer wsConn.Close() - if global.CONF.System.IsDemo { + if global.CONF.Base.IsDemo { if wshandleError(wsConn, errors.New(" demo server, prohibit this operation!")) { return } @@ -99,7 +99,7 @@ func (b *BaseApi) ContainerWsSsh(c *gin.Context) { } defer wsConn.Close() - if global.CONF.System.IsDemo { + if global.CONF.Base.IsDemo { if wshandleError(wsConn, errors.New(" demo server, prohibit this operation!")) { return } diff --git a/agent/app/model/app.go b/agent/app/model/app.go index 1842646fe..836c89218 100644 --- a/agent/app/model/app.go +++ b/agent/app/model/app.go @@ -5,6 +5,7 @@ import ( "strings" "github.com/1Panel-dev/1Panel/agent/constant" + "github.com/1Panel-dev/1Panel/agent/global" ) type App struct { @@ -43,7 +44,7 @@ func (i *App) IsLocalApp() bool { func (i *App) GetAppResourcePath() string { if i.IsLocalApp() { //这里要去掉本地应用的local前缀 - return filepath.Join(constant.LocalAppResourceDir, strings.TrimPrefix(i.Key, "local")) + return filepath.Join(global.Dir.LocalAppResourceDir, strings.TrimPrefix(i.Key, "local")) } - return filepath.Join(constant.RemoteAppResourceDir, i.Key) + return filepath.Join(global.Dir.RemoteAppResourceDir, i.Key) } diff --git a/agent/app/model/app_install.go b/agent/app/model/app_install.go index d753003b0..4fc4ae627 100644 --- a/agent/app/model/app_install.go +++ b/agent/app/model/app_install.go @@ -5,6 +5,7 @@ import ( "strings" "github.com/1Panel-dev/1Panel/agent/constant" + "github.com/1Panel-dev/1Panel/agent/global" ) type AppInstall struct { @@ -41,8 +42,8 @@ func (i *AppInstall) GetEnvPath() string { func (i *AppInstall) GetAppPath() string { if i.App.Resource == constant.AppResourceLocal { - return path.Join(constant.LocalAppInstallDir, strings.TrimPrefix(i.App.Key, constant.AppResourceLocal)) + return path.Join(global.Dir.LocalAppInstallDir, strings.TrimPrefix(i.App.Key, constant.AppResourceLocal)) } else { - return path.Join(constant.AppInstallDir, i.App.Key) + return path.Join(global.Dir.AppInstallDir, i.App.Key) } } diff --git a/agent/app/model/runtime.go b/agent/app/model/runtime.go index 0970b9cc0..9b4598d7e 100644 --- a/agent/app/model/runtime.go +++ b/agent/app/model/runtime.go @@ -3,7 +3,7 @@ package model import ( "path" - "github.com/1Panel-dev/1Panel/agent/constant" + "github.com/1Panel-dev/1Panel/agent/global" ) type Runtime struct { @@ -34,15 +34,15 @@ func (r *Runtime) GetEnvPath() string { } func (r *Runtime) GetPath() string { - return path.Join(constant.RuntimeDir, r.Type, r.Name) + return path.Join(global.Dir.RuntimeDir, r.Type, r.Name) } func (r *Runtime) GetFPMPath() string { - return path.Join(constant.RuntimeDir, r.Type, r.Name, "conf", "php-fpm.conf") + return path.Join(global.Dir.RuntimeDir, r.Type, r.Name, "conf", "php-fpm.conf") } func (r *Runtime) GetPHPPath() string { - return path.Join(constant.RuntimeDir, r.Type, r.Name, "conf", "php.ini") + return path.Join(global.Dir.RuntimeDir, r.Type, r.Name, "conf", "php.ini") } func (r *Runtime) GetLogPath() string { diff --git a/agent/app/model/website_ssl.go b/agent/app/model/website_ssl.go index da5281dc9..a3c6591a2 100644 --- a/agent/app/model/website_ssl.go +++ b/agent/app/model/website_ssl.go @@ -5,7 +5,7 @@ import ( "path" "time" - "github.com/1Panel-dev/1Panel/agent/constant" + "github.com/1Panel-dev/1Panel/agent/global" ) type WebsiteSSL struct { @@ -47,5 +47,5 @@ func (w WebsiteSSL) TableName() string { } func (w WebsiteSSL) GetLogPath() string { - return path.Join(constant.SSLLogDir, fmt.Sprintf("%s-ssl-%d.log", w.PrimaryDomain, w.ID)) + return path.Join(global.Dir.SSLLogDir, fmt.Sprintf("%s-ssl-%d.log", w.PrimaryDomain, w.ID)) } diff --git a/agent/app/service/app.go b/agent/app/service/app.go index e70b6e25e..d711768cc 100644 --- a/agent/app/service/app.go +++ b/agent/app/service/app.go @@ -218,7 +218,7 @@ func (a AppService) GetAppDetail(appID uint, version, appType string) (response. case constant.RuntimePHP: paramsPath := filepath.Join(versionPath, "data.yml") if !fileOp.Stat(paramsPath) { - return appDetailDTO, buserr.WithDetail(constant.ErrFileNotExist, paramsPath, nil) + return appDetailDTO, buserr.WithDetail("ErrFileNotExist", paramsPath, nil) } param, err := fileOp.GetContent(paramsPath) if err != nil { @@ -231,7 +231,7 @@ func (a AppService) GetAppDetail(appID uint, version, appType string) (response. appDetailDTO.Params = paramMap["additionalProperties"] composePath := filepath.Join(versionPath, "docker-compose.yml") if !fileOp.Stat(composePath) { - return appDetailDTO, buserr.WithDetail(constant.ErrFileNotExist, composePath, nil) + return appDetailDTO, buserr.WithDetail("ErrFileNotExist", composePath, nil) } compose, err := fileOp.GetContent(composePath) if err != nil { @@ -324,11 +324,11 @@ func (a AppService) GetIgnoredApp() ([]response.IgnoredApp, error) { func (a AppService) Install(req request.AppInstallCreate) (appInstall *model.AppInstall, err error) { if err = docker.CreateDefaultDockerNetwork(); err != nil { - err = buserr.WithDetail(constant.Err1PanelNetworkFailed, err.Error(), nil) + err = buserr.WithDetail("Err1PanelNetworkFailed", err.Error(), nil) return } if list, _ := appInstallRepo.ListBy(repo.WithByName(req.Name)); len(list) > 0 { - err = buserr.New(constant.ErrAppNameExist) + err = buserr.New("ErrAppNameExist") return } var ( @@ -347,7 +347,7 @@ func (a AppService) Install(req request.AppInstallCreate) (appInstall *model.App } if DatabaseKeys[app.Key] > 0 { if existDatabases, _ := databaseRepo.GetList(repo.WithByName(req.Name)); len(existDatabases) > 0 { - err = buserr.New(constant.ErrRemoteExist) + err = buserr.New("ErrRemoteExist") return } } @@ -355,7 +355,7 @@ func (a AppService) Install(req request.AppInstallCreate) (appInstall *model.App if dir, ok := req.Params["WEBSITE_DIR"]; ok { siteDir := dir.(string) if siteDir == "" || !strings.HasPrefix(siteDir, "/") { - siteDir = path.Join(constant.DataDir, dir.(string)) + siteDir = path.Join(global.Dir.DataDir, dir.(string)) } req.Params["WEBSITE_DIR"] = siteDir oldWebStePath, _ := settingRepo.GetValueByKey("WEBSITE_DIR") @@ -416,7 +416,7 @@ func (a AppService) Install(req request.AppInstallCreate) (appInstall *model.App value, ok := composeMap["services"] if !ok || value == nil { - err = buserr.New(constant.ErrFileParse) + err = buserr.New("ErrFileParse") return } servicesMap := value.(map[string]interface{}) @@ -425,7 +425,7 @@ func (a AppService) Install(req request.AppInstallCreate) (appInstall *model.App containerName = req.ContainerName appInstalls, _ := appInstallRepo.ListBy(appInstallRepo.WithContainerName(containerName)) if len(appInstalls) > 0 { - err = buserr.New(constant.ErrContainerName) + err = buserr.New("ErrContainerName") return } containerExist := false @@ -434,7 +434,7 @@ func (a AppService) Install(req request.AppInstallCreate) (appInstall *model.App return } if containerExist { - err = buserr.New(constant.ErrContainerName) + err = buserr.New("ErrContainerName") return } } @@ -549,7 +549,7 @@ func (a AppService) SyncAppListFromLocal(TaskID string) { syncTask.AddSubTask(task.GetTaskName(i18n.GetMsgByKey("LocalApp"), task.TaskSync, task.TaskScopeAppStore), func(t *task.Task) (err error) { fileOp := files.NewFileOp() - localAppDir := constant.LocalAppResourceDir + localAppDir := global.Dir.LocalAppResourceDir if !fileOp.Stat(localAppDir) { return nil } @@ -771,7 +771,7 @@ func (a AppService) GetAppUpdate() (*response.AppUpdateRes, error) { CanUpdate: false, } - versionUrl := fmt.Sprintf("%s/%s/1panel.json.version.txt", global.CONF.System.AppRepo, global.CONF.System.Mode) + versionUrl := fmt.Sprintf("%s/%s/1panel.json.version.txt", global.CONF.RemoteURL.AppRepo, global.CONF.Base.Mode) _, versionRes, err := req_helper.HandleRequest(versionUrl, http.MethodGet, constant.TimeOut20s) if err != nil { return nil, err @@ -820,11 +820,11 @@ func getAppFromRepo(downloadPath string) error { downloadUrl := downloadPath global.LOG.Infof("[AppStore] download file from %s", downloadUrl) fileOp := files.NewFileOp() - packagePath := filepath.Join(constant.ResourceDir, filepath.Base(downloadUrl)) + packagePath := filepath.Join(global.Dir.ResourceDir, filepath.Base(downloadUrl)) if err := fileOp.DownloadFile(downloadUrl, packagePath); err != nil { return err } - if err := fileOp.Decompress(packagePath, constant.ResourceDir, files.SdkZip, ""); err != nil { + if err := fileOp.Decompress(packagePath, global.Dir.ResourceDir, files.SdkZip, ""); err != nil { return err } defer func() { @@ -835,10 +835,10 @@ func getAppFromRepo(downloadPath string) error { func getAppList() (*dto.AppList, error) { list := &dto.AppList{} - if err := getAppFromRepo(fmt.Sprintf("%s/%s/1panel.json.zip", global.CONF.System.AppRepo, global.CONF.System.Mode)); err != nil { + if err := getAppFromRepo(fmt.Sprintf("%s/%s/1panel.json.zip", global.CONF.RemoteURL.AppRepo, global.CONF.Base.Mode)); err != nil { return nil, err } - listFile := filepath.Join(constant.ResourceDir, "1panel.json") + listFile := filepath.Join(global.Dir.ResourceDir, "1panel.json") content, err := os.ReadFile(listFile) if err != nil { return nil, err @@ -935,7 +935,7 @@ func (a AppService) SyncAppListFromRemote(taskID string) (err error) { oldAppIds = append(oldAppIds, old.ID) } - baseRemoteUrl := fmt.Sprintf("%s/%s/1panel", global.CONF.System.AppRepo, global.CONF.System.Mode) + baseRemoteUrl := fmt.Sprintf("%s/%s/1panel", global.CONF.RemoteURL.AppRepo, global.CONF.Base.Mode) appsMap := getApps(oldApps, list.Apps, setting.SystemVersion, t) diff --git a/agent/app/service/app_install.go b/agent/app/service/app_install.go index 69ed78ac6..74727ec55 100644 --- a/agent/app/service/app_install.go +++ b/agent/app/service/app_install.go @@ -163,7 +163,7 @@ func (a *AppInstallService) CheckExist(req request.AppInstalledInfo) (*response. res.Status = appInstall.Status res.AppInstallID = appInstall.ID res.IsExist = true - res.InstallPath = path.Join(constant.AppInstallDir, appInstall.App.Key, appInstall.Name) + res.InstallPath = path.Join(global.Dir.AppInstallDir, appInstall.App.Key, appInstall.Name) res.HttpPort = appInstall.HttpPort res.HttpsPort = appInstall.HttpsPort @@ -245,7 +245,7 @@ func (a *AppInstallService) Operate(req request.AppInstalledOperate) error { return err } if !req.ForceDelete && !files.NewFileOp().Stat(install.GetPath()) { - return buserr.New(constant.ErrInstallDirNotFound) + return buserr.New("ErrInstallDirNotFound") } dockerComposePath := install.GetComposePath() switch req.Operate { @@ -370,14 +370,14 @@ func (a *AppInstallService) Update(req request.AppInstalledUpdate) error { if installed.ContainerName != req.ContainerName { exist, _ := appInstallRepo.GetFirst(appInstallRepo.WithContainerName(req.ContainerName), appInstallRepo.WithIDNotIs(installed.ID)) if exist.ID > 0 { - return buserr.New(constant.ErrContainerName) + return buserr.New("ErrContainerName") } containerExist, err := checkContainerNameIsExist(req.ContainerName, installed.GetPath()) if err != nil { return err } if containerExist { - return buserr.New(constant.ErrContainerName) + return buserr.New("ErrContainerName") } installed.ContainerName = req.ContainerName } @@ -414,13 +414,13 @@ func (a *AppInstallService) Update(req request.AppInstalledUpdate) error { go func() { nginxInstall, err := getNginxFull(&website) if err != nil { - global.LOG.Error(buserr.WithErr(constant.ErrUpdateBuWebsite, err).Error()) + global.LOG.Error(buserr.WithErr("ErrUpdateBuWebsite", err).Error()) return } config := nginxInstall.SiteConfig.Config servers := config.FindServers() if len(servers) == 0 { - global.LOG.Error(buserr.WithErr(constant.ErrUpdateBuWebsite, errors.New("nginx config is not valid")).Error()) + global.LOG.Error(buserr.WithErr("ErrUpdateBuWebsite", errors.New("nginx config is not valid")).Error()) return } server := servers[0] @@ -428,11 +428,11 @@ func (a *AppInstallService) Update(req request.AppInstalledUpdate) error { server.UpdateRootProxy([]string{proxy}) if err := nginx.WriteConfig(config, nginx.IndentedStyle); err != nil { - global.LOG.Error(buserr.WithErr(constant.ErrUpdateBuWebsite, err).Error()) + global.LOG.Error(buserr.WithErr("ErrUpdateBuWebsite", err).Error()) return } if err := nginxCheckAndReload(nginxInstall.SiteConfig.OldContent, config.FilePath, nginxInstall.Install.ContainerName); err != nil { - global.LOG.Error(buserr.WithErr(constant.ErrUpdateBuWebsite, err).Error()) + global.LOG.Error(buserr.WithErr("ErrUpdateBuWebsite", err).Error()) return } }() @@ -588,7 +588,7 @@ func (a *AppInstallService) GetUpdateVersions(req request.AppUpdateVersion) ([]d func (a *AppInstallService) ChangeAppPort(req request.PortUpdate) error { if common.ScanPort(int(req.Port)) { - return buserr.WithDetail(constant.ErrPortInUsed, req.Port, nil) + return buserr.WithDetail("ErrPortInUsed", req.Port, nil) } appInstall, err := appInstallRepo.LoadBaseInfo(req.Key, req.Name) @@ -606,7 +606,7 @@ func (a *AppInstallService) ChangeAppPort(req request.PortUpdate) error { if err != nil { return err } - if _, err := compose.Restart(fmt.Sprintf("%s/%s/%s/docker-compose.yml", constant.AppInstallDir, appInstall.App.Key, appInstall.Name)); err != nil { + if _, err := compose.Restart(fmt.Sprintf("%s/%s/%s/docker-compose.yml", global.Dir.AppInstallDir, appInstall.App.Key, appInstall.Name)); err != nil { global.LOG.Errorf("docker-compose restart %s[%s] failed, err: %v", appInstall.App.Key, appInstall.Name, err) } } @@ -645,12 +645,12 @@ func (a *AppInstallService) GetDefaultConfigByKey(key, name string) (string, err } fileOp := files.NewFileOp() - filePath := path.Join(constant.AppResourceDir, "remote", baseInfo.Key, baseInfo.Version, "conf") + filePath := path.Join(global.Dir.AppResourceDir, "remote", baseInfo.Key, baseInfo.Version, "conf") if !fileOp.Stat(filePath) { - filePath = path.Join(constant.AppResourceDir, baseInfo.Key, "versions", baseInfo.Version, "conf") + filePath = path.Join(global.Dir.AppResourceDir, baseInfo.Key, "versions", baseInfo.Version, "conf") } if !fileOp.Stat(filePath) { - return "", buserr.New(constant.ErrPathNotFound) + return "", buserr.New("ErrPathNotFound") } if key == constant.AppMysql || key == constant.AppMariaDB { @@ -877,7 +877,7 @@ func updateInstallInfoInDB(appKey, appName, param string, value interface{}) err }, repo.WithByID(appInstall.ID)) } - ComposeFile := fmt.Sprintf("%s/%s/%s/docker-compose.yml", constant.AppInstallDir, appKey, appInstall.Name) + ComposeFile := fmt.Sprintf("%s/%s/%s/docker-compose.yml", global.Dir.AppInstallDir, appKey, appInstall.Name) stdout, err := compose.Down(ComposeFile) if err != nil { return errors.New(stdout) diff --git a/agent/app/service/app_utils.go b/agent/app/service/app_utils.go index 1a5b89d0a..10af12c9c 100644 --- a/agent/app/service/app_utils.go +++ b/agent/app/service/app_utils.go @@ -84,10 +84,10 @@ func checkPort(key string, params map[string]interface{}) (int, error) { for _, install := range oldInstalled { apps = append(apps, install.App.Name) } - return portN, buserr.WithMap(constant.ErrPortInOtherApp, map[string]interface{}{"port": portN, "apps": apps}, nil) + return portN, buserr.WithMap("ErrPortInOtherApp", map[string]interface{}{"port": portN, "apps": apps}, nil) } if common.ScanPort(portN) { - return portN, buserr.WithDetail(constant.ErrPortInUsed, portN, nil) + return portN, buserr.WithDetail("ErrPortInUsed", portN, nil) } else { return portN, nil } @@ -117,7 +117,7 @@ func checkPortExist(port int) error { return buserr.WithMap("ErrPortExist", errMap, nil) } if common.ScanPort(port) { - return buserr.WithDetail(constant.ErrPortInUsed, port, nil) + return buserr.WithDetail("ErrPortInUsed", port, nil) } return nil } @@ -264,7 +264,7 @@ func createLink(ctx context.Context, installTask *task.Task, app model.App, appI resourceId = oldPostgresqlDb.ID if oldPostgresqlDb.ID > 0 { if oldPostgresqlDb.Username != dbConfig.DbUser || oldPostgresqlDb.Password != dbConfig.Password { - return buserr.New(constant.ErrDbUserNotValid) + return buserr.New("ErrDbUserNotValid") } } else { var createPostgresql dto.PostgresqlDBCreate @@ -286,7 +286,7 @@ func createLink(ctx context.Context, installTask *task.Task, app model.App, appI resourceId = oldMysqlDb.ID if oldMysqlDb.ID > 0 { if oldMysqlDb.Username != dbConfig.DbUser || oldMysqlDb.Password != dbConfig.Password { - return buserr.New(constant.ErrDbUserNotValid) + return buserr.New("ErrDbUserNotValid") } } else { var createMysql dto.MysqlDBCreate @@ -415,12 +415,12 @@ func deleteAppInstall(deleteReq request.AppInstallDelete) error { } _ = backupRepo.DeleteRecord(ctx, repo.WithByType("app"), repo.WithByName(install.App.Key), repo.WithByDetailName(install.Name)) - uploadDir := path.Join(global.CONF.System.BaseDir, fmt.Sprintf("1panel/uploads/app/%s/%s", install.App.Key, install.Name)) + uploadDir := path.Join(global.Dir.BaseDir, fmt.Sprintf("1panel/uploads/app/%s/%s", install.App.Key, install.Name)) if _, err := os.Stat(uploadDir); err == nil { _ = os.RemoveAll(uploadDir) } if deleteReq.DeleteBackup { - backupDir := path.Join(global.CONF.System.Backup, fmt.Sprintf("app/%s/%s", install.App.Key, install.Name)) + backupDir := path.Join(global.Dir.LocalBackupDir, fmt.Sprintf("app/%s/%s", install.App.Key, install.Name)) if _, err = os.Stat(backupDir); err == nil { t.LogWithOps(task.TaskDelete, i18n.GetMsgByKey("TaskBackup")) _ = os.RemoveAll(backupDir) @@ -494,7 +494,7 @@ func getUpgradeCompose(install model.AppInstall, detail model.AppDetail) (string } value, ok := composeMap["services"] if !ok || value == nil { - return "", buserr.New(constant.ErrFileParse) + return "", buserr.New("ErrFileParse") } servicesMap := value.(map[string]interface{}) if len(servicesMap) == 1 { @@ -576,7 +576,7 @@ func upgradeInstall(req request.AppInstallUpgrade) error { } _ = backupRecordService.BatchDeleteRecord(deleteIDs) } - backupFile = path.Join(global.CONF.System.Backup, backupRecord.FileDir, backupRecord.FileName) + backupFile = path.Join(global.Dir.LocalBackupDir, backupRecord.FileDir, backupRecord.FileName) } else { return buserr.WithNameAndErr("ErrAppBackup", install.Name, err) } @@ -587,7 +587,7 @@ func upgradeInstall(req request.AppInstallUpgrade) error { upgradeApp := func(t *task.Task) error { fileOp := files.NewFileOp() - detailDir := path.Join(constant.ResourceDir, "apps", install.App.Resource, install.App.Key, detail.Version) + detailDir := path.Join(global.Dir.ResourceDir, "apps", install.App.Resource, install.App.Key, detail.Version) if install.App.Resource == constant.AppResourceRemote { if err = downloadApp(install.App, detail, &install, t.Logger); err != nil { return err @@ -605,7 +605,7 @@ func upgradeInstall(req request.AppInstallUpgrade) error { }() } if install.App.Resource == constant.AppResourceLocal { - detailDir = path.Join(constant.ResourceDir, "apps", "local", strings.TrimPrefix(install.App.Key, "local"), detail.Version) + detailDir = path.Join(global.Dir.ResourceDir, "apps", "local", strings.TrimPrefix(install.App.Key, "local"), detail.Version) } content, err := fileOp.GetContent(install.GetEnvPath()) @@ -673,15 +673,15 @@ func upgradeInstall(req request.AppInstallUpgrade) error { handleMap(envs, envParams) if install.App.Key == "openresty" && install.App.Resource == "remote" && !common.CompareVersion(install.Version, "1.25.3.2-0-1") { t.Log(i18n.GetMsgByKey("MoveSiteDir")) - siteDir := path.Join(constant.DataDir, "www") + siteDir := path.Join(global.Dir.DataDir, "www") envParams["WEBSITE_DIR"] = siteDir oldSiteDir := path.Join(install.GetPath(), "www") t.Log(i18n.GetWithName("MoveSiteToDir", siteDir)) - if err := fileOp.CopyDir(oldSiteDir, constant.DataDir); err != nil { + if err := fileOp.CopyDir(oldSiteDir, global.Dir.DataDir); err != nil { t.Log(i18n.GetMsgByKey("ErrMoveSiteDir")) return err } - newConfDir := path.Join(constant.DataDir, "www", "conf.d") + newConfDir := path.Join(global.Dir.DataDir, "www", "conf.d") _ = fileOp.CreateDir(newConfDir, constant.DirPerm) oldConfDir := path.Join(install.GetPath(), "conf/conf.d") items, err := os.ReadDir(oldConfDir) @@ -711,10 +711,10 @@ func upgradeInstall(req request.AppInstallUpgrade) error { httpDirective.UpdateDirective("include", []string{"/usr/local/openresty/nginx/conf/default/*.conf"}) if err = nginx.WriteConfig(config, nginx.IndentedStyle); err != nil { - return buserr.WithErr(constant.ErrUpdateBuWebsite, err) + return buserr.WithErr("ErrUpdateBuWebsite", err) } t.Log(i18n.GetMsgByKey("DeleteRuntimePHP")) - _ = fileOp.DeleteDir(path.Join(constant.RuntimeDir, "php")) + _ = fileOp.DeleteDir(path.Join(global.Dir.RuntimeDir, "php")) websites, _ := websiteRepo.List(repo.WithByType("runtime")) for _, website := range websites { runtime, _ := runtimeRepo.GetFirst(repo.WithByID(website.RuntimeID)) @@ -827,7 +827,7 @@ func checkLimit(app model.App) error { return err } if len(installs) >= app.Limit { - return buserr.New(constant.ErrAppLimit) + return buserr.New("ErrAppLimit") } } return nil @@ -867,7 +867,7 @@ func downloadApp(app model.App, appDetail model.AppDetail, appInstall *model.App if app.IsLocalApp() { return nil } - appResourceDir := path.Join(constant.AppResourceDir, app.Resource) + appResourceDir := path.Join(global.Dir.AppResourceDir, app.Resource) appDownloadDir := app.GetAppResourcePath() appVersionDir := path.Join(appDownloadDir, appDetail.Version) fileOp := files.NewFileOp() @@ -921,7 +921,7 @@ func downloadApp(app model.App, appDetail model.AppDetail, appInstall *model.App func copyData(task *task.Task, app model.App, appDetail model.AppDetail, appInstall *model.AppInstall, req request.AppInstallCreate) (err error) { fileOp := files.NewFileOp() - appResourceDir := path.Join(constant.AppResourceDir, app.Resource) + appResourceDir := path.Join(global.Dir.AppResourceDir, app.Resource) if app.Resource == constant.AppResourceRemote { err = downloadApp(app, appDetail, appInstall, task.Logger) @@ -933,14 +933,14 @@ func copyData(task *task.Task, app model.App, appDetail model.AppDetail, appInst }() } appKey := app.Key - installAppDir := path.Join(constant.AppInstallDir, app.Key) + installAppDir := path.Join(global.Dir.AppInstallDir, app.Key) if app.Resource == constant.AppResourceLocal { - appResourceDir = constant.LocalAppResourceDir + appResourceDir = global.Dir.LocalAppResourceDir appKey = strings.TrimPrefix(app.Key, "local") - installAppDir = path.Join(constant.LocalAppInstallDir, appKey) + installAppDir = path.Join(global.Dir.LocalAppInstallDir, appKey) } if app.Resource == constant.AppResourceCustom { - appResourceDir = path.Join(constant.AppResourceDir, "custom") + appResourceDir = path.Join(global.Dir.AppResourceDir, "custom") } resourceDir := path.Join(appResourceDir, appKey, appDetail.Version) @@ -1205,43 +1205,43 @@ func handleLocalAppDetail(versionDir string, appDetail *model.AppDetail) error { fileOp := files.NewFileOp() dockerComposePath := path.Join(versionDir, "docker-compose.yml") if !fileOp.Stat(dockerComposePath) { - return buserr.WithName(constant.ErrFileNotFound, "docker-compose.yml") + return buserr.WithName("ErrFileNotFound", "docker-compose.yml") } dockerComposeByte, _ := fileOp.GetContent(dockerComposePath) if dockerComposeByte == nil { - return buserr.WithName(constant.ErrFileParseApp, "docker-compose.yml") + return buserr.WithName("ErrFileParseApp", "docker-compose.yml") } appDetail.DockerCompose = string(dockerComposeByte) paramPath := path.Join(versionDir, "data.yml") if !fileOp.Stat(paramPath) { - return buserr.WithName(constant.ErrFileNotFound, "data.yml") + return buserr.WithName("ErrFileNotFound", "data.yml") } paramByte, _ := fileOp.GetContent(paramPath) if paramByte == nil { - return buserr.WithName(constant.ErrFileNotFound, "data.yml") + return buserr.WithName("ErrFileNotFound", "data.yml") } appParamConfig := dto.LocalAppParam{} if err := yaml.Unmarshal(paramByte, &appParamConfig); err != nil { - return buserr.WithMap(constant.ErrFileParseApp, map[string]interface{}{"name": "data.yml", "err": err.Error()}, err) + return buserr.WithMap("ErrFileParseApp", map[string]interface{}{"name": "data.yml", "err": err.Error()}, err) } dataJson, err := json.Marshal(appParamConfig.AppParams) if err != nil { - return buserr.WithMap(constant.ErrFileParseApp, map[string]interface{}{"name": "data.yml", "err": err.Error()}, err) + return buserr.WithMap("ErrFileParseApp", map[string]interface{}{"name": "data.yml", "err": err.Error()}, err) } var appParam dto.AppForm if err = json.Unmarshal(dataJson, &appParam); err != nil { - return buserr.WithMap(constant.ErrFileParseApp, map[string]interface{}{"name": "data.yml", "err": err.Error()}, err) + return buserr.WithMap("ErrFileParseApp", map[string]interface{}{"name": "data.yml", "err": err.Error()}, err) } for _, formField := range appParam.FormFields { if strings.Contains(formField.EnvKey, " ") { - return buserr.WithName(constant.ErrAppParamKey, formField.EnvKey) + return buserr.WithName("ErrAppParamKey", formField.EnvKey) } } var dataMap map[string]interface{} err = yaml.Unmarshal(paramByte, &dataMap) if err != nil { - return buserr.WithMap(constant.ErrFileParseApp, map[string]interface{}{"name": "data.yml", "err": err.Error()}, err) + return buserr.WithMap("ErrFileParseApp", map[string]interface{}{"name": "data.yml", "err": err.Error()}, err) } additionalProperties, _ := dataMap["additionalProperties"].(map[string]interface{}) @@ -1249,13 +1249,13 @@ func handleLocalAppDetail(versionDir string, appDetail *model.AppDetail) error { if ok { formFields, ok := formFieldsInterface.([]interface{}) if !ok { - return buserr.WithName(constant.ErrAppParamKey, "formFields") + return buserr.WithName("ErrAppParamKey", "formFields") } for _, item := range formFields { field := item.(map[string]interface{}) for key, value := range field { if value == nil { - return buserr.WithName(constant.ErrAppParamKey, key) + return buserr.WithName("ErrAppParamKey", key) } } } @@ -1269,22 +1269,22 @@ func handleLocalApp(appDir string) (app *model.App, err error) { fileOp := files.NewFileOp() configYamlPath := path.Join(appDir, "data.yml") if !fileOp.Stat(configYamlPath) { - err = buserr.WithName(constant.ErrFileNotFound, "data.yml") + err = buserr.WithName("ErrFileNotFound", "data.yml") return } iconPath := path.Join(appDir, "logo.png") if !fileOp.Stat(iconPath) { - err = buserr.WithName(constant.ErrFileNotFound, "logo.png") + err = buserr.WithName("ErrFileNotFound", "logo.png") return } configYamlByte, err := fileOp.GetContent(configYamlPath) if err != nil { - err = buserr.WithMap(constant.ErrFileParseApp, map[string]interface{}{"name": "data.yml", "err": err.Error()}, err) + err = buserr.WithMap("ErrFileParseApp", map[string]interface{}{"name": "data.yml", "err": err.Error()}, err) return } localAppDefine := dto.LocalAppAppDefine{} if err = yaml.Unmarshal(configYamlByte, &localAppDefine); err != nil { - err = buserr.WithMap(constant.ErrFileParseApp, map[string]interface{}{"name": "data.yml", "err": err.Error()}, err) + err = buserr.WithMap("ErrFileParseApp", map[string]interface{}{"name": "data.yml", "err": err.Error()}, err) return } app = &localAppDefine.AppProperty @@ -1578,7 +1578,7 @@ func updateToolApp(installed *model.AppInstall) { func addDockerComposeCommonParam(composeMap map[string]interface{}, serviceName string, req request.AppContainerConfig, params map[string]interface{}) error { services, serviceValid := composeMap["services"].(map[string]interface{}) if !serviceValid { - return buserr.New(constant.ErrFileParse) + return buserr.New("ErrFileParse") } imagePreFix := xpack.GetImagePrefix() if imagePreFix != "" { @@ -1598,7 +1598,7 @@ func addDockerComposeCommonParam(composeMap map[string]interface{}, serviceName service, serviceExist := services[serviceName] if !serviceExist { - return buserr.New(constant.ErrFileParse) + return buserr.New("ErrFileParse") } serviceValue := service.(map[string]interface{}) diff --git a/agent/app/service/backup.go b/agent/app/service/backup.go index a8ba8b908..a08643804 100644 --- a/agent/app/service/backup.go +++ b/agent/app/service/backup.go @@ -23,7 +23,6 @@ import ( "github.com/1Panel-dev/1Panel/agent/utils/encrypt" "github.com/1Panel-dev/1Panel/agent/utils/files" "github.com/jinzhu/copier" - "github.com/pkg/errors" ) type BackupService struct{} @@ -125,17 +124,17 @@ func (u *BackupService) SearchWithPage(req dto.SearchPageWithType) (int64, inter func (u *BackupService) Create(req dto.BackupOperate) error { if req.Type == constant.Local { - return buserr.New(constant.ErrBackupLocalCreate) + return buserr.New("ErrBackupLocalCreate") } if req.Type != constant.Sftp && req.BackupPath != "/" { req.BackupPath = strings.TrimPrefix(req.BackupPath, "/") } backup, _ := backupRepo.Get(repo.WithByName(req.Name)) if backup.ID != 0 { - return constant.ErrRecordExist + return buserr.New("ErrRecordExist") } if err := copier.Copy(&backup, &req); err != nil { - return errors.WithMessage(constant.ErrStructTransform, err.Error()) + return buserr.WithDetail("ErrStructTransform", err.Error(), nil) } itemAccessKey, err := base64.StdEncoding.DecodeString(backup.AccessKey) if err != nil { @@ -156,7 +155,7 @@ func (u *BackupService) Create(req dto.BackupOperate) error { if req.Type != "LOCAL" { isOk, err := u.checkBackupConn(&backup) if err != nil || !isOk { - return buserr.WithMap(constant.ErrBackupCheck, map[string]interface{}{"err": err.Error()}, err) + return buserr.WithMap("ErrBackupCheck", map[string]interface{}{"err": err.Error()}, err) } } @@ -208,10 +207,10 @@ func (u *BackupService) GetBuckets(req dto.ForBuckets) ([]interface{}, error) { func (u *BackupService) Delete(id uint) error { backup, _ := backupRepo.Get(repo.WithByID(id)) if backup.ID == 0 { - return constant.ErrRecordNotFound + return buserr.New("ErrRecordNotFound") } if backup.Type == constant.Local { - return buserr.New(constant.ErrBackupLocalDelete) + return buserr.New("ErrBackupLocalDelete") } return backupRepo.Delete(repo.WithByID(id)) } @@ -219,14 +218,14 @@ func (u *BackupService) Delete(id uint) error { func (u *BackupService) Update(req dto.BackupOperate) error { backup, _ := backupRepo.Get(repo.WithByID(req.ID)) if backup.ID == 0 { - return constant.ErrRecordNotFound + return buserr.New("ErrRecordNotFound") } if req.Type != constant.Sftp && req.Type != constant.Local && req.BackupPath != "/" { req.BackupPath = strings.TrimPrefix(req.BackupPath, "/") } var newBackup model.BackupAccount if err := copier.Copy(&newBackup, &req); err != nil { - return errors.WithMessage(constant.ErrStructTransform, err.Error()) + return buserr.WithDetail("ErrStructTransform", err.Error(), nil) } itemAccessKey, err := base64.StdEncoding.DecodeString(newBackup.AccessKey) if err != nil { @@ -281,7 +280,7 @@ func (u *BackupService) Update(req dto.BackupOperate) error { func (u *BackupService) RefreshToken(req dto.OperateByID) error { backup, _ := backupRepo.Get(repo.WithByID(req.ID)) if backup.ID == 0 { - return constant.ErrRecordNotFound + return buserr.New("ErrRecordNotFound") } varMap := make(map[string]interface{}) if err := json.Unmarshal([]byte(backup.Vars), &varMap); err != nil { @@ -318,7 +317,7 @@ func (u *BackupService) checkBackupConn(backup *model.BackupAccount) (bool, erro if err != nil { return false, err } - fileItem := path.Join(global.CONF.System.BaseDir, "1panel/tmp/test/1panel") + fileItem := path.Join(global.Dir.BaseDir, "1panel/tmp/test/1panel") if _, err := os.Stat(path.Dir(fileItem)); err != nil && os.IsNotExist(err) { if err = os.MkdirAll(path.Dir(fileItem), os.ModePerm); err != nil { return false, err @@ -365,12 +364,12 @@ func (u *BackupService) Sync(req dto.SyncFromMaster) error { return backupRepo.Create(&accountItem) case "delete": if account.ID == 0 { - return constant.ErrRecordNotFound + return buserr.New("ErrRecordNotFound") } return backupRepo.Delete(repo.WithByID(account.ID)) case "update": if account.ID == 0 { - return constant.ErrRecordNotFound + return buserr.New("ErrRecordNotFound") } accountItem.ID = account.ID return backupRepo.Save(&accountItem) @@ -399,12 +398,12 @@ func (u *BackupService) CheckUsed(id uint) error { cronjobs, _ := cronjobRepo.List() for _, job := range cronjobs { if job.DownloadAccountID == id { - return buserr.New(constant.ErrBackupInUsed) + return buserr.New("ErrBackupInUsed") } ids := strings.Split(job.SourceAccountIDs, ",") for _, idItem := range ids { if idItem == fmt.Sprintf("%v", id) { - return buserr.New(constant.ErrBackupInUsed) + return buserr.New("ErrBackupInUsed") } } } diff --git a/agent/app/service/backup_app.go b/agent/app/service/backup_app.go index b462ec4d8..7ce6023f6 100644 --- a/agent/app/service/backup_app.go +++ b/agent/app/service/backup_app.go @@ -4,13 +4,14 @@ import ( "context" "encoding/json" "fmt" - "github.com/1Panel-dev/1Panel/agent/app/repo" "io/fs" "os" "path" "strings" "time" + "github.com/1Panel-dev/1Panel/agent/app/repo" + "github.com/1Panel-dev/1Panel/agent/app/task" "github.com/1Panel-dev/1Panel/agent/i18n" @@ -37,7 +38,7 @@ func (u *BackupService) AppBackup(req dto.CommonBackup) (*model.BackupRecord, er } timeNow := time.Now().Format(constant.DateTimeSlimLayout) itemDir := fmt.Sprintf("app/%s/%s", req.Name, req.DetailName) - backupDir := path.Join(global.CONF.System.Backup, itemDir) + backupDir := path.Join(global.Dir.LocalBackupDir, itemDir) fileName := req.FileName if req.FileName == "" { @@ -226,7 +227,7 @@ func handleAppRecover(install *model.AppInstall, parentTask *task.Task, recoverF } if !isRollback { - rollbackFile = path.Join(global.CONF.System.TmpDir, fmt.Sprintf("app/%s_%s.tar.gz", install.Name, time.Now().Format(constant.DateTimeSlimLayout))) + rollbackFile = path.Join(global.Dir.TmpDir, fmt.Sprintf("app/%s_%s.tar.gz", install.Name, time.Now().Format(constant.DateTimeSlimLayout))) if err := handleAppBackup(install, nil, path.Dir(rollbackFile), path.Base(rollbackFile), "", "", ""); err != nil { t.Log(fmt.Sprintf("backup app %s for rollback before recover failed, err: %v", install.Name, err)) } diff --git a/agent/app/service/backup_mysql.go b/agent/app/service/backup_mysql.go index 750cf20fd..c01734431 100644 --- a/agent/app/service/backup_mysql.go +++ b/agent/app/service/backup_mysql.go @@ -2,13 +2,14 @@ package service import ( "fmt" - "github.com/1Panel-dev/1Panel/agent/app/repo" "os" "path" "path/filepath" "strings" "time" + "github.com/1Panel-dev/1Panel/agent/app/repo" + "github.com/1Panel-dev/1Panel/agent/constant" "github.com/1Panel-dev/1Panel/agent/i18n" @@ -26,7 +27,7 @@ import ( func (u *BackupService) MysqlBackup(req dto.CommonBackup) error { timeNow := time.Now().Format(constant.DateTimeSlimLayout) itemDir := fmt.Sprintf("database/%s/%s/%s", req.Type, req.Name, req.DetailName) - targetDir := path.Join(global.CONF.System.Backup, itemDir) + targetDir := path.Join(global.Dir.LocalBackupDir, itemDir) fileName := fmt.Sprintf("%s_%s.sql.gz", req.DetailName, timeNow+common.RandStrAndNum(5)) databaseHelper := DatabaseHelper{Database: req.Name, DBType: req.Type, Name: req.DetailName} @@ -180,7 +181,7 @@ func handleMysqlRecover(req dto.CommonRecover, parentTask *task.Task, isRollback } if !isRollback { - rollbackFile := path.Join(global.CONF.System.TmpDir, fmt.Sprintf("database/%s/%s_%s.sql.gz", req.Type, req.DetailName, time.Now().Format(constant.DateTimeSlimLayout))) + rollbackFile := path.Join(global.Dir.TmpDir, fmt.Sprintf("database/%s/%s_%s.sql.gz", req.Type, req.DetailName, time.Now().Format(constant.DateTimeSlimLayout))) if err := cli.Backup(client.BackupInfo{ Name: req.DetailName, Type: req.Type, diff --git a/agent/app/service/backup_postgresql.go b/agent/app/service/backup_postgresql.go index b8e41f08e..bc7b0f4ff 100644 --- a/agent/app/service/backup_postgresql.go +++ b/agent/app/service/backup_postgresql.go @@ -2,13 +2,14 @@ package service import ( "fmt" - "github.com/1Panel-dev/1Panel/agent/app/repo" "os" "path" "path/filepath" "strings" "time" + "github.com/1Panel-dev/1Panel/agent/app/repo" + "github.com/1Panel-dev/1Panel/agent/constant" "github.com/1Panel-dev/1Panel/agent/i18n" @@ -27,7 +28,7 @@ import ( func (u *BackupService) PostgresqlBackup(req dto.CommonBackup) error { timeNow := time.Now().Format(constant.DateTimeSlimLayout) itemDir := fmt.Sprintf("database/%s/%s/%s", req.Type, req.Name, req.DetailName) - targetDir := path.Join(global.CONF.System.Backup, itemDir) + targetDir := path.Join(global.Dir.LocalBackupDir, itemDir) fileName := fmt.Sprintf("%s_%s.sql.gz", req.DetailName, timeNow+common.RandStrAndNum(5)) databaseHelper := DatabaseHelper{Database: req.Name, DBType: req.Type, Name: req.DetailName} @@ -169,7 +170,7 @@ func handlePostgresqlRecover(req dto.CommonRecover, parentTask *task.Task, isRol defer cli.Close() if !isRollback { - rollbackFile := path.Join(global.CONF.System.TmpDir, fmt.Sprintf("database/%s/%s_%s.sql.gz", req.Type, req.DetailName, time.Now().Format(constant.DateTimeSlimLayout))) + rollbackFile := path.Join(global.Dir.TmpDir, fmt.Sprintf("database/%s/%s_%s.sql.gz", req.Type, req.DetailName, time.Now().Format(constant.DateTimeSlimLayout))) if err := cli.Backup(client.BackupInfo{ Name: req.DetailName, TargetDir: path.Dir(rollbackFile), diff --git a/agent/app/service/backup_record.go b/agent/app/service/backup_record.go index 18bca392e..f40c16708 100644 --- a/agent/app/service/backup_record.go +++ b/agent/app/service/backup_record.go @@ -10,7 +10,6 @@ import ( "github.com/1Panel-dev/1Panel/agent/app/dto" "github.com/1Panel-dev/1Panel/agent/app/model" "github.com/1Panel-dev/1Panel/agent/app/repo" - "github.com/1Panel-dev/1Panel/agent/constant" "github.com/1Panel-dev/1Panel/agent/global" "github.com/jinzhu/copier" ) @@ -81,9 +80,9 @@ func (u *BackupRecordService) DownloadRecord(info dto.DownloadRecord) (string, e return "", fmt.Errorf("new cloud storage client failed, err: %v", err) } if account.Type == "LOCAL" { - return path.Join(global.CONF.System.Backup, info.FileDir, info.FileName), nil + return path.Join(global.Dir.LocalBackupDir, info.FileDir, info.FileName), nil } - targetPath := fmt.Sprintf("%s/download/%s/%s", constant.DataDir, info.FileDir, info.FileName) + targetPath := fmt.Sprintf("%s/download/%s/%s", global.Dir.DataDir, info.FileDir, info.FileName) if _, err := os.Stat(path.Dir(targetPath)); err != nil && os.IsNotExist(err) { if err = os.MkdirAll(path.Dir(targetPath), os.ModePerm); err != nil { global.LOG.Errorf("mkdir %s failed, err: %v", path.Dir(targetPath), err) diff --git a/agent/app/service/backup_redis.go b/agent/app/service/backup_redis.go index 8ca3491a6..d6d25aa59 100644 --- a/agent/app/service/backup_redis.go +++ b/agent/app/service/backup_redis.go @@ -43,7 +43,7 @@ func (u *BackupService) RedisBackup(req dto.CommonBackup) error { } } itemDir := fmt.Sprintf("database/redis/%s", redisInfo.Name) - backupDir := path.Join(global.CONF.System.Backup, itemDir) + backupDir := path.Join(global.Dir.LocalBackupDir, itemDir) if err := handleRedisBackup(redisInfo, nil, backupDir, fileName, req.Secret, req.TaskID); err != nil { return err } @@ -101,7 +101,7 @@ func handleRedisBackup(redisInfo *repo.RootInfo, parentTask *task.Task, backupDi } if strings.HasSuffix(fileName, ".tar.gz") { - redisDataDir := fmt.Sprintf("%s/%s/%s/data/appendonlydir", constant.AppInstallDir, "redis", redisInfo.Name) + redisDataDir := fmt.Sprintf("%s/%s/%s/data/appendonlydir", global.Dir.AppInstallDir, "redis", redisInfo.Name) if err := fileOp.TarGzCompressPro(true, redisDataDir, path.Join(backupDir, fileName), secret, ""); err != nil { return err } @@ -155,14 +155,14 @@ func handleRedisRecover(redisInfo *repo.RootInfo, parentTask *task.Task, recover if appendonly == "yes" { if strings.HasPrefix(redisInfo.Version, "6.") && !strings.HasSuffix(recoverFile, ".aof") { - return buserr.New(constant.ErrTypeOfRedis) + return buserr.New("ErrTypeOfRedis") } if strings.HasPrefix(redisInfo.Version, "7.") && !strings.HasSuffix(recoverFile, ".tar.gz") { - return buserr.New(constant.ErrTypeOfRedis) + return buserr.New("ErrTypeOfRedis") } } else { if !strings.HasSuffix(recoverFile, ".rdb") { - return buserr.New(constant.ErrTypeOfRedis) + return buserr.New("ErrTypeOfRedis") } } @@ -177,7 +177,7 @@ func handleRedisRecover(redisInfo *repo.RootInfo, parentTask *task.Task, recover suffix = "tar.gz" } } - rollbackFile := path.Join(global.CONF.System.TmpDir, fmt.Sprintf("database/redis/%s_%s.%s", redisInfo.Name, time.Now().Format(constant.DateTimeSlimLayout), suffix)) + rollbackFile := path.Join(global.Dir.TmpDir, fmt.Sprintf("database/redis/%s_%s.%s", redisInfo.Name, time.Now().Format(constant.DateTimeSlimLayout), suffix)) if err := handleRedisBackup(redisInfo, nil, path.Dir(rollbackFile), path.Base(rollbackFile), secret, ""); err != nil { return fmt.Errorf("backup database %s for rollback before recover failed, err: %v", redisInfo.Name, err) } @@ -195,12 +195,12 @@ func handleRedisRecover(redisInfo *repo.RootInfo, parentTask *task.Task, recover } }() } - composeDir := fmt.Sprintf("%s/redis/%s", constant.AppInstallDir, redisInfo.Name) + composeDir := fmt.Sprintf("%s/redis/%s", global.Dir.AppInstallDir, redisInfo.Name) if _, err := compose.Down(composeDir + "/docker-compose.yml"); err != nil { return err } if appendonly == "yes" && strings.HasPrefix(redisInfo.Version, "7.") { - redisDataDir := fmt.Sprintf("%s/%s/%s/data", constant.AppInstallDir, "redis", redisInfo.Name) + redisDataDir := fmt.Sprintf("%s/%s/%s/data", global.Dir.AppInstallDir, "redis", redisInfo.Name) if err := fileOp.TarGzExtractPro(recoverFile, redisDataDir, secret); err != nil { return err } diff --git a/agent/app/service/backup_runtime.go b/agent/app/service/backup_runtime.go index 38e89bc23..4bfc65ee2 100644 --- a/agent/app/service/backup_runtime.go +++ b/agent/app/service/backup_runtime.go @@ -72,7 +72,7 @@ func handleRuntimeRecover(runtime *model.Runtime, recoverFile string, isRollback } if !isRollback { - rollbackFile := path.Join(global.CONF.System.TmpDir, fmt.Sprintf("runtime/%s_%s.tar.gz", runtime.Name, time.Now().Format(constant.DateTimeSlimLayout))) + rollbackFile := path.Join(global.Dir.TmpDir, fmt.Sprintf("runtime/%s_%s.tar.gz", runtime.Name, time.Now().Format(constant.DateTimeSlimLayout))) if err := handleRuntimeBackup(runtime, path.Dir(rollbackFile), path.Base(rollbackFile), "", secret); err != nil { return fmt.Errorf("backup runtime %s for rollback before recover failed, err: %v", runtime.Name, err) } @@ -100,7 +100,7 @@ func handleRuntimeRecover(runtime *model.Runtime, recoverFile string, isRollback _ = fileOp.Rename(runtimeDir, backPath) _ = fileOp.CreateDir(runtimeDir, constant.DirPerm) - if err := fileOp.TarGzExtractPro(tmpPath+"/runtime.tar.gz", fmt.Sprintf("%s/%s", constant.RuntimeDir, runtime.Type), secret); err != nil { + if err := fileOp.TarGzExtractPro(tmpPath+"/runtime.tar.gz", fmt.Sprintf("%s/%s", global.Dir.RuntimeDir, runtime.Type), secret); err != nil { global.LOG.Errorf("handle recover from runtime.tar.gz failed, err: %v", err) _ = fileOp.DeleteDir(runtimeDir) _ = fileOp.Rename(backPath, runtimeDir) @@ -109,7 +109,7 @@ func handleRuntimeRecover(runtime *model.Runtime, recoverFile string, isRollback _ = fileOp.DeleteDir(backPath) if len(newEnvFile) != 0 { - envPath := fmt.Sprintf("%s/%s/%s/.env", constant.RuntimeDir, runtime.Type, runtime.Name) + envPath := fmt.Sprintf("%s/%s/%s/.env", global.Dir.RuntimeDir, runtime.Type, runtime.Name) file, err := os.OpenFile(envPath, os.O_WRONLY|os.O_TRUNC, 0640) if err != nil { return err diff --git a/agent/app/service/backup_website.go b/agent/app/service/backup_website.go index 53feb8dbb..5be930b89 100644 --- a/agent/app/service/backup_website.go +++ b/agent/app/service/backup_website.go @@ -3,13 +3,14 @@ package service import ( "encoding/json" "fmt" - "github.com/1Panel-dev/1Panel/agent/app/repo" "io/fs" "os" "path" "strings" "time" + "github.com/1Panel-dev/1Panel/agent/app/repo" + "github.com/1Panel-dev/1Panel/agent/app/task" "github.com/1Panel-dev/1Panel/agent/i18n" "github.com/1Panel-dev/1Panel/agent/utils/cmd" @@ -33,7 +34,7 @@ func (u *BackupService) WebsiteBackup(req dto.CommonBackup) error { timeNow := time.Now().Format(constant.DateTimeSlimLayout) itemDir := fmt.Sprintf("website/%s", req.Name) - backupDir := path.Join(global.CONF.System.Backup, itemDir) + backupDir := path.Join(global.Dir.LocalBackupDir, itemDir) fileName := fmt.Sprintf("%s_%s.tar.gz", website.Alias, timeNow+common.RandStrAndNum(5)) go func() { @@ -103,17 +104,17 @@ func handleWebsiteRecover(website *model.Website, recoverFile string, isRollback temPathWithName := tmpPath + "/" + website.Alias if !fileOp.Stat(tmpPath+"/website.json") || !fileOp.Stat(temPathWithName+".conf") || !fileOp.Stat(temPathWithName+".web.tar.gz") { - return buserr.WithDetail(constant.ErrBackupExist, ".conf or .web.tar.gz", nil) + return buserr.WithDetail("ErrBackupExist", ".conf or .web.tar.gz", nil) } if website.Type == constant.Deployment { if !fileOp.Stat(temPathWithName + ".app.tar.gz") { - return buserr.WithDetail(constant.ErrBackupExist, ".app.tar.gz", nil) + return buserr.WithDetail("ErrBackupExist", ".app.tar.gz", nil) } } isOk := false if !isRollback { - rollbackFile := path.Join(global.CONF.System.TmpDir, fmt.Sprintf("website/%s_%s.tar.gz", website.Alias, time.Now().Format(constant.DateTimeSlimLayout))) + rollbackFile := path.Join(global.Dir.TmpDir, fmt.Sprintf("website/%s_%s.tar.gz", website.Alias, time.Now().Format(constant.DateTimeSlimLayout))) if err := handleWebsiteBackup(website, path.Dir(rollbackFile), path.Base(rollbackFile), "", "", ""); err != nil { return fmt.Errorf("backup website %s for rollback before recover failed, err: %v", website.Alias, err) } @@ -153,7 +154,7 @@ func handleWebsiteRecover(website *model.Website, recoverFile string, isRollback return err } t.LogSuccess(taskName) - if _, err = compose.DownAndUp(fmt.Sprintf("%s/%s/%s/docker-compose.yml", constant.AppInstallDir, app.App.Key, app.Name)); err != nil { + if _, err = compose.DownAndUp(fmt.Sprintf("%s/%s/%s/docker-compose.yml", global.Dir.AppInstallDir, app.App.Key, app.Name)); err != nil { t.LogFailedWithErr("Run", err) return err } @@ -278,22 +279,22 @@ func handleWebsiteBackup(website *model.Website, backupDir, fileName, excludes, func checkValidOfWebsite(oldWebsite, website *model.Website) error { if oldWebsite.Alias != website.Alias || oldWebsite.Type != website.Type { - return buserr.WithDetail(constant.ErrBackupMatch, fmt.Sprintf("oldName: %s, oldType: %v", oldWebsite.Alias, oldWebsite.Type), nil) + return buserr.WithDetail("ErrBackupMatch", fmt.Sprintf("oldName: %s, oldType: %v", oldWebsite.Alias, oldWebsite.Type), nil) } if oldWebsite.AppInstallID != 0 { _, err := appInstallRepo.GetFirst(repo.WithByID(oldWebsite.AppInstallID)) if err != nil { - return buserr.WithDetail(constant.ErrBackupMatch, "app", nil) + return buserr.WithDetail("ErrBackupMatch", "app", nil) } } if oldWebsite.RuntimeID != 0 { if _, err := runtimeRepo.GetFirst(repo.WithByID(oldWebsite.RuntimeID)); err != nil { - return buserr.WithDetail(constant.ErrBackupMatch, "runtime", nil) + return buserr.WithDetail("ErrBackupMatch", "runtime", nil) } } if oldWebsite.WebsiteSSLID != 0 { if _, err := websiteSSLRepo.GetFirst(repo.WithByID(oldWebsite.WebsiteSSLID)); err != nil { - return buserr.WithDetail(constant.ErrBackupMatch, "ssl", nil) + return buserr.WithDetail("ErrBackupMatch", "ssl", nil) } } return nil diff --git a/agent/app/service/clam.go b/agent/app/service/clam.go index 45bca8848..2fe2095b3 100644 --- a/agent/app/service/clam.go +++ b/agent/app/service/clam.go @@ -25,8 +25,6 @@ import ( "github.com/1Panel-dev/1Panel/agent/utils/xpack" "github.com/jinzhu/copier" "github.com/robfig/cron/v3" - - "github.com/pkg/errors" ) const ( @@ -139,7 +137,7 @@ func (c *ClamService) SearchWithPage(req dto.SearchClamWithPage) (int64, interfa for _, command := range commands { var item dto.ClamInfo if err := copier.Copy(&item, &command); err != nil { - return 0, nil, errors.WithMessage(constant.ErrStructTransform, err.Error()) + return 0, nil, buserr.WithDetail("ErrStructTransform", err.Error(), nil) } item.LastHandleDate = "-" datas = append(datas, item) @@ -174,10 +172,10 @@ func (c *ClamService) SearchWithPage(req dto.SearchClamWithPage) (int64, interfa func (c *ClamService) Create(req dto.ClamCreate) error { clam, _ := clamRepo.Get(repo.WithByName(req.Name)) if clam.ID != 0 { - return constant.ErrRecordExist + return buserr.New("ErrRecordExist") } if err := copier.Copy(&clam, &req); err != nil { - return errors.WithMessage(constant.ErrStructTransform, err.Error()) + return buserr.WithDetail("ErrStructTransform", err.Error(), nil) } if clam.InfectedStrategy == "none" || clam.InfectedStrategy == "remove" { clam.InfectedDir = "" @@ -211,14 +209,14 @@ func (c *ClamService) Create(req dto.ClamCreate) error { func (c *ClamService) Update(req dto.ClamUpdate) error { clam, _ := clamRepo.Get(repo.WithByName(req.Name)) if clam.ID == 0 { - return constant.ErrRecordNotFound + return buserr.New("ErrRecordNotFound") } if req.InfectedStrategy == "none" || req.InfectedStrategy == "remove" { req.InfectedDir = "" } var clamItem model.Clam if err := copier.Copy(&clamItem, &req); err != nil { - return errors.WithMessage(constant.ErrStructTransform, err.Error()) + return buserr.WithDetail("ErrStructTransform", err.Error(), nil) } clamItem.EntryID = clam.EntryID upMap := map[string]interface{}{} @@ -266,7 +264,7 @@ func (c *ClamService) Update(req dto.ClamUpdate) error { func (c *ClamService) UpdateStatus(id uint, status string) error { clam, _ := clamRepo.Get(repo.WithByID(id)) if clam.ID == 0 { - return constant.ErrRecordNotFound + return buserr.New("ErrRecordNotFound") } var ( entryID int @@ -292,7 +290,7 @@ func (c *ClamService) Delete(req dto.ClamDelete) error { continue } if req.RemoveRecord { - _ = os.RemoveAll(path.Join(global.CONF.System.DataDir, resultDir, clam.Name)) + _ = os.RemoveAll(path.Join(global.Dir.DataDir, resultDir, clam.Name)) } if req.RemoveInfected { _ = os.RemoveAll(path.Join(clam.InfectedDir, "1panel-infected", clam.Name)) @@ -318,13 +316,13 @@ func (c *ClamService) HandleOnce(req dto.OperateByID) error { } clam, _ := clamRepo.Get(repo.WithByID(req.ID)) if clam.ID == 0 { - return constant.ErrRecordNotFound + return buserr.New("ErrRecordNotFound") } if cmd.CheckIllegal(clam.Path) { - return buserr.New(constant.ErrCmdIllegal) + return buserr.New("ErrCmdIllegal") } timeNow := time.Now().Format(constant.DateTimeSlimLayout) - logFile := path.Join(global.CONF.System.DataDir, resultDir, clam.Name, timeNow) + logFile := path.Join(global.Dir.DataDir, resultDir, clam.Name, timeNow) if _, err := os.Stat(path.Dir(logFile)); err != nil { _ = os.MkdirAll(path.Dir(logFile), os.ModePerm) } @@ -359,7 +357,7 @@ func (c *ClamService) HandleOnce(req dto.OperateByID) error { func (c *ClamService) LoadRecords(req dto.ClamLogSearch) (int64, interface{}, error) { clam, _ := clamRepo.Get(repo.WithByID(req.ClamID)) if clam.ID == 0 { - return 0, nil, constant.ErrRecordNotFound + return 0, nil, buserr.New("ErrRecordNotFound") } logPaths := loadFileByName(clam.Name) if len(logPaths) == 0 { @@ -398,13 +396,13 @@ func (c *ClamService) LoadRecords(req dto.ClamLogSearch) (int64, interface{}, er var datas []dto.ClamLog for i := 0; i < len(records); i++ { - item := loadResultFromLog(path.Join(global.CONF.System.DataDir, resultDir, clam.Name, records[i])) + item := loadResultFromLog(path.Join(global.Dir.DataDir, resultDir, clam.Name, records[i])) datas = append(datas, item) } return int64(total), datas, nil } func (c *ClamService) LoadRecordLog(req dto.ClamLogReq) (string, error) { - logPath := path.Join(global.CONF.System.DataDir, resultDir, req.ClamName, req.RecordName) + logPath := path.Join(global.Dir.DataDir, resultDir, req.ClamName, req.RecordName) var tail string if req.Tail != "0" { tail = req.Tail @@ -422,9 +420,9 @@ func (c *ClamService) LoadRecordLog(req dto.ClamLogReq) (string, error) { func (c *ClamService) CleanRecord(req dto.OperateByID) error { clam, _ := clamRepo.Get(repo.WithByID(req.ID)) if clam.ID == 0 { - return constant.ErrRecordNotFound + return buserr.New("ErrRecordNotFound") } - pathItem := path.Join(global.CONF.System.DataDir, resultDir, clam.Name) + pathItem := path.Join(global.Dir.DataDir, resultDir, clam.Name) _ = os.RemoveAll(pathItem) return nil } @@ -544,7 +542,7 @@ func StopAllCronJob(withCheck bool) bool { func loadFileByName(name string) []string { var logPaths []string - pathItem := path.Join(global.CONF.System.DataDir, resultDir, name) + pathItem := path.Join(global.Dir.DataDir, resultDir, name) _ = filepath.Walk(pathItem, func(path string, info os.FileInfo, err error) error { if err != nil { return nil diff --git a/agent/app/service/compose_template.go b/agent/app/service/compose_template.go index f5c143d45..8aaea8bc7 100644 --- a/agent/app/service/compose_template.go +++ b/agent/app/service/compose_template.go @@ -3,9 +3,8 @@ package service import ( "github.com/1Panel-dev/1Panel/agent/app/dto" "github.com/1Panel-dev/1Panel/agent/app/repo" - "github.com/1Panel-dev/1Panel/agent/constant" + "github.com/1Panel-dev/1Panel/agent/buserr" "github.com/jinzhu/copier" - "github.com/pkg/errors" ) type ComposeTemplateService struct{} @@ -25,13 +24,13 @@ func NewIComposeTemplateService() IComposeTemplateService { func (u *ComposeTemplateService) List() ([]dto.ComposeTemplateInfo, error) { composes, err := composeRepo.List() if err != nil { - return nil, constant.ErrRecordNotFound + return nil, buserr.New("ErrRecordNotFound") } var dtoLists []dto.ComposeTemplateInfo for _, compose := range composes { var item dto.ComposeTemplateInfo if err := copier.Copy(&item, &compose); err != nil { - return nil, errors.WithMessage(constant.ErrStructTransform, err.Error()) + return nil, buserr.WithDetail("ErrStructTransform", err.Error(), nil) } dtoLists = append(dtoLists, item) } @@ -44,7 +43,7 @@ func (u *ComposeTemplateService) SearchWithPage(req dto.SearchWithPage) (int64, for _, compose := range composes { var item dto.ComposeTemplateInfo if err := copier.Copy(&item, &compose); err != nil { - return 0, nil, errors.WithMessage(constant.ErrStructTransform, err.Error()) + return 0, nil, buserr.WithDetail("ErrStructTransform", err.Error(), nil) } dtoComposeTemplates = append(dtoComposeTemplates, item) } @@ -54,10 +53,10 @@ func (u *ComposeTemplateService) SearchWithPage(req dto.SearchWithPage) (int64, func (u *ComposeTemplateService) Create(composeDto dto.ComposeTemplateCreate) error { compose, _ := composeRepo.Get(repo.WithByName(composeDto.Name)) if compose.ID != 0 { - return constant.ErrRecordExist + return buserr.New("ErrRecordExist") } if err := copier.Copy(&compose, &composeDto); err != nil { - return errors.WithMessage(constant.ErrStructTransform, err.Error()) + return buserr.WithDetail("ErrStructTransform", err.Error(), nil) } if err := composeRepo.Create(&compose); err != nil { return err @@ -69,7 +68,7 @@ func (u *ComposeTemplateService) Delete(ids []uint) error { if len(ids) == 1 { compose, _ := composeRepo.Get(repo.WithByID(ids[0])) if compose.ID == 0 { - return constant.ErrRecordNotFound + return buserr.New("ErrRecordNotFound") } return composeRepo.Delete(repo.WithByID(ids[0])) } diff --git a/agent/app/service/container.go b/agent/app/service/container.go index e667bc798..9b6ddb3f7 100644 --- a/agent/app/service/container.go +++ b/agent/app/service/container.go @@ -317,7 +317,7 @@ func (u *ContainerService) ContainerListStats() ([]dto.ContainerListStats, error func (u *ContainerService) ContainerCreateByCommand(req dto.ContainerCreateByCommand) error { if cmd.CheckIllegal(req.Command) { - return buserr.New(constant.ErrCmdIllegal) + return buserr.New("ErrCmdIllegal") } if !strings.HasPrefix(strings.TrimSpace(req.Command), "docker run ") { return errors.New("error command format") @@ -343,7 +343,7 @@ func (u *ContainerService) ContainerCreateByCommand(req dto.ContainerCreateByCom } go func() { taskItem.AddSubTask(i18n.GetWithName("ContainerCreate", containerName), func(t *task.Task) error { - logPath := path.Join(constant.LogDir, task.TaskScopeContainer, req.TaskID+".log") + logPath := path.Join(global.Dir.LogDir, task.TaskScopeContainer, req.TaskID+".log") return cmd.ExecShell(logPath, 5*time.Minute, "bash", "-c", req.Command) }, nil) _ = taskItem.Execute() @@ -466,7 +466,7 @@ func (u *ContainerService) ContainerCreate(req dto.ContainerOperate) error { ctx := context.Background() newContainer, _ := client.ContainerInspect(ctx, req.Name) if newContainer.ContainerJSONBase != nil { - return buserr.New(constant.ErrContainerName) + return buserr.New("ErrContainerName") } taskItem, err := task.NewTaskWithOps(req.Name, task.TaskCreate, task.TaskScopeContainer, req.TaskID, 1) @@ -605,7 +605,7 @@ func (u *ContainerService) ContainerUpdate(req dto.ContainerOperate) error { ctx := context.Background() newContainer, _ := client.ContainerInspect(ctx, req.Name) if newContainer.ContainerJSONBase != nil && newContainer.ID != req.ContainerID { - return buserr.New(constant.ErrContainerName) + return buserr.New("ErrContainerName") } oldContainer, err := client.ContainerInspect(ctx, req.ContainerID) @@ -702,7 +702,7 @@ func (u *ContainerService) ContainerRename(req dto.ContainerRename) error { newContainer, _ := client.ContainerInspect(ctx, req.NewName) if newContainer.ContainerJSONBase != nil { - return buserr.New(constant.ErrContainerName) + return buserr.New("ErrContainerName") } return client.ContainerRename(ctx, req.Name, req.NewName) } @@ -890,7 +890,7 @@ func collectLogs(params dto.StreamLog, messageChan chan<- string, errorChan chan func (u *ContainerService) DownloadContainerLogs(containerType, container, since, tail string, c *gin.Context) error { if cmd.CheckIllegal(container, since, tail) { - return buserr.New(constant.ErrCmdIllegal) + return buserr.New("ErrCmdIllegal") } commandName := "docker" commandArg := []string{"logs", container} @@ -1192,17 +1192,17 @@ func checkPortStats(ports []dto.PortHelper) (nat.PortMap, error) { for _, port := range ports { if strings.Contains(port.ContainerPort, "-") { if !strings.Contains(port.HostPort, "-") { - return portMap, buserr.New(constant.ErrPortRules) + return portMap, buserr.New("ErrPortRules") } hostStart, _ := strconv.Atoi(strings.Split(port.HostPort, "-")[0]) hostEnd, _ := strconv.Atoi(strings.Split(port.HostPort, "-")[1]) containerStart, _ := strconv.Atoi(strings.Split(port.ContainerPort, "-")[0]) containerEnd, _ := strconv.Atoi(strings.Split(port.ContainerPort, "-")[1]) if (hostEnd-hostStart) <= 0 || (containerEnd-containerStart) <= 0 { - return portMap, buserr.New(constant.ErrPortRules) + return portMap, buserr.New("ErrPortRules") } if (containerEnd - containerStart) != (hostEnd - hostStart) { - return portMap, buserr.New(constant.ErrPortRules) + return portMap, buserr.New("ErrPortRules") } for i := 0; i <= hostEnd-hostStart; i++ { bindItem := nat.PortBinding{HostPort: strconv.Itoa(hostStart + i), HostIP: port.HostIP} @@ -1210,7 +1210,7 @@ func checkPortStats(ports []dto.PortHelper) (nat.PortMap, error) { } for i := hostStart; i <= hostEnd; i++ { if common.ScanPort(i) { - return portMap, buserr.WithDetail(constant.ErrPortInUsed, i, nil) + return portMap, buserr.WithDetail("ErrPortInUsed", i, nil) } } } else { @@ -1221,7 +1221,7 @@ func checkPortStats(ports []dto.PortHelper) (nat.PortMap, error) { portItem, _ = strconv.Atoi(port.HostPort) } if common.ScanPort(portItem) { - return portMap, buserr.WithDetail(constant.ErrPortInUsed, portItem, nil) + return portMap, buserr.WithDetail("ErrPortInUsed", portItem, nil) } bindItem := nat.PortBinding{HostPort: strconv.Itoa(portItem), HostIP: port.HostIP} portMap[nat.Port(fmt.Sprintf("%s/%s", port.ContainerPort, port.Protocol))] = []nat.PortBinding{bindItem} diff --git a/agent/app/service/container_compose.go b/agent/app/service/container_compose.go index 3eafecfa0..edcf15e52 100644 --- a/agent/app/service/container_compose.go +++ b/agent/app/service/container_compose.go @@ -4,7 +4,6 @@ import ( "bufio" "errors" "fmt" - "github.com/1Panel-dev/1Panel/agent/app/repo" "os" "os/exec" "path" @@ -12,6 +11,8 @@ import ( "strings" "time" + "github.com/1Panel-dev/1Panel/agent/app/repo" + "github.com/docker/docker/api/types/container" "github.com/1Panel-dev/1Panel/agent/app/dto" @@ -161,11 +162,11 @@ func (u *ContainerService) PageCompose(req dto.SearchWithPage) (int64, interface func (u *ContainerService) TestCompose(req dto.ComposeCreate) (bool, error) { if cmd.CheckIllegal(req.Path) { - return false, buserr.New(constant.ErrCmdIllegal) + return false, buserr.New("ErrCmdIllegal") } composeItem, _ := composeRepo.GetRecord(repo.WithByName(req.Name)) if composeItem.ID != 0 { - return false, constant.ErrRecordExist + return false, buserr.New("ErrRecordExist") } if err := u.loadPath(&req); err != nil { return false, err @@ -183,7 +184,7 @@ func (u *ContainerService) TestCompose(req dto.ComposeCreate) (bool, error) { func (u *ContainerService) CreateCompose(req dto.ComposeCreate) error { if cmd.CheckIllegal(req.Name, req.Path) { - return buserr.New(constant.ErrCmdIllegal) + return buserr.New("ErrCmdIllegal") } if err := u.loadPath(&req); err != nil { return err @@ -222,7 +223,7 @@ func (u *ContainerService) ComposeOperation(req dto.ComposeOperation) error { return nil } if cmd.CheckIllegal(req.Path, req.Operation) { - return buserr.New(constant.ErrCmdIllegal) + return buserr.New("ErrCmdIllegal") } if _, err := os.Stat(req.Path); err != nil { return fmt.Errorf("load file with path %s failed, %v", req.Path, err) @@ -259,7 +260,7 @@ func (u *ContainerService) ComposeOperation(req dto.ComposeOperation) error { func (u *ContainerService) ComposeUpdate(req dto.ComposeUpdate) error { if cmd.CheckIllegal(req.Name, req.Path) { - return buserr.New(constant.ErrCmdIllegal) + return buserr.New("ErrCmdIllegal") } oldFile, err := os.ReadFile(req.Path) if err != nil { @@ -291,7 +292,7 @@ func (u *ContainerService) ComposeUpdate(req dto.ComposeUpdate) error { func (u *ContainerService) loadPath(req *dto.ComposeCreate) error { if req.From == "template" || req.From == "edit" { - dir := fmt.Sprintf("%s/docker/compose/%s", constant.DataDir, req.Name) + dir := fmt.Sprintf("%s/docker/compose/%s", global.Dir.DataDir, req.Name) if _, err := os.Stat(dir); err != nil && os.IsNotExist(err) { if err = os.MkdirAll(dir, os.ModePerm); err != nil { return err diff --git a/agent/app/service/container_network.go b/agent/app/service/container_network.go index 2e5e01028..ef5ac9c83 100644 --- a/agent/app/service/container_network.go +++ b/agent/app/service/container_network.go @@ -8,7 +8,6 @@ import ( "github.com/1Panel-dev/1Panel/agent/app/dto" "github.com/1Panel-dev/1Panel/agent/buserr" - "github.com/1Panel-dev/1Panel/agent/constant" "github.com/1Panel-dev/1Panel/agent/utils/docker" "github.com/docker/docker/api/types/network" ) @@ -105,7 +104,7 @@ func (u *ContainerService) DeleteNetwork(req dto.BatchDelete) error { for _, id := range req.Names { if err := client.NetworkRemove(context.TODO(), id); err != nil { if strings.Contains(err.Error(), "has active endpoints") { - return buserr.WithDetail(constant.ErrInUsed, id, nil) + return buserr.WithDetail("ErrInUsed", id, nil) } return err } diff --git a/agent/app/service/container_volume.go b/agent/app/service/container_volume.go index 5ba34dfe6..e9fcf389c 100644 --- a/agent/app/service/container_volume.go +++ b/agent/app/service/container_volume.go @@ -8,7 +8,6 @@ import ( "github.com/1Panel-dev/1Panel/agent/app/dto" "github.com/1Panel-dev/1Panel/agent/buserr" - "github.com/1Panel-dev/1Panel/agent/constant" "github.com/1Panel-dev/1Panel/agent/utils/common" "github.com/1Panel-dev/1Panel/agent/utils/docker" "github.com/docker/docker/api/types/filters" @@ -107,7 +106,7 @@ func (u *ContainerService) DeleteVolume(req dto.BatchDelete) error { for _, id := range req.Names { if err := client.VolumeRemove(context.TODO(), id, true); err != nil { if strings.Contains(err.Error(), "volume is in use") { - return buserr.WithDetail(constant.ErrInUsed, id, nil) + return buserr.WithDetail("ErrInUsed", id, nil) } return err } @@ -126,7 +125,7 @@ func (u *ContainerService) CreateVolume(req dto.VolumeCreate) error { if len(vos.Volumes) != 0 { for _, v := range vos.Volumes { if v.Name == req.Name { - return constant.ErrRecordExist + return buserr.New("ErrRecordExist") } } } diff --git a/agent/app/service/cronjob.go b/agent/app/service/cronjob.go index 8aee0698f..f14a1aae6 100644 --- a/agent/app/service/cronjob.go +++ b/agent/app/service/cronjob.go @@ -10,6 +10,7 @@ import ( "time" "github.com/1Panel-dev/1Panel/agent/app/repo" + "github.com/1Panel-dev/1Panel/agent/buserr" "github.com/1Panel-dev/1Panel/agent/utils/xpack" "github.com/1Panel-dev/1Panel/agent/app/dto" @@ -49,7 +50,7 @@ func (u *CronjobService) SearchWithPage(search dto.PageCronjob) (int64, interfac for _, cronjob := range cronjobs { var item dto.CronjobInfo if err := copier.Copy(&item, &cronjob); err != nil { - return 0, nil, errors.WithMessage(constant.ErrStructTransform, err.Error()) + return 0, nil, buserr.WithDetail("ErrStructTransform", err.Error(), nil) } record, _ := cronjobRepo.RecordFirst(cronjob.ID) if record.ID != 0 { @@ -85,7 +86,7 @@ func (u *CronjobService) SearchRecords(search dto.SearchRecord) (int64, interfac for _, record := range records { var item dto.Record if err := copier.Copy(&item, &record); err != nil { - return 0, nil, errors.WithMessage(constant.ErrStructTransform, err.Error()) + return 0, nil, buserr.WithDetail("ErrStructTransform", err.Error(), nil) } item.StartTime = record.StartTime.Format(constant.DateTimeLayout) dtoCronjobs = append(dtoCronjobs, item) @@ -165,7 +166,7 @@ func (u *CronjobService) CleanRecord(req dto.CronjobClean) error { func (u *CronjobService) Download(req dto.CronjobDownload) (string, error) { record, _ := cronjobRepo.GetRecord(repo.WithByID(req.RecordID)) if record.ID == 0 { - return "", constant.ErrRecordNotFound + return "", buserr.New("ErrRecordNotFound") } account, client, err := NewBackupClientWithID(req.BackupAccountID) if err != nil { @@ -177,7 +178,7 @@ func (u *CronjobService) Download(req dto.CronjobDownload) (string, error) { } return record.File, nil } - tempPath := fmt.Sprintf("%s/download/%s", constant.DataDir, record.File) + tempPath := fmt.Sprintf("%s/download/%s", global.Dir.DataDir, record.File) if _, err := os.Stat(tempPath); err != nil && os.IsNotExist(err) { _ = os.MkdirAll(path.Dir(tempPath), os.ModePerm) isOK, err := client.Download(record.File, tempPath) @@ -191,7 +192,7 @@ func (u *CronjobService) Download(req dto.CronjobDownload) (string, error) { func (u *CronjobService) HandleOnce(id uint) error { cronjob, _ := cronjobRepo.Get(repo.WithByID(id)) if cronjob.ID == 0 { - return constant.ErrRecordNotFound + return buserr.New("ErrRecordNotFound") } u.HandleJob(&cronjob) return nil @@ -200,11 +201,11 @@ func (u *CronjobService) HandleOnce(id uint) error { func (u *CronjobService) Create(req dto.CronjobCreate) error { cronjob, _ := cronjobRepo.Get(repo.WithByName(req.Name)) if cronjob.ID != 0 { - return constant.ErrRecordExist + return buserr.New("ErrRecordExist") } cronjob.Secret = req.Secret if err := copier.Copy(&cronjob, &req); err != nil { - return errors.WithMessage(constant.ErrStructTransform, err.Error()) + return buserr.WithDetail("ErrStructTransform", err.Error(), nil) } cronjob.Status = constant.StatusEnable @@ -289,11 +290,11 @@ func (u *CronjobService) Delete(req dto.CronjobBatchDelete) error { func (u *CronjobService) Update(id uint, req dto.CronjobUpdate) error { var cronjob model.Cronjob if err := copier.Copy(&cronjob, &req); err != nil { - return errors.WithMessage(constant.ErrStructTransform, err.Error()) + return buserr.WithDetail("ErrStructTransform", err.Error(), nil) } cronModel, err := cronjobRepo.Get(repo.WithByID(id)) if err != nil { - return constant.ErrRecordNotFound + return buserr.New("ErrRecordNotFound") } upMap := make(map[string]interface{}) cronjob.EntryIDs = cronModel.EntryIDs @@ -354,7 +355,7 @@ func (u *CronjobService) Update(id uint, req dto.CronjobUpdate) error { func (u *CronjobService) UpdateStatus(id uint, status string) error { cronjob, _ := cronjobRepo.Get(repo.WithByID(id)) if cronjob.ID == 0 { - return errors.WithMessage(constant.ErrRecordNotFound, "record not found") + return errors.WithMessage(buserr.New("ErrRecordNotFound"), "record not found") } var ( entryIDs string @@ -391,7 +392,7 @@ func (u *CronjobService) AddCronJob(cronjob *model.Cronjob) (int, error) { } func mkdirAndWriteFile(cronjob *model.Cronjob, startTime time.Time, msg []byte) (string, error) { - dir := fmt.Sprintf("%s/task/%s/%s", constant.DataDir, cronjob.Type, cronjob.Name) + dir := fmt.Sprintf("%s/task/%s/%s", global.Dir.DataDir, cronjob.Type, cronjob.Name) if _, err := os.Stat(dir); err != nil && os.IsNotExist(err) { if err = os.MkdirAll(dir, os.ModePerm); err != nil { return "", err diff --git a/agent/app/service/cronjob_backup.go b/agent/app/service/cronjob_backup.go index 14e0255ea..511609e90 100644 --- a/agent/app/service/cronjob_backup.go +++ b/agent/app/service/cronjob_backup.go @@ -2,13 +2,14 @@ package service import ( "fmt" - "github.com/1Panel-dev/1Panel/agent/app/repo" "os" "path" "strconv" "strings" "time" + "github.com/1Panel-dev/1Panel/agent/app/repo" + "github.com/1Panel-dev/1Panel/agent/app/dto" "github.com/1Panel-dev/1Panel/agent/app/model" "github.com/1Panel-dev/1Panel/agent/constant" @@ -45,7 +46,7 @@ func (u *CronjobService) handleApp(cronjob model.Cronjob, startTime time.Time, t record.Name = app.App.Key record.DetailName = app.Name record.DownloadAccountID, record.SourceAccountIDs = cronjob.DownloadAccountID, cronjob.SourceAccountIDs - backupDir := path.Join(global.CONF.System.TmpDir, fmt.Sprintf("app/%s/%s", app.App.Key, app.Name)) + backupDir := path.Join(global.Dir.TmpDir, fmt.Sprintf("app/%s/%s", app.App.Key, app.Name)) record.FileName = fmt.Sprintf("app_%s_%s.tar.gz", app.Name, startTime.Format(constant.DateTimeSlimLayout)+common.RandStrAndNum(5)) if err := handleAppBackup(&app, nil, backupDir, record.FileName, cronjob.ExclusionRules, cronjob.Secret, taskID); err != nil { return err @@ -81,7 +82,7 @@ func (u *CronjobService) handleWebsite(cronjob model.Cronjob, startTime time.Tim record.Name = web.PrimaryDomain record.DetailName = web.Alias record.DownloadAccountID, record.SourceAccountIDs = cronjob.DownloadAccountID, cronjob.SourceAccountIDs - backupDir := path.Join(global.CONF.System.TmpDir, fmt.Sprintf("website/%s", web.PrimaryDomain)) + backupDir := path.Join(global.Dir.TmpDir, fmt.Sprintf("website/%s", web.PrimaryDomain)) record.FileName = fmt.Sprintf("website_%s_%s.tar.gz", web.PrimaryDomain, startTime.Format(constant.DateTimeSlimLayout)+common.RandStrAndNum(5)) if err := handleWebsiteBackup(&web, backupDir, record.FileName, cronjob.ExclusionRules, cronjob.Secret, taskID); err != nil { return err @@ -118,7 +119,7 @@ func (u *CronjobService) handleDatabase(cronjob model.Cronjob, startTime time.Ti record.DetailName = dbInfo.Name record.DownloadAccountID, record.SourceAccountIDs = cronjob.DownloadAccountID, cronjob.SourceAccountIDs - backupDir := path.Join(global.CONF.System.TmpDir, fmt.Sprintf("database/%s/%s/%s", dbInfo.DBType, record.Name, dbInfo.Name)) + backupDir := path.Join(global.Dir.TmpDir, fmt.Sprintf("database/%s/%s/%s", dbInfo.DBType, record.Name, dbInfo.Name)) record.FileName = fmt.Sprintf("db_%s_%s.sql.gz", dbInfo.Name, startTime.Format(constant.DateTimeSlimLayout)+common.RandStrAndNum(5)) if cronjob.DBType == "mysql" || cronjob.DBType == "mariadb" { if err := handleMysqlBackup(dbInfo, nil, backupDir, record.FileName, taskID); err != nil { @@ -149,7 +150,7 @@ func (u *CronjobService) handleDirectory(cronjob model.Cronjob, startTime time.T return err } fileName := fmt.Sprintf("directory%s_%s.tar.gz", strings.ReplaceAll(cronjob.SourceDir, "/", "_"), startTime.Format(constant.DateTimeSlimLayout)+common.RandStrAndNum(5)) - backupDir := path.Join(global.CONF.System.TmpDir, fmt.Sprintf("%s/%s", cronjob.Type, cronjob.Name)) + backupDir := path.Join(global.Dir.TmpDir, fmt.Sprintf("%s/%s", cronjob.Type, cronjob.Name)) fileOp := files.NewFileOp() if cronjob.IsDir { @@ -189,7 +190,7 @@ func (u *CronjobService) handleSystemLog(cronjob model.Cronjob, startTime time.T } nameItem := startTime.Format(constant.DateTimeSlimLayout) + common.RandStrAndNum(5) fileName := fmt.Sprintf("system_log_%s.tar.gz", nameItem) - backupDir := path.Join(global.CONF.System.TmpDir, "log", nameItem) + backupDir := path.Join(global.Dir.TmpDir, "log", nameItem) if err := handleBackupLogs(backupDir, fileName, cronjob.Secret); err != nil { return err } @@ -362,7 +363,7 @@ func handleBackupLogs(targetDir, fileName string, secret string) error { } } } - itemDir2 := path.Join(global.CONF.System.Backup, "log/website", website.Alias) + itemDir2 := path.Join(global.Dir.LocalBackupDir, "log/website", website.Alias) logFiles2, _ := os.ReadDir(itemDir2) if len(logFiles2) != 0 { for i := 0; i < len(logFiles2); i++ { @@ -375,18 +376,17 @@ func handleBackupLogs(targetDir, fileName string, secret string) error { global.LOG.Debug("backup website log successful!") } - systemLogDir := path.Join(global.CONF.System.BaseDir, "1panel/log") systemDir := path.Join(targetDir, "system") if _, err := os.Stat(systemDir); err != nil && os.IsNotExist(err) { if err = os.MkdirAll(systemDir, os.ModePerm); err != nil { return err } } - systemLogFiles, _ := os.ReadDir(systemLogDir) + systemLogFiles, _ := os.ReadDir(global.Dir.LogDir) if len(systemLogFiles) != 0 { for i := 0; i < len(systemLogFiles); i++ { if !systemLogFiles[i].IsDir() { - _ = fileOp.CopyFile(path.Join(systemLogDir, systemLogFiles[i].Name()), systemDir) + _ = fileOp.CopyFile(path.Join(global.Dir.LogDir, systemLogFiles[i].Name()), systemDir) } } } diff --git a/agent/app/service/cronjob_helper.go b/agent/app/service/cronjob_helper.go index 1600a1125..1153ada39 100644 --- a/agent/app/service/cronjob_helper.go +++ b/agent/app/service/cronjob_helper.go @@ -104,7 +104,7 @@ func (u *CronjobService) handleShell(cronjob model.Cronjob, taskID string) error cronjob.Executor = "bash" } if cronjob.ScriptMode == "input" { - fileItem := pathUtils.Join(global.CONF.System.BaseDir, "1panel", "task", "shell", cronjob.Name, cronjob.Name+".sh") + fileItem := pathUtils.Join(global.Dir.DataDir, "task", "shell", cronjob.Name, cronjob.Name+".sh") _ = os.MkdirAll(pathUtils.Dir(fileItem), os.ModePerm) shellFile, err := os.OpenFile(fileItem, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, constant.FilePerm) if err != nil { @@ -192,7 +192,7 @@ func (u *CronjobService) handleCutWebsiteLog(cronjob *model.Cronjob, startTime t websiteLogDir := pathUtils.Join(baseDir, website.Alias, "log") srcAccessLogPath := pathUtils.Join(websiteLogDir, "access.log") srcErrorLogPath := pathUtils.Join(websiteLogDir, "error.log") - dstLogDir := pathUtils.Join(global.CONF.System.Backup, "log", "website", website.Alias) + dstLogDir := pathUtils.Join(global.Dir.LocalBackupDir, "log", "website", website.Alias) if !fileOp.Stat(dstLogDir) { _ = os.MkdirAll(dstLogDir, constant.DirPerm) } @@ -251,7 +251,7 @@ func (u *CronjobService) uploadCronjobBackFile(cronjob model.Cronjob, accountMap _ = os.Remove(file) }() accounts := strings.Split(cronjob.SourceAccountIDs, ",") - cloudSrc := strings.TrimPrefix(file, global.CONF.System.TmpDir+"/") + cloudSrc := strings.TrimPrefix(file, global.Dir.TmpDir+"/") for _, account := range accounts { if len(account) != 0 { global.LOG.Debugf("start upload file to %s, dir: %s", accountMap[account].name, pathUtils.Join(accountMap[account].backupPath, cloudSrc)) diff --git a/agent/app/service/dashboard.go b/agent/app/service/dashboard.go index 9c2bf6fa2..7a6c9c4ef 100644 --- a/agent/app/service/dashboard.go +++ b/agent/app/service/dashboard.go @@ -11,6 +11,7 @@ import ( "time" "github.com/1Panel-dev/1Panel/agent/app/repo" + "github.com/1Panel-dev/1Panel/agent/buserr" "github.com/1Panel-dev/1Panel/agent/app/dto" "github.com/1Panel-dev/1Panel/agent/app/model" @@ -62,12 +63,12 @@ func (u *DashboardService) Sync(req dto.SyncFromMaster) error { return launcherRepo.Create(&launcherItem) case "delete": if launcher.ID == 0 { - return constant.ErrRecordNotFound + return buserr.New("ErrRecordNotFound") } return launcherRepo.Delete(repo.WithByID(launcher.ID)) case "update": if launcher.ID == 0 { - return constant.ErrRecordNotFound + return buserr.New("ErrRecordNotFound") } launcherItem.ID = launcher.ID return launcherRepo.Save(&launcherItem) @@ -105,7 +106,7 @@ func (u *DashboardService) LoadOsInfo() (*dto.OsInfo, error) { baseInfo.KernelArch = hostInfo.KernelArch baseInfo.KernelVersion = hostInfo.KernelVersion - diskInfo, err := disk.Usage(global.CONF.System.BaseDir) + diskInfo, err := disk.Usage(global.Dir.BaseDir) if err == nil { baseInfo.DiskSize = int64(diskInfo.Free) } diff --git a/agent/app/service/database.go b/agent/app/service/database.go index 26598c2c7..66393af7a 100644 --- a/agent/app/service/database.go +++ b/agent/app/service/database.go @@ -3,10 +3,11 @@ package service import ( "context" "fmt" - "github.com/1Panel-dev/1Panel/agent/app/repo" "os" "path" + "github.com/1Panel-dev/1Panel/agent/app/repo" + "github.com/1Panel-dev/1Panel/agent/utils/postgresql" pgclient "github.com/1Panel-dev/1Panel/agent/utils/postgresql/client" redisclient "github.com/1Panel-dev/1Panel/agent/utils/redis" @@ -51,7 +52,7 @@ func (u *DatabaseService) SearchWithPage(search dto.DatabaseSearch) (int64, inte for _, db := range dbs { var item dto.DatabaseInfo if err := copier.Copy(&item, &db); err != nil { - return 0, nil, errors.WithMessage(constant.ErrStructTransform, err.Error()) + return 0, nil, buserr.WithDetail("ErrStructTransform", err.Error(), nil) } datas = append(datas, item) } @@ -65,7 +66,7 @@ func (u *DatabaseService) Get(name string) (dto.DatabaseInfo, error) { return data, err } if err := copier.Copy(&data, &remote); err != nil { - return data, errors.WithMessage(constant.ErrStructTransform, err.Error()) + return data, buserr.WithDetail("ErrStructTransform", err.Error(), nil) } return data, nil } @@ -79,7 +80,7 @@ func (u *DatabaseService) List(dbType string) ([]dto.DatabaseOption, error) { for _, db := range dbs { var item dto.DatabaseOption if err := copier.Copy(&item, &db); err != nil { - return nil, errors.WithMessage(constant.ErrStructTransform, err.Error()) + return nil, buserr.WithDetail("ErrStructTransform", err.Error(), nil) } item.Database = db.Name datas = append(datas, item) @@ -160,9 +161,9 @@ func (u *DatabaseService) Create(req dto.DatabaseCreate) error { db, _ := databaseRepo.Get(repo.WithByName(req.Name)) if db.ID != 0 { if db.From == "local" { - return buserr.New(constant.ErrLocalExist) + return buserr.New("ErrLocalExist") } - return constant.ErrRecordExist + return buserr.New("ErrRecordExist") } switch req.Type { case constant.AppPostgresql: @@ -206,7 +207,7 @@ func (u *DatabaseService) Create(req dto.DatabaseCreate) error { } if err := copier.Copy(&db, &req); err != nil { - return errors.WithMessage(constant.ErrStructTransform, err.Error()) + return buserr.WithDetail("ErrStructTransform", err.Error(), nil) } if err := databaseRepo.Create(context.Background(), &db); err != nil { return err @@ -230,15 +231,15 @@ func (u *DatabaseService) DeleteCheck(id uint) ([]string, error) { func (u *DatabaseService) Delete(req dto.DatabaseDelete) error { db, _ := databaseRepo.Get(repo.WithByID(req.ID)) if db.ID == 0 { - return constant.ErrRecordNotFound + return buserr.New("ErrRecordNotFound") } if req.DeleteBackup { - uploadDir := path.Join(global.CONF.System.BaseDir, fmt.Sprintf("1panel/uploads/database/%s/%s", db.Type, db.Name)) + uploadDir := path.Join(global.Dir.DataDir, fmt.Sprintf("uploads/database/%s/%s", db.Type, db.Name)) if _, err := os.Stat(uploadDir); err == nil { _ = os.RemoveAll(uploadDir) } - backupDir := path.Join(global.CONF.System.Backup, fmt.Sprintf("database/%s/%s", db.Type, db.Name)) + backupDir := path.Join(global.Dir.LocalBackupDir, fmt.Sprintf("database/%s/%s", db.Type, db.Name)) if _, err := os.Stat(backupDir); err == nil { _ = os.RemoveAll(backupDir) } diff --git a/agent/app/service/database_common.go b/agent/app/service/database_common.go index 6b7389714..f7cce94e6 100644 --- a/agent/app/service/database_common.go +++ b/agent/app/service/database_common.go @@ -43,17 +43,17 @@ func (u *DBCommonService) LoadDatabaseFile(req dto.OperationWithNameAndType) (st filePath := "" switch req.Type { case "mysql-conf": - filePath = path.Join(global.CONF.System.DataDir, fmt.Sprintf("apps/mysql/%s/conf/my.cnf", req.Name)) + filePath = path.Join(global.Dir.DataDir, fmt.Sprintf("apps/mysql/%s/conf/my.cnf", req.Name)) case "mariadb-conf": - filePath = path.Join(global.CONF.System.DataDir, fmt.Sprintf("apps/mariadb/%s/conf/my.cnf", req.Name)) + filePath = path.Join(global.Dir.DataDir, fmt.Sprintf("apps/mariadb/%s/conf/my.cnf", req.Name)) case "postgresql-conf": - filePath = path.Join(global.CONF.System.DataDir, fmt.Sprintf("apps/postgresql/%s/data/postgresql.conf", req.Name)) + filePath = path.Join(global.Dir.DataDir, fmt.Sprintf("apps/postgresql/%s/data/postgresql.conf", req.Name)) case "redis-conf": - filePath = path.Join(global.CONF.System.DataDir, fmt.Sprintf("apps/redis/%s/conf/redis.conf", req.Name)) + filePath = path.Join(global.Dir.DataDir, fmt.Sprintf("apps/redis/%s/conf/redis.conf", req.Name)) case "mysql-slow-logs": - filePath = path.Join(global.CONF.System.DataDir, fmt.Sprintf("apps/mysql/%s/data/1Panel-slow.log", req.Name)) + filePath = path.Join(global.Dir.DataDir, fmt.Sprintf("apps/mysql/%s/data/1Panel-slow.log", req.Name)) case "mariadb-slow-logs": - filePath = path.Join(global.CONF.System.DataDir, fmt.Sprintf("apps/mariadb/%s/db/data/1Panel-slow.log", req.Name)) + filePath = path.Join(global.Dir.DataDir, fmt.Sprintf("apps/mariadb/%s/db/data/1Panel-slow.log", req.Name)) } if _, err := os.Stat(filePath); err != nil { return "", buserr.New("ErrHttpReqNotFound") @@ -73,11 +73,11 @@ func (u *DBCommonService) UpdateConfByFile(req dto.DBConfUpdateByFile) error { path := "" switch req.Type { case constant.AppMariaDB, constant.AppMysql: - path = fmt.Sprintf("%s/%s/%s/conf/my.cnf", constant.AppInstallDir, req.Type, app.Name) + path = fmt.Sprintf("%s/%s/%s/conf/my.cnf", global.Dir.AppInstallDir, req.Type, app.Name) case constant.AppPostgresql: - path = fmt.Sprintf("%s/%s/%s/data/postgresql.conf", constant.AppInstallDir, req.Type, app.Name) + path = fmt.Sprintf("%s/%s/%s/data/postgresql.conf", global.Dir.AppInstallDir, req.Type, app.Name) case constant.AppRedis: - path = fmt.Sprintf("%s/%s/%s/conf/redis.conf", constant.AppInstallDir, req.Type, app.Name) + path = fmt.Sprintf("%s/%s/%s/conf/redis.conf", global.Dir.AppInstallDir, req.Type, app.Name) } file, err := os.OpenFile(path, os.O_WRONLY|os.O_TRUNC, 0640) if err != nil { @@ -87,7 +87,7 @@ func (u *DBCommonService) UpdateConfByFile(req dto.DBConfUpdateByFile) error { write := bufio.NewWriter(file) _, _ = write.WriteString(req.File) write.Flush() - if _, err := compose.Restart(fmt.Sprintf("%s/%s/%s/docker-compose.yml", constant.AppInstallDir, req.Type, app.Name)); err != nil { + if _, err := compose.Restart(fmt.Sprintf("%s/%s/%s/docker-compose.yml", global.Dir.AppInstallDir, req.Type, app.Name)); err != nil { return err } return nil diff --git a/agent/app/service/database_mysql.go b/agent/app/service/database_mysql.go index 16fff8cce..5897cbaec 100644 --- a/agent/app/service/database_mysql.go +++ b/agent/app/service/database_mysql.go @@ -4,7 +4,6 @@ import ( "context" "encoding/json" "fmt" - "github.com/1Panel-dev/1Panel/agent/app/repo" "os" "os/exec" "path" @@ -13,6 +12,8 @@ import ( "strings" "time" + "github.com/1Panel-dev/1Panel/agent/app/repo" + "github.com/1Panel-dev/1Panel/agent/app/dto" "github.com/1Panel-dev/1Panel/agent/app/model" "github.com/1Panel-dev/1Panel/agent/buserr" @@ -63,7 +64,7 @@ func (u *MysqlService) SearchWithPage(search dto.MysqlDBSearch) (int64, interfac for _, mysql := range mysqls { var item dto.MysqlDBInfo if err := copier.Copy(&item, &mysql); err != nil { - return 0, nil, errors.WithMessage(constant.ErrStructTransform, err.Error()) + return 0, nil, buserr.WithDetail("ErrStructTransform", err.Error(), nil) } dtoMysqls = append(dtoMysqls, item) } @@ -84,7 +85,7 @@ func (u *MysqlService) ListDBOption() ([]dto.MysqlOption, error) { for _, mysql := range mysqls { var item dto.MysqlOption if err := copier.Copy(&item, &mysql); err != nil { - return nil, errors.WithMessage(constant.ErrStructTransform, err.Error()) + return nil, buserr.WithDetail("ErrStructTransform", err.Error(), nil) } item.Database = mysql.MysqlName for _, database := range databases { @@ -99,17 +100,17 @@ func (u *MysqlService) ListDBOption() ([]dto.MysqlOption, error) { func (u *MysqlService) Create(ctx context.Context, req dto.MysqlDBCreate) (*model.DatabaseMysql, error) { if cmd.CheckIllegal(req.Name, req.Username, req.Password, req.Format, req.Permission) { - return nil, buserr.New(constant.ErrCmdIllegal) + return nil, buserr.New("ErrCmdIllegal") } mysql, _ := mysqlRepo.Get(repo.WithByName(req.Name), mysqlRepo.WithByMysqlName(req.Database), repo.WithByFrom(req.From)) if mysql.ID != 0 { - return nil, constant.ErrRecordExist + return nil, buserr.New("ErrRecordExist") } var createItem model.DatabaseMysql if err := copier.Copy(&createItem, &req); err != nil { - return nil, errors.WithMessage(constant.ErrStructTransform, err.Error()) + return nil, buserr.WithDetail("ErrStructTransform", err.Error(), nil) } if req.From == "local" && req.Username == "root" { @@ -143,7 +144,7 @@ func (u *MysqlService) Create(ctx context.Context, req dto.MysqlDBCreate) (*mode func (u *MysqlService) BindUser(req dto.BindUser) error { if cmd.CheckIllegal(req.Username, req.Password, req.Permission) { - return buserr.New(constant.ErrCmdIllegal) + return buserr.New("ErrCmdIllegal") } dbItem, err := mysqlRepo.Get(mysqlRepo.WithByMysqlName(req.Database), repo.WithByName(req.DB)) @@ -211,7 +212,7 @@ func (u *MysqlService) LoadFromRemote(req dto.MysqlLoadDB) error { if !hasOld { var createItem model.DatabaseMysql if err := copier.Copy(&createItem, &data); err != nil { - return errors.WithMessage(constant.ErrStructTransform, err.Error()) + return buserr.WithDetail("ErrStructTransform", err.Error(), nil) } if err := mysqlRepo.Create(context.Background(), &createItem); err != nil { return err @@ -281,11 +282,11 @@ func (u *MysqlService) Delete(ctx context.Context, req dto.MysqlDBDelete) error } if req.DeleteBackup { - uploadDir := path.Join(global.CONF.System.BaseDir, fmt.Sprintf("1panel/uploads/database/%s/%s/%s", req.Type, req.Database, db.Name)) + uploadDir := path.Join(global.Dir.DataDir, fmt.Sprintf("uploads/database/%s/%s/%s", req.Type, req.Database, db.Name)) if _, err := os.Stat(uploadDir); err == nil { _ = os.RemoveAll(uploadDir) } - backupDir := path.Join(global.CONF.System.Backup, fmt.Sprintf("database/%s/%s/%s", req.Type, db.MysqlName, db.Name)) + backupDir := path.Join(global.Dir.LocalBackupDir, fmt.Sprintf("database/%s/%s/%s", req.Type, db.MysqlName, db.Name)) if _, err := os.Stat(backupDir); err == nil { _ = os.RemoveAll(backupDir) } @@ -299,7 +300,7 @@ func (u *MysqlService) Delete(ctx context.Context, req dto.MysqlDBDelete) error func (u *MysqlService) ChangePassword(req dto.ChangeDBInfo) error { if cmd.CheckIllegal(req.Value) { - return buserr.New(constant.ErrCmdIllegal) + return buserr.New("ErrCmdIllegal") } cli, version, err := LoadMysqlClientByFrom(req.Database) if err != nil { @@ -383,7 +384,7 @@ func (u *MysqlService) ChangePassword(req dto.ChangeDBInfo) error { func (u *MysqlService) ChangeAccess(req dto.ChangeDBInfo) error { if cmd.CheckIllegal(req.Value) { - return buserr.New(constant.ErrCmdIllegal) + return buserr.New("ErrCmdIllegal") } cli, version, err := LoadMysqlClientByFrom(req.Database) if err != nil { @@ -428,7 +429,7 @@ func (u *MysqlService) UpdateVariables(req dto.MysqlVariablesUpdate) error { } var files []string - path := fmt.Sprintf("%s/%s/%s/conf/my.cnf", constant.AppInstallDir, req.Type, app.Name) + path := fmt.Sprintf("%s/%s/%s/conf/my.cnf", global.Dir.AppInstallDir, req.Type, app.Name) lineBytes, err := os.ReadFile(path) if err != nil { return err @@ -459,7 +460,7 @@ func (u *MysqlService) UpdateVariables(req dto.MysqlVariablesUpdate) error { return err } - if _, err := compose.Restart(fmt.Sprintf("%s/%s/%s/docker-compose.yml", constant.AppInstallDir, req.Type, app.Name)); err != nil { + if _, err := compose.Restart(fmt.Sprintf("%s/%s/%s/docker-compose.yml", global.Dir.AppInstallDir, req.Type, app.Name)); err != nil { return err } diff --git a/agent/app/service/database_postgresql.go b/agent/app/service/database_postgresql.go index ab790d886..6f2686d9d 100644 --- a/agent/app/service/database_postgresql.go +++ b/agent/app/service/database_postgresql.go @@ -3,15 +3,15 @@ package service import ( "context" "fmt" - "github.com/1Panel-dev/1Panel/agent/app/repo" "os" "path" "strings" + "github.com/1Panel-dev/1Panel/agent/app/repo" + "github.com/1Panel-dev/1Panel/agent/app/dto" "github.com/1Panel-dev/1Panel/agent/app/model" "github.com/1Panel-dev/1Panel/agent/buserr" - "github.com/1Panel-dev/1Panel/agent/constant" "github.com/1Panel-dev/1Panel/agent/global" "github.com/1Panel-dev/1Panel/agent/utils/cmd" "github.com/1Panel-dev/1Panel/agent/utils/encrypt" @@ -51,7 +51,7 @@ func (u *PostgresqlService) SearchWithPage(search dto.PostgresqlDBSearch) (int64 for _, pg := range postgresqls { var item dto.PostgresqlDBInfo if err := copier.Copy(&item, &pg); err != nil { - return 0, nil, errors.WithMessage(constant.ErrStructTransform, err.Error()) + return 0, nil, buserr.WithDetail("ErrStructTransform", err.Error(), nil) } dtoPostgresqls = append(dtoPostgresqls, item) } @@ -72,7 +72,7 @@ func (u *PostgresqlService) ListDBOption() ([]dto.PostgresqlOption, error) { for _, pg := range postgresqls { var item dto.PostgresqlOption if err := copier.Copy(&item, &pg); err != nil { - return nil, errors.WithMessage(constant.ErrStructTransform, err.Error()) + return nil, buserr.WithDetail("ErrStructTransform", err.Error(), nil) } item.Database = pg.PostgresqlName for _, database := range databases { @@ -87,7 +87,7 @@ func (u *PostgresqlService) ListDBOption() ([]dto.PostgresqlOption, error) { func (u *PostgresqlService) BindUser(req dto.PostgresqlBindUser) error { if cmd.CheckIllegal(req.Name, req.Username, req.Password) { - return buserr.New(constant.ErrCmdIllegal) + return buserr.New("ErrCmdIllegal") } dbItem, err := postgresqlRepo.Get(postgresqlRepo.WithByPostgresqlName(req.Database), repo.WithByName(req.Name)) if err != nil { @@ -123,17 +123,17 @@ func (u *PostgresqlService) BindUser(req dto.PostgresqlBindUser) error { func (u *PostgresqlService) Create(ctx context.Context, req dto.PostgresqlDBCreate) (*model.DatabasePostgresql, error) { if cmd.CheckIllegal(req.Name, req.Username, req.Password, req.Format) { - return nil, buserr.New(constant.ErrCmdIllegal) + return nil, buserr.New("ErrCmdIllegal") } pgsql, _ := postgresqlRepo.Get(repo.WithByName(req.Name), postgresqlRepo.WithByPostgresqlName(req.Database), repo.WithByFrom(req.From)) if pgsql.ID != 0 { - return nil, constant.ErrRecordExist + return nil, buserr.New("ErrRecordExist") } var createItem model.DatabasePostgresql if err := copier.Copy(&createItem, &req); err != nil { - return nil, errors.WithMessage(constant.ErrStructTransform, err.Error()) + return nil, buserr.WithDetail("ErrStructTransform", err.Error(), nil) } if req.From == "local" && req.Username == "root" { @@ -233,7 +233,7 @@ func (u *PostgresqlService) LoadFromRemote(database string) error { if !hasOld { var createItem model.DatabasePostgresql if err := copier.Copy(&createItem, &data); err != nil { - return errors.WithMessage(constant.ErrStructTransform, err.Error()) + return buserr.WithDetail("ErrStructTransform", err.Error(), nil) } if err := postgresqlRepo.Create(context.Background(), &createItem); err != nil { return err @@ -302,11 +302,11 @@ func (u *PostgresqlService) Delete(ctx context.Context, req dto.PostgresqlDBDele } if req.DeleteBackup { - uploadDir := path.Join(global.CONF.System.BaseDir, fmt.Sprintf("1panel/uploads/database/%s/%s/%s", req.Type, req.Database, db.Name)) + uploadDir := path.Join(global.Dir.DataDir, fmt.Sprintf("uploads/database/%s/%s/%s", req.Type, req.Database, db.Name)) if _, err := os.Stat(uploadDir); err == nil { _ = os.RemoveAll(uploadDir) } - backupDir := path.Join(global.CONF.System.Backup, fmt.Sprintf("database/%s/%s/%s", req.Type, db.PostgresqlName, db.Name)) + backupDir := path.Join(global.Dir.LocalBackupDir, fmt.Sprintf("database/%s/%s/%s", req.Type, db.PostgresqlName, db.Name)) if _, err := os.Stat(backupDir); err == nil { _ = os.RemoveAll(backupDir) } @@ -320,7 +320,7 @@ func (u *PostgresqlService) Delete(ctx context.Context, req dto.PostgresqlDBDele func (u *PostgresqlService) ChangePrivileges(req dto.PostgresqlPrivileges) error { if cmd.CheckIllegal(req.Database, req.Username) { - return buserr.New(constant.ErrCmdIllegal) + return buserr.New("ErrCmdIllegal") } dbItem, err := postgresqlRepo.Get(postgresqlRepo.WithByPostgresqlName(req.Database), repo.WithByName(req.Name)) if err != nil { @@ -345,7 +345,7 @@ func (u *PostgresqlService) ChangePrivileges(req dto.PostgresqlPrivileges) error func (u *PostgresqlService) ChangePassword(req dto.ChangeDBInfo) error { if cmd.CheckIllegal(req.Value) { - return buserr.New(constant.ErrCmdIllegal) + return buserr.New("ErrCmdIllegal") } cli, err := LoadPostgresqlClientByFrom(req.Database) if err != nil { diff --git a/agent/app/service/database_redis.go b/agent/app/service/database_redis.go index 918dec5ec..c9d44a042 100644 --- a/agent/app/service/database_redis.go +++ b/agent/app/service/database_redis.go @@ -5,11 +5,13 @@ import ( "encoding/json" "errors" "fmt" - "github.com/1Panel-dev/1Panel/agent/app/repo" "os" "os/exec" "strings" + "github.com/1Panel-dev/1Panel/agent/app/repo" + "github.com/1Panel-dev/1Panel/agent/global" + "github.com/1Panel-dev/1Panel/agent/app/dto" "github.com/1Panel-dev/1Panel/agent/constant" "github.com/1Panel-dev/1Panel/agent/utils/compose" @@ -51,7 +53,7 @@ func (u *RedisService) UpdateConf(req dto.RedisConfUpdate) error { if err := confSet(redisInfo.Name, "", confs); err != nil { return err } - if _, err := compose.Restart(fmt.Sprintf("%s/redis/%s/docker-compose.yml", constant.AppInstallDir, redisInfo.Name)); err != nil { + if _, err := compose.Restart(fmt.Sprintf("%s/redis/%s/docker-compose.yml", global.Dir.AppInstallDir, redisInfo.Name)); err != nil { return err } @@ -120,7 +122,7 @@ func (u *RedisService) UpdatePersistenceConf(req dto.RedisConfPersistenceUpdate) if err := confSet(redisInfo.Name, req.Type, confs); err != nil { return err } - if _, err := compose.Restart(fmt.Sprintf("%s/redis/%s/docker-compose.yml", constant.AppInstallDir, redisInfo.Name)); err != nil { + if _, err := compose.Restart(fmt.Sprintf("%s/redis/%s/docker-compose.yml", global.Dir.AppInstallDir, redisInfo.Name)); err != nil { return err } @@ -213,7 +215,7 @@ type redisConfig struct { } func confSet(redisName string, updateType string, changeConf []redisConfig) error { - path := fmt.Sprintf("%s/redis/%s/conf/redis.conf", constant.AppInstallDir, redisName) + path := fmt.Sprintf("%s/redis/%s/conf/redis.conf", global.Dir.AppInstallDir, redisName) lineBytes, err := os.ReadFile(path) if err != nil { return err diff --git a/agent/app/service/device.go b/agent/app/service/device.go index 07f5d11e1..e89da75c7 100644 --- a/agent/app/service/device.go +++ b/agent/app/service/device.go @@ -115,7 +115,7 @@ func (u *DeviceService) Update(key, value string) error { switch key { case "TimeZone": if cmd.CheckIllegal(value) { - return buserr.New(constant.ErrCmdIllegal) + return buserr.New("ErrCmdIllegal") } if err := ntp.UpdateSystemTimeZone(value); err != nil { return err @@ -132,7 +132,7 @@ func (u *DeviceService) Update(key, value string) error { } case "Hostname": if cmd.CheckIllegal(value) { - return buserr.New(constant.ErrCmdIllegal) + return buserr.New("ErrCmdIllegal") } std, err := cmd.Execf("%s hostnamectl set-hostname %s", cmd.SudoHandleCmd(), value) if err != nil { @@ -140,7 +140,7 @@ func (u *DeviceService) Update(key, value string) error { } case "Ntp", "LocalTime": if cmd.CheckIllegal(value) { - return buserr.New(constant.ErrCmdIllegal) + return buserr.New("ErrCmdIllegal") } ntpValue := value if key == "LocalTime" { @@ -223,12 +223,12 @@ func (u *DeviceService) UpdateHosts(req []dto.HostHelper) error { func (u *DeviceService) UpdatePasswd(req dto.ChangePasswd) error { if cmd.CheckIllegal(req.User, req.Passwd) { - return buserr.New(constant.ErrCmdIllegal) + return buserr.New("ErrCmdIllegal") } std, err := cmd.Execf("%s echo '%s:%s' | %s chpasswd", cmd.SudoHandleCmd(), req.User, req.Passwd, cmd.SudoHandleCmd()) if err != nil { if strings.Contains(err.Error(), "does not exist") { - return buserr.New(constant.ErrNotExistUser) + return buserr.New("ErrNotExistUser") } return errors.New(std) } @@ -237,7 +237,7 @@ func (u *DeviceService) UpdatePasswd(req dto.ChangePasswd) error { func (u *DeviceService) UpdateSwap(req dto.SwapHelper) error { if cmd.CheckIllegal(req.Path) { - return buserr.New(constant.ErrCmdIllegal) + return buserr.New("ErrCmdIllegal") } if !req.IsNew { std, err := cmd.Execf("%s swapoff %s", cmd.SudoHandleCmd(), req.Path) @@ -246,8 +246,8 @@ func (u *DeviceService) UpdateSwap(req dto.SwapHelper) error { } } if req.Size == 0 { - if req.Path == path.Join(global.CONF.System.BaseDir, ".1panel_swap") { - _ = os.Remove(path.Join(global.CONF.System.BaseDir, ".1panel_swap")) + if req.Path == path.Join(global.Dir.BaseDir, ".1panel_swap") { + _ = os.Remove(path.Join(global.Dir.BaseDir, ".1panel_swap")) } return operateSwapWithFile(true, req) } diff --git a/agent/app/service/device_clean.go b/agent/app/service/device_clean.go index b98c5e504..06d03553d 100644 --- a/agent/app/service/device_clean.go +++ b/agent/app/service/device_clean.go @@ -47,7 +47,7 @@ func (u *DeviceService) Scan() dto.CleanData { ) fileOp := fileUtils.NewFileOp() - originalPath := path.Join(global.CONF.System.BaseDir, "1panel_original") + originalPath := path.Join(global.Dir.BaseDir, "1panel_original") originalSize, _ := fileOp.GetDirSize(originalPath) treeData = append(treeData, dto.CleanTree{ ID: uuid.NewString(), @@ -59,7 +59,7 @@ func (u *DeviceService) Scan() dto.CleanData { Children: loadTreeWithDir(true, "1panel_original", originalPath, fileOp), }) - upgradePath := path.Join(global.CONF.System.BaseDir, upgradePath) + upgradePath := path.Join(global.Dir.BaseDir, upgradePath) upgradeSize, _ := fileOp.GetDirSize(upgradePath) treeData = append(treeData, dto.CleanTree{ ID: uuid.NewString(), @@ -101,7 +101,7 @@ func (u *DeviceService) Scan() dto.CleanData { Children: rollBackTree, }) - cachePath := path.Join(global.CONF.System.BaseDir, cachePath) + cachePath := path.Join(global.Dir.BaseDir, cachePath) cacheSize, _ := fileOp.GetDirSize(cachePath) treeData = append(treeData, dto.CleanTree{ ID: uuid.NewString(), @@ -150,97 +150,97 @@ func (u *DeviceService) Clean(req []dto.Clean) { size += item.Size switch item.TreeType { case "1panel_original": - dropFileOrDir(path.Join(global.CONF.System.BaseDir, "1panel_original", item.Name)) + dropFileOrDir(path.Join(global.Dir.BaseDir, "1panel_original", item.Name)) case "upgrade": - dropFileOrDir(path.Join(global.CONF.System.BaseDir, upgradePath, item.Name)) + dropFileOrDir(path.Join(global.Dir.BaseDir, upgradePath, item.Name)) case "snapshot": - dropFileOrDir(path.Join(global.CONF.System.BaseDir, snapshotTmpPath, item.Name)) - dropFileOrDir(path.Join(global.CONF.System.Backup, "system", item.Name)) + dropFileOrDir(path.Join(global.Dir.BaseDir, snapshotTmpPath, item.Name)) + dropFileOrDir(path.Join(global.Dir.LocalBackupDir, "system", item.Name)) case "snapshot_tmp": - dropFileOrDir(path.Join(global.CONF.System.BaseDir, snapshotTmpPath, item.Name)) + dropFileOrDir(path.Join(global.Dir.BaseDir, snapshotTmpPath, item.Name)) case "snapshot_local": - dropFileOrDir(path.Join(global.CONF.System.Backup, "system", item.Name)) + dropFileOrDir(path.Join(global.Dir.LocalBackupDir, "system", item.Name)) case "rollback": - dropFileOrDir(path.Join(global.CONF.System.BaseDir, rollbackPath, "app")) - dropFileOrDir(path.Join(global.CONF.System.BaseDir, rollbackPath, "database")) - dropFileOrDir(path.Join(global.CONF.System.BaseDir, rollbackPath, "website")) + dropFileOrDir(path.Join(global.Dir.BaseDir, rollbackPath, "app")) + dropFileOrDir(path.Join(global.Dir.BaseDir, rollbackPath, "database")) + dropFileOrDir(path.Join(global.Dir.BaseDir, rollbackPath, "website")) case "rollback_app": - dropFileOrDir(path.Join(global.CONF.System.BaseDir, rollbackPath, "app", item.Name)) + dropFileOrDir(path.Join(global.Dir.BaseDir, rollbackPath, "app", item.Name)) case "rollback_database": - dropFileOrDir(path.Join(global.CONF.System.BaseDir, rollbackPath, "database", item.Name)) + dropFileOrDir(path.Join(global.Dir.BaseDir, rollbackPath, "database", item.Name)) case "rollback_website": - dropFileOrDir(path.Join(global.CONF.System.BaseDir, rollbackPath, "website", item.Name)) + dropFileOrDir(path.Join(global.Dir.BaseDir, rollbackPath, "website", item.Name)) case "cache": - dropFileOrDir(path.Join(global.CONF.System.BaseDir, cachePath, item.Name)) + dropFileOrDir(path.Join(global.Dir.BaseDir, cachePath, item.Name)) restart = true case "unused": - dropFileOrDir(path.Join(global.CONF.System.BaseDir, oldOriginalPath)) - dropFileOrDir(path.Join(global.CONF.System.BaseDir, oldAppBackupPath)) - dropFileOrDir(path.Join(global.CONF.System.BaseDir, oldDownloadPath)) - files, _ := os.ReadDir(path.Join(global.CONF.System.BaseDir, oldUpgradePath)) + dropFileOrDir(path.Join(global.Dir.BaseDir, oldOriginalPath)) + dropFileOrDir(path.Join(global.Dir.BaseDir, oldAppBackupPath)) + dropFileOrDir(path.Join(global.Dir.BaseDir, oldDownloadPath)) + files, _ := os.ReadDir(path.Join(global.Dir.BaseDir, oldUpgradePath)) if len(files) == 0 { continue } for _, file := range files { if strings.HasPrefix(file.Name(), "upgrade_") { - dropFileOrDir(path.Join(global.CONF.System.BaseDir, oldUpgradePath, file.Name())) + dropFileOrDir(path.Join(global.Dir.BaseDir, oldUpgradePath, file.Name())) } } case "old_original": - dropFileOrDir(path.Join(global.CONF.System.BaseDir, oldOriginalPath, item.Name)) + dropFileOrDir(path.Join(global.Dir.BaseDir, oldOriginalPath, item.Name)) case "old_apps_bak": - dropFileOrDir(path.Join(global.CONF.System.BaseDir, oldAppBackupPath, item.Name)) + dropFileOrDir(path.Join(global.Dir.BaseDir, oldAppBackupPath, item.Name)) case "old_download": - dropFileOrDir(path.Join(global.CONF.System.BaseDir, oldDownloadPath, item.Name)) + dropFileOrDir(path.Join(global.Dir.BaseDir, oldDownloadPath, item.Name)) case "old_upgrade": if len(item.Name) == 0 { - files, _ := os.ReadDir(path.Join(global.CONF.System.BaseDir, oldUpgradePath)) + files, _ := os.ReadDir(path.Join(global.Dir.BaseDir, oldUpgradePath)) if len(files) == 0 { continue } for _, file := range files { if strings.HasPrefix(file.Name(), "upgrade_") { - dropFileOrDir(path.Join(global.CONF.System.BaseDir, oldUpgradePath, file.Name())) + dropFileOrDir(path.Join(global.Dir.BaseDir, oldUpgradePath, file.Name())) } } } else { - dropFileOrDir(path.Join(global.CONF.System.BaseDir, oldUpgradePath, item.Name)) + dropFileOrDir(path.Join(global.Dir.BaseDir, oldUpgradePath, item.Name)) } case "upload": - dropFileOrDir(path.Join(global.CONF.System.BaseDir, uploadPath, item.Name)) + dropFileOrDir(path.Join(global.Dir.BaseDir, uploadPath, item.Name)) if len(item.Name) == 0 { - dropFileOrDir(path.Join(global.CONF.System.BaseDir, tmpUploadPath)) + dropFileOrDir(path.Join(global.Dir.BaseDir, tmpUploadPath)) } case "upload_tmp": - dropFileOrDir(path.Join(global.CONF.System.BaseDir, tmpUploadPath, item.Name)) + dropFileOrDir(path.Join(global.Dir.BaseDir, tmpUploadPath, item.Name)) case "upload_app": - dropFileOrDir(path.Join(global.CONF.System.BaseDir, uploadPath, "app", item.Name)) + dropFileOrDir(path.Join(global.Dir.BaseDir, uploadPath, "app", item.Name)) case "upload_database": - dropFileOrDir(path.Join(global.CONF.System.BaseDir, uploadPath, "database", item.Name)) + dropFileOrDir(path.Join(global.Dir.BaseDir, uploadPath, "database", item.Name)) case "upload_website": - dropFileOrDir(path.Join(global.CONF.System.BaseDir, uploadPath, "website", item.Name)) + dropFileOrDir(path.Join(global.Dir.BaseDir, uploadPath, "website", item.Name)) case "upload_directory": - dropFileOrDir(path.Join(global.CONF.System.BaseDir, uploadPath, "directory", item.Name)) + dropFileOrDir(path.Join(global.Dir.BaseDir, uploadPath, "directory", item.Name)) case "download": - dropFileOrDir(path.Join(global.CONF.System.BaseDir, downloadPath, item.Name)) + dropFileOrDir(path.Join(global.Dir.BaseDir, downloadPath, item.Name)) case "download_app": - dropFileOrDir(path.Join(global.CONF.System.BaseDir, downloadPath, "app", item.Name)) + dropFileOrDir(path.Join(global.Dir.BaseDir, downloadPath, "app", item.Name)) case "download_database": - dropFileOrDir(path.Join(global.CONF.System.BaseDir, downloadPath, "database", item.Name)) + dropFileOrDir(path.Join(global.Dir.BaseDir, downloadPath, "database", item.Name)) case "download_website": - dropFileOrDir(path.Join(global.CONF.System.BaseDir, downloadPath, "website", item.Name)) + dropFileOrDir(path.Join(global.Dir.BaseDir, downloadPath, "website", item.Name)) case "download_directory": - dropFileOrDir(path.Join(global.CONF.System.BaseDir, downloadPath, "directory", item.Name)) + dropFileOrDir(path.Join(global.Dir.BaseDir, downloadPath, "directory", item.Name)) case "system_log": if len(item.Name) == 0 { - files, _ := os.ReadDir(path.Join(global.CONF.System.BaseDir, logPath)) + files, _ := os.ReadDir(path.Join(global.Dir.BaseDir, logPath)) if len(files) == 0 { continue } @@ -248,14 +248,14 @@ func (u *DeviceService) Clean(req []dto.Clean) { if file.Name() == "1Panel.log" || file.IsDir() { continue } - dropFileOrDir(path.Join(global.CONF.System.BaseDir, logPath, file.Name())) + dropFileOrDir(path.Join(global.Dir.BaseDir, logPath, file.Name())) } } else { - dropFileOrDir(path.Join(global.CONF.System.BaseDir, logPath, item.Name)) + dropFileOrDir(path.Join(global.Dir.BaseDir, logPath, item.Name)) } case "task_log": - pathItem := path.Join(global.CONF.System.BaseDir, taskPath, item.Name) - dropFileOrDir(path.Join(global.CONF.System.BaseDir, taskPath, item.Name)) + pathItem := path.Join(global.Dir.BaseDir, taskPath, item.Name) + dropFileOrDir(path.Join(global.Dir.BaseDir, taskPath, item.Name)) if len(item.Name) == 0 { files, _ := os.ReadDir(pathItem) if len(files) == 0 { @@ -296,9 +296,9 @@ func systemClean(taskItem *task.Task) error { taskItem.AddSubTask(i18n.GetMsgByKey("HandleSystemClean"), func(t *task.Task) error { size := int64(0) fileCount := 0 - dropWithTask(path.Join(global.CONF.System.BaseDir, "1panel_original"), taskItem, &size, &fileCount) + dropWithTask(path.Join(global.Dir.BaseDir, "1panel_original"), taskItem, &size, &fileCount) - upgradePath := path.Join(global.CONF.System.BaseDir, upgradePath) + upgradePath := path.Join(global.Dir.BaseDir, upgradePath) upgradeFiles, _ := os.ReadDir(upgradePath) if len(upgradeFiles) != 0 { sort.Slice(upgradeFiles, func(i, j int) bool { @@ -311,17 +311,17 @@ func systemClean(taskItem *task.Task) error { } } - dropWithTask(path.Join(global.CONF.System.BaseDir, snapshotTmpPath), taskItem, &size, &fileCount) - dropWithTask(path.Join(global.CONF.System.Backup, "system"), taskItem, &size, &fileCount) + dropWithTask(path.Join(global.Dir.BaseDir, snapshotTmpPath), taskItem, &size, &fileCount) + dropWithTask(path.Join(global.Dir.LocalBackupDir, "system"), taskItem, &size, &fileCount) - dropWithTask(path.Join(global.CONF.System.BaseDir, rollbackPath, "app"), taskItem, &size, &fileCount) - dropWithTask(path.Join(global.CONF.System.BaseDir, rollbackPath, "website"), taskItem, &size, &fileCount) - dropWithTask(path.Join(global.CONF.System.BaseDir, rollbackPath, "database"), taskItem, &size, &fileCount) + dropWithTask(path.Join(global.Dir.BaseDir, rollbackPath, "app"), taskItem, &size, &fileCount) + dropWithTask(path.Join(global.Dir.BaseDir, rollbackPath, "website"), taskItem, &size, &fileCount) + dropWithTask(path.Join(global.Dir.BaseDir, rollbackPath, "database"), taskItem, &size, &fileCount) - dropWithTask(path.Join(global.CONF.System.BaseDir, oldOriginalPath), taskItem, &size, &fileCount) - dropWithTask(path.Join(global.CONF.System.BaseDir, oldAppBackupPath), taskItem, &size, &fileCount) - dropWithTask(path.Join(global.CONF.System.BaseDir, oldDownloadPath), taskItem, &size, &fileCount) - oldUpgradePath := path.Join(global.CONF.System.BaseDir, oldUpgradePath) + dropWithTask(path.Join(global.Dir.BaseDir, oldOriginalPath), taskItem, &size, &fileCount) + dropWithTask(path.Join(global.Dir.BaseDir, oldAppBackupPath), taskItem, &size, &fileCount) + dropWithTask(path.Join(global.Dir.BaseDir, oldDownloadPath), taskItem, &size, &fileCount) + oldUpgradePath := path.Join(global.Dir.BaseDir, oldUpgradePath) oldUpgradeFiles, _ := os.ReadDir(oldUpgradePath) if len(oldUpgradeFiles) != 0 { for i := 0; i < len(oldUpgradeFiles); i++ { @@ -329,11 +329,11 @@ func systemClean(taskItem *task.Task) error { } } - dropWithTask(path.Join(global.CONF.System.BaseDir, tmpUploadPath), taskItem, &size, &fileCount) - dropWithTask(path.Join(global.CONF.System.BaseDir, uploadPath), taskItem, &size, &fileCount) - dropWithTask(path.Join(global.CONF.System.BaseDir, downloadPath), taskItem, &size, &fileCount) + dropWithTask(path.Join(global.Dir.BaseDir, tmpUploadPath), taskItem, &size, &fileCount) + dropWithTask(path.Join(global.Dir.BaseDir, uploadPath), taskItem, &size, &fileCount) + dropWithTask(path.Join(global.Dir.BaseDir, downloadPath), taskItem, &size, &fileCount) - logPath := path.Join(global.CONF.System.BaseDir, logPath) + logPath := path.Join(global.Dir.BaseDir, logPath) logFiles, _ := os.ReadDir(logPath) if len(logFiles) != 0 { for i := 0; i < len(logFiles); i++ { @@ -361,14 +361,14 @@ func systemClean(taskItem *task.Task) error { func loadSnapshotTree(fileOp fileUtils.FileOp) []dto.CleanTree { var treeData []dto.CleanTree - path1 := path.Join(global.CONF.System.BaseDir, snapshotTmpPath) + path1 := path.Join(global.Dir.BaseDir, snapshotTmpPath) list1 := loadTreeWithAllFile(true, path1, "snapshot_tmp", path1, fileOp) if len(list1) != 0 { size, _ := fileOp.GetDirSize(path1) treeData = append(treeData, dto.CleanTree{ID: uuid.NewString(), Label: "snapshot_tmp", Size: uint64(size), Children: list1, Type: "snapshot_tmp", IsRecommend: true}) } - path2 := path.Join(global.CONF.System.Backup, "system") + path2 := path.Join(global.Dir.LocalBackupDir, "system") list2 := loadTreeWithAllFile(true, path2, "snapshot_local", path2, fileOp) if len(list2) != 0 { size, _ := fileOp.GetDirSize(path2) @@ -379,17 +379,17 @@ func loadSnapshotTree(fileOp fileUtils.FileOp) []dto.CleanTree { func loadRollBackTree(fileOp fileUtils.FileOp) []dto.CleanTree { var treeData []dto.CleanTree - path1 := path.Join(global.CONF.System.BaseDir, rollbackPath, "app") + path1 := path.Join(global.Dir.BaseDir, rollbackPath, "app") list1 := loadTreeWithAllFile(true, path1, "rollback_app", path1, fileOp) size1, _ := fileOp.GetDirSize(path1) treeData = append(treeData, dto.CleanTree{ID: uuid.NewString(), Label: "rollback_app", Size: uint64(size1), Children: list1, Type: "rollback_app", IsRecommend: true}) - path2 := path.Join(global.CONF.System.BaseDir, rollbackPath, "website") + path2 := path.Join(global.Dir.BaseDir, rollbackPath, "website") list2 := loadTreeWithAllFile(true, path2, "rollback_website", path2, fileOp) size2, _ := fileOp.GetDirSize(path2) treeData = append(treeData, dto.CleanTree{ID: uuid.NewString(), Label: "rollback_website", Size: uint64(size2), Children: list2, Type: "rollback_website", IsRecommend: true}) - path3 := path.Join(global.CONF.System.BaseDir, rollbackPath, "database") + path3 := path.Join(global.Dir.BaseDir, rollbackPath, "database") list3 := loadTreeWithAllFile(true, path3, "rollback_database", path3, fileOp) size3, _ := fileOp.GetDirSize(path3) treeData = append(treeData, dto.CleanTree{ID: uuid.NewString(), Label: "rollback_database", Size: uint64(size3), Children: list3, Type: "rollback_database", IsRecommend: true}) @@ -399,28 +399,28 @@ func loadRollBackTree(fileOp fileUtils.FileOp) []dto.CleanTree { func loadUnusedFile(fileOp fileUtils.FileOp) []dto.CleanTree { var treeData []dto.CleanTree - path1 := path.Join(global.CONF.System.BaseDir, oldOriginalPath) + path1 := path.Join(global.Dir.BaseDir, oldOriginalPath) list1 := loadTreeWithAllFile(true, path1, "old_original", path1, fileOp) if len(list1) != 0 { size, _ := fileOp.GetDirSize(path1) treeData = append(treeData, dto.CleanTree{ID: uuid.NewString(), Label: "old_original", Size: uint64(size), Children: list1, Type: "old_original"}) } - path2 := path.Join(global.CONF.System.BaseDir, oldAppBackupPath) + path2 := path.Join(global.Dir.BaseDir, oldAppBackupPath) list2 := loadTreeWithAllFile(true, path2, "old_apps_bak", path2, fileOp) if len(list2) != 0 { size, _ := fileOp.GetDirSize(path2) treeData = append(treeData, dto.CleanTree{ID: uuid.NewString(), Label: "old_apps_bak", Size: uint64(size), Children: list2, Type: "old_apps_bak"}) } - path3 := path.Join(global.CONF.System.BaseDir, oldDownloadPath) + path3 := path.Join(global.Dir.BaseDir, oldDownloadPath) list3 := loadTreeWithAllFile(true, path3, "old_download", path3, fileOp) if len(list3) != 0 { size, _ := fileOp.GetDirSize(path3) treeData = append(treeData, dto.CleanTree{ID: uuid.NewString(), Label: "old_download", Size: uint64(size), Children: list3, Type: "old_download"}) } - path4 := path.Join(global.CONF.System.BaseDir, oldUpgradePath) + path4 := path.Join(global.Dir.BaseDir, oldUpgradePath) list4 := loadTreeWithDir(true, "old_upgrade", path4, fileOp) itemSize := uint64(0) for _, item := range list4 { @@ -435,32 +435,32 @@ func loadUnusedFile(fileOp fileUtils.FileOp) []dto.CleanTree { func loadUploadTree(fileOp fileUtils.FileOp) []dto.CleanTree { var treeData []dto.CleanTree - path0 := path.Join(global.CONF.System.BaseDir, tmpUploadPath) + path0 := path.Join(global.Dir.BaseDir, tmpUploadPath) list0 := loadTreeWithAllFile(true, path0, "upload_tmp", path0, fileOp) size0, _ := fileOp.GetDirSize(path0) treeData = append(treeData, dto.CleanTree{ID: uuid.NewString(), Label: "upload_tmp", Size: uint64(size0), Children: list0, Type: "upload_tmp", IsRecommend: true}) - path1 := path.Join(global.CONF.System.BaseDir, uploadPath, "app") + path1 := path.Join(global.Dir.BaseDir, uploadPath, "app") list1 := loadTreeWithAllFile(true, path1, "upload_app", path1, fileOp) size1, _ := fileOp.GetDirSize(path1) treeData = append(treeData, dto.CleanTree{ID: uuid.NewString(), Label: "upload_app", Size: uint64(size1), Children: list1, Type: "upload_app", IsRecommend: true}) - path2 := path.Join(global.CONF.System.BaseDir, uploadPath, "website") + path2 := path.Join(global.Dir.BaseDir, uploadPath, "website") list2 := loadTreeWithAllFile(true, path2, "upload_website", path2, fileOp) size2, _ := fileOp.GetDirSize(path2) treeData = append(treeData, dto.CleanTree{ID: uuid.NewString(), Label: "upload_website", Size: uint64(size2), Children: list2, Type: "upload_website", IsRecommend: true}) - path3 := path.Join(global.CONF.System.BaseDir, uploadPath, "database") + path3 := path.Join(global.Dir.BaseDir, uploadPath, "database") list3 := loadTreeWithAllFile(true, path3, "upload_database", path3, fileOp) size3, _ := fileOp.GetDirSize(path3) treeData = append(treeData, dto.CleanTree{ID: uuid.NewString(), Label: "upload_database", Size: uint64(size3), Children: list3, Type: "upload_database", IsRecommend: true}) - path4 := path.Join(global.CONF.System.BaseDir, uploadPath, "directory") + path4 := path.Join(global.Dir.BaseDir, uploadPath, "directory") list4 := loadTreeWithAllFile(true, path4, "upload_directory", path4, fileOp) size4, _ := fileOp.GetDirSize(path4) treeData = append(treeData, dto.CleanTree{ID: uuid.NewString(), Label: "upload_directory", Size: uint64(size4), Children: list4, Type: "upload_directory", IsRecommend: true}) - path5 := path.Join(global.CONF.System.BaseDir, uploadPath) + path5 := path.Join(global.Dir.BaseDir, uploadPath) uploadTreeData := loadTreeWithAllFile(true, path5, "upload", path5, fileOp) treeData = append(treeData, uploadTreeData...) @@ -469,27 +469,27 @@ func loadUploadTree(fileOp fileUtils.FileOp) []dto.CleanTree { func loadDownloadTree(fileOp fileUtils.FileOp) []dto.CleanTree { var treeData []dto.CleanTree - path1 := path.Join(global.CONF.System.BaseDir, downloadPath, "app") + path1 := path.Join(global.Dir.BaseDir, downloadPath, "app") list1 := loadTreeWithAllFile(true, path1, "download_app", path1, fileOp) size1, _ := fileOp.GetDirSize(path1) treeData = append(treeData, dto.CleanTree{ID: uuid.NewString(), Label: "download_app", Size: uint64(size1), Children: list1, Type: "download_app", IsRecommend: true}) - path2 := path.Join(global.CONF.System.BaseDir, downloadPath, "website") + path2 := path.Join(global.Dir.BaseDir, downloadPath, "website") list2 := loadTreeWithAllFile(true, path2, "download_website", path2, fileOp) size2, _ := fileOp.GetDirSize(path2) treeData = append(treeData, dto.CleanTree{ID: uuid.NewString(), Label: "download_website", Size: uint64(size2), Children: list2, Type: "download_website", IsRecommend: true}) - path3 := path.Join(global.CONF.System.BaseDir, downloadPath, "database") + path3 := path.Join(global.Dir.BaseDir, downloadPath, "database") list3 := loadTreeWithAllFile(true, path3, "download_database", path3, fileOp) size3, _ := fileOp.GetDirSize(path3) treeData = append(treeData, dto.CleanTree{ID: uuid.NewString(), Label: "download_database", Size: uint64(size3), Children: list3, Type: "download_database", IsRecommend: true}) - path4 := path.Join(global.CONF.System.BaseDir, downloadPath, "directory") + path4 := path.Join(global.Dir.BaseDir, downloadPath, "directory") list4 := loadTreeWithAllFile(true, path4, "download_directory", path4, fileOp) size4, _ := fileOp.GetDirSize(path4) treeData = append(treeData, dto.CleanTree{ID: uuid.NewString(), Label: "download_directory", Size: uint64(size4), Children: list4, Type: "download_directory", IsRecommend: true}) - path5 := path.Join(global.CONF.System.BaseDir, downloadPath) + path5 := path.Join(global.Dir.BaseDir, downloadPath) uploadTreeData := loadTreeWithAllFile(true, path5, "download", path5, fileOp) treeData = append(treeData, uploadTreeData...) @@ -498,7 +498,7 @@ func loadDownloadTree(fileOp fileUtils.FileOp) []dto.CleanTree { func loadLogTree(fileOp fileUtils.FileOp) []dto.CleanTree { var treeData []dto.CleanTree - path1 := path.Join(global.CONF.System.BaseDir, logPath) + path1 := path.Join(global.Dir.BaseDir, logPath) list1 := loadTreeWithAllFile(true, path1, "system_log", path1, fileOp) size := uint64(0) for _, file := range list1 { @@ -506,7 +506,7 @@ func loadLogTree(fileOp fileUtils.FileOp) []dto.CleanTree { } treeData = append(treeData, dto.CleanTree{ID: uuid.NewString(), Label: "system_log", Size: uint64(size), Children: list1, Type: "system_log", IsRecommend: true}) - path2 := path.Join(global.CONF.System.BaseDir, taskPath) + path2 := path.Join(global.Dir.BaseDir, taskPath) list2 := loadTreeWithAllFile(false, path2, "task_log", path2, fileOp) size2, _ := fileOp.GetDirSize(path2) treeData = append(treeData, dto.CleanTree{ID: uuid.NewString(), Label: "task_log", Size: uint64(size2), Children: list2, Type: "task_log"}) diff --git a/agent/app/service/favorite.go b/agent/app/service/favorite.go index 95c1faa0f..95c04dea0 100644 --- a/agent/app/service/favorite.go +++ b/agent/app/service/favorite.go @@ -7,7 +7,6 @@ import ( "github.com/1Panel-dev/1Panel/agent/app/model" "github.com/1Panel-dev/1Panel/agent/app/repo" "github.com/1Panel-dev/1Panel/agent/buserr" - "github.com/1Panel-dev/1Panel/agent/constant" "github.com/1Panel-dev/1Panel/agent/utils/files" "github.com/spf13/afero" ) @@ -42,11 +41,11 @@ func (f *FavoriteService) Page(req dto.PageInfo) (int64, []response.FavoriteDTO, func (f *FavoriteService) Create(req request.FavoriteCreate) (*model.Favorite, error) { exist, _ := favoriteRepo.GetFirst(favoriteRepo.WithByPath(req.Path)) if exist.ID > 0 { - return nil, buserr.New(constant.ErrFavoriteExist) + return nil, buserr.New("ErrFavoriteExist") } op := files.NewFileOp() if !op.Stat(req.Path) { - return nil, buserr.New(constant.ErrLinkPathNotFound) + return nil, buserr.New("ErrLinkPathNotFound") } openFile, err := op.OpenFile(req.Path) if err != nil { diff --git a/agent/app/service/file.go b/agent/app/service/file.go index 356fa8cda..b0c954189 100644 --- a/agent/app/service/file.go +++ b/agent/app/service/file.go @@ -190,7 +190,7 @@ func (f *FileService) Create(op request.FileCreate) error { } fo := files.NewFileOp() if fo.Stat(op.Path) { - return buserr.New(constant.ErrFileIsExist) + return buserr.New("ErrFileIsExist") } mode := op.Mode if mode == 0 { @@ -206,7 +206,7 @@ func (f *FileService) Create(op request.FileCreate) error { } if op.IsLink { if !fo.Stat(op.LinkPath) { - return buserr.New(constant.ErrLinkPathNotFound) + return buserr.New("ErrLinkPathNotFound") } return fo.LinkFile(op.LinkPath, op.Path, op.IsSymlink) } @@ -215,9 +215,9 @@ func (f *FileService) Create(op request.FileCreate) error { func (f *FileService) Delete(op request.FileDelete) error { if op.IsDir { - excludeDir := global.CONF.System.DataDir + excludeDir := global.Dir.DataDir if filepath.Base(op.Path) == ".1panel_clash" || op.Path == excludeDir { - return buserr.New(constant.ErrPathNotDelete) + return buserr.New("ErrPathNotDelete") } } fo := files.NewFileOp() @@ -265,7 +265,7 @@ func (f *FileService) BatchChangeModeAndOwner(op request.FileRoleReq) error { fo := files.NewFileOp() for _, path := range op.Paths { if !fo.Stat(path) { - return buserr.New(constant.ErrPathNotFound) + return buserr.New("ErrPathNotFound") } if err := fo.ChownR(path, op.User, op.Group, op.Sub); err != nil { return err @@ -286,7 +286,7 @@ func (f *FileService) ChangeOwner(req request.FileRoleUpdate) error { func (f *FileService) Compress(c request.FileCompress) error { fo := files.NewFileOp() if !c.Replace && fo.Stat(filepath.Join(c.Dst, c.Name)) { - return buserr.New(constant.ErrFileIsExist) + return buserr.New("ErrFileIsExist") } return fo.Compress(c.Files, c.Dst, c.Name, files.CompressType(c.Type), c.Secret) } @@ -358,14 +358,14 @@ func (f *FileService) Wget(w request.FileWget) (string, error) { func (f *FileService) MvFile(m request.FileMove) error { fo := files.NewFileOp() if !fo.Stat(m.NewPath) { - return buserr.New(constant.ErrPathNotFound) + return buserr.New("ErrPathNotFound") } for _, oldPath := range m.OldPaths { if !fo.Stat(oldPath) { - return buserr.WithName(constant.ErrFileNotFound, oldPath) + return buserr.WithName("ErrFileNotFound", oldPath) } if oldPath == m.NewPath || strings.Contains(m.NewPath, filepath.Clean(oldPath)+"/") { - return buserr.New(constant.ErrMovePathFailed) + return buserr.New("ErrMovePathFailed") } } if m.Type == "cut" { @@ -451,9 +451,9 @@ func (f *FileService) ReadLogByLine(req request.FileReadByLineReq) (*response.Fi } else { fileName = "1Panel-" + req.Name + ".log" } - logFilePath = path.Join(global.CONF.System.DataDir, "log", fileName) + logFilePath = path.Join(global.Dir.DataDir, "log", fileName) if _, err := os.Stat(logFilePath); err != nil { - fileGzPath := path.Join(global.CONF.System.DataDir, "log", fileName+".gz") + fileGzPath := path.Join(global.Dir.DataDir, "log", fileName+".gz") if _, err := os.Stat(fileGzPath); err != nil { return nil, buserr.New("ErrHttpReqNotFound") } @@ -500,7 +500,7 @@ func (f *FileService) GetPathByType(pathType string) string { if pathType == "websiteDir" { value, _ := settingRepo.GetValueByKey("WEBSITE_DIR") if value == "" { - return path.Join(global.CONF.System.BaseDir, "www") + return path.Join(global.Dir.BaseDir, "www") } return value } diff --git a/agent/app/service/firewall.go b/agent/app/service/firewall.go index a1805f268..aab13f0c0 100644 --- a/agent/app/service/firewall.go +++ b/agent/app/service/firewall.go @@ -10,6 +10,7 @@ import ( "github.com/1Panel-dev/1Panel/agent/app/dto" "github.com/1Panel-dev/1Panel/agent/app/model" + "github.com/1Panel-dev/1Panel/agent/buserr" "github.com/1Panel-dev/1Panel/agent/constant" "github.com/1Panel-dev/1Panel/agent/global" "github.com/1Panel-dev/1Panel/agent/utils/cmd" @@ -17,7 +18,6 @@ import ( "github.com/1Panel-dev/1Panel/agent/utils/firewall" fireClient "github.com/1Panel-dev/1Panel/agent/utils/firewall/client" "github.com/jinzhu/copier" - "github.com/pkg/errors" ) const confPath = "/etc/sysctl.conf" @@ -347,7 +347,7 @@ func (u *FirewallService) OperateForwardRule(req dto.ForwardRuleOperate) error { reqRule.TargetPort == rule.TargetPort && reqRule.TargetIP == rule.TargetIP && proto == rule.Protocol { - return constant.ErrRecordExist + return buserr.New("ErrRecordExist") } } } @@ -446,7 +446,7 @@ func (u *FirewallService) UpdateAddrRule(req dto.AddrRuleUpdate) error { func (u *FirewallService) UpdateDescription(req dto.UpdateFirewallDescription) error { var firewall model.Firewall if err := copier.Copy(&firewall, &req); err != nil { - return errors.WithMessage(constant.ErrStructTransform, err.Error()) + return buserr.WithDetail("ErrStructTransform", err.Error(), nil) } return hostRepo.SaveFirewallRecord(&firewall) } diff --git a/agent/app/service/ftp.go b/agent/app/service/ftp.go index 6d0cd6e34..b213fff18 100644 --- a/agent/app/service/ftp.go +++ b/agent/app/service/ftp.go @@ -1,17 +1,18 @@ package service import ( - "github.com/1Panel-dev/1Panel/agent/app/repo" "os" "sort" + "github.com/1Panel-dev/1Panel/agent/app/repo" + "github.com/1Panel-dev/1Panel/agent/buserr" + "github.com/1Panel-dev/1Panel/agent/app/dto" "github.com/1Panel-dev/1Panel/agent/app/model" "github.com/1Panel-dev/1Panel/agent/constant" "github.com/1Panel-dev/1Panel/agent/utils/encrypt" "github.com/1Panel-dev/1Panel/agent/utils/toolbox" "github.com/jinzhu/copier" - "github.com/pkg/errors" ) type FtpService struct{} @@ -83,7 +84,7 @@ func (f *FtpService) SearchWithPage(req dto.SearchWithPage) (int64, interface{}, for _, user := range lists { var item dto.FtpInfo if err := copier.Copy(&item, &user); err != nil { - return 0, nil, errors.WithMessage(constant.ErrStructTransform, err.Error()) + return 0, nil, buserr.WithDetail("ErrStructTransform", err.Error(), nil) } item.Password, _ = encrypt.StringDecrypt(item.Password) users = append(users, item) @@ -145,7 +146,7 @@ func (f *FtpService) Create(req dto.FtpCreate) (uint, error) { } userInDB, _ := ftpRepo.Get(ftpRepo.WithByUser(req.User)) if userInDB.ID != 0 { - return 0, constant.ErrRecordExist + return 0, buserr.New("ErrRecordExist") } client, err := toolbox.NewFtpClient() if err != nil { @@ -156,7 +157,7 @@ func (f *FtpService) Create(req dto.FtpCreate) (uint, error) { } var ftp model.Ftp if err := copier.Copy(&ftp, &req); err != nil { - return 0, errors.WithMessage(constant.ErrStructTransform, err.Error()) + return 0, buserr.WithDetail("ErrStructTransform", err.Error(), nil) } ftp.Status = constant.StatusEnable ftp.Password = pass @@ -199,7 +200,7 @@ func (f *FtpService) Update(req dto.FtpUpdate) error { } ftpItem, _ := ftpRepo.Get(repo.WithByID(req.ID)) if ftpItem.ID == 0 { - return constant.ErrRecordNotFound + return buserr.New("ErrRecordNotFound") } passItem, err := encrypt.StringDecrypt(ftpItem.Password) if err != nil { diff --git a/agent/app/service/host_tool.go b/agent/app/service/host_tool.go index ce7175e7d..a0e883883 100644 --- a/agent/app/service/host_tool.go +++ b/agent/app/service/host_tool.go @@ -154,7 +154,7 @@ func (h *HostToolService) CreateToolConfig(req request.HostToolCreate) error { return err } } - supervisorDir := path.Join(global.CONF.System.BaseDir, "1panel", "tools", "supervisord") + supervisorDir := path.Join(global.Dir.DataDir, "tools", "supervisord") includeDir := path.Join(supervisorDir, "supervisor.d") if !fileOp.Stat(includeDir) { if err = fileOp.CreateDir(includeDir, constant.DirPerm); err != nil { @@ -282,7 +282,7 @@ func (h *HostToolService) GetToolLog(req request.HostToolLogReq) (string, error) func (h *HostToolService) OperateSupervisorProcess(req request.SupervisorProcessConfig) error { var ( - supervisordDir = path.Join(global.CONF.System.BaseDir, "1panel", "tools", "supervisord") + supervisordDir = path.Join(global.Dir.DataDir, "tools", "supervisord") fileOp = files.NewFileOp() ) if req.Operate == "update" || req.Operate == "create" { @@ -432,13 +432,13 @@ func handleProcessConfig(configDir, containerName string) ([]response.Supervisor } func (h *HostToolService) GetSupervisorProcessConfig() ([]response.SupervisorProcessConfig, error) { - configDir := path.Join(global.CONF.System.BaseDir, "1panel", "tools", "supervisord", "supervisor.d") + configDir := path.Join(global.Dir.DataDir, "tools", "supervisord", "supervisor.d") return handleProcessConfig(configDir, "") } func (h *HostToolService) OperateSupervisorProcessFile(req request.SupervisorProcessFileReq) (string, error) { var ( - includeDir = path.Join(global.CONF.System.BaseDir, "1panel", "tools", "supervisord", "supervisor.d") + includeDir = path.Join(global.Dir.DataDir, "tools", "supervisord", "supervisor.d") ) return handleSupervisorFile(req, includeDir, "", "") } diff --git a/agent/app/service/image.go b/agent/app/service/image.go index 8fbd42ffb..d093135a4 100644 --- a/agent/app/service/image.go +++ b/agent/app/service/image.go @@ -19,6 +19,7 @@ import ( "github.com/1Panel-dev/1Panel/agent/app/task" "github.com/1Panel-dev/1Panel/agent/buserr" "github.com/1Panel-dev/1Panel/agent/constant" + "github.com/1Panel-dev/1Panel/agent/global" "github.com/1Panel-dev/1Panel/agent/i18n" "github.com/1Panel-dev/1Panel/agent/utils/docker" "github.com/docker/docker/api/types" @@ -162,7 +163,7 @@ func (u *ImageService) ImageBuild(req dto.ImageBuild) error { defer client.Close() fileName := "Dockerfile" if req.From == "edit" { - dir := fmt.Sprintf("%s/docker/build/%s", constant.DataDir, strings.ReplaceAll(req.Name, ":", "_")) + dir := fmt.Sprintf("%s/docker/build/%s", global.Dir.DataDir, strings.ReplaceAll(req.Name, ":", "_")) if _, err := os.Stat(dir); err != nil && os.IsNotExist(err) { if err = os.MkdirAll(dir, os.ModePerm); err != nil { return err @@ -414,12 +415,12 @@ func (u *ImageService) ImageRemove(req dto.BatchDelete) (dto.ContainerPruneRepor if _, err := client.ImageRemove(context.TODO(), id, image.RemoveOptions{Force: req.Force, PruneChildren: true}); err != nil { if strings.Contains(err.Error(), "image is being used") || strings.Contains(err.Error(), "is using") { if strings.Contains(id, "sha256:") { - return report, buserr.New(constant.ErrObjectInUsed) + return report, buserr.New("ErrObjectInUsed") } - return report, buserr.WithDetail(constant.ErrInUsed, id, nil) + return report, buserr.WithDetail("ErrInUsed", id, nil) } if strings.Contains(err.Error(), "image has dependent") { - return report, buserr.New(constant.ErrObjectBeDependent) + return report, buserr.New("ErrObjectBeDependent") } return report, err } diff --git a/agent/app/service/image_repo.go b/agent/app/service/image_repo.go index fbdcc6461..22d7e1e30 100644 --- a/agent/app/service/image_repo.go +++ b/agent/app/service/image_repo.go @@ -4,11 +4,12 @@ import ( "context" "encoding/json" "fmt" - "github.com/1Panel-dev/1Panel/agent/app/repo" "os" "strings" "time" + "github.com/1Panel-dev/1Panel/agent/app/repo" + "github.com/1Panel-dev/1Panel/agent/app/dto" "github.com/1Panel-dev/1Panel/agent/buserr" "github.com/1Panel-dev/1Panel/agent/constant" @@ -40,7 +41,7 @@ func (u *ImageRepoService) Page(req dto.SearchWithPage) (int64, interface{}, err for _, op := range ops { var item dto.ImageRepoInfo if err := copier.Copy(&item, &op); err != nil { - return 0, nil, errors.WithMessage(constant.ErrStructTransform, err.Error()) + return 0, nil, buserr.WithDetail("ErrStructTransform", err.Error(), nil) } dtoOps = append(dtoOps, item) } @@ -69,7 +70,7 @@ func (u *ImageRepoService) List() ([]dto.ImageRepoOption, error) { if op.Status == constant.StatusSuccess { var item dto.ImageRepoOption if err := copier.Copy(&item, &op); err != nil { - return nil, errors.WithMessage(constant.ErrStructTransform, err.Error()) + return nil, buserr.WithDetail("ErrStructTransform", err.Error(), nil) } dtoOps = append(dtoOps, item) } @@ -79,11 +80,11 @@ func (u *ImageRepoService) List() ([]dto.ImageRepoOption, error) { func (u *ImageRepoService) Create(req dto.ImageRepoCreate) error { if cmd.CheckIllegal(req.Username, req.Password, req.DownloadUrl) { - return buserr.New(constant.ErrCmdIllegal) + return buserr.New("ErrCmdIllegal") } imageRepo, _ := imageRepoRepo.Get(repo.WithByName(req.Name)) if imageRepo.ID != 0 { - return constant.ErrRecordExist + return buserr.New("ErrRecordExist") } if req.Protocol == "http" { @@ -124,7 +125,7 @@ func (u *ImageRepoService) Create(req dto.ImageRepoCreate) error { } if err := copier.Copy(&imageRepo, &req); err != nil { - return errors.WithMessage(constant.ErrStructTransform, err.Error()) + return buserr.WithDetail("ErrStructTransform", err.Error(), nil) } imageRepo.Status = constant.StatusSuccess @@ -148,7 +149,7 @@ func (u *ImageRepoService) Update(req dto.ImageRepoUpdate) error { return errors.New("The default value cannot be deleted !") } if cmd.CheckIllegal(req.Username, req.Password, req.DownloadUrl) { - return buserr.New(constant.ErrCmdIllegal) + return buserr.New("ErrCmdIllegal") } repo, err := imageRepoRepo.Get(repo.WithByID(req.ID)) if err != nil { diff --git a/agent/app/service/logs.go b/agent/app/service/logs.go index ce9276469..64c4d30a7 100644 --- a/agent/app/service/logs.go +++ b/agent/app/service/logs.go @@ -25,9 +25,8 @@ func NewILogService() ILogService { } func (u *LogService) ListSystemLogFile() ([]string, error) { - logDir := path.Join(global.CONF.System.BaseDir, "1panel/log") var files []string - if err := filepath.Walk(logDir, func(pathItem string, info os.FileInfo, err error) error { + if err := filepath.Walk(global.Dir.LogDir, func(pathItem string, info os.FileInfo, err error) error { if err != nil { return err } @@ -63,9 +62,9 @@ func (u *LogService) LoadSystemLog(name string) (string, error) { } else { name = "1Panel-" + name + ".log" } - filePath := path.Join(global.CONF.System.DataDir, "log", name) + filePath := path.Join(global.Dir.LogDir, name) if _, err := os.Stat(filePath); err != nil { - fileGzPath := path.Join(global.CONF.System.DataDir, "log", name+".gz") + fileGzPath := path.Join(global.Dir.LogDir, name+".gz") if _, err := os.Stat(fileGzPath); err != nil { return "", buserr.New("ErrHttpReqNotFound") } diff --git a/agent/app/service/monitor.go b/agent/app/service/monitor.go index 03d19717d..750c9a7d3 100644 --- a/agent/app/service/monitor.go +++ b/agent/app/service/monitor.go @@ -8,10 +8,10 @@ import ( "time" "github.com/1Panel-dev/1Panel/agent/app/repo" + "github.com/1Panel-dev/1Panel/agent/buserr" "github.com/1Panel-dev/1Panel/agent/app/dto" "github.com/1Panel-dev/1Panel/agent/app/model" - "github.com/1Panel-dev/1Panel/agent/constant" "github.com/1Panel-dev/1Panel/agent/global" "github.com/1Panel-dev/1Panel/agent/utils/common" "github.com/robfig/cron/v3" @@ -101,7 +101,7 @@ func (m *MonitorService) LoadMonitorData(req dto.MonitorSearch) ([]dto.MonitorDa func (m *MonitorService) LoadSetting() (*dto.MonitorSetting, error) { setting, err := settingRepo.GetList() if err != nil { - return nil, constant.ErrRecordNotFound + return nil, buserr.New("ErrRecordNotFound") } settingMap := make(map[string]string) for _, set := range setting { diff --git a/agent/app/service/nginx.go b/agent/app/service/nginx.go index 8b659687a..26b7c7e0c 100644 --- a/agent/app/service/nginx.go +++ b/agent/app/service/nginx.go @@ -4,10 +4,6 @@ import ( "bufio" "encoding/json" "fmt" - "github.com/1Panel-dev/1Panel/agent/app/task" - "github.com/1Panel-dev/1Panel/agent/buserr" - cmd2 "github.com/1Panel-dev/1Panel/agent/utils/cmd" - "github.com/subosito/gotenv" "io" "net/http" "os" @@ -16,6 +12,12 @@ import ( "strings" "time" + "github.com/1Panel-dev/1Panel/agent/app/task" + "github.com/1Panel-dev/1Panel/agent/buserr" + "github.com/1Panel-dev/1Panel/agent/global" + cmd2 "github.com/1Panel-dev/1Panel/agent/utils/cmd" + "github.com/subosito/gotenv" + "github.com/1Panel-dev/1Panel/agent/utils/compose" "github.com/1Panel-dev/1Panel/agent/app/dto/request" @@ -50,7 +52,7 @@ func (n NginxService) GetNginxConfig() (*response.NginxFile, error) { if err != nil { return nil, err } - configPath := path.Join(constant.AppInstallDir, constant.AppOpenresty, nginxInstall.Name, "conf", "nginx.conf") + configPath := path.Join(global.Dir.AppInstallDir, constant.AppOpenresty, nginxInstall.Name, "conf", "nginx.conf") byteContent, err := files.NewFileOp().GetContent(configPath) if err != nil { return nil, err @@ -131,7 +133,7 @@ func (n NginxService) UpdateConfigFile(req request.NginxConfigFileUpdate) error if err != nil { return err } - filePath := path.Join(constant.AppInstallDir, constant.AppOpenresty, nginxInstall.Name, "conf", "nginx.conf") + filePath := path.Join(global.Dir.AppInstallDir, constant.AppOpenresty, nginxInstall.Name, "conf", "nginx.conf") if req.Backup { backupPath := path.Join(path.Dir(filePath), "bak") if !fileOp.Stat(backupPath) { diff --git a/agent/app/service/nginx_utils.go b/agent/app/service/nginx_utils.go index acd48897f..341bd36f2 100644 --- a/agent/app/service/nginx_utils.go +++ b/agent/app/service/nginx_utils.go @@ -13,6 +13,7 @@ import ( "github.com/1Panel-dev/1Panel/agent/app/model" "github.com/1Panel-dev/1Panel/agent/cmd/server/nginx_conf" "github.com/1Panel-dev/1Panel/agent/constant" + "github.com/1Panel-dev/1Panel/agent/global" "github.com/1Panel-dev/1Panel/agent/utils/cmd" "github.com/1Panel-dev/1Panel/agent/utils/files" "github.com/1Panel-dev/1Panel/agent/utils/nginx" @@ -27,7 +28,7 @@ func getNginxFull(website *model.Website) (dto.NginxFull, error) { return nginxFull, err } nginxFull.Install = nginxInstall - nginxFull.Dir = path.Join(constant.AppInstallDir, constant.AppOpenresty, nginxInstall.Name) + nginxFull.Dir = path.Join(global.Dir.AppInstallDir, constant.AppOpenresty, nginxInstall.Name) nginxFull.ConfigDir = path.Join(nginxFull.Dir, "conf") nginxFull.ConfigFile = "nginx.conf" nginxFull.SiteDir = path.Join(nginxFull.Dir, "www") diff --git a/agent/app/service/php_extensions.go b/agent/app/service/php_extensions.go index eccc32dfe..6698150aa 100644 --- a/agent/app/service/php_extensions.go +++ b/agent/app/service/php_extensions.go @@ -6,7 +6,6 @@ import ( "github.com/1Panel-dev/1Panel/agent/app/model" "github.com/1Panel-dev/1Panel/agent/app/repo" "github.com/1Panel-dev/1Panel/agent/buserr" - "github.com/1Panel-dev/1Panel/agent/constant" ) type PHPExtensionsService struct { @@ -64,7 +63,7 @@ func (p PHPExtensionsService) List() ([]response.PHPExtensionsDTO, error) { func (p PHPExtensionsService) Create(req request.PHPExtensionsCreate) error { exist, _ := phpExtensionsRepo.GetFirst(repo.WithByName(req.Name)) if exist.ID > 0 { - return buserr.New(constant.ErrNameIsExist) + return buserr.New("ErrNameIsExist") } extension := model.PHPExtensions{ Name: req.Name, diff --git a/agent/app/service/recycle_bin.go b/agent/app/service/recycle_bin.go index 9e45d2407..8f86ab2f6 100644 --- a/agent/app/service/recycle_bin.go +++ b/agent/app/service/recycle_bin.go @@ -15,6 +15,7 @@ import ( "github.com/1Panel-dev/1Panel/agent/app/dto/response" "github.com/1Panel-dev/1Panel/agent/buserr" "github.com/1Panel-dev/1Panel/agent/constant" + "github.com/1Panel-dev/1Panel/agent/global" "github.com/1Panel-dev/1Panel/agent/utils/files" "github.com/shirou/gopsutil/v3/disk" ) @@ -77,7 +78,7 @@ func (r RecycleBinService) Page(search dto.PageInfo) (int64, []response.RecycleB func (r RecycleBinService) Create(create request.RecycleBinCreate) error { op := files.NewFileOp() if !op.Stat(create.SourcePath) { - return buserr.New(constant.ErrLinkPathNotFound) + return buserr.New("ErrLinkPathNotFound") } clashDir, err := getClashDir(create.SourcePath) if err != nil { @@ -113,7 +114,7 @@ func (r RecycleBinService) Reduce(reduce request.RecycleBinReduce) error { filePath := path.Join(reduce.From, reduce.RName) op := files.NewFileOp() if !op.Stat(filePath) { - return buserr.New(constant.ErrLinkPathNotFound) + return buserr.New("ErrLinkPathNotFound") } recycleBinDTO, err := getRecycleBinDTOFromName(reduce.RName) if err != nil { @@ -169,7 +170,7 @@ func getClashDir(realPath string) (string, error) { return clashDir, nil } } - return constant.RecycleBinDir, createClashDir(constant.RecycleBinDir) + return global.Dir.RecycleBinDir, createClashDir(global.Dir.RecycleBinDir) } func createClashDir(clashDir string) error { diff --git a/agent/app/service/runtime.go b/agent/app/service/runtime.go index 11598edd4..d65d1989a 100644 --- a/agent/app/service/runtime.go +++ b/agent/app/service/runtime.go @@ -5,9 +5,6 @@ import ( "context" "encoding/json" "fmt" - "github.com/1Panel-dev/1Panel/agent/app/task" - "github.com/1Panel-dev/1Panel/agent/cmd/server/nginx_conf" - "gopkg.in/ini.v1" "os" "path" "path/filepath" @@ -17,6 +14,10 @@ import ( "strings" "time" + "github.com/1Panel-dev/1Panel/agent/app/task" + "github.com/1Panel-dev/1Panel/agent/cmd/server/nginx_conf" + "gopkg.in/ini.v1" + "github.com/1Panel-dev/1Panel/agent/app/dto" "github.com/1Panel-dev/1Panel/agent/app/dto/request" "github.com/1Panel-dev/1Panel/agent/app/dto/response" @@ -82,11 +83,11 @@ func (r *RuntimeService) Create(create request.RuntimeCreate) (*model.Runtime, e } exist, _ := runtimeRepo.GetFirst(opts...) if exist != nil { - return nil, buserr.New(constant.ErrNameIsExist) + return nil, buserr.New("ErrNameIsExist") } fileOp := files.NewFileOp() - runtimeDir := path.Join(constant.RuntimeDir, create.Type) + runtimeDir := path.Join(global.Dir.RuntimeDir, create.Type) if !fileOp.Stat(runtimeDir) { if err := fileOp.CreateDir(runtimeDir, constant.DirPerm); err != nil { return nil, err @@ -107,11 +108,11 @@ func (r *RuntimeService) Create(create request.RuntimeCreate) (*model.Runtime, e } exist, _ = runtimeRepo.GetFirst(runtimeRepo.WithImage(create.Image)) if exist != nil { - return nil, buserr.New(constant.ErrImageExist) + return nil, buserr.New("ErrImageExist") } case constant.RuntimeNode, constant.RuntimeJava, constant.RuntimeGo, constant.RuntimePython, constant.RuntimeDotNet: if !fileOp.Stat(create.CodeDir) { - return nil, buserr.New(constant.ErrPathNotFound) + return nil, buserr.New("ErrPathNotFound") } create.Install = true for _, export := range create.ExposedPorts { @@ -229,7 +230,7 @@ func (r *RuntimeService) Delete(runtimeDelete request.RuntimeDelete) error { } website, _ := websiteRepo.GetFirst(websiteRepo.WithRuntimeID(runtimeDelete.ID)) if website.ID > 0 { - return buserr.New(constant.ErrDelWithWebsite) + return buserr.New("ErrDelWithWebsite") } if runtime.Resource != constant.ResourceAppstore { return runtimeRepo.DeleteBy(repo.WithByID(runtimeDelete.ID)) @@ -441,7 +442,7 @@ func (r *RuntimeService) Update(req request.RuntimeUpdate) error { case constant.RuntimePHP: exist, _ := runtimeRepo.GetFirst(runtimeRepo.WithImage(req.Name), runtimeRepo.WithNotId(req.ID)) if exist != nil { - return buserr.New(constant.ErrImageExist) + return buserr.New("ErrImageExist") } case constant.RuntimeNode, constant.RuntimeJava, constant.RuntimeGo, constant.RuntimePython, constant.RuntimeDotNet: if runtime.Port != port { @@ -465,7 +466,7 @@ func (r *RuntimeService) Update(req request.RuntimeUpdate) error { return err } fileOp := files.NewFileOp() - appVersionDir := path.Join(constant.AppResourceDir, app.Resource, app.Key, appDetail.Version) + appVersionDir := path.Join(global.Dir.AppResourceDir, app.Resource, app.Key, appDetail.Version) if !fileOp.Stat(appVersionDir) || appDetail.Update { if err := downloadApp(app, appDetail, nil, nil); err != nil { return err @@ -481,7 +482,7 @@ func (r *RuntimeService) Update(req request.RuntimeUpdate) error { } } - projectDir := path.Join(constant.RuntimeDir, runtime.Type, runtime.Name) + projectDir := path.Join(global.Dir.RuntimeDir, runtime.Type, runtime.Name) create := request.RuntimeCreate{ Image: req.Image, Type: runtime.Type, @@ -532,10 +533,10 @@ func (r *RuntimeService) Update(req request.RuntimeUpdate) error { func (r *RuntimeService) GetNodePackageRunScript(req request.NodePackageReq) ([]response.PackageScripts, error) { fileOp := files.NewFileOp() if !fileOp.Stat(req.CodeDir) { - return nil, buserr.New(constant.ErrPathNotFound) + return nil, buserr.New("ErrPathNotFound") } if !fileOp.Stat(path.Join(req.CodeDir, "package.json")) { - return nil, buserr.New(constant.ErrPackageJsonNotFound) + return nil, buserr.New("ErrPackageJsonNotFound") } content, err := fileOp.GetContent(path.Join(req.CodeDir, "package.json")) if err != nil { @@ -548,7 +549,7 @@ func (r *RuntimeService) GetNodePackageRunScript(req request.NodePackageReq) ([] } scripts, ok := packageMap["scripts"] if !ok { - return nil, buserr.New(constant.ErrScriptsNotFound) + return nil, buserr.New("ErrScriptsNotFound") } var packageScripts []response.PackageScripts for k, v := range scripts.(map[string]interface{}) { @@ -1050,7 +1051,7 @@ func (r *RuntimeService) GetSupervisorProcess(id uint) ([]response.SupervisorPro if err != nil { return nil, err } - configDir := path.Join(constant.RuntimeDir, "php", runtime.Name, "supervisor", "supervisor.d") + configDir := path.Join(global.Dir.RuntimeDir, "php", runtime.Name, "supervisor", "supervisor.d") return handleProcessConfig(configDir, runtime.ContainerName) } @@ -1059,7 +1060,7 @@ func (r *RuntimeService) OperateSupervisorProcess(req request.PHPSupervisorProce if err != nil { return err } - configDir := path.Join(constant.RuntimeDir, "php", runtime.Name, "supervisor") + configDir := path.Join(global.Dir.RuntimeDir, "php", runtime.Name, "supervisor") return handleProcess(configDir, req.SupervisorProcessConfig, runtime.ContainerName) } @@ -1068,7 +1069,7 @@ func (r *RuntimeService) OperateSupervisorProcessFile(req request.PHPSupervisorP if err != nil { return "", err } - supervisorDir := path.Join(constant.RuntimeDir, "php", runtime.Name, "supervisor") + supervisorDir := path.Join(global.Dir.RuntimeDir, "php", runtime.Name, "supervisor") configDir := path.Join(supervisorDir, "supervisor.d") logFile := path.Join(supervisorDir, "log", fmt.Sprintf("%s.out.log", req.SupervisorProcessFileReq.Name)) return handleSupervisorFile(req.SupervisorProcessFileReq, configDir, runtime.ContainerName, logFile) diff --git a/agent/app/service/runtime_utils.go b/agent/app/service/runtime_utils.go index ba155fbd0..f2c236021 100644 --- a/agent/app/service/runtime_utils.go +++ b/agent/app/service/runtime_utils.go @@ -6,6 +6,14 @@ import ( "context" "encoding/json" "fmt" + "io" + "os" + "os/exec" + "path" + "path/filepath" + "strings" + "time" + "github.com/1Panel-dev/1Panel/agent/app/dto" "github.com/1Panel-dev/1Panel/agent/app/dto/request" "github.com/1Panel-dev/1Panel/agent/app/dto/response" @@ -22,17 +30,10 @@ import ( "github.com/pkg/errors" "github.com/subosito/gotenv" "gopkg.in/yaml.v3" - "io" - "os" - "os/exec" - "path" - "path/filepath" - "strings" - "time" ) func handleRuntime(create request.RuntimeCreate, runtime *model.Runtime, fileOp files.FileOp, appVersionDir string) (err error) { - runtimeDir := path.Join(constant.RuntimeDir, create.Type) + runtimeDir := path.Join(global.Dir.RuntimeDir, create.Type) if err = fileOp.CopyDir(appVersionDir, runtimeDir); err != nil { return } @@ -69,7 +70,7 @@ func handleRuntime(create request.RuntimeCreate, runtime *model.Runtime, fileOp } func handlePHP(create request.RuntimeCreate, runtime *model.Runtime, fileOp files.FileOp, appVersionDir string) (err error) { - runtimeDir := path.Join(constant.RuntimeDir, create.Type) + runtimeDir := path.Join(global.Dir.RuntimeDir, create.Type) if err = fileOp.CopyDirWithNewName(appVersionDir, runtimeDir, create.Name); err != nil { return } @@ -147,7 +148,7 @@ func runComposeCmdWithLog(operate string, composePath string, logPath string) er err = cmd.Run() if err != nil { - return errors.New(buserr.New(constant.ErrRuntimeStart).Error() + ":" + err.Error()) + return errors.New(buserr.New("ErrRuntimeStart").Error() + ":" + err.Error()) } return nil } @@ -230,11 +231,11 @@ func buildRuntime(runtime *model.Runtime, oldImageID string, oldEnv string, rebu err = cmd.Run() if err != nil { runtime.Status = constant.RuntimeError - runtime.Message = buserr.New(constant.ErrImageBuildErr).Error() + ":" + stderrBuf.String() + runtime.Message = buserr.New("ErrImageBuildErr").Error() + ":" + stderrBuf.String() if errors.Is(ctx.Err(), context.DeadlineExceeded) { - runtime.Message = buserr.New(constant.ErrImageBuildErr).Error() + ":" + buserr.New("ErrCmdTimeout").Error() + runtime.Message = buserr.New("ErrImageBuildErr").Error() + ":" + buserr.New("ErrCmdTimeout").Error() } else { - runtime.Message = buserr.New(constant.ErrImageBuildErr).Error() + ":" + stderrBuf.String() + runtime.Message = buserr.New("ErrImageBuildErr").Error() + ":" + stderrBuf.String() } } else { if err = runComposeCmdWithLog(constant.RuntimeDown, runtime.GetComposePath(), runtime.GetLogPath()); err != nil { @@ -292,7 +293,7 @@ func buildRuntime(runtime *model.Runtime, oldImageID string, oldEnv string, rebu err = cmd2.ExecWithLogFile(installCmd, 60*time.Minute, logPath) if err != nil { runtime.Status = constant.RuntimeError - runtime.Message = buserr.New(constant.ErrImageBuildErr).Error() + ":" + err.Error() + runtime.Message = buserr.New("ErrImageBuildErr").Error() + ":" + err.Error() _ = runtimeRepo.Save(runtime) return } @@ -422,7 +423,7 @@ func handleCompose(env gotenv.Env, composeContent []byte, create request.Runtime } services, serviceValid := composeMap["services"].(map[string]interface{}) if !serviceValid { - err = buserr.New(constant.ErrFileParse) + err = buserr.New("ErrFileParse") return } serviceName := "" @@ -500,7 +501,7 @@ func checkContainerName(name string) error { return err } if len(names) > 0 { - return buserr.New(constant.ErrContainerName) + return buserr.New("ErrContainerName") } return nil } diff --git a/agent/app/service/setting.go b/agent/app/service/setting.go index dc24eba07..1dc89583c 100644 --- a/agent/app/service/setting.go +++ b/agent/app/service/setting.go @@ -6,7 +6,7 @@ import ( "time" "github.com/1Panel-dev/1Panel/agent/app/dto" - "github.com/1Panel-dev/1Panel/agent/constant" + "github.com/1Panel-dev/1Panel/agent/buserr" "github.com/1Panel-dev/1Panel/agent/global" "github.com/1Panel-dev/1Panel/agent/utils/encrypt" "github.com/1Panel-dev/1Panel/agent/utils/xpack" @@ -28,7 +28,7 @@ func NewISettingService() ISettingService { func (u *SettingService) GetSettingInfo() (*dto.SettingInfo, error) { setting, err := settingRepo.GetList() if err != nil { - return nil, constant.ErrRecordNotFound + return nil, buserr.New("ErrRecordNotFound") } settingMap := make(map[string]string) for _, set := range setting { @@ -92,11 +92,12 @@ func (u *SettingService) ReloadConn() error { return nil } - global.CONF.System.BaseDir = nodeInfo.BaseDir - global.CONF.System.Version = nodeInfo.Version - global.CONF.System.Port = fmt.Sprintf("%v", nodeInfo.NodePort) - if global.CONF.System.Port == "0" { - global.CONF.System.Port = "9999" + global.Dir.BaseDir = nodeInfo.BaseDir + global.CONF.Base.Version = nodeInfo.Version + global.CONF.Base.Port = fmt.Sprintf("%v", nodeInfo.NodePort) + global.CONF.Base.InstallDir = nodeInfo.BaseDir + if global.CONF.Base.Port == "0" { + global.CONF.Base.Port = "9999" } global.IsMaster = nodeInfo.Scope == "master" return nil diff --git a/agent/app/service/snapshot.go b/agent/app/service/snapshot.go index 429a9ee3e..745b744ae 100644 --- a/agent/app/service/snapshot.go +++ b/agent/app/service/snapshot.go @@ -8,6 +8,7 @@ import ( "strings" "github.com/1Panel-dev/1Panel/agent/app/repo" + "github.com/1Panel-dev/1Panel/agent/buserr" "github.com/1Panel-dev/1Panel/agent/app/dto" "github.com/1Panel-dev/1Panel/agent/app/model" @@ -67,7 +68,7 @@ func (u *SnapshotService) SnapshotImport(req dto.SnapshotImport) error { for _, snapName := range req.Names { snap, _ := snapshotRepo.Get(repo.WithByName(strings.ReplaceAll(snapName, ".tar.gz", ""))) if snap.ID != 0 { - return constant.ErrRecordExist + return buserr.New("ErrRecordExist") } } for _, snap := range req.Names { @@ -108,7 +109,7 @@ func (u *SnapshotService) LoadSnapshotData() (dto.SnapshotData, error) { if err != nil { return data, err } - itemBackups, err := loadFile(global.CONF.System.Backup, 8, fileOp) + itemBackups, err := loadFile(global.Dir.LocalBackupDir, 8, fileOp) if err != nil { return data, err } @@ -220,7 +221,7 @@ func loadApps(fileOp fileUtils.FileOp) ([]dto.DataTree, error) { Key: app.App.Key, Name: app.Name, } - appPath := path.Join(global.CONF.System.BaseDir, "1panel/apps", app.App.Key, app.Name) + appPath := path.Join(global.Dir.DataDir, "apps", app.App.Key, app.Name) itemAppData := dto.DataTree{ID: uuid.NewString(), Label: "appData", Key: app.App.Key, Name: app.Name, IsCheck: true, Path: appPath} if app.App.Key == constant.AppOpenresty && len(websites) != 0 { itemAppData.IsDisable = true @@ -257,7 +258,7 @@ func loadApps(fileOp fileUtils.FileOp) ([]dto.DataTree, error) { } func loadAppBackup(list []dto.DataTree, fileOp fileUtils.FileOp) []dto.DataTree { for i := 0; i < len(list); i++ { - appBackupPath := path.Join(global.CONF.System.BaseDir, "1panel/backup/app", list[i].Key, list[i].Name) + appBackupPath := path.Join(global.Dir.LocalBackupDir, "app", list[i].Key, list[i].Name) itemAppBackupTree, err := loadFile(appBackupPath, 8, fileOp) itemAppBackup := dto.DataTree{ID: uuid.NewString(), Label: "appBackup", IsCheck: true, Children: itemAppBackupTree, Path: appBackupPath} if err == nil { @@ -286,7 +287,7 @@ func loadAppImage(list []dto.DataTree) []dto.DataTree { for i := 0; i < len(list); i++ { itemAppImage := dto.DataTree{ID: uuid.NewString(), Label: "appImage"} - stdout, err := cmd.Execf("cat %s | grep image: ", path.Join(global.CONF.System.BaseDir, "1panel/apps", list[i].Key, list[i].Name, "docker-compose.yml")) + stdout, err := cmd.Execf("cat %s | grep image: ", path.Join(global.Dir.AppDir, list[i].Key, list[i].Name, "docker-compose.yml")) if err != nil { list[i].Children = append(list[i].Children, itemAppImage) continue @@ -307,7 +308,7 @@ func loadAppImage(list []dto.DataTree) []dto.DataTree { func loadPanelFile(fileOp fileUtils.FileOp) ([]dto.DataTree, error) { var data []dto.DataTree - snapFiles, err := os.ReadDir(path.Join(global.CONF.System.BaseDir, "1panel")) + snapFiles, err := os.ReadDir(global.Dir.DataDir) if err != nil { return data, err } @@ -316,19 +317,19 @@ func loadPanelFile(fileOp fileUtils.FileOp) ([]dto.DataTree, error) { ID: uuid.NewString(), Label: fileItem.Name(), IsCheck: true, - Path: path.Join(global.CONF.System.BaseDir, "1panel", fileItem.Name()), + Path: path.Join(global.Dir.DataDir, fileItem.Name()), } switch itemData.Label { case "agent", "conf", "runtime", "docker", "secret", "task": itemData.IsDisable = true case "clamav": - panelPath := path.Join(global.CONF.System.BaseDir, "1panel", itemData.Label) + panelPath := path.Join(global.Dir.DataDir, itemData.Label) itemData.Children, _ = loadFile(panelPath, 5, fileOp) default: continue } if fileItem.IsDir() { - sizeItem, err := fileOp.GetDirSize(path.Join(global.CONF.System.BaseDir, "1panel", itemData.Label)) + sizeItem, err := fileOp.GetDirSize(path.Join(global.Dir.DataDir, itemData.Label)) if err != nil { continue } diff --git a/agent/app/service/snapshot_create.go b/agent/app/service/snapshot_create.go index 2bf3ff89f..06952a905 100644 --- a/agent/app/service/snapshot_create.go +++ b/agent/app/service/snapshot_create.go @@ -111,7 +111,7 @@ func (u *SnapshotService) SnapshotReCreate(id uint) error { } func handleSnapshot(req dto.SnapshotCreate, taskItem *task.Task) { - rootDir := path.Join(global.CONF.System.BaseDir, "1panel/tmp/system", req.Name) + rootDir := path.Join(global.Dir.TmpDir, "system", req.Name) itemHelper := snapHelper{SnapID: req.ID, Task: *taskItem, FileOp: files.NewFileOp(), Ctx: context.Background()} baseDir := path.Join(rootDir, "base") _ = os.MkdirAll(baseDir, os.ModePerm) @@ -204,7 +204,7 @@ type snapHelper struct { func loadDbConn(snap *snapHelper, targetDir string, req dto.SnapshotCreate) error { snap.Task.Log("---------------------- 1 / 8 ----------------------") snap.Task.LogStart(i18n.GetMsgByKey("SnapDBInfo")) - pathDB := path.Join(global.CONF.System.BaseDir, "1panel/db") + pathDB := path.Join(global.Dir.DataDir, "db") err := snap.FileOp.CopyDir(pathDB, targetDir) snap.Task.LogWithStatus(i18n.GetWithName("SnapCopy", pathDB), err) @@ -296,8 +296,8 @@ func snapBaseData(snap snapHelper, targetDir string) error { } remarkInfo, _ := json.MarshalIndent(SnapshotJson{ - BaseDir: global.CONF.System.BaseDir, - BackupDataDir: global.CONF.System.Backup, + BaseDir: global.Dir.BaseDir, + BackupDataDir: global.Dir.LocalBackupDir, }, "", "\t") err = os.WriteFile(path.Join(targetDir, "snapshot.json"), remarkInfo, 0640) snap.Task.LogWithStatus(i18n.GetWithName("SnapCopy", path.Join(targetDir, "snapshot.json")), err) @@ -352,7 +352,7 @@ func snapBackupData(snap snapHelper, req dto.SnapshotCreate, targetDir string) e } } } - err := snap.FileOp.TarGzCompressPro(false, global.CONF.System.Backup, path.Join(targetDir, "1panel_backup.tar.gz"), "", strings.Join(excludes, ";")) + err := snap.FileOp.TarGzCompressPro(false, global.Dir.LocalBackupDir, path.Join(targetDir, "1panel_backup.tar.gz"), "", strings.Join(excludes, ";")) snap.Task.LogWithStatus(i18n.GetMsgByKey("SnapCompressBackup"), err) return err @@ -364,18 +364,18 @@ func loadBackupExcludes(snap snapHelper, req []dto.DataTree) []string { if item.IsCheck { continue } - if strings.HasPrefix(item.Path, path.Join(global.CONF.System.Backup, "system_snapshot")) { + if strings.HasPrefix(item.Path, path.Join(global.Dir.LocalBackupDir, "system_snapshot")) { fmt.Println(strings.TrimSuffix(item.Name, ".tar.gz")) if err := snap.snapAgentDB.Where("name = ? AND download_account_id = ?", strings.TrimSuffix(item.Name, ".tar.gz"), "1").Delete(&model.Snapshot{}).Error; err != nil { snap.Task.LogWithStatus("delete snapshot from database", err) } } else { - fmt.Println(strings.TrimPrefix(path.Dir(item.Path), global.CONF.System.Backup+"/"), path.Base(item.Path)) - if err := snap.snapAgentDB.Where("file_dir = ? AND file_name = ?", strings.TrimPrefix(path.Dir(item.Path), global.CONF.System.Backup+"/"), path.Base(item.Path)).Delete(&model.BackupRecord{}).Error; err != nil { + fmt.Println(strings.TrimPrefix(path.Dir(item.Path), global.Dir.LocalBackupDir+"/"), path.Base(item.Path)) + if err := snap.snapAgentDB.Where("file_dir = ? AND file_name = ?", strings.TrimPrefix(path.Dir(item.Path), global.Dir.LocalBackupDir+"/"), path.Base(item.Path)).Delete(&model.BackupRecord{}).Error; err != nil { snap.Task.LogWithStatus("delete backup file from database", err) } } - excludes = append(excludes, "."+strings.TrimPrefix(item.Path, global.CONF.System.Backup)) + excludes = append(excludes, "."+strings.TrimPrefix(item.Path, global.Dir.LocalBackupDir)) } else { excludes = append(excludes, loadBackupExcludes(snap, item.Children)...) } @@ -387,7 +387,7 @@ func loadAppBackupExcludes(req []dto.DataTree) []string { for _, item := range req { if len(item.Children) == 0 { if !item.IsCheck { - excludes = append(excludes, "."+strings.TrimPrefix(item.Path, path.Join(global.CONF.System.Backup))) + excludes = append(excludes, "."+strings.TrimPrefix(item.Path, path.Join(global.Dir.LocalBackupDir))) } } else { excludes = append(excludes, loadAppBackupExcludes(item.Children)...) @@ -423,9 +423,9 @@ func snapPanelData(snap snapHelper, req dto.SnapshotCreate, targetDir string) er excludes = append(excludes, "./log/Website") } - rootDir := path.Join(global.CONF.System.BaseDir, "1panel") - if strings.Contains(global.CONF.System.Backup, rootDir) { - excludes = append(excludes, "."+strings.ReplaceAll(global.CONF.System.Backup, rootDir, "")) + rootDir := global.Dir.DataDir + if strings.Contains(global.Dir.LocalBackupDir, rootDir) { + excludes = append(excludes, "."+strings.ReplaceAll(global.Dir.LocalBackupDir, rootDir, "")) } ignoreVal, _ := settingRepo.Get(settingRepo.WithByKey("SnapshotIgnore")) rules := strings.Split(ignoreVal.Value, ",") @@ -445,7 +445,7 @@ func loadPanelExcludes(req []dto.DataTree) []string { for _, item := range req { if len(item.Children) == 0 { if !item.IsCheck { - excludes = append(excludes, "."+strings.TrimPrefix(item.Path, path.Join(global.CONF.System.BaseDir, "1panel"))) + excludes = append(excludes, "."+strings.TrimPrefix(item.Path, path.Join(global.Dir.BaseDir, "1panel"))) } } else { excludes = append(excludes, loadPanelExcludes(item.Children)...) @@ -458,7 +458,7 @@ func snapCompress(snap snapHelper, rootDir string, secret string) error { snap.Task.Log("---------------------- 7 / 8 ----------------------") snap.Task.LogStart(i18n.GetMsgByKey("SnapCompress")) - tmpDir := path.Join(global.CONF.System.TmpDir, "system") + tmpDir := path.Join(global.Dir.TmpDir, "system") fileName := fmt.Sprintf("%s.tar.gz", path.Base(rootDir)) err := snap.FileOp.TarGzCompressPro(true, rootDir, path.Join(tmpDir, fileName), secret, "") snap.Task.LogWithStatus(i18n.GetMsgByKey("SnapCompressFile"), err) @@ -482,7 +482,7 @@ func snapUpload(snap snapHelper, accounts string, file string) error { snap.Task.Log("---------------------- 8 / 8 ----------------------") snap.Task.LogStart(i18n.GetMsgByKey("SnapUpload")) - source := path.Join(global.CONF.System.TmpDir, "system", path.Base(file)) + source := path.Join(global.Dir.TmpDir, "system", path.Base(file)) accountMap, err := NewBackupClientMap(strings.Split(accounts, ",")) snap.Task.LogWithStatus(i18n.GetMsgByKey("SnapLoadBackup"), err) if err != nil { diff --git a/agent/app/service/snapshot_recover.go b/agent/app/service/snapshot_recover.go index 42f4db3f9..26eeb8d58 100644 --- a/agent/app/service/snapshot_recover.go +++ b/agent/app/service/snapshot_recover.go @@ -4,12 +4,13 @@ import ( "context" "encoding/json" "fmt" - "github.com/1Panel-dev/1Panel/agent/app/repo" "os" "path" "strings" "sync" + "github.com/1Panel-dev/1Panel/agent/app/repo" + "github.com/1Panel-dev/1Panel/agent/app/dto" "github.com/1Panel-dev/1Panel/agent/app/model" "github.com/1Panel-dev/1Panel/agent/app/task" @@ -60,7 +61,7 @@ func (u *SnapshotService) SnapshotRecover(req dto.SnapshotRecover) error { global.LOG.Errorf("new task for create snapshot failed, err: %v", err) return err } - rootDir := path.Join(global.CONF.System.TmpDir, "system", snap.Name) + rootDir := path.Join(global.Dir.TmpDir, "system", snap.Name) if _, err := os.Stat(rootDir); err != nil && os.IsNotExist(err) { _ = os.MkdirAll(rootDir, os.ModePerm) } @@ -204,19 +205,19 @@ func backupBeforeRecover(name string, itemHelper *snapRecoverHelper) error { itemHelper.Task.Log("---------------------- 3 / 10 ----------------------") itemHelper.Task.LogStart(i18n.GetMsgByKey("BackupBeforeRecover")) - rootDir := fmt.Sprintf("%s/1panel_original/original_%s", global.CONF.System.BaseDir, name) + rootDir := fmt.Sprintf("%s/1panel_original/original_%s", global.Dir.BaseDir, name) baseDir := path.Join(rootDir, "base") if _, err := os.Stat(baseDir); err != nil { _ = os.MkdirAll(baseDir, os.ModePerm) } - err := itemHelper.FileOp.CopyDirWithExclude(path.Join(global.CONF.System.BaseDir, "1panel"), rootDir, []string{"cache", "tmp"}) - itemHelper.Task.LogWithStatus(i18n.GetWithName("SnapCopy", path.Join(global.CONF.System.BaseDir, "1panel")), err) + err := itemHelper.FileOp.CopyDirWithExclude(global.Dir.DataDir, rootDir, []string{"cache", "tmp"}) + itemHelper.Task.LogWithStatus(i18n.GetWithName("SnapCopy", global.Dir.DataDir), err) if err != nil { return err } - err = itemHelper.FileOp.CopyDirWithExclude(global.CONF.System.Backup, rootDir, []string{"system_snapshot"}) - itemHelper.Task.LogWithStatus(i18n.GetWithName("SnapCopy", global.CONF.System.Backup), err) + err = itemHelper.FileOp.CopyDirWithExclude(global.Dir.LocalBackupDir, rootDir, []string{"system_snapshot"}) + itemHelper.Task.LogWithStatus(i18n.GetWithName("SnapCopy", global.Dir.LocalBackupDir), err) if err != nil { return err } @@ -369,7 +370,7 @@ func recoverBaseData(src string, itemHelper *snapRecoverHelper) error { func recoverDBData(src string, itemHelper *snapRecoverHelper) error { itemHelper.Task.Log("---------------------- 7 / 10 ----------------------") itemHelper.Task.LogStart(i18n.GetMsgByKey("RecoverDBData")) - err := itemHelper.FileOp.CopyDirWithExclude(src, path.Join(global.CONF.System.BaseDir, "1panel"), nil) + err := itemHelper.FileOp.CopyDirWithExclude(src, global.Dir.DataDir, nil) itemHelper.Task.LogWithStatus(i18n.GetMsgByKey("RecoverDBData"), err) return err diff --git a/agent/app/service/snapshot_rollback.go b/agent/app/service/snapshot_rollback.go index f2ab1e35a..f0da28fcc 100644 --- a/agent/app/service/snapshot_rollback.go +++ b/agent/app/service/snapshot_rollback.go @@ -2,10 +2,11 @@ package service import ( "fmt" - "github.com/1Panel-dev/1Panel/agent/app/repo" "os" "path" + "github.com/1Panel-dev/1Panel/agent/app/repo" + "github.com/1Panel-dev/1Panel/agent/app/dto" "github.com/1Panel-dev/1Panel/agent/app/task" "github.com/1Panel-dev/1Panel/agent/constant" @@ -31,7 +32,7 @@ func (u *SnapshotService) SnapshotRollback(req dto.SnapshotRecover) error { return err } go func() { - rootDir := fmt.Sprintf("%s/1panel_original/original_%s", global.CONF.System.BaseDir, snap.Name) + rootDir := fmt.Sprintf("%s/1panel_original/original_%s", global.Dir.BaseDir, snap.Name) baseDir := path.Join(rootDir, "base") FileOp := files.NewFileOp() @@ -78,16 +79,16 @@ func (u *SnapshotService) SnapshotRollback(req dto.SnapshotRecover) error { nil, ) taskItem.AddSubTask( - i18n.GetWithName("SnapCopy", global.CONF.System.Backup), + i18n.GetWithName("SnapCopy", global.Dir.LocalBackupDir), func(t *task.Task) error { - return FileOp.CopyDir(path.Join(rootDir, "backup"), global.CONF.System.Backup) + return FileOp.CopyDir(path.Join(rootDir, "backup"), global.Dir.LocalBackupDir) }, nil, ) taskItem.AddSubTask( - i18n.GetWithName("SnapCopy", global.CONF.System.BaseDir), + i18n.GetWithName("SnapCopy", global.Dir.BaseDir), func(t *task.Task) error { - return FileOp.CopyDir(path.Join(rootDir, "1panel"), global.CONF.System.BaseDir) + return FileOp.CopyDir(path.Join(rootDir, "1panel"), global.Dir.BaseDir) }, nil, ) diff --git a/agent/app/service/ssh.go b/agent/app/service/ssh.go index 75b94c879..58125209b 100644 --- a/agent/app/service/ssh.go +++ b/agent/app/service/ssh.go @@ -2,8 +2,6 @@ package service import ( "fmt" - "github.com/1Panel-dev/1Panel/agent/utils/geo" - "github.com/gin-gonic/gin" "os" "os/user" "path" @@ -12,6 +10,9 @@ import ( "strings" "time" + "github.com/1Panel-dev/1Panel/agent/utils/geo" + "github.com/gin-gonic/gin" + "github.com/1Panel-dev/1Panel/agent/app/dto" "github.com/1Panel-dev/1Panel/agent/buserr" "github.com/1Panel-dev/1Panel/agent/constant" @@ -216,7 +217,7 @@ func (u *SSHService) UpdateByFile(value string) error { func (u *SSHService) GenerateSSH(req dto.GenerateSSH) error { if cmd.CheckIllegal(req.EncryptionMode, req.Password) { - return buserr.New(constant.ErrCmdIllegal) + return buserr.New("ErrCmdIllegal") } currentUser, err := user.Current() if err != nil { diff --git a/agent/app/service/website.go b/agent/app/service/website.go index 5f80e0f72..cb8a77ca9 100644 --- a/agent/app/service/website.go +++ b/agent/app/service/website.go @@ -232,7 +232,7 @@ func (w WebsiteService) CreateWebsite(create request.WebsiteCreate) (err error) } } if exist, _ := websiteRepo.GetBy(websiteRepo.WithAlias(alias)); len(exist) > 0 { - return buserr.New(constant.ErrAliasIsExist) + return buserr.New("ErrAliasIsExist") } if len(create.FtpPassword) != 0 { pass, err := base64.StdEncoding.DecodeString(create.FtpPassword) @@ -297,7 +297,7 @@ func (w WebsiteService) CreateWebsite(create request.WebsiteCreate) (err error) case constant.AppPostgresql, constant.AppPostgres: oldPostgresqlDb, _ := postgresqlRepo.Get(repo.WithByName(create.DbName), repo.WithByFrom(constant.ResourceLocal)) if oldPostgresqlDb.ID > 0 { - return buserr.New(constant.ErrDbUserNotValid) + return buserr.New("ErrDbUserNotValid") } var createPostgresql dto.PostgresqlDBCreate createPostgresql.Name = dbConfig.DbName @@ -316,7 +316,7 @@ func (w WebsiteService) CreateWebsite(create request.WebsiteCreate) (err error) case constant.AppMysql, constant.AppMariaDB: oldMysqlDb, _ := mysqlRepo.Get(repo.WithByName(dbConfig.DbName), repo.WithByFrom(constant.ResourceLocal)) if oldMysqlDb.ID > 0 { - return buserr.New(constant.ErrDbUserNotValid) + return buserr.New("ErrDbUserNotValid") } var createMysql dto.MysqlDBCreate createMysql.Name = dbConfig.DbName @@ -616,7 +616,7 @@ func (w WebsiteService) DeleteWebsite(req request.WebsiteDelete) error { } tx.Commit() - uploadDir := path.Join(global.CONF.System.BaseDir, fmt.Sprintf("1panel/uploads/website/%s", website.Alias)) + uploadDir := path.Join(global.Dir.DataDir, "uploads/website", website.Alias) if _, err := os.Stat(uploadDir); err == nil { _ = os.RemoveAll(uploadDir) } @@ -1130,7 +1130,7 @@ func (w WebsiteService) PreInstallCheck(req request.WebsiteInstallCheckReq) ([]r res = append(res, response.WebsitePreInstallCheck{ Name: appInstall.Name, AppName: app.Name, - Status: buserr.WithDetail(constant.ErrNotInstall, app.Name, nil).Error(), + Status: buserr.WithDetail("ErrNotInstall", app.Name, nil).Error(), Version: appInstall.Version, }) showErr = true @@ -1473,7 +1473,7 @@ func (w WebsiteService) OperateCustomRewrite(req request.CustomRewriteOperate) e switch req.Operate { case "create": if fileOp.Stat(rewriteFile) { - return buserr.New(constant.ErrNameIsExist) + return buserr.New("ErrNameIsExist") } return fileOp.WriteFile(rewriteFile, strings.NewReader(req.Content), constant.DirPerm) case "delete": @@ -1562,7 +1562,7 @@ func (w WebsiteService) OperateProxy(req request.WebsiteProxyConfig) (err error) backPath := path.Join(includeDir, backName) if req.Operate == "create" && (fileOp.Stat(includePath) || fileOp.Stat(backPath)) { - err = buserr.New(constant.ErrNameIsExist) + err = buserr.New("ErrNameIsExist") return } @@ -1642,7 +1642,7 @@ func (w WebsiteService) OperateProxy(req request.WebsiteProxyConfig) (err error) location.UpdateDirective("proxy_ssl_server_name", []string{"off"}) } if err = nginx.WriteConfig(config, nginx.IndentedStyle); err != nil { - return buserr.WithErr(constant.ErrUpdateBuWebsite, err) + return buserr.WithErr("ErrUpdateBuWebsite", err) } nginxInclude := fmt.Sprintf("/www/sites/%s/proxy/*.conf", website.Alias) return updateNginxConfig(constant.NginxScopeServer, []dto.NginxParam{{Name: "include", Params: []string{nginxInclude}}}, &website) @@ -1935,7 +1935,7 @@ func (w WebsiteService) UpdateAuthBasic(req request.NginxAuthUpdate) (err error) authParams := strings.Split(line, ":") username := authParams[0] if username == req.Username { - err = buserr.New(constant.ErrUsernameIsExist) + err = buserr.New("ErrUsernameIsExist") return } } @@ -1969,7 +1969,7 @@ func (w WebsiteService) UpdateAuthBasic(req request.NginxAuthUpdate) (err error) } } if !userExist { - err = buserr.New(constant.ErrUsernameIsNotExist) + err = buserr.New("ErrUsernameIsNotExist") return } case "delete": @@ -2120,7 +2120,7 @@ func (w WebsiteService) UpdatePathAuthBasic(req request.NginxPathAuthUpdate) err return err } if fileOp.Stat(confPath) || fileOp.Stat(passPath) { - return buserr.New(constant.ErrNameIsExist) + return buserr.New("ErrNameIsExist") } case "edit": par, err := parser.NewParser(confPath) @@ -2148,7 +2148,7 @@ func (w WebsiteService) UpdatePathAuthBasic(req request.NginxPathAuthUpdate) err } _ = fileOp.SaveFile(passPath, line, constant.DirPerm) if err = nginx.WriteConfig(config, nginx.IndentedStyle); err != nil { - return buserr.WithErr(constant.ErrUpdateBuWebsite, err) + return buserr.WithErr("ErrUpdateBuWebsite", err) } nginxInclude := fmt.Sprintf("/www/sites/%s/path_auth/*.conf", website.Alias) if err = updateNginxConfig(constant.NginxScopeServer, []dto.NginxParam{{Name: "include", Params: []string{nginxInclude}}}, &website); err != nil { @@ -2343,7 +2343,7 @@ func (w WebsiteService) OperateRedirect(req request.NginxRedirectReq) (err error backPath := path.Join(includeDir, backName) if req.Operate == "create" && (fileOp.Stat(includePath) || fileOp.Stat(backPath)) { - err = buserr.New(constant.ErrNameIsExist) + err = buserr.New("ErrNameIsExist") return } @@ -2461,7 +2461,7 @@ func (w WebsiteService) OperateRedirect(req request.NginxRedirectReq) (err error config.Block = block if err = nginx.WriteConfig(config, nginx.IndentedStyle); err != nil { - return buserr.WithErr(constant.ErrUpdateBuWebsite, err) + return buserr.WithErr("ErrUpdateBuWebsite", err) } nginxInclude := fmt.Sprintf("/www/sites/%s/redirect/*.conf", website.Alias) @@ -2876,7 +2876,7 @@ func (w WebsiteService) CreateLoadBalance(req request.WebsiteLBCreate) error { } filePath := path.Join(includeDir, fmt.Sprintf("%s.conf", req.Name)) if fileOp.Stat(filePath) { - return buserr.New(constant.ErrNameIsExist) + return buserr.New("ErrNameIsExist") } config, err := parser.NewStringParser(string(nginx_conf.Upstream)).Parse() if err != nil { @@ -2926,7 +2926,7 @@ func (w WebsiteService) CreateLoadBalance(req request.WebsiteLBCreate) error { }() if err = nginx.WriteConfig(config, nginx.IndentedStyle); err != nil { - return buserr.WithErr(constant.ErrUpdateBuWebsite, err) + return buserr.WithErr("ErrUpdateBuWebsite", err) } nginxInclude := fmt.Sprintf("/www/sites/%s/upstream/*.conf", website.Alias) if err = updateNginxConfig("", []dto.NginxParam{{Name: "include", Params: []string{nginxInclude}}}, &website); err != nil { @@ -2999,7 +2999,7 @@ func (w WebsiteService) UpdateLoadBalance(req request.WebsiteLBUpdate) error { } } if err = nginx.WriteConfig(config, nginx.IndentedStyle); err != nil { - return buserr.WithErr(constant.ErrUpdateBuWebsite, err) + return buserr.WithErr("ErrUpdateBuWebsite", err) } if err = opNginx(nginxInstall.ContainerName, constant.NginxReload); err != nil { return err diff --git a/agent/app/service/website_acme_account.go b/agent/app/service/website_acme_account.go index 06665bb6e..1c74dac29 100644 --- a/agent/app/service/website_acme_account.go +++ b/agent/app/service/website_acme_account.go @@ -7,7 +7,6 @@ import ( "github.com/1Panel-dev/1Panel/agent/app/model" "github.com/1Panel-dev/1Panel/agent/app/repo" "github.com/1Panel-dev/1Panel/agent/buserr" - "github.com/1Panel-dev/1Panel/agent/constant" "github.com/1Panel-dev/1Panel/agent/utils/ssl" ) @@ -38,7 +37,7 @@ func (w WebsiteAcmeAccountService) Page(search dto.PageInfo) (int64, []response. func (w WebsiteAcmeAccountService) Create(create request.WebsiteAcmeAccountCreate) (*response.WebsiteAcmeAccountDTO, error) { exist, _ := websiteAcmeRepo.GetFirst(websiteAcmeRepo.WithEmail(create.Email), websiteAcmeRepo.WithType(create.Type)) if exist != nil { - return nil, buserr.New(constant.ErrEmailIsExist) + return nil, buserr.New("ErrEmailIsExist") } acmeAccount := &model.WebsiteAcmeAccount{ Email: create.Email, @@ -48,7 +47,7 @@ func (w WebsiteAcmeAccountService) Create(create request.WebsiteAcmeAccountCreat if create.Type == "google" { if create.EabKid == "" || create.EabHmacKey == "" { - return nil, buserr.New(constant.ErrEabKidOrEabHmacKeyCannotBlank) + return nil, buserr.New("ErrEabKidOrEabHmacKeyCannotBlank") } acmeAccount.EabKid = create.EabKid acmeAccount.EabHmacKey = create.EabHmacKey @@ -73,7 +72,7 @@ func (w WebsiteAcmeAccountService) Create(create request.WebsiteAcmeAccountCreat func (w WebsiteAcmeAccountService) Delete(id uint) error { if ssls, _ := websiteSSLRepo.List(websiteSSLRepo.WithByAcmeAccountId(id)); len(ssls) > 0 { - return buserr.New(constant.ErrAccountCannotDelete) + return buserr.New("ErrAccountCannotDelete") } return websiteAcmeRepo.DeleteBy(repo.WithByID(id)) } diff --git a/agent/app/service/website_ca.go b/agent/app/service/website_ca.go index bd17e9a93..a0315d49b 100644 --- a/agent/app/service/website_ca.go +++ b/agent/app/service/website_ca.go @@ -10,8 +10,6 @@ import ( "crypto/x509/pkix" "encoding/pem" "fmt" - "github.com/1Panel-dev/1Panel/agent/app/repo" - "github.com/1Panel-dev/1Panel/agent/utils/common" "log" "math/big" "net" @@ -20,6 +18,9 @@ import ( "strings" "time" + "github.com/1Panel-dev/1Panel/agent/app/repo" + "github.com/1Panel-dev/1Panel/agent/utils/common" + "github.com/1Panel-dev/1Panel/agent/app/dto/request" "github.com/1Panel-dev/1Panel/agent/app/dto/response" "github.com/1Panel-dev/1Panel/agent/app/model" @@ -65,7 +66,7 @@ func (w WebsiteCAService) Page(search request.WebsiteCASearch) (int64, []respons func (w WebsiteCAService) Create(create request.WebsiteCACreate) (*request.WebsiteCACreate, error) { if exist, _ := websiteCARepo.GetFirst(repo.WithByName(create.Name)); exist.ID > 0 { - return nil, buserr.New(constant.ErrNameIsExist) + return nil, buserr.New("ErrNameIsExist") } ca := &model.WebsiteCA{ @@ -212,7 +213,7 @@ func (w WebsiteCAService) ObtainSSL(req request.WebsiteCAObtain) (*model.Website } if req.PushDir { if !files.NewFileOp().Stat(req.Dir) { - return nil, buserr.New(constant.ErrLinkPathNotFound) + return nil, buserr.New("ErrLinkPathNotFound") } websiteSSL.Dir = req.Dir } @@ -366,13 +367,13 @@ func (w WebsiteCAService) ObtainSSL(req request.WebsiteCAObtain) (*model.Website } } - logFile, _ := os.OpenFile(path.Join(constant.SSLLogDir, fmt.Sprintf("%s-ssl-%d.log", websiteSSL.PrimaryDomain, websiteSSL.ID)), os.O_CREATE|os.O_WRONLY|os.O_TRUNC, constant.FilePerm) + logFile, _ := os.OpenFile(path.Join(global.Dir.SSLLogDir, fmt.Sprintf("%s-ssl-%d.log", websiteSSL.PrimaryDomain, websiteSSL.ID)), os.O_CREATE|os.O_WRONLY|os.O_TRUNC, constant.FilePerm) defer logFile.Close() logger := log.New(logFile, "", log.LstdFlags) logger.Println(i18n.GetMsgWithMap("ApplySSLSuccess", map[string]interface{}{"domain": strings.Join(domains, ",")})) saveCertificateFile(websiteSSL, logger) if websiteSSL.ExecShell { - workDir := constant.DataDir + workDir := global.Dir.DataDir if websiteSSL.PushDir { workDir = websiteSSL.Dir } @@ -425,7 +426,7 @@ func (w WebsiteCAService) DownloadFile(id uint) (*os.File, error) { return nil, err } fileOp := files.NewFileOp() - dir := path.Join(global.CONF.System.BaseDir, "1panel/tmp/ssl", ca.Name) + dir := path.Join(global.Dir.DataDir, "tmp/ssl", ca.Name) if fileOp.Stat(dir) { if err = fileOp.DeleteDir(dir); err != nil { return nil, err diff --git a/agent/app/service/website_dns_account.go b/agent/app/service/website_dns_account.go index b45ff9d0c..61b84e0d7 100644 --- a/agent/app/service/website_dns_account.go +++ b/agent/app/service/website_dns_account.go @@ -2,6 +2,7 @@ package service import ( "encoding/json" + "github.com/1Panel-dev/1Panel/agent/app/repo" "github.com/1Panel-dev/1Panel/agent/app/dto" @@ -9,7 +10,6 @@ import ( "github.com/1Panel-dev/1Panel/agent/app/dto/response" "github.com/1Panel-dev/1Panel/agent/app/model" "github.com/1Panel-dev/1Panel/agent/buserr" - "github.com/1Panel-dev/1Panel/agent/constant" ) type WebsiteDnsAccountService struct { @@ -43,7 +43,7 @@ func (w WebsiteDnsAccountService) Page(search dto.PageInfo) (int64, []response.W func (w WebsiteDnsAccountService) Create(create request.WebsiteDnsAccountCreate) (request.WebsiteDnsAccountCreate, error) { exist, _ := websiteDnsRepo.GetFirst(repo.WithByName(create.Name)) if exist != nil { - return request.WebsiteDnsAccountCreate{}, buserr.New(constant.ErrNameIsExist) + return request.WebsiteDnsAccountCreate{}, buserr.New("ErrNameIsExist") } authorization, err := json.Marshal(create.Authorization) @@ -70,7 +70,7 @@ func (w WebsiteDnsAccountService) Update(update request.WebsiteDnsAccountUpdate) exists, _ := websiteDnsRepo.List(repo.WithByName(update.Name)) for _, exist := range exists { if exist.ID != update.ID { - return request.WebsiteDnsAccountUpdate{}, buserr.New(constant.ErrNameIsExist) + return request.WebsiteDnsAccountUpdate{}, buserr.New("ErrNameIsExist") } } if err := websiteDnsRepo.Save(model.WebsiteDnsAccount{ @@ -89,7 +89,7 @@ func (w WebsiteDnsAccountService) Update(update request.WebsiteDnsAccountUpdate) func (w WebsiteDnsAccountService) Delete(id uint) error { if ssls, _ := websiteSSLRepo.List(websiteSSLRepo.WithByDnsAccountId(id)); len(ssls) > 0 { - return buserr.New(constant.ErrAccountCannotDelete) + return buserr.New("ErrAccountCannotDelete") } return websiteDnsRepo.DeleteBy(repo.WithByID(id)) } diff --git a/agent/app/service/website_ssl.go b/agent/app/service/website_ssl.go index a7d064ec2..ac53b865f 100644 --- a/agent/app/service/website_ssl.go +++ b/agent/app/service/website_ssl.go @@ -64,7 +64,7 @@ func (w WebsiteSSLService) Page(search request.WebsiteSSLSearch) (int64, []respo for _, model := range sslList { result = append(result, response.WebsiteSSLDTO{ WebsiteSSL: model, - LogPath: path.Join(constant.SSLLogDir, fmt.Sprintf("%s-ssl-%d.log", model.PrimaryDomain, model.ID)), + LogPath: path.Join(global.Dir.SSLLogDir, fmt.Sprintf("%s-ssl-%d.log", model.PrimaryDomain, model.ID)), }) } return total, result, err @@ -194,8 +194,8 @@ func reloadSystemSSL(websiteSSL *model.WebsiteSSL, logger *log.Logger) { systemSSLEnable, sslID := GetSystemSSL() if systemSSLEnable && sslID == websiteSSL.ID { fileOp := files.NewFileOp() - certPath := path.Join(global.CONF.System.BaseDir, "1panel/secret/server.crt") - keyPath := path.Join(global.CONF.System.BaseDir, "1panel/secret/server.key") + certPath := path.Join(global.Dir.DataDir, "secret/server.crt") + keyPath := path.Join(global.Dir.DataDir, "secret/server.key") printSSLLog(logger, "StartUpdateSystemSSL", nil, logger == nil) if err := fileOp.WriteFile(certPath, strings.NewReader(websiteSSL.Pem), 0600); err != nil { logger.Printf("Failed to update the SSL certificate File for 1Panel System domain [%s] , err:%s", websiteSSL.PrimaryDomain, err.Error()) @@ -300,7 +300,7 @@ func (w WebsiteSSLService) ObtainSSL(apply request.WebsiteSSLApply) error { } go func() { - logFile, _ := os.OpenFile(path.Join(constant.SSLLogDir, fmt.Sprintf("%s-ssl-%d.log", websiteSSL.PrimaryDomain, websiteSSL.ID)), os.O_CREATE|os.O_WRONLY|os.O_TRUNC, constant.FilePerm) + logFile, _ := os.OpenFile(path.Join(global.Dir.SSLLogDir, fmt.Sprintf("%s-ssl-%d.log", websiteSSL.PrimaryDomain, websiteSSL.ID)), os.O_CREATE|os.O_WRONLY|os.O_TRUNC, constant.FilePerm) defer logFile.Close() logger := log.New(logFile, "", log.LstdFlags) legoLogger.Logger = logger @@ -334,7 +334,7 @@ func (w WebsiteSSLService) ObtainSSL(apply request.WebsiteSSLApply) error { saveCertificateFile(websiteSSL, logger) if websiteSSL.ExecShell { - workDir := constant.DataDir + workDir := global.Dir.DataDir if websiteSSL.PushDir { workDir = websiteSSL.Dir } @@ -364,7 +364,7 @@ func (w WebsiteSSLService) ObtainSSL(apply request.WebsiteSSLApply) error { return } if err := opNginx(nginxInstall.ContainerName, constant.NginxReload); err != nil { - printSSLLog(logger, constant.ErrSSLApply, nil, apply.DisableLog) + printSSLLog(logger, "ErrSSLApply", nil, apply.DisableLog) return } printSSLLog(logger, "ApplyWebSiteSSLSuccess", nil, apply.DisableLog) @@ -636,7 +636,7 @@ func (w WebsiteSSLService) DownloadFile(id uint) (*os.File, error) { return nil, err } fileOp := files.NewFileOp() - dir := path.Join(global.CONF.System.BaseDir, "1panel/tmp/ssl", websiteSSL.PrimaryDomain) + dir := path.Join(global.Dir.DataDir, "tmp/ssl", websiteSSL.PrimaryDomain) if fileOp.Stat(dir) { if err = fileOp.DeleteDir(dir); err != nil { return nil, err diff --git a/agent/app/service/website_utils.go b/agent/app/service/website_utils.go index 527f94b6c..d9c6ad82a 100644 --- a/agent/app/service/website_utils.go +++ b/agent/app/service/website_utils.go @@ -3,7 +3,6 @@ package service import ( "encoding/json" "fmt" - "github.com/1Panel-dev/1Panel/agent/app/repo" "log" "os" "path" @@ -12,6 +11,8 @@ import ( "strings" "time" + "github.com/1Panel-dev/1Panel/agent/app/repo" + "github.com/1Panel-dev/1Panel/agent/utils/xpack" "github.com/1Panel-dev/1Panel/agent/app/dto/request" @@ -118,7 +119,7 @@ func createProxyFile(website *model.Website) error { location.UpdateDirective("proxy_pass", []string{website.Proxy}) location.UpdateDirective("proxy_set_header", []string{"Host", "$host"}) if err := nginx.WriteConfig(config, nginx.IndentedStyle); err != nil { - return buserr.WithErr(constant.ErrUpdateBuWebsite, err) + return buserr.WithErr("ErrUpdateBuWebsite", err) } return nil } @@ -760,7 +761,7 @@ func toMapStr(m map[string]interface{}) map[string]string { } func deleteWebsiteFolder(nginxInstall model.AppInstall, website *model.Website) error { - nginxFolder := path.Join(constant.AppInstallDir, constant.AppOpenresty, nginxInstall.Name) + nginxFolder := path.Join(global.Dir.AppInstallDir, constant.AppOpenresty, nginxInstall.Name) siteFolder := path.Join(nginxFolder, "www", "sites", website.Alias) fileOp := files.NewFileOp() if fileOp.Stat(siteFolder) { @@ -965,7 +966,7 @@ func getWebsiteDomains(domains []request.WebsiteDomain, defaultPort int, website for _, domain := range domainModels { if exist, _ := websiteDomainRepo.GetFirst(websiteDomainRepo.WithDomain(domain.Domain), websiteDomainRepo.WithPort(domain.Port)); exist.ID > 0 { website, _ := websiteRepo.GetFirst(repo.WithByID(exist.WebsiteID)) - err = buserr.WithName(constant.ErrDomainIsUsed, website.PrimaryDomain) + err = buserr.WithName("ErrDomainIsUsed", website.PrimaryDomain) return } } @@ -993,7 +994,7 @@ func getWebsiteDomains(domains []request.WebsiteDomain, defaultPort int, website return } if common.ScanPort(port) { - err = buserr.WithDetail(constant.ErrPortInUsed, port, nil) + err = buserr.WithDetail("ErrPortInUsed", port, nil) return } } @@ -1057,13 +1058,13 @@ func UpdateSSLConfig(websiteSSL model.WebsiteSSL) error { return err } if err := opNginx(nginxInstall.ContainerName, constant.NginxReload); err != nil { - return buserr.WithErr(constant.ErrSSLApply, err) + return buserr.WithErr("ErrSSLApply", err) } } enable, sslID := GetSystemSSL() if enable && sslID == websiteSSL.ID { fileOp := files.NewFileOp() - secretDir := path.Join(global.CONF.System.BaseDir, "1panel/secret") + secretDir := path.Join(global.Dir.DataDir, "secret") if err := fileOp.WriteFile(path.Join(secretDir, "server.crt"), strings.NewReader(websiteSSL.Pem), 0600); err != nil { global.LOG.Errorf("Failed to update the SSL certificate File for 1Panel System domain [%s] , err:%s", websiteSSL.PrimaryDomain, err.Error()) return err @@ -1108,7 +1109,7 @@ func ChangeHSTSConfig(enable bool, nginxInstall model.AppInstall, website model. location.RemoveDirective("add_header", []string{"Strict-Transport-Security", "\"max-age=31536000\""}) } if err = nginx.WriteConfig(config, nginx.IndentedStyle); err != nil { - return buserr.WithErr(constant.ErrUpdateBuWebsite, err) + return buserr.WithErr("ErrUpdateBuWebsite", err) } } } @@ -1147,7 +1148,7 @@ func GetWebSiteRootDir() string { siteSetting, _ := settingRepo.Get(settingRepo.WithByKey("WEBSITE_DIR")) dir := siteSetting.Value if dir == "" { - dir = path.Join(constant.DataDir, "www") + dir = path.Join(global.Dir.DataDir, "www") } return dir } diff --git a/agent/app/task/task.go b/agent/app/task/task.go index 243d5fcf6..320db398c 100644 --- a/agent/app/task/task.go +++ b/agent/app/task/task.go @@ -10,6 +10,7 @@ import ( "time" "github.com/1Panel-dev/1Panel/agent/buserr" + "github.com/1Panel-dev/1Panel/agent/global" "github.com/1Panel-dev/1Panel/agent/app/model" "github.com/1Panel-dev/1Panel/agent/app/repo" @@ -99,13 +100,13 @@ func NewTask(name, operate, taskScope, taskID string, resourceID uint) (*Task, e if taskID == "" { taskID = uuid.New().String() } - logDir := path.Join(constant.LogDir, taskScope) + logDir := path.Join(global.Dir.LogDir, taskScope) if _, err := os.Stat(logDir); os.IsNotExist(err) { if err = os.MkdirAll(logDir, constant.DirPerm); err != nil { return nil, fmt.Errorf("failed to create log directory: %w", err) } } - logPath := path.Join(constant.LogDir, taskScope, taskID+".log") + logPath := path.Join(global.Dir.LogDir, taskScope, taskID+".log") file, err := os.OpenFile(logPath, os.O_TRUNC|os.O_CREATE|os.O_WRONLY, constant.FilePerm) if err != nil { return nil, fmt.Errorf("failed to open log file: %w", err) diff --git a/agent/cmd/server/conf/app.yaml b/agent/cmd/server/conf/app.yaml index 4bc15ba72..c49283ac0 100644 --- a/agent/cmd/server/conf/app.yaml +++ b/agent/cmd/server/conf/app.yaml @@ -1,6 +1,8 @@ -system: - base_dir: /opt +base: + install_dir: /opt mode: dev + +remote_rul: repo_url: https://resource.fit2cloud.com/1panel/package resource_url: https://resource.fit2cloud.com/1panel/resource app_repo: https://apps-assets.fit2cloud.com diff --git a/agent/configs/config.go b/agent/configs/config.go deleted file mode 100644 index 7d8116b68..000000000 --- a/agent/configs/config.go +++ /dev/null @@ -1,6 +0,0 @@ -package configs - -type ServerConfig struct { - System System `mapstructure:"system"` - LogConfig LogConfig `mapstructure:"log"` -} diff --git a/agent/configs/log.go b/agent/configs/log.go deleted file mode 100644 index 8fe60a91d..000000000 --- a/agent/configs/log.go +++ /dev/null @@ -1,9 +0,0 @@ -package configs - -type LogConfig struct { - Level string `mapstructure:"level"` - TimeZone string `mapstructure:"timeZone"` - LogName string `mapstructure:"log_name"` - LogSuffix string `mapstructure:"log_suffix"` - MaxBackup int `mapstructure:"max_backup"` -} diff --git a/agent/configs/system.go b/agent/configs/system.go deleted file mode 100644 index 56ee39955..000000000 --- a/agent/configs/system.go +++ /dev/null @@ -1,23 +0,0 @@ -package configs - -type System struct { - Mode string `mapstructure:"mode"` - - Port string `mapstructure:"port"` - Version string `mapstructure:"version"` - BaseDir string `mapstructure:"base_dir"` - EncryptKey string `mapstructure:"encrypt_key"` - - DbFile string `mapstructure:"db_agent_file"` - DbPath string `mapstructure:"db_path"` - LogPath string `mapstructure:"log_path"` - DataDir string `mapstructure:"data_dir"` - TmpDir string `mapstructure:"tmp_dir"` - Cache string `mapstructure:"cache"` - Backup string `mapstructure:"backup"` - - RepoUrl string `mapstructure:"repo_url"` - ResourceUrl string `mapstructure:"resource_url"` - IsDemo bool `mapstructure:"is_demo"` - AppRepo string `mapstructure:"app_repo"` -} diff --git a/agent/constant/dir.go b/agent/constant/dir.go deleted file mode 100644 index 743d50c0e..000000000 --- a/agent/constant/dir.go +++ /dev/null @@ -1,22 +0,0 @@ -package constant - -import ( - "path" - - "github.com/1Panel-dev/1Panel/agent/global" -) - -var ( - DataDir = global.CONF.System.DataDir - ResourceDir = path.Join(DataDir, "resource") - AppResourceDir = path.Join(ResourceDir, "apps") - AppInstallDir = path.Join(DataDir, "apps") - LocalAppResourceDir = path.Join(AppResourceDir, "local") - LocalAppInstallDir = path.Join(AppInstallDir, "local") - RemoteAppResourceDir = path.Join(AppResourceDir, "remote") - CustomAppResourceDir = path.Join(AppResourceDir, "custom") - RuntimeDir = path.Join(DataDir, "runtime") - RecycleBinDir = "/.1panel_clash" - SSLLogDir = path.Join(global.CONF.System.DataDir, "log", "ssl") - LogDir = path.Join(global.CONF.System.DataDir, "log") -) diff --git a/agent/constant/errs.go b/agent/constant/errs.go deleted file mode 100644 index edff902e8..000000000 --- a/agent/constant/errs.go +++ /dev/null @@ -1,155 +0,0 @@ -package constant - -import ( - "errors" -) - -const ( - CodeSuccess = 200 - CodeErrBadRequest = 400 - CodeGlobalLoading = 407 - CodeErrInternalServer = 500 - - CodeErrXpack = 410 -) - -// internal -var ( - ErrRecordExist = errors.New("ErrRecordExist") - ErrRecordNotFound = errors.New("ErrRecordNotFound") - ErrStructTransform = errors.New("ErrStructTransform") - ErrNotSupportType = errors.New("ErrNotSupportType") - ErrInvalidParams = errors.New("ErrInvalidParams") -) - -// api -var ( - ErrTypeInternalServer = "ErrInternalServer" - ErrTypeInvalidParams = "ErrInvalidParams" - ErrNameIsExist = "ErrNameIsExist" - ErrDemoEnvironment = "ErrDemoEnvironment" - ErrCmdIllegal = "ErrCmdIllegal" - ErrXpackNotFound = "ErrXpackNotFound" - ErrXpackExceptional = "ErrXpackExceptional" - ErrXpackOutOfDate = "ErrXpackOutOfDate" -) - -// app -var ( - ErrPortInUsed = "ErrPortInUsed" - ErrAppLimit = "ErrAppLimit" - ErrFileCanNotRead = "ErrFileCanNotRead" - ErrNotInstall = "ErrNotInstall" - ErrPortInOtherApp = "ErrPortInOtherApp" - ErrDbUserNotValid = "ErrDbUserNotValid" - ErrUpdateBuWebsite = "ErrUpdateBuWebsite" - Err1PanelNetworkFailed = "Err1PanelNetworkFailed" - ErrCmdTimeout = "ErrCmdTimeout" - ErrFileParse = "ErrFileParse" - ErrInstallDirNotFound = "ErrInstallDirNotFound" - ErrContainerName = "ErrContainerName" - ErrAppNameExist = "ErrAppNameExist" - ErrFileNotFound = "ErrFileNotFound" - ErrFileParseApp = "ErrFileParseApp" - ErrAppParamKey = "ErrAppParamKey" -) - -// website -var ( - ErrDomainIsExist = "ErrDomainIsExist" - ErrAliasIsExist = "ErrAliasIsExist" - ErrGroupIsUsed = "ErrGroupIsUsed" - ErrUsernameIsExist = "ErrUsernameIsExist" - ErrUsernameIsNotExist = "ErrUsernameIsNotExist" - ErrBackupMatch = "ErrBackupMatch" - ErrBackupExist = "ErrBackupExist" - ErrDomainIsUsed = "ErrDomainIsUsed" -) - -// ssl -var ( - ErrSSLCannotDelete = "ErrSSLCannotDelete" - ErrAccountCannotDelete = "ErrAccountCannotDelete" - ErrSSLApply = "ErrSSLApply" - ErrEmailIsExist = "ErrEmailIsExist" - ErrEabKidOrEabHmacKeyCannotBlank = "ErrEabKidOrEabHmacKeyCannotBlank" -) - -// file -var ( - ErrPathNotFound = "ErrPathNotFound" - ErrMovePathFailed = "ErrMovePathFailed" - ErrLinkPathNotFound = "ErrLinkPathNotFound" - ErrFileIsExist = "ErrFileIsExist" - ErrFileUpload = "ErrFileUpload" - ErrFileDownloadDir = "ErrFileDownloadDir" - ErrCmdNotFound = "ErrCmdNotFound" - ErrFavoriteExist = "ErrFavoriteExist" - ErrPathNotDelete = "ErrPathNotDelete" -) - -// mysql -var ( - ErrUserIsExist = "ErrUserIsExist" - ErrDatabaseIsExist = "ErrDatabaseIsExist" - ErrExecTimeOut = "ErrExecTimeOut" - ErrRemoteExist = "ErrRemoteExist" - ErrLocalExist = "ErrLocalExist" -) - -// redis -var ( - ErrTypeOfRedis = "ErrTypeOfRedis" -) - -// container -var ( - ErrInUsed = "ErrInUsed" - ErrObjectInUsed = "ErrObjectInUsed" - ErrObjectBeDependent = "ErrObjectBeDependent" - ErrPortRules = "ErrPortRules" - ErrPgImagePull = "ErrPgImagePull" -) - -// runtime -var ( - ErrDirNotFound = "ErrDirNotFound" - ErrFileNotExist = "ErrFileNotExist" - ErrImageBuildErr = "ErrImageBuildErr" - ErrImageExist = "ErrImageExist" - ErrDelWithWebsite = "ErrDelWithWebsite" - ErrRuntimeStart = "ErrRuntimeStart" - ErrPackageJsonNotFound = "ErrPackageJsonNotFound" - ErrScriptsNotFound = "ErrScriptsNotFound" -) - -var ( - ErrOSSConn = "ErrOSSConn" - ErrEntrance = "ErrEntrance" -) - -var ( - ErrFirewallNone = "ErrFirewallNone" - ErrFirewallBoth = "ErrFirewallBoth" -) - -// backup -var ( - ErrBackupInUsed = "ErrBackupInUsed" - ErrBackupCheck = "ErrBackupCheck" - ErrBackupLocalDelete = "ErrBackupLocalDelete" - ErrBackupLocalCreate = "ErrBackupLocalCreate" -) - -var ( - ErrNotExistUser = "ErrNotExistUser" -) - -// alert -var ( - ErrAlert = "ErrAlert" - ErrAlertPush = "ErrAlertPush" - ErrAlertSave = "ErrAlertSave" - ErrAlertSync = "ErrAlertSync" - ErrAlertRemote = "ErrAlertRemote" -) diff --git a/agent/global/config.go b/agent/global/config.go new file mode 100644 index 000000000..41b9d4fe4 --- /dev/null +++ b/agent/global/config.go @@ -0,0 +1,51 @@ +package global + +type ServerConfig struct { + Base Base `mapstructure:"base"` + RemoteURL RemoteURL `mapstructure:"remote_url"` + Log LogConfig `mapstructure:"log"` +} + +type Base struct { + Port string `mapstructure:"port"` + Version string `mapstructure:"version"` + EncryptKey string `mapstructure:"encrypt_key"` + Mode string `mapstructure:"mode"` // xpack [ Enable / Disable ] + IsDemo bool `mapstructure:"is_demo"` + InstallDir string `mapstructure:"install_dir"` +} + +type RemoteURL struct { + AppRepo string `mapstructure:"app_repo"` + RepoUrl string `mapstructure:"repo_url"` + ResourceUrl string `mapstructure:"resource_url"` +} + +type SystemDir struct { + BaseDir string + DbDir string + LogDir string + DataDir string + TmpDir string + LocalBackupDir string + + AppDir string + ResourceDir string + AppResourceDir string + AppInstallDir string + LocalAppResourceDir string + LocalAppInstallDir string + RemoteAppResourceDir string + CustomAppResourceDir string + RuntimeDir string + RecycleBinDir string + SSLLogDir string +} + +type LogConfig struct { + Level string `mapstructure:"level"` + TimeZone string `mapstructure:"timeZone"` + LogName string `mapstructure:"log_name"` + LogSuffix string `mapstructure:"log_suffix"` + MaxBackup int `mapstructure:"max_backup"` +} diff --git a/agent/global/global.go b/agent/global/global.go index 41aa92dbe..1cb39ddd7 100644 --- a/agent/global/global.go +++ b/agent/global/global.go @@ -1,7 +1,6 @@ package global import ( - "github.com/1Panel-dev/1Panel/agent/configs" badger_db "github.com/1Panel-dev/1Panel/agent/init/cache/db" "github.com/go-playground/validator/v10" "github.com/nicksnyder/go-i18n/v2/i18n" @@ -16,11 +15,14 @@ var ( MonitorDB *gorm.DB TaskDB *gorm.DB CoreDB *gorm.DB - LOG *logrus.Logger - CONF configs.ServerConfig - VALID *validator.Validate - CACHE *badger_db.Cache - Viper *viper.Viper + + LOG *logrus.Logger + CONF ServerConfig + VALID *validator.Validate + CACHE *badger_db.Cache + Viper *viper.Viper + + Dir SystemDir Cron *cron.Cron MonitorCronID cron.EntryID diff --git a/agent/i18n/lang/zh.yaml b/agent/i18n/lang/zh.yaml index 5cfbb23c3..eaf95b377 100644 --- a/agent/i18n/lang/zh.yaml +++ b/agent/i18n/lang/zh.yaml @@ -4,10 +4,10 @@ ErrInitialPassword: "原密码错误" ErrInternalServer: "服务内部错误: {{ .detail }}" ErrRecordExist: "记录已存在" ErrRecordNotFound: "记录未能找到" -ErrStructTransform: "类型转换失败: {{ .detail }}" +ErrStructTransform: "类型转换失败: {{ .err }}" ErrNotLogin: "用户未登录: {{ .detail }}" ErrPasswordExpired: "当前密码已过期: {{ .detail }}" -ErrNotSupportType: "系统暂不支持当前类型: {{ .detail }}" +ErrNotSupportType: "系统暂不支持当前类型: {{ .name }}" ErrProxy: "请求错误,请检查该节点状态: {{ .detail }}" ErrApiConfigStatusInvalid: "API 接口禁止访问: {{ .detail }}" ErrApiConfigKeyInvalid: "API 接口密钥错误: {{ .detail }}" @@ -112,7 +112,6 @@ ErrPathNotDelete: "所选目录不可删除" ErrDomainIsExist: "域名已存在" ErrAliasIsExist: "代号已存在" ErrAppDelete: '其他网站使用此应用,无法删除' -ErrGroupIsUsed: '分组正在使用中,无法删除' ErrBackupMatch: '该备份文件与当前网站部分数据不匹配 {{ .detail}}' ErrBackupExist: '该备份文件对应部分源数据不存在 {{ .detail}}' ErrPHPResource: '本地运行环境不支持切换!' diff --git a/agent/init/app/app.go b/agent/init/app/app.go index 9bc5c6dcf..a8aae80ee 100644 --- a/agent/init/app/app.go +++ b/agent/init/app/app.go @@ -1,43 +1,11 @@ package app import ( - "path" - "github.com/1Panel-dev/1Panel/agent/utils/docker" "github.com/1Panel-dev/1Panel/agent/utils/firewall" - - "github.com/1Panel-dev/1Panel/agent/constant" - "github.com/1Panel-dev/1Panel/agent/global" - "github.com/1Panel-dev/1Panel/agent/utils/files" ) func Init() { - constant.DataDir = global.CONF.System.DataDir - constant.ResourceDir = path.Join(constant.DataDir, "resource") - constant.AppResourceDir = path.Join(constant.ResourceDir, "apps") - constant.AppInstallDir = path.Join(constant.DataDir, "apps") - constant.RuntimeDir = path.Join(constant.DataDir, "runtime") - - constant.LocalAppResourceDir = path.Join(constant.AppResourceDir, "local") - constant.LocalAppInstallDir = path.Join(constant.AppInstallDir, "local") - constant.RemoteAppResourceDir = path.Join(constant.AppResourceDir, "remote") - constant.CustomAppResourceDir = path.Join(constant.AppResourceDir, "custom") - - constant.LogDir = path.Join(global.CONF.System.DataDir, "log") - constant.SSLLogDir = path.Join(constant.LogDir, "ssl") - - dirs := []string{ - constant.DataDir, constant.ResourceDir, constant.AppResourceDir, constant.AppInstallDir, - global.CONF.System.Backup, constant.RuntimeDir, constant.LocalAppResourceDir, - constant.RemoteAppResourceDir, constant.SSLLogDir, - constant.CustomAppResourceDir, - } - - fileOp := files.NewFileOp() - for _, dir := range dirs { - createDir(fileOp, dir) - } - go func() { _ = docker.CreateDefaultDockerNetwork() @@ -46,9 +14,3 @@ func Init() { } }() } - -func createDir(fileOp files.FileOp, dirPath string) { - if !fileOp.Stat(dirPath) { - _ = fileOp.CreateDir(dirPath, constant.DirPerm) - } -} diff --git a/agent/init/db/db.go b/agent/init/db/db.go index ae56663d8..22bada9e1 100644 --- a/agent/init/db/db.go +++ b/agent/init/db/db.go @@ -8,7 +8,7 @@ import ( ) func Init() { - global.DB = common.LoadDBConnByPath(path.Join(global.CONF.System.DbPath, "agent.db"), "agent") - global.TaskDB = common.LoadDBConnByPath(path.Join(global.CONF.System.DbPath, "task.db"), "task") - global.MonitorDB = common.LoadDBConnByPath(path.Join(global.CONF.System.DbPath, "monitor.db"), "monitor") + global.DB = common.LoadDBConnByPath(path.Join(global.Dir.DbDir, "agent.db"), "agent") + global.TaskDB = common.LoadDBConnByPath(path.Join(global.Dir.DbDir, "task.db"), "task") + global.MonitorDB = common.LoadDBConnByPath(path.Join(global.Dir.DbDir, "monitor.db"), "monitor") } diff --git a/agent/init/dir/dir.go b/agent/init/dir/dir.go new file mode 100644 index 000000000..7bdc79cb9 --- /dev/null +++ b/agent/init/dir/dir.go @@ -0,0 +1,44 @@ +package dir + +import ( + "path" + + "github.com/1Panel-dev/1Panel/agent/app/model" + "github.com/1Panel-dev/1Panel/agent/constant" + "github.com/1Panel-dev/1Panel/agent/global" + "github.com/1Panel-dev/1Panel/agent/utils/files" +) + +func Init() { + fileOp := files.NewFileOp() + baseDir := global.CONF.Base.InstallDir + _, _ = fileOp.CreateDirWithPath(true, path.Join(baseDir, "1panel/docker/compose/")) + + global.Dir.BaseDir, _ = fileOp.CreateDirWithPath(true, baseDir) + global.Dir.DataDir, _ = fileOp.CreateDirWithPath(true, path.Join(baseDir, "1panel")) + global.Dir.DbDir, _ = fileOp.CreateDirWithPath(true, path.Join(baseDir, "1panel/db")) + global.Dir.LogDir, _ = fileOp.CreateDirWithPath(true, path.Join(baseDir, "1panel/log")) + global.Dir.TmpDir, _ = fileOp.CreateDirWithPath(true, path.Join(baseDir, "1panel/tmp")) + + global.Dir.ResourceDir, _ = fileOp.CreateDirWithPath(true, path.Join(baseDir, "1panel/resource")) + global.Dir.AppResourceDir, _ = fileOp.CreateDirWithPath(true, path.Join(baseDir, "1panel/resource/apps")) + global.Dir.AppInstallDir, _ = fileOp.CreateDirWithPath(true, path.Join(baseDir, "1panel/apps")) + global.Dir.LocalAppResourceDir, _ = fileOp.CreateDirWithPath(true, path.Join(baseDir, "1panel/resource/apps/local")) + global.Dir.LocalAppInstallDir, _ = fileOp.CreateDirWithPath(true, path.Join(baseDir, "1panel/apps/local")) + global.Dir.RemoteAppResourceDir, _ = fileOp.CreateDirWithPath(true, path.Join(baseDir, "1panel/resource/apps/remote")) + global.Dir.CustomAppResourceDir, _ = fileOp.CreateDirWithPath(true, path.Join(baseDir, "1panel/resource/apps/custom")) + global.Dir.RuntimeDir, _ = fileOp.CreateDirWithPath(true, path.Join(baseDir, "1panel/runtime")) + global.Dir.RecycleBinDir, _ = fileOp.CreateDirWithPath(true, "/.1panel_clash") + global.Dir.SSLLogDir, _ = fileOp.CreateDirWithPath(true, path.Join(baseDir, "1panel/log/ssl")) + + loadLocalDir() +} + +func loadLocalDir() { + var account model.BackupAccount + if err := global.DB.Where("`type` = ?", constant.Local).First(&account).Error; err != nil { + global.LOG.Errorf("load local backup account info failed, err: %v", err) + return + } + global.Dir.LocalBackupDir = account.BackupPath +} diff --git a/agent/init/hook/hook.go b/agent/init/hook/hook.go index 5605b2bac..7bb58918a 100644 --- a/agent/init/hook/hook.go +++ b/agent/init/hook/hook.go @@ -17,7 +17,6 @@ func Init() { initGlobalData() handleCronjobStatus() handleSnapStatus() - loadLocalDir() } func initGlobalData() { @@ -28,10 +27,10 @@ func initGlobalData() { if err := settingRepo.Update("SystemStatus", "Free"); err != nil { global.LOG.Fatalf("init service before start failed, err: %v", err) } - global.CONF.System.EncryptKey, _ = settingRepo.GetValueByKey("EncryptKey") + global.CONF.Base.EncryptKey, _ = settingRepo.GetValueByKey("EncryptKey") _ = service.NewISettingService().ReloadConn() if global.IsMaster { - global.CoreDB = common.LoadDBConnByPath(path.Join(global.CONF.System.DbPath, "core.db"), "core") + global.CoreDB = common.LoadDBConnByPath(path.Join(global.Dir.DbDir, "core.db"), "core") } } @@ -80,15 +79,6 @@ func handleCronjobStatus() { } } -func loadLocalDir() { - var account model.BackupAccount - if err := global.DB.Where("`type` = ?", constant.Local).First(&account).Error; err != nil { - global.LOG.Errorf("load local backup account info failed, err: %v", err) - return - } - global.CONF.System.Backup = account.BackupPath -} - func handleCronJobAlert(cronjob *model.Cronjob) { pushAlert := dto.PushAlert{ TaskName: cronjob.Name, diff --git a/agent/init/log/log.go b/agent/init/log/log.go index 9e8e5c5c6..372117bbd 100644 --- a/agent/init/log/log.go +++ b/agent/init/log/log.go @@ -9,7 +9,6 @@ import ( "github.com/1Panel-dev/1Panel/agent/log" - "github.com/1Panel-dev/1Panel/agent/configs" "github.com/1Panel-dev/1Panel/agent/global" "github.com/sirupsen/logrus" @@ -23,14 +22,14 @@ const ( func Init() { l := logrus.New() - setOutput(l, global.CONF.LogConfig) + setOutput(l, (global.CONF.Log)) global.LOG = l global.LOG.Info("init logger successfully") } -func setOutput(logger *logrus.Logger, config configs.LogConfig) { +func setOutput(logger *logrus.Logger, config global.LogConfig) { writer, err := log.NewWriterFromConfig(&log.Config{ - LogPath: global.CONF.System.LogPath, + LogPath: global.Dir.LogDir, FileName: config.LogName, TimeTagFormat: FileTImeFormat, MaxRemain: config.MaxBackup, diff --git a/agent/init/migration/migrations/init.go b/agent/init/migration/migrations/init.go index edf592243..1201ba5a5 100644 --- a/agent/init/migration/migrations/init.go +++ b/agent/init/migration/migrations/init.go @@ -75,7 +75,7 @@ var AddMonitorTable = &gormigrate.Migration{ var InitSetting = &gormigrate.Migration{ ID: "20240722-init-setting", Migrate: func(tx *gorm.DB) error { - global.CONF.System.EncryptKey = common.RandStr(16) + global.CONF.Base.EncryptKey = common.RandStr(16) _, nodeInfo, err := xpack.LoadNodeInfo() if err != nil { return err @@ -238,7 +238,7 @@ var InitBackup = &gormigrate.Migration{ if err := tx.Create(&model.BackupAccount{ Name: "localhost", Type: "LOCAL", - BackupPath: path.Join(global.CONF.System.BaseDir, "1panel/backup"), + BackupPath: path.Join(global.Dir.DataDir, "backup"), }).Error; err != nil { return err } diff --git a/agent/init/viper/viper.go b/agent/init/viper/viper.go index 25f673930..11ba88d13 100644 --- a/agent/init/viper/viper.go +++ b/agent/init/viper/viper.go @@ -6,7 +6,6 @@ import ( "path" "github.com/1Panel-dev/1Panel/agent/cmd/server/conf" - "github.com/1Panel-dev/1Panel/agent/configs" "github.com/1Panel-dev/1Panel/agent/global" "github.com/1Panel-dev/1Panel/agent/utils/files" "github.com/1Panel-dev/1Panel/agent/utils/xpack" @@ -21,12 +20,12 @@ func Init() { v := viper.NewWithOptions() v.SetConfigType("yaml") - config := configs.ServerConfig{} + config := global.ServerConfig{} if err := yaml.Unmarshal(conf.AppYaml, &config); err != nil { panic(err) } - if config.System.Mode != "" { - mode = config.System.Mode + if config.Base.Mode != "" { + mode = config.Base.Mode } if mode == "dev" && fileOp.Stat("/opt/1panel/conf/app.yaml") { v.SetConfigName("app") @@ -45,30 +44,22 @@ func Init() { panic(err) } }) - serverConfig := configs.ServerConfig{} + serverConfig := global.ServerConfig{} if err := v.Unmarshal(&serverConfig); err != nil { panic(err) } global.CONF = serverConfig - global.CONF.System.IsDemo = v.GetBool("system.is_demo") + global.CONF.Base.IsDemo = v.GetBool("system.is_demo") - initDir() + initInstallDir() global.Viper = v } -func initDir() { +func initInstallDir() { _, nodeInfo, err := xpack.LoadNodeInfo() if err != nil { panic(err) } - global.CONF.System.BaseDir = nodeInfo.BaseDir - - fileOp := files.NewFileOp() - _, _ = fileOp.CreateDirWithPath(true, path.Join(global.CONF.System.BaseDir, "1panel/docker/compose/")) - global.CONF.System.DataDir, _ = fileOp.CreateDirWithPath(true, path.Join(global.CONF.System.BaseDir, "1panel")) - global.CONF.System.Cache, _ = fileOp.CreateDirWithPath(true, path.Join(global.CONF.System.DataDir, "cache")) - global.CONF.System.DbPath, _ = fileOp.CreateDirWithPath(true, path.Join(global.CONF.System.DataDir, "db")) - global.CONF.System.LogPath, _ = fileOp.CreateDirWithPath(true, path.Join(global.CONF.System.DataDir, "log")) - global.CONF.System.TmpDir, _ = fileOp.CreateDirWithPath(true, path.Join(global.CONF.System.DataDir, "tmp")) + global.CONF.Base.InstallDir = nodeInfo.BaseDir } diff --git a/agent/middleware/certificate.go b/agent/middleware/certificate.go index a36fc6c1c..700003a5b 100644 --- a/agent/middleware/certificate.go +++ b/agent/middleware/certificate.go @@ -5,7 +5,6 @@ import ( "fmt" "github.com/1Panel-dev/1Panel/agent/app/api/v2/helper" - "github.com/1Panel-dev/1Panel/agent/constant" "github.com/1Panel-dev/1Panel/agent/global" "github.com/gin-gonic/gin" ) @@ -17,12 +16,12 @@ func Certificate() gin.HandlerFunc { return } if !c.Request.TLS.HandshakeComplete || len(c.Request.TLS.PeerCertificates) == 0 { - helper.ErrorWithDetail(c, constant.CodeErrInternalServer, constant.ErrTypeInternalServer, errors.New("no such tls peer certificates")) + helper.InternalServer(c, errors.New("no such tls peer certificates")) return } cert := c.Request.TLS.PeerCertificates[0] if cert.Subject.CommonName != "panel_client" { - helper.ErrorWithDetail(c, constant.CodeErrInternalServer, constant.ErrTypeInternalServer, fmt.Errorf("err certificate")) + helper.InternalServer(c, fmt.Errorf("err certificate")) return } c.Next() diff --git a/agent/middleware/demo_handle.go b/agent/middleware/demo_handle.go index 5547c49ae..9e46bf983 100644 --- a/agent/middleware/demo_handle.go +++ b/agent/middleware/demo_handle.go @@ -6,7 +6,6 @@ import ( "github.com/1Panel-dev/1Panel/agent/app/dto" "github.com/1Panel-dev/1Panel/agent/buserr" - "github.com/1Panel-dev/1Panel/agent/constant" "github.com/gin-gonic/gin" ) @@ -51,7 +50,7 @@ func DemoHandle() gin.HandlerFunc { c.JSON(http.StatusInternalServerError, dto.Response{ Code: http.StatusInternalServerError, - Message: buserr.New(constant.ErrDemoEnvironment).Error(), + Message: buserr.New("ErrDemoEnvironment").Error(), }) c.Abort() } diff --git a/agent/middleware/loading.go b/agent/middleware/loading.go index 82a15d320..f004cae56 100644 --- a/agent/middleware/loading.go +++ b/agent/middleware/loading.go @@ -1,9 +1,10 @@ package middleware import ( + "net/http" + "github.com/1Panel-dev/1Panel/agent/app/api/v2/helper" "github.com/1Panel-dev/1Panel/agent/app/repo" - "github.com/1Panel-dev/1Panel/agent/constant" "github.com/gin-gonic/gin" ) @@ -12,11 +13,11 @@ func GlobalLoading() gin.HandlerFunc { settingRepo := repo.NewISettingRepo() status, err := settingRepo.Get(settingRepo.WithByKey("SystemStatus")) if err != nil { - helper.ErrorWithDetail(c, constant.CodeErrInternalServer, constant.ErrTypeInternalServer, err) + helper.InternalServer(c, err) return } if status.Value != "Free" { - helper.ErrorWithDetail(c, constant.CodeGlobalLoading, status.Value, err) + helper.ErrorWithDetail(c, http.StatusProxyAuthRequired, status.Value, err) return } c.Next() diff --git a/agent/server/server.go b/agent/server/server.go index 23d19dbc7..58028530c 100644 --- a/agent/server/server.go +++ b/agent/server/server.go @@ -17,6 +17,7 @@ import ( "github.com/1Panel-dev/1Panel/agent/init/business" "github.com/1Panel-dev/1Panel/agent/init/cache" "github.com/1Panel-dev/1Panel/agent/init/db" + "github.com/1Panel-dev/1Panel/agent/init/dir" "github.com/1Panel-dev/1Panel/agent/init/hook" "github.com/1Panel-dev/1Panel/agent/init/log" "github.com/1Panel-dev/1Panel/agent/init/migration" @@ -32,6 +33,7 @@ import ( func Start() { viper.Init() + dir.Init() i18n.Init() log.Init() db.Init() @@ -65,7 +67,7 @@ func Start() { _ = server.Serve(listener) return } else { - server.Addr = fmt.Sprintf("0.0.0.0:%s", global.CONF.System.Port) + server.Addr = fmt.Sprintf("0.0.0.0:%s", global.CONF.Base.Port) settingRepo := repo.NewISettingRepo() certItem, err := settingRepo.Get(settingRepo.WithByKey("ServerCrt")) if err != nil { @@ -87,7 +89,7 @@ func Start() { ClientAuth: tls.RequireAnyClientCert, } business.Init() - global.LOG.Infof("listen at https://0.0.0.0:%s", global.CONF.System.Port) + global.LOG.Infof("listen at https://0.0.0.0:%s", global.CONF.Base.Port) if err := server.ListenAndServeTLS("", ""); err != nil { panic(err) } diff --git a/agent/utils/cloud_storage/client/minio.go b/agent/utils/cloud_storage/client/minio.go index bf608af51..36fef7df8 100644 --- a/agent/utils/cloud_storage/client/minio.go +++ b/agent/utils/cloud_storage/client/minio.go @@ -3,12 +3,13 @@ package client import ( "context" "crypto/tls" + "fmt" "io" "net/http" "os" "strings" - "github.com/1Panel-dev/1Panel/agent/constant" + "github.com/1Panel-dev/1Panel/agent/buserr" "github.com/minio/minio-go/v7" "github.com/minio/minio-go/v7/pkg/credentials" ) @@ -25,7 +26,7 @@ func NewMinIoClient(vars map[string]interface{}) (*minIoClient, error) { bucket := loadParamFromVars("bucket", vars) ssl := strings.Split(endpoint, ":")[0] if len(ssl) == 0 || (ssl != "https" && ssl != "http") { - return nil, constant.ErrInvalidParams + return nil, buserr.WithDetail("ErrInvalidParams", "ssl", fmt.Errorf("no such proto in ssl: %s", ssl)) } secure := false diff --git a/agent/utils/cloud_storage/cloud_storage_client.go b/agent/utils/cloud_storage/cloud_storage_client.go index 731753eac..f50b050d3 100644 --- a/agent/utils/cloud_storage/cloud_storage_client.go +++ b/agent/utils/cloud_storage/cloud_storage_client.go @@ -1,6 +1,7 @@ package cloud_storage import ( + "github.com/1Panel-dev/1Panel/agent/buserr" "github.com/1Panel-dev/1Panel/agent/constant" "github.com/1Panel-dev/1Panel/agent/utils/cloud_storage/client" ) @@ -41,6 +42,6 @@ func NewCloudStorageClient(backupType string, vars map[string]interface{}) (Clou case constant.ALIYUN: return client.NewALIClient(vars) default: - return nil, constant.ErrNotSupportType + return nil, buserr.WithName("ErrNotSupportType", backupType) } } diff --git a/agent/utils/cmd/cmd.go b/agent/utils/cmd/cmd.go index 51ce0cf4b..8b604011a 100644 --- a/agent/utils/cmd/cmd.go +++ b/agent/utils/cmd/cmd.go @@ -51,7 +51,7 @@ func ExecWithTimeOut(cmdStr string, timeout time.Duration) (string, error) { select { case <-after: _ = cmd.Process.Kill() - return "", buserr.New(constant.ErrCmdTimeout) + return "", buserr.New("ErrCmdTimeout") case err := <-done: if err != nil { return handleErr(stdout, stderr, err) @@ -86,7 +86,7 @@ func ExecWithLogFile(cmdStr string, timeout time.Duration, outputFile string) er select { case <-after: _ = cmd.Process.Kill() - return buserr.New(constant.ErrCmdTimeout) + return buserr.New("ErrCmdTimeout") case err := <-done: if err != nil { return err @@ -129,7 +129,7 @@ func ExecShell(outPath string, timeout time.Duration, name string, arg ...string select { case <-after: _ = cmd.Process.Kill() - return buserr.New(constant.ErrCmdTimeout) + return buserr.New("ErrCmdTimeout") case err := <-done: if err != nil { return err @@ -162,7 +162,7 @@ func ExecShellWithTask(taskItem *task.Task, timeout time.Duration, name string, select { case <-after: _ = cmd.Process.Kill() - return buserr.New(constant.ErrCmdTimeout) + return buserr.New("ErrCmdTimeout") case err := <-done: if err != nil { return err @@ -212,7 +212,7 @@ func ExecScript(scriptPath, workDir string) (string, error) { select { case <-after: _ = cmd.Process.Kill() - return "", buserr.New(constant.ErrCmdTimeout) + return "", buserr.New("ErrCmdTimeout") case err := <-done: if err != nil { return handleErr(stdout, stderr, err) @@ -291,7 +291,7 @@ func ExecShellWithTimeOut(cmdStr, workdir string, logger *log.Logger, timeout ti } err := cmd.Wait() if errors.Is(ctx.Err(), context.DeadlineExceeded) { - return buserr.New(constant.ErrCmdTimeout) + return buserr.New("ErrCmdTimeout") } return err } diff --git a/agent/utils/encrypt/encrypt.go b/agent/utils/encrypt/encrypt.go index 6ef1e9ec4..6062c1f63 100644 --- a/agent/utils/encrypt/encrypt.go +++ b/agent/utils/encrypt/encrypt.go @@ -29,14 +29,14 @@ func StringEncrypt(text string) (string, error) { if len(text) == 0 { return "", nil } - if len(global.CONF.System.EncryptKey) == 0 { + if len(global.CONF.Base.EncryptKey) == 0 { var encryptSetting model.Setting if err := global.DB.Where("key = ?", "EncryptKey").First(&encryptSetting).Error; err != nil { return "", err } - global.CONF.System.EncryptKey = encryptSetting.Value + global.CONF.Base.EncryptKey = encryptSetting.Value } - key := global.CONF.System.EncryptKey + key := global.CONF.Base.EncryptKey pass := []byte(text) xpass, err := aesEncryptWithSalt([]byte(key), pass) if err == nil { @@ -75,14 +75,14 @@ func StringDecrypt(text string) (string, error) { if len(text) == 0 { return "", nil } - if len(global.CONF.System.EncryptKey) == 0 { + if len(global.CONF.Base.EncryptKey) == 0 { var encryptSetting model.Setting if err := global.DB.Where("key = ?", "EncryptKey").First(&encryptSetting).Error; err != nil { return "", err } - global.CONF.System.EncryptKey = encryptSetting.Value + global.CONF.Base.EncryptKey = encryptSetting.Value } - key := global.CONF.System.EncryptKey + key := global.CONF.Base.EncryptKey return StringDecryptWithKey(text, key) } diff --git a/agent/utils/files/archiver.go b/agent/utils/files/archiver.go index 089709e75..4f90a629f 100644 --- a/agent/utils/files/archiver.go +++ b/agent/utils/files/archiver.go @@ -2,7 +2,6 @@ package files import ( "github.com/1Panel-dev/1Panel/agent/buserr" - "github.com/1Panel-dev/1Panel/agent/constant" "github.com/1Panel-dev/1Panel/agent/utils/cmd" ) @@ -34,5 +33,5 @@ func checkCmdAvailability(cmdStr string) error { if cmd.Which(cmdStr) { return nil } - return buserr.WithName(constant.ErrCmdNotFound, cmdStr) + return buserr.WithName("ErrCmdNotFound", cmdStr) } diff --git a/agent/utils/files/fileinfo.go b/agent/utils/files/fileinfo.go index 60a0a5ded..32f3dd8bc 100644 --- a/agent/utils/files/fileinfo.go +++ b/agent/utils/files/fileinfo.go @@ -17,7 +17,6 @@ import ( "github.com/1Panel-dev/1Panel/agent/app/repo" "github.com/1Panel-dev/1Panel/agent/buserr" - "github.com/1Panel-dev/1Panel/agent/constant" "github.com/spf13/afero" ) @@ -74,7 +73,7 @@ func NewFileInfo(op FileOption) (*FileInfo, error) { info, err := appFs.Stat(op.Path) if err != nil { if os.IsNotExist(err) { - return nil, buserr.New(constant.ErrLinkPathNotFound) + return nil, buserr.New("ErrLinkPathNotFound") } return nil, err } @@ -411,7 +410,7 @@ func (f *FileInfo) checkSymlink(df FileSearchInfo) (bool, bool) { func (f *FileInfo) getContent() error { if IsBlockDevice(f.FileMode) { - return buserr.New(constant.ErrFileCanNotRead) + return buserr.New("ErrFileCanNotRead") } if f.Size > 10*1024*1024 { return buserr.New("ErrFileToLarge") @@ -422,7 +421,7 @@ func (f *FileInfo) getContent() error { return nil } if len(cByte) > 0 && DetectBinary(cByte) { - return buserr.New(constant.ErrFileCanNotRead) + return buserr.New("ErrFileCanNotRead") } f.Content = string(cByte) return nil diff --git a/agent/utils/files/zip.go b/agent/utils/files/zip.go index 2f3298bb2..390605af1 100644 --- a/agent/utils/files/zip.go +++ b/agent/utils/files/zip.go @@ -28,7 +28,7 @@ func (z ZipArchiver) Extract(filePath, dstDir string, secret string) error { func (z ZipArchiver) Compress(sourcePaths []string, dstFile string, _ string) error { var err error - tmpFile := path.Join(global.CONF.System.TmpDir, fmt.Sprintf("%s%s.zip", common.RandStr(50), time.Now().Format(constant.DateTimeSlimLayout))) + tmpFile := path.Join(global.Dir.TmpDir, fmt.Sprintf("%s%s.zip", common.RandStr(50), time.Now().Format(constant.DateTimeSlimLayout))) op := NewFileOp() defer func() { _ = op.DeleteFile(tmpFile) diff --git a/agent/utils/firewall/client.go b/agent/utils/firewall/client.go index c106e5654..9291b3502 100644 --- a/agent/utils/firewall/client.go +++ b/agent/utils/firewall/client.go @@ -2,7 +2,6 @@ package firewall import ( "github.com/1Panel-dev/1Panel/agent/buserr" - "github.com/1Panel-dev/1Panel/agent/constant" "github.com/1Panel-dev/1Panel/agent/utils/cmd" "github.com/1Panel-dev/1Panel/agent/utils/firewall/client" ) @@ -32,7 +31,7 @@ func NewFirewallClient() (FirewallClient, error) { ufw := cmd.Which("ufw") if firewalld && ufw { - return nil, buserr.New(constant.ErrFirewallBoth) + return nil, buserr.New("ErrFirewallBoth") } if firewalld { @@ -41,5 +40,5 @@ func NewFirewallClient() (FirewallClient, error) { if ufw { return client.NewUfw() } - return nil, buserr.New(constant.ErrFirewallNone) + return nil, buserr.New("ErrFirewallNone") } diff --git a/agent/utils/firewall/client/firewalld.go b/agent/utils/firewall/client/firewalld.go index 1016682f0..92684ddd9 100644 --- a/agent/utils/firewall/client/firewalld.go +++ b/agent/utils/firewall/client/firewalld.go @@ -7,7 +7,6 @@ import ( "sync" "github.com/1Panel-dev/1Panel/agent/buserr" - "github.com/1Panel-dev/1Panel/agent/constant" "github.com/1Panel-dev/1Panel/agent/global" "github.com/1Panel-dev/1Panel/agent/utils/cmd" ) @@ -168,7 +167,7 @@ func (f *Firewall) ListAddress() ([]FireInfo, error) { func (f *Firewall) Port(port FireInfo, operation string) error { if cmd.CheckIllegal(operation, port.Protocol, port.Port) { - return buserr.New(constant.ErrCmdIllegal) + return buserr.New("ErrCmdIllegal") } stdout, err := cmd.Execf("firewall-cmd --zone=public --%s-port=%s/%s --permanent", operation, port.Port, port.Protocol) @@ -180,7 +179,7 @@ func (f *Firewall) Port(port FireInfo, operation string) error { func (f *Firewall) RichRules(rule FireInfo, operation string) error { if cmd.CheckIllegal(operation, rule.Address, rule.Protocol, rule.Port, rule.Strategy) { - return buserr.New(constant.ErrCmdIllegal) + return buserr.New("ErrCmdIllegal") } ruleStr := "rule family=ipv4 " if strings.Contains(rule.Address, ":") { diff --git a/agent/utils/firewall/client/ufw.go b/agent/utils/firewall/client/ufw.go index 6cf77d863..904fa9bff 100644 --- a/agent/utils/firewall/client/ufw.go +++ b/agent/utils/firewall/client/ufw.go @@ -5,7 +5,6 @@ import ( "strings" "github.com/1Panel-dev/1Panel/agent/buserr" - "github.com/1Panel-dev/1Panel/agent/constant" "github.com/1Panel-dev/1Panel/agent/global" "github.com/1Panel-dev/1Panel/agent/utils/cmd" ) @@ -181,7 +180,7 @@ func (f *Ufw) Port(port FireInfo, operation string) error { return fmt.Errorf("unsupported strategy %s", port.Strategy) } if cmd.CheckIllegal(port.Protocol, port.Port) { - return buserr.New(constant.ErrCmdIllegal) + return buserr.New("ErrCmdIllegal") } command := fmt.Sprintf("%s %s %s", f.CmdStr, port.Strategy, port.Port) @@ -209,7 +208,7 @@ func (f *Ufw) RichRules(rule FireInfo, operation string) error { } if cmd.CheckIllegal(operation, rule.Protocol, rule.Address, rule.Port) { - return buserr.New(constant.ErrCmdIllegal) + return buserr.New("ErrCmdIllegal") } ruleStr := fmt.Sprintf("%s insert 1 %s ", f.CmdStr, rule.Strategy) diff --git a/agent/utils/geo/geo.go b/agent/utils/geo/geo.go index 972dc6829..7af4edf77 100644 --- a/agent/utils/geo/geo.go +++ b/agent/utils/geo/geo.go @@ -1,10 +1,11 @@ package geo import ( - "github.com/1Panel-dev/1Panel/agent/global" - "github.com/oschwald/maxminddb-golang" "net" "path" + + "github.com/1Panel-dev/1Panel/agent/global" + "github.com/oschwald/maxminddb-golang" ) type Location struct { @@ -21,7 +22,7 @@ type LocationRes struct { } func NewGeo() (*maxminddb.Reader, error) { - geoPath := path.Join(global.CONF.System.BaseDir, "1panel", "geo", "GeoIP.mmdb") + geoPath := path.Join(global.Dir.DataDir, "geo", "GeoIP.mmdb") return maxminddb.Open(geoPath) } @@ -29,7 +30,7 @@ func GetIPLocation(reader *maxminddb.Reader, ip, lang string) (string, error) { var err error var geoLocation LocationRes if reader == nil { - geoPath := path.Join(global.CONF.System.BaseDir, "1panel", "geo", "GeoIP.mmdb") + geoPath := path.Join(global.Dir.DataDir, "geo", "GeoIP.mmdb") reader, err = maxminddb.Open(geoPath) if err != nil { return "", err diff --git a/agent/utils/mysql/client.go b/agent/utils/mysql/client.go index 64bcfe5a2..17a413d67 100644 --- a/agent/utils/mysql/client.go +++ b/agent/utils/mysql/client.go @@ -9,7 +9,6 @@ import ( "time" "github.com/1Panel-dev/1Panel/agent/buserr" - "github.com/1Panel-dev/1Panel/agent/constant" "github.com/1Panel-dev/1Panel/agent/global" "github.com/1Panel-dev/1Panel/agent/utils/mysql/client" ) @@ -56,7 +55,7 @@ func NewMysqlClient(conn client.DBInfo) (MysqlClient, error) { return nil, err } if errors.Is(ctx.Err(), context.DeadlineExceeded) { - return nil, buserr.New(constant.ErrExecTimeOut) + return nil, buserr.New("ErrExecTimeOut") } return client.NewRemote(client.Remote{ diff --git a/agent/utils/mysql/client/local.go b/agent/utils/mysql/client/local.go index 99a050300..3736c43b1 100644 --- a/agent/utils/mysql/client/local.go +++ b/agent/utils/mysql/client/local.go @@ -34,7 +34,7 @@ func (r *Local) Create(info CreateInfo) error { createSql := fmt.Sprintf("create database `%s` default character set %s collate %s", info.Name, info.Format, formatMap[info.Format]) if err := r.ExecSQL(createSql, info.Timeout); err != nil { if strings.Contains(strings.ToLower(err.Error()), "error 1007") { - return buserr.New(constant.ErrDatabaseIsExist) + return buserr.New("ErrDatabaseIsExist") } return err } @@ -63,7 +63,7 @@ func (r *Local) CreateUser(info CreateInfo, withDeleteDB bool) error { for _, user := range userlist { if err := r.ExecSQL(fmt.Sprintf("create user %s identified by '%s';", user, info.Password), info.Timeout); err != nil { if strings.Contains(strings.ToLower(err.Error()), "error 1396") { - return buserr.New(constant.ErrUserIsExist) + return buserr.New("ErrUserIsExist") } if withDeleteDB { _ = r.Delete(DeleteInfo{ @@ -354,7 +354,7 @@ func (r *Local) ExecSQL(command string, timeout uint) error { cmd := exec.CommandContext(ctx, "docker", itemCommand...) stdout, err := cmd.CombinedOutput() if errors.Is(ctx.Err(), context.DeadlineExceeded) { - return buserr.New(constant.ErrExecTimeOut) + return buserr.New("ErrExecTimeOut") } stdStr := strings.ReplaceAll(string(stdout), "mysql: [Warning] Using a password on the command line interface can be insecure.\n", "") if err != nil || strings.HasPrefix(string(stdStr), "ERROR ") { @@ -371,7 +371,7 @@ func (r *Local) ExecSQLForRows(command string, timeout uint) ([]string, error) { cmd := exec.CommandContext(ctx, "docker", itemCommand...) stdout, err := cmd.CombinedOutput() if errors.Is(ctx.Err(), context.DeadlineExceeded) { - return nil, buserr.New(constant.ErrExecTimeOut) + return nil, buserr.New("ErrExecTimeOut") } stdStr := strings.ReplaceAll(string(stdout), "mysql: [Warning] Using a password on the command line interface can be insecure.\n", "") if err != nil || strings.HasPrefix(string(stdStr), "ERROR ") { diff --git a/agent/utils/mysql/client/remote.go b/agent/utils/mysql/client/remote.go index f5907770f..91bd0323f 100644 --- a/agent/utils/mysql/client/remote.go +++ b/agent/utils/mysql/client/remote.go @@ -45,7 +45,7 @@ func (r *Remote) Create(info CreateInfo) error { createSql := fmt.Sprintf("create database `%s` default character set %s collate %s", info.Name, info.Format, formatMap[info.Format]) if err := r.ExecSQL(createSql, info.Timeout); err != nil { if strings.Contains(strings.ToLower(err.Error()), "error 1007") { - return buserr.New(constant.ErrDatabaseIsExist) + return buserr.New("ErrDatabaseIsExist") } return err } @@ -74,7 +74,7 @@ func (r *Remote) CreateUser(info CreateInfo, withDeleteDB bool) error { for _, user := range userlist { if err := r.ExecSQL(fmt.Sprintf("create user %s identified by '%s';", user, info.Password), info.Timeout); err != nil { if strings.Contains(strings.ToLower(err.Error()), "error 1396") { - return buserr.New(constant.ErrUserIsExist) + return buserr.New("ErrUserIsExist") } if withDeleteDB { _ = r.Delete(DeleteInfo{ @@ -391,7 +391,7 @@ func (r *Remote) ExecSQL(command string, timeout uint) error { return err } if errors.Is(ctx.Err(), context.DeadlineExceeded) { - return buserr.New(constant.ErrExecTimeOut) + return buserr.New("ErrExecTimeOut") } return nil @@ -406,7 +406,7 @@ func (r *Remote) ExecSQLForHosts(timeout uint) ([]string, error) { return nil, err } if errors.Is(ctx.Err(), context.DeadlineExceeded) { - return nil, buserr.New(constant.ErrExecTimeOut) + return nil, buserr.New("ErrExecTimeOut") } var rows []string for results.Next() { diff --git a/agent/utils/postgresql/client.go b/agent/utils/postgresql/client.go index 6f6169a41..09f1ef168 100644 --- a/agent/utils/postgresql/client.go +++ b/agent/utils/postgresql/client.go @@ -9,7 +9,6 @@ import ( "time" "github.com/1Panel-dev/1Panel/agent/buserr" - "github.com/1Panel-dev/1Panel/agent/constant" "github.com/1Panel-dev/1Panel/agent/utils/postgresql/client" _ "github.com/jackc/pgx/v5/stdlib" ) @@ -46,7 +45,7 @@ func NewPostgresqlClient(conn client.DBInfo) (PostgresqlClient, error) { return nil, err } if errors.Is(ctx.Err(), context.DeadlineExceeded) { - return nil, buserr.New(constant.ErrExecTimeOut) + return nil, buserr.New("ErrExecTimeOut") } return client.NewRemote(client.Remote{ diff --git a/agent/utils/postgresql/client/local.go b/agent/utils/postgresql/client/local.go index 3d2cd3b1a..14fc4e64d 100644 --- a/agent/utils/postgresql/client/local.go +++ b/agent/utils/postgresql/client/local.go @@ -34,7 +34,7 @@ func (r *Local) Create(info CreateInfo) error { createSql := fmt.Sprintf("CREATE DATABASE \"%s\"", info.Name) if err := r.ExecSQL(createSql, info.Timeout); err != nil { if strings.Contains(strings.ToLower(err.Error()), "already exists") { - return buserr.New(constant.ErrDatabaseIsExist) + return buserr.New("ErrDatabaseIsExist") } return err } @@ -60,7 +60,7 @@ func (r *Local) CreateUser(info CreateInfo, withDeleteDB bool) error { createSql := fmt.Sprintf("CREATE USER \"%s\" WITH PASSWORD '%s'", info.Username, info.Password) if err := r.ExecSQL(createSql, info.Timeout); err != nil { if strings.Contains(strings.ToLower(err.Error()), "already exists") { - return buserr.New(constant.ErrUserIsExist) + return buserr.New("ErrUserIsExist") } if withDeleteDB { _ = r.Delete(DeleteInfo{ @@ -107,7 +107,7 @@ func (r *Local) Delete(info DeleteInfo) error { dropSql := fmt.Sprintf("DROP USER \"%s\"", info.Username) if err := r.ExecSQL(dropSql, info.Timeout); err != nil && !info.ForceDelete { if strings.Contains(strings.ToLower(err.Error()), "depend on it") { - return buserr.WithDetail(constant.ErrInUsed, info.Username, nil) + return buserr.WithDetail("ErrInUsed", info.Username, nil) } return err } @@ -205,7 +205,7 @@ func (r *Local) ExecSQL(command string, timeout uint) error { cmd := exec.CommandContext(ctx, "docker", itemCommand...) stdout, err := cmd.CombinedOutput() if errors.Is(ctx.Err(), context.DeadlineExceeded) { - return buserr.New(constant.ErrExecTimeOut) + return buserr.New("ErrExecTimeOut") } if err != nil || strings.HasPrefix(string(stdout), "ERROR ") { return errors.New(string(stdout)) @@ -221,7 +221,7 @@ func (r *Local) ExecSQLForRows(command string, timeout uint) ([]string, error) { cmd := exec.CommandContext(ctx, "docker", itemCommand...) stdout, err := cmd.CombinedOutput() if errors.Is(ctx.Err(), context.DeadlineExceeded) { - return nil, buserr.New(constant.ErrExecTimeOut) + return nil, buserr.New("ErrExecTimeOut") } if err != nil || strings.HasPrefix(string(stdout), "ERROR ") { return nil, errors.New(string(stdout)) diff --git a/agent/utils/postgresql/client/remote.go b/agent/utils/postgresql/client/remote.go index 92ae075fe..3156fc5d6 100644 --- a/agent/utils/postgresql/client/remote.go +++ b/agent/utils/postgresql/client/remote.go @@ -18,7 +18,6 @@ import ( "github.com/pkg/errors" "github.com/1Panel-dev/1Panel/agent/buserr" - "github.com/1Panel-dev/1Panel/agent/constant" "github.com/1Panel-dev/1Panel/agent/utils/docker" "github.com/1Panel-dev/1Panel/agent/utils/files" _ "github.com/jackc/pgx/v5/stdlib" @@ -41,7 +40,7 @@ func (r *Remote) Create(info CreateInfo) error { createSql := fmt.Sprintf("CREATE DATABASE \"%s\"", info.Name) if err := r.ExecSQL(createSql, info.Timeout); err != nil { if strings.Contains(strings.ToLower(err.Error()), "already exists") { - return buserr.New(constant.ErrDatabaseIsExist) + return buserr.New("ErrDatabaseIsExist") } return err } @@ -55,7 +54,7 @@ func (r *Remote) CreateUser(info CreateInfo, withDeleteDB bool) error { createSql := fmt.Sprintf("CREATE USER \"%s\" WITH PASSWORD '%s'", info.Username, info.Password) if err := r.ExecSQL(createSql, info.Timeout); err != nil { if strings.Contains(strings.ToLower(err.Error()), "already exists") { - return buserr.New(constant.ErrUserIsExist) + return buserr.New("ErrUserIsExist") } if withDeleteDB { _ = r.Delete(DeleteInfo{ @@ -103,7 +102,7 @@ func (r *Remote) Delete(info DeleteInfo) error { dropSql := fmt.Sprintf("DROP USER \"%s\"", info.Username) if err := r.ExecSQL(dropSql, info.Timeout); err != nil && !info.ForceDelete { if strings.Contains(strings.ToLower(err.Error()), "depend on it") { - return buserr.WithDetail(constant.ErrInUsed, info.Username, nil) + return buserr.WithDetail("ErrInUsed", info.Username, nil) } return err } @@ -225,7 +224,7 @@ func (r *Remote) SyncDB() ([]SyncDBInfo, error) { datas = append(datas, SyncDBInfo{Name: dbName, From: r.From, PostgresqlName: r.Database}) } if errors.Is(ctx.Err(), context.DeadlineExceeded) { - return nil, buserr.New(constant.ErrExecTimeOut) + return nil, buserr.New("ErrExecTimeOut") } return datas, nil } @@ -242,7 +241,7 @@ func (r *Remote) ExecSQL(command string, timeout uint) error { return err } if errors.Is(ctx.Err(), context.DeadlineExceeded) { - return buserr.New(constant.ErrExecTimeOut) + return buserr.New("ErrExecTimeOut") } return nil @@ -306,7 +305,7 @@ func loadImageTag() (string, error) { defer cancel() if _, err := client.ImagePull(ctx, itemTag, image.PullOptions{}); err != nil { if errors.Is(ctx.Err(), context.DeadlineExceeded) { - return itemTag, buserr.WithName(constant.ErrPgImagePull, itemTag) + return itemTag, buserr.WithName("ErrPgImagePull", itemTag) } global.LOG.Errorf("image %s pull failed, err: %v", itemTag, err) return itemTag, fmt.Errorf("image %s pull failed, err: %v", itemTag, err) diff --git a/agent/utils/xpack/xpack.go b/agent/utils/xpack/xpack.go index 81736fb37..cfbfbd59d 100644 --- a/agent/utils/xpack/xpack.go +++ b/agent/utils/xpack/xpack.go @@ -9,7 +9,6 @@ import ( "github.com/1Panel-dev/1Panel/agent/app/dto" "github.com/1Panel-dev/1Panel/agent/app/model" "github.com/1Panel-dev/1Panel/agent/buserr" - "github.com/1Panel-dev/1Panel/agent/constant" "github.com/1Panel-dev/1Panel/agent/utils/cmd" ) @@ -24,7 +23,7 @@ func LoadXpuInfo() []interface{} { } func StartClam(startClam model.Clam, isUpdate bool) (int, error) { - return 0, buserr.New(constant.ErrXpackNotFound) + return 0, buserr.New("ErrXpackNotFound") } func LoadNodeInfo() (bool, model.NodeInfo, error) { diff --git a/core/app/api/v2/app_launcher.go b/core/app/api/v2/app_launcher.go index 8b5e8cd72..a3bc1647a 100644 --- a/core/app/api/v2/app_launcher.go +++ b/core/app/api/v2/app_launcher.go @@ -3,14 +3,13 @@ package v2 import ( "github.com/1Panel-dev/1Panel/core/app/api/v2/helper" "github.com/1Panel-dev/1Panel/core/app/dto" - "github.com/1Panel-dev/1Panel/core/constant" "github.com/gin-gonic/gin" ) func (b *BaseApi) SearchAppLauncher(c *gin.Context) { data, err := appLauncherService.Search() if err != nil { - helper.ErrorWithDetail(c, constant.CodeErrInternalServer, constant.ErrTypeInternalServer, err) + helper.InternalServer(c, err) return } helper.SuccessWithData(c, data) @@ -32,7 +31,7 @@ func (b *BaseApi) UpdateAppLauncher(c *gin.Context) { } if err := appLauncherService.ChangeShow(req); err != nil { - helper.ErrorWithDetail(c, constant.CodeErrInternalServer, constant.ErrTypeInternalServer, err) + helper.InternalServer(c, err) return } helper.SuccessWithOutData(c) diff --git a/core/app/api/v2/auth.go b/core/app/api/v2/auth.go index 71bc991ff..87dd37842 100644 --- a/core/app/api/v2/auth.go +++ b/core/app/api/v2/auth.go @@ -116,7 +116,7 @@ func (b *BaseApi) GetResponsePage(c *gin.Context) { // @Success 200 {boolean} demo // @Router /core/auth/demo [get] func (b *BaseApi) CheckIsDemo(c *gin.Context) { - helper.SuccessWithData(c, global.CONF.System.IsDemo) + helper.SuccessWithData(c, global.CONF.Base.IsDemo) } // @Tags Auth @@ -159,5 +159,5 @@ func saveLoginLogs(c *gin.Context, err error) { // @Success 200 {string} intl // @Router /auth/intl [get] func (b *BaseApi) CheckIsIntl(c *gin.Context) { - helper.SuccessWithData(c, global.CONF.System.IsIntl) + helper.SuccessWithData(c, global.CONF.Base.IsIntl) } diff --git a/core/app/api/v2/command.go b/core/app/api/v2/command.go index 27d07d722..33906d11b 100644 --- a/core/app/api/v2/command.go +++ b/core/app/api/v2/command.go @@ -3,7 +3,6 @@ package v2 import ( "github.com/1Panel-dev/1Panel/core/app/api/v2/helper" "github.com/1Panel-dev/1Panel/core/app/dto" - "github.com/1Panel-dev/1Panel/core/constant" "github.com/gin-gonic/gin" ) @@ -23,7 +22,7 @@ func (b *BaseApi) CreateCommand(c *gin.Context) { } if err := commandService.Create(req); err != nil { - helper.ErrorWithDetail(c, constant.CodeErrInternalServer, constant.ErrTypeInternalServer, err) + helper.InternalServer(c, err) return } helper.SuccessWithOutData(c) diff --git a/core/app/api/v2/group.go b/core/app/api/v2/group.go index 10dfbd9f5..c532ce7df 100644 --- a/core/app/api/v2/group.go +++ b/core/app/api/v2/group.go @@ -3,7 +3,6 @@ package v2 import ( "github.com/1Panel-dev/1Panel/core/app/api/v2/helper" "github.com/1Panel-dev/1Panel/core/app/dto" - "github.com/1Panel-dev/1Panel/core/constant" "github.com/gin-gonic/gin" ) @@ -23,7 +22,7 @@ func (b *BaseApi) CreateGroup(c *gin.Context) { } if err := groupService.Create(req); err != nil { - helper.ErrorWithDetail(c, constant.CodeErrInternalServer, constant.ErrTypeInternalServer, err) + helper.InternalServer(c, err) return } helper.SuccessWithOutData(c) diff --git a/core/app/api/v2/helper/helper.go b/core/app/api/v2/helper/helper.go index 994f4b241..392506b05 100644 --- a/core/app/api/v2/helper/helper.go +++ b/core/app/api/v2/helper/helper.go @@ -4,12 +4,9 @@ import ( "net/http" "github.com/1Panel-dev/1Panel/core/app/dto" - "github.com/1Panel-dev/1Panel/core/buserr" - "github.com/1Panel-dev/1Panel/core/constant" "github.com/1Panel-dev/1Panel/core/global" "github.com/1Panel-dev/1Panel/core/i18n" "github.com/gin-gonic/gin" - "github.com/pkg/errors" ) func ErrorWithDetail(ctx *gin.Context, code int, msgKey string, err error) { @@ -17,42 +14,21 @@ func ErrorWithDetail(ctx *gin.Context, code int, msgKey string, err error) { Code: code, Message: "", } - if msgKey == constant.ErrTypeInternalServer { - switch { - case errors.Is(err, constant.ErrRecordExist): - res.Message = i18n.GetMsgWithMap("ErrRecordExist", nil) - case errors.Is(constant.ErrRecordNotFound, err): - res.Message = i18n.GetMsgWithMap("ErrRecordNotFound", nil) - case errors.Is(constant.ErrInvalidParams, err): - res.Message = i18n.GetMsgWithMap("ErrInvalidParams", nil) - case errors.Is(constant.ErrTransform, err): - res.Message = i18n.GetMsgWithMap("ErrTransform", map[string]interface{}{"detail": err}) - case errors.Is(constant.ErrCaptchaCode, err): - res.Code = constant.CodeAuth - res.Message = "ErrCaptchaCode" - case errors.Is(constant.ErrAuth, err): - res.Code = constant.CodeAuth - res.Message = "ErrAuth" - case errors.Is(constant.ErrInitialPassword, err): - res.Message = i18n.GetMsgWithMap("ErrInitialPassword", map[string]interface{}{"detail": err}) - case errors.As(err, &buserr.BusinessError{}): - res.Message = err.Error() - default: - res.Message = i18n.GetMsgWithMap(msgKey, map[string]interface{}{"detail": err}) - } - } else { - res.Message = i18n.GetMsgWithMap(msgKey, map[string]interface{}{"detail": err}) - } + res.Message = i18n.GetMsgWithMap(msgKey, map[string]interface{}{"detail": err}) ctx.JSON(http.StatusOK, res) ctx.Abort() } func InternalServer(ctx *gin.Context, err error) { - ErrorWithDetail(ctx, constant.CodeErrInternalServer, constant.ErrTypeInternalServer, err) + ErrorWithDetail(ctx, http.StatusInternalServerError, "ErrInternalServer", err) } func BadRequest(ctx *gin.Context, err error) { - ErrorWithDetail(ctx, constant.CodeErrBadRequest, constant.ErrTypeInvalidParams, err) + ErrorWithDetail(ctx, http.StatusBadRequest, "ErrInvalidParams", err) +} + +func BadAuth(ctx *gin.Context, msgKey string, err error) { + ErrorWithDetail(ctx, http.StatusUnauthorized, msgKey, err) } func SuccessWithData(ctx *gin.Context, data interface{}) { @@ -60,7 +36,7 @@ func SuccessWithData(ctx *gin.Context, data interface{}) { data = gin.H{} } res := dto.Response{ - Code: constant.CodeSuccess, + Code: http.StatusOK, Data: data, } ctx.JSON(http.StatusOK, res) @@ -69,7 +45,7 @@ func SuccessWithData(ctx *gin.Context, data interface{}) { func SuccessWithOutData(ctx *gin.Context) { res := dto.Response{ - Code: constant.CodeSuccess, + Code: http.StatusOK, Message: "success", } ctx.JSON(http.StatusOK, res) @@ -78,11 +54,11 @@ func SuccessWithOutData(ctx *gin.Context) { func CheckBindAndValidate(req interface{}, c *gin.Context) error { if err := c.ShouldBindJSON(req); err != nil { - ErrorWithDetail(c, constant.CodeErrBadRequest, constant.ErrTypeInvalidParams, err) + ErrorWithDetail(c, http.StatusBadRequest, "ErrInvalidParams", err) return err } if err := global.VALID.Struct(req); err != nil { - ErrorWithDetail(c, constant.CodeErrBadRequest, constant.ErrTypeInvalidParams, err) + ErrorWithDetail(c, http.StatusBadRequest, "ErrInvalidParams", err) return err } return nil diff --git a/core/app/api/v2/host.go b/core/app/api/v2/host.go index bf5e31b90..558312fe1 100644 --- a/core/app/api/v2/host.go +++ b/core/app/api/v2/host.go @@ -9,7 +9,6 @@ import ( "github.com/1Panel-dev/1Panel/core/app/api/v2/helper" "github.com/1Panel-dev/1Panel/core/app/dto" - "github.com/1Panel-dev/1Panel/core/constant" "github.com/1Panel-dev/1Panel/core/global" "github.com/1Panel-dev/1Panel/core/utils/copier" "github.com/1Panel-dev/1Panel/core/utils/encrypt" @@ -72,7 +71,7 @@ func (b *BaseApi) TestByInfo(c *gin.Context) { func (b *BaseApi) TestByID(c *gin.Context) { idParam, ok := c.Params.Get("id") if !ok { - helper.ErrorWithDetail(c, constant.CodeErrBadRequest, constant.ErrTypeInvalidParams, errors.New("no such params find in request")) + helper.BadRequest(c, errors.New("no such params find in request")) return } intNum, err := strconv.Atoi(idParam) diff --git a/core/app/api/v2/logs.go b/core/app/api/v2/logs.go index f6f2bbe03..177e18f35 100644 --- a/core/app/api/v2/logs.go +++ b/core/app/api/v2/logs.go @@ -3,7 +3,6 @@ package v2 import ( "github.com/1Panel-dev/1Panel/core/app/api/v2/helper" "github.com/1Panel-dev/1Panel/core/app/dto" - "github.com/1Panel-dev/1Panel/core/constant" "github.com/gin-gonic/gin" ) @@ -23,7 +22,7 @@ func (b *BaseApi) GetLoginLogs(c *gin.Context) { total, list, err := logService.PageLoginLog(c, req) if err != nil { - helper.ErrorWithDetail(c, constant.CodeErrInternalServer, constant.ErrTypeInternalServer, err) + helper.InternalServer(c, err) return } diff --git a/core/app/api/v2/setting.go b/core/app/api/v2/setting.go index 09710b4fc..8d9818791 100644 --- a/core/app/api/v2/setting.go +++ b/core/app/api/v2/setting.go @@ -23,7 +23,7 @@ import ( func (b *BaseApi) GetSettingInfo(c *gin.Context) { setting, err := settingService.GetSettingInfo() if err != nil { - helper.ErrorWithDetail(c, constant.CodeErrInternalServer, constant.ErrTypeInternalServer, err) + helper.InternalServer(c, err) return } helper.SuccessWithData(c, setting) @@ -38,7 +38,7 @@ func (b *BaseApi) GetSettingInfo(c *gin.Context) { func (b *BaseApi) GetTerminalSettingInfo(c *gin.Context) { setting, err := settingService.GetTerminalInfo() if err != nil { - helper.ErrorWithDetail(c, constant.CodeErrInternalServer, constant.ErrTypeInternalServer, err) + helper.InternalServer(c, err) return } helper.SuccessWithData(c, setting) @@ -70,7 +70,7 @@ func (b *BaseApi) UpdateSetting(c *gin.Context) { } if err := settingService.Update(req.Key, req.Value); err != nil { - helper.ErrorWithDetail(c, constant.CodeErrInternalServer, constant.ErrTypeInternalServer, err) + helper.InternalServer(c, err) return } helper.SuccessWithOutData(c) @@ -92,7 +92,7 @@ func (b *BaseApi) UpdateTerminalSetting(c *gin.Context) { } if err := settingService.UpdateTerminal(req); err != nil { - helper.ErrorWithDetail(c, constant.CodeErrInternalServer, constant.ErrTypeInternalServer, err) + helper.InternalServer(c, err) return } helper.SuccessWithOutData(c) @@ -123,7 +123,7 @@ func (b *BaseApi) UpdateProxy(c *gin.Context) { } if err := settingService.UpdateProxy(req); err != nil { - helper.ErrorWithDetail(c, constant.CodeErrInternalServer, constant.ErrTypeInternalServer, err) + helper.InternalServer(c, err) return } helper.SuccessWithOutData(c) @@ -145,7 +145,7 @@ func (b *BaseApi) UpdateMenu(c *gin.Context) { } if err := settingService.Update(req.Key, req.Value); err != nil { - helper.ErrorWithDetail(c, constant.CodeErrInternalServer, constant.ErrTypeInternalServer, err) + helper.InternalServer(c, err) return } helper.SuccessWithOutData(c) @@ -167,7 +167,7 @@ func (b *BaseApi) UpdatePassword(c *gin.Context) { } if err := settingService.UpdatePassword(c, req.OldPassword, req.NewPassword); err != nil { - helper.ErrorWithDetail(c, constant.CodeErrInternalServer, constant.ErrTypeInternalServer, err) + helper.InternalServer(c, err) return } helper.SuccessWithOutData(c) @@ -189,7 +189,7 @@ func (b *BaseApi) UpdateSSL(c *gin.Context) { } if err := settingService.UpdateSSL(c, req); err != nil { - helper.ErrorWithDetail(c, constant.CodeErrInternalServer, constant.ErrTypeInternalServer, err) + helper.InternalServer(c, err) return } helper.SuccessWithOutData(c) @@ -204,7 +204,7 @@ func (b *BaseApi) UpdateSSL(c *gin.Context) { func (b *BaseApi) LoadFromCert(c *gin.Context) { info, err := settingService.LoadFromCert() if err != nil { - helper.ErrorWithDetail(c, constant.CodeErrInternalServer, constant.ErrTypeInternalServer, err) + helper.InternalServer(c, err) return } helper.SuccessWithData(c, info) @@ -217,9 +217,9 @@ func (b *BaseApi) LoadFromCert(c *gin.Context) { // @Security Timestamp // @Router /core/settings/ssl/download [post] func (b *BaseApi) DownloadSSL(c *gin.Context) { - pathItem := path.Join(global.CONF.System.BaseDir, "1panel/secret/server.crt") + pathItem := path.Join(global.CONF.Base.InstallDir, "1panel/secret/server.crt") if _, err := os.Stat(pathItem); err != nil { - helper.ErrorWithDetail(c, constant.CodeErrInternalServer, constant.ErrTypeInternalServer, err) + helper.InternalServer(c, err) return } @@ -236,7 +236,7 @@ func (b *BaseApi) DownloadSSL(c *gin.Context) { func (b *BaseApi) LoadInterfaceAddr(c *gin.Context) { data, err := settingService.LoadInterfaceAddr() if err != nil { - helper.ErrorWithDetail(c, constant.CodeErrInternalServer, constant.ErrTypeInternalServer, err) + helper.InternalServer(c, err) return } helper.SuccessWithData(c, data) @@ -258,7 +258,7 @@ func (b *BaseApi) UpdateBindInfo(c *gin.Context) { } if err := settingService.UpdateBindInfo(req); err != nil { - helper.ErrorWithDetail(c, constant.CodeErrInternalServer, constant.ErrTypeInternalServer, err) + helper.InternalServer(c, err) return } helper.SuccessWithOutData(c) @@ -280,7 +280,7 @@ func (b *BaseApi) UpdatePort(c *gin.Context) { } if err := settingService.UpdatePort(req.ServerPort); err != nil { - helper.ErrorWithDetail(c, constant.CodeErrInternalServer, constant.ErrTypeInternalServer, err) + helper.InternalServer(c, err) return } helper.SuccessWithOutData(c) @@ -302,7 +302,7 @@ func (b *BaseApi) HandlePasswordExpired(c *gin.Context) { } if err := settingService.HandlePasswordExpired(c, req.OldPassword, req.NewPassword); err != nil { - helper.ErrorWithDetail(c, constant.CodeErrInternalServer, constant.ErrTypeInternalServer, err) + helper.InternalServer(c, err) return } helper.SuccessWithOutData(c) @@ -324,7 +324,7 @@ func (b *BaseApi) LoadMFA(c *gin.Context) { otp, err := mfa.GetOtp("admin", req.Title, req.Interval) if err != nil { - helper.ErrorWithDetail(c, constant.CodeErrInternalServer, constant.ErrTypeInternalServer, err) + helper.InternalServer(c, err) return } @@ -348,22 +348,22 @@ func (b *BaseApi) MFABind(c *gin.Context) { success := mfa.ValidCode(req.Code, req.Interval, req.Secret) if !success { - helper.ErrorWithDetail(c, constant.CodeErrInternalServer, constant.ErrTypeInternalServer, errors.New("code is not valid")) + helper.InternalServer(c, errors.New("code is not valid")) return } if err := settingService.Update("MFAInterval", req.Interval); err != nil { - helper.ErrorWithDetail(c, constant.CodeErrInternalServer, constant.ErrTypeInternalServer, err) + helper.InternalServer(c, err) return } if err := settingService.Update("MFAStatus", constant.StatusEnable); err != nil { - helper.ErrorWithDetail(c, constant.CodeErrInternalServer, constant.ErrTypeInternalServer, err) + helper.InternalServer(c, err) return } if err := settingService.Update("MFASecret", req.Secret); err != nil { - helper.ErrorWithDetail(c, constant.CodeErrInternalServer, constant.ErrTypeInternalServer, err) + helper.InternalServer(c, err) return } @@ -373,11 +373,11 @@ func (b *BaseApi) MFABind(c *gin.Context) { func (b *BaseApi) ReloadSSL(c *gin.Context) { clientIP := c.ClientIP() if clientIP != "127.0.0.1" { - helper.ErrorWithDetail(c, constant.CodeErrInternalServer, constant.ErrTypeInternalServer, errors.New("only localhost can reload ssl")) + helper.InternalServer(c, errors.New("only localhost can reload ssl")) return } if err := settingService.UpdateSystemSSL(); err != nil { - helper.ErrorWithDetail(c, constant.CodeErrInternalServer, constant.ErrTypeInternalServer, err) + helper.InternalServer(c, err) return } helper.SuccessWithOutData(c) @@ -394,12 +394,12 @@ func (b *BaseApi) ReloadSSL(c *gin.Context) { func (b *BaseApi) GenerateApiKey(c *gin.Context) { panelToken := c.GetHeader("1Panel-Token") if panelToken != "" { - helper.ErrorWithDetail(c, constant.CodeErrUnauthorized, constant.ErrApiConfigDisable, nil) + helper.BadAuth(c, "ErrApiConfigDisable", nil) return } apiKey, err := settingService.GenerateApiKey() if err != nil { - helper.ErrorWithDetail(c, constant.CodeErrInternalServer, constant.ErrTypeInternalServer, err) + helper.InternalServer(c, err) return } helper.SuccessWithData(c, apiKey) @@ -417,7 +417,7 @@ func (b *BaseApi) GenerateApiKey(c *gin.Context) { func (b *BaseApi) UpdateApiConfig(c *gin.Context) { panelToken := c.GetHeader("1Panel-Token") if panelToken != "" { - helper.ErrorWithDetail(c, constant.CodeErrUnauthorized, constant.ErrApiConfigDisable, nil) + helper.BadAuth(c, "ErrApiConfigDisable", nil) return } var req dto.ApiInterfaceConfig @@ -426,7 +426,7 @@ func (b *BaseApi) UpdateApiConfig(c *gin.Context) { } if err := settingService.UpdateApiConfig(req); err != nil { - helper.ErrorWithDetail(c, constant.CodeErrInternalServer, constant.ErrTypeInternalServer, err) + helper.InternalServer(c, err) return } helper.SuccessWithOutData(c) diff --git a/core/app/api/v2/upgrade.go b/core/app/api/v2/upgrade.go index 5ce9f1f5b..ab48111e0 100644 --- a/core/app/api/v2/upgrade.go +++ b/core/app/api/v2/upgrade.go @@ -3,7 +3,6 @@ package v2 import ( "github.com/1Panel-dev/1Panel/core/app/api/v2/helper" "github.com/1Panel-dev/1Panel/core/app/dto" - "github.com/1Panel-dev/1Panel/core/constant" "github.com/gin-gonic/gin" ) @@ -16,7 +15,7 @@ import ( func (b *BaseApi) GetUpgradeInfo(c *gin.Context) { info, err := upgradeService.SearchUpgrade() if err != nil { - helper.ErrorWithDetail(c, constant.CodeErrInternalServer, constant.ErrTypeInternalServer, err) + helper.InternalServer(c, err) return } helper.SuccessWithData(c, info) diff --git a/core/app/repo/setting.go b/core/app/repo/setting.go index e7b3a26cc..034c2ad92 100644 --- a/core/app/repo/setting.go +++ b/core/app/repo/setting.go @@ -10,6 +10,7 @@ type SettingRepo struct{} type ISettingRepo interface { List(opts ...global.DBOption) ([]model.Setting, error) Get(opts ...global.DBOption) (model.Setting, error) + GetValueByKey(key string) (string, error) Create(key, value string) error Update(key, value string) error } @@ -46,6 +47,14 @@ func (u *SettingRepo) Get(opts ...global.DBOption) (model.Setting, error) { return settings, err } +func (u *SettingRepo) GetValueByKey(key string) (string, error) { + var setting model.Setting + if err := global.DB.Model(&model.Setting{}).Where("key = ?", key).First(&setting).Error; err != nil { + return "", err + } + return setting.Value, nil +} + func (u *SettingRepo) Update(key, value string) error { return global.DB.Model(&model.Setting{}).Where("key = ?", key).Updates(map[string]interface{}{"value": value}).Error } diff --git a/core/app/service/auth.go b/core/app/service/auth.go index 2f59bcdfd..1a6f44585 100644 --- a/core/app/service/auth.go +++ b/core/app/service/auth.go @@ -13,7 +13,6 @@ import ( "github.com/1Panel-dev/1Panel/core/utils/jwt" "github.com/1Panel-dev/1Panel/core/utils/mfa" "github.com/gin-gonic/gin" - "github.com/pkg/errors" ) type AuthService struct{} @@ -36,25 +35,25 @@ func NewIAuthService() IAuthService { func (u *AuthService) Login(c *gin.Context, info dto.Login, entrance string) (*dto.UserLoginInfo, error) { nameSetting, err := settingRepo.Get(repo.WithByKey("UserName")) if err != nil { - return nil, errors.WithMessage(constant.ErrRecordNotFound, err.Error()) + return nil, buserr.New("ErrRecordNotFound") } passwordSetting, err := settingRepo.Get(repo.WithByKey("Password")) if err != nil { - return nil, errors.WithMessage(constant.ErrRecordNotFound, err.Error()) + return nil, buserr.New("ErrRecordNotFound") } pass, err := encrypt.StringDecrypt(passwordSetting.Value) if err != nil { - return nil, constant.ErrAuth + return nil, buserr.New("ErrAuth") } if !hmac.Equal([]byte(info.Password), []byte(pass)) || nameSetting.Value != info.Name { - return nil, constant.ErrAuth + return nil, buserr.New("ErrAuth") } entranceSetting, err := settingRepo.Get(repo.WithByKey("SecurityEntrance")) if err != nil { return nil, err } if len(entranceSetting.Value) != 0 && entranceSetting.Value != entrance { - return nil, buserr.New(constant.ErrEntrance) + return nil, buserr.New("ErrEntrance") } mfa, err := settingRepo.Get(repo.WithByKey("MFAStatus")) if err != nil { @@ -72,25 +71,25 @@ func (u *AuthService) Login(c *gin.Context, info dto.Login, entrance string) (*d func (u *AuthService) MFALogin(c *gin.Context, info dto.MFALogin, entrance string) (*dto.UserLoginInfo, error) { nameSetting, err := settingRepo.Get(repo.WithByKey("UserName")) if err != nil { - return nil, errors.WithMessage(constant.ErrRecordNotFound, err.Error()) + return nil, buserr.New("ErrRecordNotFound") } passwordSetting, err := settingRepo.Get(repo.WithByKey("Password")) if err != nil { - return nil, errors.WithMessage(constant.ErrRecordNotFound, err.Error()) + return nil, buserr.New("ErrRecordNotFound") } pass, err := encrypt.StringDecrypt(passwordSetting.Value) if err != nil { return nil, err } if !hmac.Equal([]byte(info.Password), []byte(pass)) || nameSetting.Value != info.Name { - return nil, constant.ErrAuth + return nil, buserr.New("ErrAuth") } entranceSetting, err := settingRepo.Get(repo.WithByKey("SecurityEntrance")) if err != nil { return nil, err } if len(entranceSetting.Value) != 0 && entranceSetting.Value != entrance { - return nil, buserr.New(constant.ErrEntrance) + return nil, buserr.New("ErrEntrance") } mfaSecret, err := settingRepo.Get(repo.WithByKey("MFASecret")) if err != nil { @@ -102,7 +101,7 @@ func (u *AuthService) MFALogin(c *gin.Context, info dto.MFALogin, entrance strin } success := mfa.ValidCode(info.Code, mfaInterval.Value, mfaSecret.Value) if !success { - return nil, constant.ErrAuth + return nil, buserr.New("ErrAuth") } return u.generateSession(c, info.Name, info.AuthMethod) diff --git a/core/app/service/backup.go b/core/app/service/backup.go index bec79e9b8..72517adb9 100644 --- a/core/app/service/backup.go +++ b/core/app/service/backup.go @@ -24,7 +24,6 @@ import ( "github.com/1Panel-dev/1Panel/core/utils/req_helper" "github.com/1Panel-dev/1Panel/core/utils/xpack" "github.com/jinzhu/copier" - "github.com/pkg/errors" ) type BackupService struct{} @@ -77,17 +76,17 @@ func (u *BackupService) LoadBackupClientInfo(clientType string) (dto.BackupClien func (u *BackupService) Create(req dto.BackupOperate) error { if !req.IsPublic { - return buserr.New(constant.ErrBackupPublic) + return buserr.New("ErrBackupPublic") } backup, _ := backupRepo.Get(repo.WithByName(req.Name)) if backup.ID != 0 { - return constant.ErrRecordExist + return buserr.New("ErrRecordExist") } if req.Type != constant.Sftp && req.BackupPath != "/" { req.BackupPath = strings.TrimPrefix(req.BackupPath, "/") } if err := copier.Copy(&backup, &req); err != nil { - return errors.WithMessage(constant.ErrStructTransform, err.Error()) + return buserr.WithDetail("ErrStructTransform", err.Error(), nil) } itemAccessKey, err := base64.StdEncoding.DecodeString(backup.AccessKey) if err != nil { @@ -160,21 +159,21 @@ func (u *BackupService) GetBuckets(req dto.ForBuckets) ([]interface{}, error) { func (u *BackupService) Delete(id uint) error { backup, _ := backupRepo.Get(repo.WithByID(id)) if backup.ID == 0 { - return constant.ErrRecordNotFound + return buserr.New("ErrRecordNotFound") } if !backup.IsPublic { - return buserr.New(constant.ErrBackupPublic) + return buserr.New("ErrBackupPublic") } if backup.Type == constant.Local { - return buserr.New(constant.ErrBackupLocal) + return buserr.New("ErrBackupLocal") } if _, err := req_helper.NewLocalClient(fmt.Sprintf("/api/v2/backups/check/%v", id), http.MethodGet, nil); err != nil { global.LOG.Errorf("check used of local cronjob failed, err: %v", err) - return buserr.New(constant.ErrBackupInUsed) + return buserr.New("ErrBackupInUsed") } if err := xpack.CheckBackupUsed(id); err != nil { global.LOG.Errorf("check used of node cronjob failed, err: %v", err) - return buserr.New(constant.ErrBackupInUsed) + return buserr.New("ErrBackupInUsed") } go syncAccountToAgent(backup, "delete") @@ -184,20 +183,20 @@ func (u *BackupService) Delete(id uint) error { func (u *BackupService) Update(req dto.BackupOperate) error { backup, _ := backupRepo.Get(repo.WithByID(req.ID)) if backup.ID == 0 { - return constant.ErrRecordNotFound + return buserr.New("ErrRecordNotFound") } if !backup.IsPublic { - return buserr.New(constant.ErrBackupPublic) + return buserr.New("ErrBackupPublic") } if backup.Type == constant.Local { - return buserr.New(constant.ErrBackupLocal) + return buserr.New("ErrBackupLocal") } if req.Type != constant.Sftp && req.BackupPath != "/" { req.BackupPath = strings.TrimPrefix(req.BackupPath, "/") } var newBackup model.BackupAccount if err := copier.Copy(&newBackup, &req); err != nil { - return errors.WithMessage(constant.ErrStructTransform, err.Error()) + return buserr.WithDetail("ErrStructTransform", err.Error(), nil) } itemAccessKey, err := base64.StdEncoding.DecodeString(newBackup.AccessKey) if err != nil { @@ -239,10 +238,10 @@ func (u *BackupService) Update(req dto.BackupOperate) error { func (u *BackupService) RefreshToken(req dto.OperateByID) error { backup, _ := backupRepo.Get(repo.WithByID(req.ID)) if backup.ID == 0 { - return constant.ErrRecordNotFound + return buserr.New("ErrRecordNotFound") } if !backup.IsPublic { - return buserr.New(constant.ErrBackupPublic) + return buserr.New("ErrBackupPublic") } varMap := make(map[string]interface{}) if err := json.Unmarshal([]byte(backup.Vars), &varMap); err != nil { @@ -335,7 +334,7 @@ func (u *BackupService) checkBackupConn(backup *model.BackupAccount) (bool, erro if err != nil { return false, err } - fileItem := path.Join(global.CONF.System.BaseDir, "1panel/tmp/test/1panel") + fileItem := path.Join(global.CONF.Base.InstallDir, "1panel/tmp/test/1panel") if _, err := os.Stat(path.Dir(fileItem)); err != nil && os.IsNotExist(err) { if err = os.MkdirAll(path.Dir(fileItem), os.ModePerm); err != nil { return false, err diff --git a/core/app/service/command.go b/core/app/service/command.go index e465fce1d..1d50a624c 100644 --- a/core/app/service/command.go +++ b/core/app/service/command.go @@ -3,10 +3,9 @@ package service import ( "github.com/1Panel-dev/1Panel/core/app/dto" "github.com/1Panel-dev/1Panel/core/app/repo" - "github.com/1Panel-dev/1Panel/core/constant" + "github.com/1Panel-dev/1Panel/core/buserr" "github.com/1Panel-dev/1Panel/core/global" "github.com/jinzhu/copier" - "github.com/pkg/errors" ) type CommandService struct{} @@ -27,13 +26,13 @@ func NewICommandService() ICommandService { func (u *CommandService) List(req dto.OperateByType) ([]dto.CommandInfo, error) { commands, err := commandRepo.List(repo.WithOrderBy("name"), repo.WithByType(req.Type)) if err != nil { - return nil, constant.ErrRecordNotFound + return nil, buserr.New("ErrRecordNotFound") } var dtoCommands []dto.CommandInfo for _, command := range commands { var item dto.CommandInfo if err := copier.Copy(&item, &command); err != nil { - return nil, errors.WithMessage(constant.ErrStructTransform, err.Error()) + return nil, buserr.WithDetail("ErrStructTransform", err.Error(), nil) } dtoCommands = append(dtoCommands, item) } @@ -86,7 +85,7 @@ func (u *CommandService) SearchWithPage(req dto.SearchCommandWithPage) (int64, i for _, command := range commands { var item dto.CommandInfo if err := copier.Copy(&item, &command); err != nil { - return 0, nil, errors.WithMessage(constant.ErrStructTransform, err.Error()) + return 0, nil, buserr.WithDetail("ErrStructTransform", err.Error(), nil) } for _, group := range groups { if command.GroupID == group.ID { @@ -102,10 +101,10 @@ func (u *CommandService) SearchWithPage(req dto.SearchCommandWithPage) (int64, i func (u *CommandService) Create(commandDto dto.CommandOperate) error { command, _ := commandRepo.Get(repo.WithByName(commandDto.Name)) if command.ID != 0 { - return constant.ErrRecordExist + return buserr.New("ErrRecordExist") } if err := copier.Copy(&command, &commandDto); err != nil { - return errors.WithMessage(constant.ErrStructTransform, err.Error()) + return buserr.WithDetail("ErrStructTransform", err.Error(), nil) } if err := commandRepo.Create(&command); err != nil { return err @@ -117,7 +116,7 @@ func (u *CommandService) Delete(ids []uint) error { if len(ids) == 1 { command, _ := commandRepo.Get(repo.WithByID(ids[0])) if command.ID == 0 { - return constant.ErrRecordNotFound + return buserr.New("ErrRecordNotFound") } return commandRepo.Delete(repo.WithByID(ids[0])) } diff --git a/core/app/service/group.go b/core/app/service/group.go index ce040d4f6..c693c5735 100644 --- a/core/app/service/group.go +++ b/core/app/service/group.go @@ -9,12 +9,10 @@ import ( "github.com/1Panel-dev/1Panel/core/app/model" "github.com/1Panel-dev/1Panel/core/app/repo" "github.com/1Panel-dev/1Panel/core/buserr" - "github.com/1Panel-dev/1Panel/core/constant" "github.com/1Panel-dev/1Panel/core/global" "github.com/1Panel-dev/1Panel/core/utils/req_helper" "github.com/1Panel-dev/1Panel/core/utils/xpack" "github.com/jinzhu/copier" - "github.com/pkg/errors" ) type GroupService struct{} @@ -44,13 +42,13 @@ func (u *GroupService) List(req dto.OperateByType) ([]dto.GroupInfo, error) { ) groups, err = groupRepo.GetList(options...) if err != nil { - return nil, constant.ErrRecordNotFound + return nil, buserr.New("ErrRecordNotFound") } var dtoUsers []dto.GroupInfo for _, group := range groups { var item dto.GroupInfo if err := copier.Copy(&item, &group); err != nil { - return nil, errors.WithMessage(constant.ErrStructTransform, err.Error()) + return nil, buserr.WithDetail("ErrStructTransform", err.Error(), nil) } dtoUsers = append(dtoUsers, item) } @@ -60,10 +58,10 @@ func (u *GroupService) List(req dto.OperateByType) ([]dto.GroupInfo, error) { func (u *GroupService) Create(req dto.GroupCreate) error { group, _ := groupRepo.Get(repo.WithByName(req.Name), repo.WithByType(req.Type)) if group.ID != 0 { - return constant.ErrRecordExist + return buserr.New("ErrRecordExist") } if err := copier.Copy(&group, &req); err != nil { - return errors.WithMessage(constant.ErrStructTransform, err.Error()) + return buserr.WithDetail("ErrStructTransform", err.Error(), nil) } if err := groupRepo.Create(&group); err != nil { return err @@ -74,10 +72,10 @@ func (u *GroupService) Create(req dto.GroupCreate) error { func (u *GroupService) Delete(id uint) error { group, _ := groupRepo.Get(repo.WithByID(id)) if group.ID == 0 { - return constant.ErrRecordNotFound + return buserr.New("ErrRecordNotFound") } if group.IsDefault { - return buserr.New(constant.ErrGroupIsDefault) + return buserr.New("ErrGroupIsDefault") } defaultGroup, err := groupRepo.Get(repo.WithByType(group.Type), groupRepo.WithByDefault(true)) if err != nil { @@ -99,7 +97,7 @@ func (u *GroupService) Delete(id uint) error { return err } default: - return constant.ErrNotSupportType + return buserr.New("ErrNotSupportType") } if err != nil { return err diff --git a/core/app/service/host.go b/core/app/service/host.go index 3f99cdcfb..eabffe7ab 100644 --- a/core/app/service/host.go +++ b/core/app/service/host.go @@ -7,7 +7,7 @@ import ( "github.com/1Panel-dev/1Panel/core/app/dto" "github.com/1Panel-dev/1Panel/core/app/model" "github.com/1Panel-dev/1Panel/core/app/repo" - "github.com/1Panel-dev/1Panel/core/constant" + "github.com/1Panel-dev/1Panel/core/buserr" "github.com/1Panel-dev/1Panel/core/global" "github.com/1Panel-dev/1Panel/core/utils/encrypt" "github.com/1Panel-dev/1Panel/core/utils/ssh" @@ -127,7 +127,7 @@ func (u *HostService) TestLocalConn(id uint) bool { func (u *HostService) GetHostInfo(id uint) (*model.Host, error) { host, err := hostRepo.Get(repo.WithByID(id)) if err != nil { - return nil, constant.ErrRecordNotFound + return nil, buserr.New("ErrRecordNotFound") } if len(host.Password) != 0 { host.Password, err = encrypt.StringDecrypt(host.Password) @@ -167,7 +167,7 @@ func (u *HostService) SearchWithPage(req dto.SearchHostWithPage) (int64, interfa for _, host := range hosts { var item dto.HostInfo if err := copier.Copy(&item, &host); err != nil { - return 0, nil, errors.WithMessage(constant.ErrStructTransform, err.Error()) + return 0, nil, buserr.WithDetail("ErrStructTransform", err.Error(), nil) } group, _ := groupRepo.Get(repo.WithByID(host.GroupID)) item.GroupBelong = group.Name @@ -255,7 +255,7 @@ func (u *HostService) Create(req dto.HostOperate) (*dto.HostInfo, error) { } var host model.Host if err := copier.Copy(&host, &req); err != nil { - return nil, errors.WithMessage(constant.ErrStructTransform, err.Error()) + return nil, buserr.WithDetail("ErrStructTransform", err.Error(), nil) } if req.GroupID == 0 { group, err := groupRepo.Get(repo.WithByType("host"), groupRepo.WithByDefault(true)) @@ -292,7 +292,7 @@ func (u *HostService) Create(req dto.HostOperate) (*dto.HostInfo, error) { } var hostinfo dto.HostInfo if err := copier.Copy(&hostinfo, &host); err != nil { - return nil, errors.WithMessage(constant.ErrStructTransform, err.Error()) + return nil, buserr.WithDetail("ErrStructTransform", err.Error(), nil) } return &hostinfo, nil } @@ -302,7 +302,7 @@ func (u *HostService) Create(req dto.HostOperate) (*dto.HostInfo, error) { } var hostinfo dto.HostInfo if err := copier.Copy(&hostinfo, &host); err != nil { - return nil, errors.WithMessage(constant.ErrStructTransform, err.Error()) + return nil, buserr.WithDetail("ErrStructTransform", err.Error(), nil) } return &hostinfo, nil } @@ -311,7 +311,7 @@ func (u *HostService) Delete(ids []uint) error { hosts, _ := hostRepo.GetList(repo.WithByIDs(ids)) for _, host := range hosts { if host.ID == 0 { - return constant.ErrRecordNotFound + return buserr.New("ErrRecordNotFound") } if host.Addr == "127.0.0.1" { return errors.New("the local connection information cannot be deleted!") diff --git a/core/app/service/logs.go b/core/app/service/logs.go index 2dc277c08..48a432424 100644 --- a/core/app/service/logs.go +++ b/core/app/service/logs.go @@ -1,9 +1,6 @@ package service import ( - "github.com/1Panel-dev/1Panel/core/utils/common" - geo2 "github.com/1Panel-dev/1Panel/core/utils/geo" - "github.com/gin-gonic/gin" "os" "path" "path/filepath" @@ -11,14 +8,17 @@ import ( "strings" "time" + "github.com/1Panel-dev/1Panel/core/buserr" + "github.com/1Panel-dev/1Panel/core/utils/common" + geo2 "github.com/1Panel-dev/1Panel/core/utils/geo" + "github.com/gin-gonic/gin" + "github.com/1Panel-dev/1Panel/core/app/dto" "github.com/1Panel-dev/1Panel/core/app/model" "github.com/1Panel-dev/1Panel/core/app/repo" - "github.com/1Panel-dev/1Panel/core/constant" "github.com/1Panel-dev/1Panel/core/global" "github.com/1Panel-dev/1Panel/core/utils/cmd" "github.com/jinzhu/copier" - "github.com/pkg/errors" ) type LogService struct{} @@ -45,7 +45,7 @@ func (u *LogService) CreateLoginLog(operation model.LoginLog) error { } func (u *LogService) ListSystemLogFile() ([]string, error) { - logDir := path.Join(global.CONF.System.BaseDir, "1panel/log") + logDir := path.Join(global.CONF.Base.InstallDir, "1panel/log") var files []string if err := filepath.Walk(logDir, func(pathItem string, info os.FileInfo, err error) error { if err != nil { @@ -97,7 +97,7 @@ func (u *LogService) PageLoginLog(ctx *gin.Context, req dto.SearchLgLogWithPage) for _, op := range ops { var item dto.LoginLog if err := copier.Copy(&item, &op); err != nil { - return 0, nil, errors.WithMessage(constant.ErrTransform, err.Error()) + return 0, nil, buserr.WithErr("ErrTransform", err) } if geoDB != nil { item.Address, _ = geo2.GetIPLocation(geoDB, item.IP, common.GetLang(ctx)) @@ -132,7 +132,7 @@ func (u *LogService) PageOperationLog(req dto.SearchOpLogWithPage) (int64, inter for _, op := range ops { var item dto.OperationLog if err := copier.Copy(&item, &op); err != nil { - return 0, nil, errors.WithMessage(constant.ErrTransform, err.Error()) + return 0, nil, buserr.WithErr("ErrTransform", err) } dtoOps = append(dtoOps, item) } diff --git a/core/app/service/setting.go b/core/app/service/setting.go index 26f05a1e3..cf904a4a7 100644 --- a/core/app/service/setting.go +++ b/core/app/service/setting.go @@ -54,7 +54,7 @@ func NewISettingService() ISettingService { func (u *SettingService) GetSettingInfo() (*dto.SettingInfo, error) { setting, err := settingRepo.List() if err != nil { - return nil, constant.ErrRecordNotFound + return nil, buserr.New("ErrRecordNotFound") } settingMap := make(map[string]string) for _, set := range setting { @@ -179,7 +179,7 @@ func (u *SettingService) UpdateProxy(req dto.ProxyUpdate) error { func (u *SettingService) UpdatePort(port uint) error { if common.ScanPort(int(port)) { - return buserr.WithDetail(constant.ErrPortInUsed, port, nil) + return buserr.WithDetail("ErrPortInUsed", port, nil) } oldPort, err := settingRepo.Get(repo.WithByKey("ServerPort")) if err != nil { @@ -205,7 +205,7 @@ func (u *SettingService) UpdatePort(port uint) error { } func (u *SettingService) UpdateSSL(c *gin.Context, req dto.SSLUpdate) error { - secretDir := path.Join(global.CONF.System.BaseDir, "1panel/secret") + secretDir := path.Join(global.CONF.Base.InstallDir, "1panel/secret") if req.SSL == constant.StatusDisable { if err := settingRepo.Update("SSL", constant.StatusDisable); err != nil { return err @@ -293,16 +293,16 @@ func (u *SettingService) LoadFromCert() (*dto.SSLInfo, error) { if err != nil { return nil, err } - if _, err := os.Stat(path.Join(global.CONF.System.BaseDir, "1panel/secret/server.crt")); err != nil { + if _, err := os.Stat(path.Join(global.CONF.Base.InstallDir, "1panel/secret/server.crt")); err != nil { return nil, fmt.Errorf("load server.crt file failed, err: %v", err) } - certFile, _ := os.ReadFile(path.Join(global.CONF.System.BaseDir, "1panel/secret/server.crt")) + certFile, _ := os.ReadFile(path.Join(global.CONF.Base.InstallDir, "1panel/secret/server.crt")) data.Cert = string(certFile) - if _, err := os.Stat(path.Join(global.CONF.System.BaseDir, "1panel/secret/server.key")); err != nil { + if _, err := os.Stat(path.Join(global.CONF.Base.InstallDir, "1panel/secret/server.key")); err != nil { return nil, fmt.Errorf("load server.key file failed, err: %v", err) } - keyFile, _ := os.ReadFile(path.Join(global.CONF.System.BaseDir, "1panel/secret/server.key")) + keyFile, _ := os.ReadFile(path.Join(global.CONF.Base.InstallDir, "1panel/secret/server.key")) data.Key = string(keyFile) case "select": // TODO select ssl from website @@ -338,13 +338,13 @@ func (u *SettingService) HandlePasswordExpired(c *gin.Context, old, new string) } return nil } - return constant.ErrInitialPassword + return buserr.New("ErrInitialPassword") } func (u *SettingService) GetTerminalInfo() (*dto.TerminalInfo, error) { setting, err := settingRepo.List() if err != nil { - return nil, constant.ErrRecordNotFound + return nil, buserr.New("ErrRecordNotFound") } settingMap := make(map[string]string) for _, set := range setting { @@ -394,8 +394,8 @@ func (u *SettingService) UpdatePassword(c *gin.Context, old, new string) error { } func (u *SettingService) UpdateSystemSSL() error { - certPath := path.Join(global.CONF.System.BaseDir, "1panel/secret/server.crt") - keyPath := path.Join(global.CONF.System.BaseDir, "1panel/secret/server.key") + certPath := path.Join(global.CONF.Base.InstallDir, "1panel/secret/server.crt") + keyPath := path.Join(global.CONF.Base.InstallDir, "1panel/secret/server.key") certificate, err := os.ReadFile(certPath) if err != nil { return err @@ -415,9 +415,9 @@ func (u *SettingService) UpdateSystemSSL() error { func (u *SettingService) GenerateApiKey() (string, error) { apiKey := common.RandStr(32) if err := settingRepo.Update("ApiKey", apiKey); err != nil { - return global.CONF.System.ApiKey, err + return global.Api.ApiKey, err } - global.CONF.System.ApiKey = apiKey + global.Api.ApiKey = apiKey return apiKey, nil } @@ -425,25 +425,25 @@ func (u *SettingService) UpdateApiConfig(req dto.ApiInterfaceConfig) error { if err := settingRepo.Update("ApiInterfaceStatus", req.ApiInterfaceStatus); err != nil { return err } - global.CONF.System.ApiInterfaceStatus = req.ApiInterfaceStatus + global.Api.ApiInterfaceStatus = req.ApiInterfaceStatus if err := settingRepo.Update("ApiKey", req.ApiKey); err != nil { return err } - global.CONF.System.ApiKey = req.ApiKey + global.Api.ApiKey = req.ApiKey if err := settingRepo.Update("IpWhiteList", req.IpWhiteList); err != nil { return err } - global.CONF.System.IpWhiteList = req.IpWhiteList + global.Api.IpWhiteList = req.IpWhiteList if err := settingRepo.Update("ApiKeyValidityTime", req.ApiKeyValidityTime); err != nil { return err } - global.CONF.System.ApiKeyValidityTime = req.ApiKeyValidityTime + global.Api.ApiKeyValidityTime = req.ApiKeyValidityTime return nil } func loadInfoFromCert() (dto.SSLInfo, error) { var info dto.SSLInfo - certFile := path.Join(global.CONF.System.BaseDir, "1panel/secret/server.crt") + certFile := path.Join(global.CONF.Base.InstallDir, "1panel/secret/server.crt") if _, err := os.Stat(certFile); err != nil { return info, err } @@ -471,16 +471,16 @@ func loadInfoFromCert() (dto.SSLInfo, error) { return dto.SSLInfo{ Domain: strings.Join(domains, ","), Timeout: certObj.NotAfter.Format(constant.DateTimeLayout), - RootPath: path.Join(global.CONF.System.BaseDir, "1panel/secret/server.crt"), + RootPath: path.Join(global.CONF.Base.InstallDir, "1panel/secret/server.crt"), }, nil } func checkCertValid() error { - certificate, err := os.ReadFile(path.Join(global.CONF.System.BaseDir, "1panel/secret/server.crt.tmp")) + certificate, err := os.ReadFile(path.Join(global.CONF.Base.InstallDir, "1panel/secret/server.crt.tmp")) if err != nil { return err } - key, err := os.ReadFile(path.Join(global.CONF.System.BaseDir, "1panel/secret/server.key.tmp")) + key, err := os.ReadFile(path.Join(global.CONF.Base.InstallDir, "1panel/secret/server.key.tmp")) if err != nil { return err } diff --git a/core/app/service/upgrade.go b/core/app/service/upgrade.go index c95bb41f9..a85e61de2 100644 --- a/core/app/service/upgrade.go +++ b/core/app/service/upgrade.go @@ -13,6 +13,7 @@ import ( "github.com/1Panel-dev/1Panel/core/app/dto" "github.com/1Panel-dev/1Panel/core/app/model" "github.com/1Panel-dev/1Panel/core/app/repo" + "github.com/1Panel-dev/1Panel/core/buserr" "github.com/1Panel-dev/1Panel/core/constant" "github.com/1Panel-dev/1Panel/core/global" "github.com/1Panel-dev/1Panel/core/utils/cmd" @@ -53,17 +54,17 @@ func (u *UpgradeService) SearchUpgrade() (*dto.UpgradeInfo, error) { if len(upgrade.NewVersion) != 0 { itemVersion = upgrade.NewVersion } - if (global.CONF.System.Mode == "dev" || DeveloperMode.Value == constant.StatusEnable) && len(upgrade.TestVersion) != 0 { + if (global.CONF.Base.Mode == "dev" || DeveloperMode.Value == constant.StatusEnable) && len(upgrade.TestVersion) != 0 { itemVersion = upgrade.TestVersion } if len(itemVersion) == 0 { return &upgrade, nil } - mode := global.CONF.System.Mode + mode := global.CONF.Base.Mode if strings.Contains(itemVersion, "beta") { mode = "beta" } - notes, err := u.loadReleaseNotes(fmt.Sprintf("%s/%s/%s/release/1panel-%s-release-notes", global.CONF.System.RepoUrl, mode, itemVersion, itemVersion)) + notes, err := u.loadReleaseNotes(fmt.Sprintf("%s/%s/%s/release/1panel-%s-release-notes", global.CONF.RemoteURL.RepoUrl, mode, itemVersion, itemVersion)) if err != nil { return nil, fmt.Errorf("load releases-notes of version %s failed, err: %v", itemVersion, err) } @@ -72,11 +73,11 @@ func (u *UpgradeService) SearchUpgrade() (*dto.UpgradeInfo, error) { } func (u *UpgradeService) LoadNotes(req dto.Upgrade) (string, error) { - mode := global.CONF.System.Mode + mode := global.CONF.Base.Mode if strings.Contains(req.Version, "beta") { mode = "beta" } - notes, err := u.loadReleaseNotes(fmt.Sprintf("%s/%s/%s/release/1panel-%s-release-notes", global.CONF.System.RepoUrl, mode, req.Version, req.Version)) + notes, err := u.loadReleaseNotes(fmt.Sprintf("%s/%s/%s/release/1panel-%s-release-notes", global.CONF.RemoteURL.RepoUrl, mode, req.Version, req.Version)) if err != nil { return "", fmt.Errorf("load releases-notes of version %s failed, err: %v", req.Version, err) } @@ -86,7 +87,7 @@ func (u *UpgradeService) LoadNotes(req dto.Upgrade) (string, error) { func (u *UpgradeService) Upgrade(req dto.Upgrade) error { global.LOG.Info("start to upgrade now...") timeStr := time.Now().Format(constant.DateTimeSlimLayout) - baseDir := path.Join(global.CONF.System.BaseDir, fmt.Sprintf("1panel/tmp/upgrade/%s", req.Version)) + baseDir := path.Join(global.CONF.Base.InstallDir, fmt.Sprintf("1panel/tmp/upgrade/%s", req.Version)) rootDir := path.Join(baseDir, fmt.Sprintf("upgrade_%s/downloads", timeStr)) _ = os.RemoveAll(baseDir) originalDir := path.Join(baseDir, fmt.Sprintf("upgrade_%s/original", timeStr)) @@ -101,11 +102,11 @@ func (u *UpgradeService) Upgrade(req dto.Upgrade) error { return err } - mode := global.CONF.System.Mode + mode := global.CONF.Base.Mode if strings.Contains(req.Version, "beta") { mode = "beta" } - downloadPath := fmt.Sprintf("%s/%s/%s/release", global.CONF.System.RepoUrl, mode, req.Version) + downloadPath := fmt.Sprintf("%s/%s/%s/release", global.CONF.RemoteURL.RepoUrl, mode, req.Version) fileName := fmt.Sprintf("1panel-%s-%s-%s.tar.gz", req.Version, "linux", itemArch) _ = settingRepo.Update("SystemStatus", "Upgrading") go func() { @@ -130,7 +131,7 @@ func (u *UpgradeService) Upgrade(req dto.Upgrade) error { _ = settingRepo.Update("SystemStatus", "Free") return } - itemLog := model.UpgradeLog{NodeID: 0, OldVersion: global.CONF.System.Version, NewVersion: req.Version, BackupFile: originalDir} + itemLog := model.UpgradeLog{NodeID: 0, OldVersion: global.CONF.Base.Version, NewVersion: req.Version, BackupFile: originalDir} _ = upgradeLogRepo.Create(&itemLog) global.LOG.Info("backup original data successful, now start to upgrade!") @@ -146,7 +147,7 @@ func (u *UpgradeService) Upgrade(req dto.Upgrade) error { u.handleRollback(originalDir, 2) return } - if _, err := cmd.Execf("sed -i -e 's#BASE_DIR=.*#BASE_DIR=%s#g' /usr/local/bin/1pctl", global.CONF.System.BaseDir); err != nil { + if _, err := cmd.Execf("sed -i -e 's#BASE_DIR=.*#BASE_DIR=%s#g' /usr/local/bin/1pctl", global.CONF.Base.InstallDir); err != nil { global.LOG.Errorf("upgrade basedir in 1pctl failed, err: %v", err) u.handleRollback(originalDir, 2) return @@ -170,7 +171,7 @@ func (u *UpgradeService) Upgrade(req dto.Upgrade) error { func (u *UpgradeService) Rollback(req dto.OperateByID) error { log, _ := upgradeLogRepo.Get(repo.WithByID(req.ID)) if log.ID == 0 { - return constant.ErrRecordNotFound + return buserr.New("ErrRecordNotFound") } u.handleRollback(log.BackupFile, 3) return nil @@ -186,7 +187,7 @@ func (u *UpgradeService) handleBackup(originalDir string) error { if err := files.CopyItem(false, true, "/etc/systemd/system/1panel*.service", originalDir); err != nil { return err } - if err := files.CopyItem(true, true, path.Join(global.CONF.System.BaseDir, "1panel/db"), originalDir); err != nil { + if err := files.CopyItem(true, true, path.Join(global.CONF.Base.InstallDir, "1panel/db"), originalDir); err != nil { return err } return nil @@ -195,7 +196,7 @@ func (u *UpgradeService) handleBackup(originalDir string) error { func (u *UpgradeService) handleRollback(originalDir string, errStep int) { _ = settingRepo.Update("SystemStatus", "Free") - dbPath := path.Join(global.CONF.System.BaseDir, "1panel/db") + dbPath := path.Join(global.CONF.Base.InstallDir, "1panel/db") if _, err := os.Stat(path.Join(originalDir, "db")); err == nil { if err := files.CopyItem(true, true, path.Join(originalDir, "db"), dbPath); err != nil { global.LOG.Errorf("rollback 1panel db failed, err: %v", err) @@ -220,7 +221,7 @@ func (u *UpgradeService) handleRollback(originalDir string, errStep int) { func (u *UpgradeService) loadVersionByMode(developer, currentVersion string) (string, string, string) { var current, latest string - if global.CONF.System.Mode == "dev" { + if global.CONF.Base.Mode == "dev" { betaVersionLatest := u.loadVersion(true, currentVersion, "beta") devVersionLatest := u.loadVersion(true, currentVersion, "dev") if common.ComparePanelVersion(betaVersionLatest, devVersionLatest) { @@ -260,9 +261,9 @@ func (u *UpgradeService) loadVersionByMode(developer, currentVersion string) (st } func (u *UpgradeService) loadVersion(isLatest bool, currentVersion, mode string) string { - path := fmt.Sprintf("%s/%s/latest", global.CONF.System.RepoUrl, mode) + path := fmt.Sprintf("%s/%s/latest", global.CONF.RemoteURL.RepoUrl, mode) if !isLatest { - path = fmt.Sprintf("%s/%s/latest.current", global.CONF.System.RepoUrl, mode) + path = fmt.Sprintf("%s/%s/latest.current", global.CONF.RemoteURL.RepoUrl, mode) } _, latestVersionRes, err := req_helper.HandleRequestWithProxy(path, http.MethodGet, constant.TimeOut20s) if err != nil { diff --git a/core/app/task/task.go b/core/app/task/task.go index f77876485..7cacd80e9 100644 --- a/core/app/task/task.go +++ b/core/app/task/task.go @@ -70,7 +70,7 @@ func NewTask(name, operate, taskScope, taskID string, resourceID uint) (*Task, e if taskID == "" { taskID = uuid.New().String() } - logItem := path.Join(global.CONF.System.BaseDir, "1panel/log") + logItem := path.Join(global.CONF.Base.InstallDir, "1panel/log") logDir := path.Join(logItem, taskScope) if _, err := os.Stat(logDir); os.IsNotExist(err) { if err = os.MkdirAll(logDir, constant.DirPerm); err != nil { diff --git a/core/cmd/server/cmd/restore.go b/core/cmd/server/cmd/restore.go index 4d5a7f260..ae30448d4 100644 --- a/core/cmd/server/cmd/restore.go +++ b/core/cmd/server/cmd/restore.go @@ -55,7 +55,7 @@ var restoreCmd = &cobra.Command{ return err } _, _ = cmdUtils.Execf("cp -r %s /usr/local/bin", path.Join(tmpPath, "lang")) - geoPath := path.Join(global.CONF.System.BaseDir, "1panel/geo") + geoPath := path.Join(global.CONF.Base.InstallDir, "1panel/geo") _, _ = cmdUtils.Execf("mkdir %s && cp %s %s/", geoPath, path.Join(tmpPath, "GeoIP.mmdb"), geoPath) fmt.Println(i18n.GetMsgByKeyForCmd("RestoreStep3")) if err := files.CopyFile(path.Join(tmpPath, "1panel.service"), "/etc/systemd/system", true); err != nil { diff --git a/core/cmd/server/cmd/update.go b/core/cmd/server/cmd/update.go index 148a33867..4b7d58523 100644 --- a/core/cmd/server/cmd/update.go +++ b/core/cmd/server/cmd/update.go @@ -164,7 +164,7 @@ func password() { p := "" encryptSetting := getSettingByKey(db, "EncryptKey") if len(encryptSetting) == 16 { - global.CONF.System.EncryptKey = encryptSetting + global.CONF.Base.EncryptKey = encryptSetting p, _ = encrypt.StringEncrypt(newPassword) } else { p = newPassword diff --git a/core/cmd/server/cmd/user-info.go b/core/cmd/server/cmd/user-info.go index dfd40e577..0bdab2f26 100644 --- a/core/cmd/server/cmd/user-info.go +++ b/core/cmd/server/cmd/user-info.go @@ -31,7 +31,7 @@ var userinfoCmd = &cobra.Command{ encryptSetting := getSettingByKey(db, "EncryptKey") pass = getSettingByKey(db, "Password") if len(encryptSetting) == 16 { - global.CONF.System.EncryptKey = encryptSetting + global.CONF.Base.EncryptKey = encryptSetting pass, _ = encrypt.StringDecrypt(pass) } } diff --git a/core/cmd/server/cmd/version.go b/core/cmd/server/cmd/version.go index 150bd94f8..176e63c39 100644 --- a/core/cmd/server/cmd/version.go +++ b/core/cmd/server/cmd/version.go @@ -4,7 +4,7 @@ import ( "fmt" "github.com/1Panel-dev/1Panel/core/cmd/server/conf" - "github.com/1Panel-dev/1Panel/core/configs" + "github.com/1Panel-dev/1Panel/core/global" "github.com/1Panel-dev/1Panel/core/i18n" "gopkg.in/yaml.v3" @@ -30,11 +30,11 @@ var versionCmd = &cobra.Command{ version := getSettingByKey(db, "SystemVersion") fmt.Println(i18n.GetMsgByKeyForCmd("SystemVersion") + version) - config := configs.ServerConfig{} + config := global.ServerConfig{} if err := yaml.Unmarshal(conf.AppYaml, &config); err != nil { return fmt.Errorf("unmarshal conf.App.Yaml failed, err: %v", err) } else { - fmt.Println(i18n.GetMsgByKeyForCmd("SystemMode") + config.System.Mode) + fmt.Println(i18n.GetMsgByKeyForCmd("SystemMode") + config.Base.Mode) } return nil }, diff --git a/core/configs/config.go b/core/configs/config.go deleted file mode 100644 index 7d8116b68..000000000 --- a/core/configs/config.go +++ /dev/null @@ -1,6 +0,0 @@ -package configs - -type ServerConfig struct { - System System `mapstructure:"system"` - LogConfig LogConfig `mapstructure:"log"` -} diff --git a/core/configs/log.go b/core/configs/log.go deleted file mode 100644 index 8fe60a91d..000000000 --- a/core/configs/log.go +++ /dev/null @@ -1,9 +0,0 @@ -package configs - -type LogConfig struct { - Level string `mapstructure:"level"` - TimeZone string `mapstructure:"timeZone"` - LogName string `mapstructure:"log_name"` - LogSuffix string `mapstructure:"log_suffix"` - MaxBackup int `mapstructure:"max_backup"` -} diff --git a/core/configs/system.go b/core/configs/system.go deleted file mode 100644 index 502a60c7d..000000000 --- a/core/configs/system.go +++ /dev/null @@ -1,28 +0,0 @@ -package configs - -type System struct { - Port string `mapstructure:"port"` - Ipv6 string `mapstructure:"ipv6"` - BindAddress string `mapstructure:"bindAddress"` - SSL string `mapstructure:"ssl"` - DbCoreFile string `mapstructure:"db_core_file"` - EncryptKey string `mapstructure:"encrypt_key"` - BaseDir string `mapstructure:"base_dir"` - BackupDir string `mapstructure:"backup_dir"` - Mode string `mapstructure:"mode"` - RepoUrl string `mapstructure:"repo_url"` - ResourceUrl string `mapstructure:"resource_url"` - Version string `mapstructure:"version"` - Username string `mapstructure:"username"` - Password string `mapstructure:"password"` - Entrance string `mapstructure:"entrance"` - Language string `mapstructure:"language"` - IsDemo bool `mapstructure:"is_demo"` - IsIntl bool `mapstructure:"is_intl"` - ChangeUserInfo string `mapstructure:"change_user_info"` - - ApiInterfaceStatus string `mapstructure:"api_interface_status"` - ApiKey string `mapstructure:"api_key"` - IpWhiteList string `mapstructure:"ip_white_list"` - ApiKeyValidityTime string `mapstructure:"api_key_validity_time"` -} diff --git a/core/constant/errs.go b/core/constant/errs.go deleted file mode 100644 index 67da38fd4..000000000 --- a/core/constant/errs.go +++ /dev/null @@ -1,87 +0,0 @@ -package constant - -import ( - "errors" -) - -const ( - CodeSuccess = 200 - CodeErrBadRequest = 400 - CodeErrUnauthorized = 401 - CodeErrNotFound = 404 - CodeAuth = 406 - CodeGlobalLoading = 407 - CodeErrInternalServer = 500 - - CodeErrIP = 310 - CodeErrDomain = 311 - CodeErrEntrance = 312 - CodePasswordExpired = 313 - - CodeErrXpack = 410 -) - -// internal -var ( - ErrCaptchaCode = errors.New("ErrCaptchaCode") - ErrAuth = errors.New("ErrAuth") - ErrRecordExist = errors.New("ErrRecordExist") - ErrRecordNotFound = errors.New("ErrRecordNotFound") - ErrTransform = errors.New("ErrTransform") - ErrInitialPassword = errors.New("ErrInitialPassword") - ErrInvalidParams = errors.New("ErrInvalidParams") - ErrNotSupportType = errors.New("ErrNotSupportType") - ErrApiConfigStatusInvalid = "ErrApiConfigStatusInvalid" - ErrApiConfigKeyInvalid = "ErrApiConfigKeyInvalid" - ErrApiConfigIPInvalid = "ErrApiConfigIPInvalid" - ErrApiConfigDisable = "ErrApiConfigDisable" - ErrApiConfigKeyTimeInvalid = "ErrApiConfigKeyTimeInvalid" - - ErrTokenParse = errors.New("ErrTokenParse") - ErrStructTransform = errors.New("ErrStructTransform") - ErrPortInUsed = "ErrPortInUsed" - ErrCmdTimeout = "ErrCmdTimeout" - ErrGroupIsUsed = "ErrGroupIsUsed" - ErrGroupIsDefault = "ErrGroupIsDefault" -) - -// api -var ( - ErrTypeInternalServer = "ErrInternalServer" - ErrTypeInvalidParams = "ErrInvalidParams" - ErrTypeNotLogin = "ErrNotLogin" - ErrTypePasswordExpired = "ErrPasswordExpired" - ErrDemoEnvironment = "ErrDemoEnvironment" - ErrEntrance = "ErrEntrance" - ErrProxy = "ErrProxy" - ErrLocalDelete = "ErrLocalDelete" - - ErrXpackNotFound = "ErrXpackNotFound" - ErrXpackExceptional = "ErrXpackExceptional" - ErrXpackLost = "ErrXpackLost" - ErrXpackTimeout = "ErrXpackTimeout" - ErrXpackOutOfDate = "ErrXpackOutOfDate" - ErrNoSuchNode = "ErrNoSuchNode" - ErrNodeUnbind = "ErrNodeUnbind" -) - -// backup -var ( - ErrBackupInUsed = "ErrBackupInUsed" - ErrBackupLocal = "ErrBackupLocal" - ErrBackupPublic = "ErrBackupPublic" -) - -var ( - ErrLicense = "ErrLicense" - ErrLicenseCheck = "ErrLicenseCheck" - ErrLicenseSave = "ErrLicenseSave" - ErrLicenseSync = "ErrLicenseSync" - ErrUnbindMaster = "ErrUnbindMaster" - ErrFreeNodeLimit = "ErrFreeNodeLimit" - ErrNodeBound = "ErrNodeBound" - ErrNodeBind = "ErrNodeBind" - ConnInfoNotMatch = "ConnInfoNotMatch" - - ErrAlertSync = "ErrAlertSync" -) diff --git a/core/global/config.go b/core/global/config.go new file mode 100644 index 000000000..1c5e91730 --- /dev/null +++ b/core/global/config.go @@ -0,0 +1,49 @@ +package global + +type ServerConfig struct { + Base Base `mapstructure:"base"` + Conn Conn `mapstructure:"conn"` + RemoteURL RemoteURL `mapstructure:"remote_url"` + LogConfig LogConfig `mapstructure:"log"` +} + +type Base struct { + Mode string `mapstructure:"mode"` + Username string `mapstructure:"username"` + Password string `mapstructure:"password"` + Language string `mapstructure:"language"` + IsDemo bool `mapstructure:"is_demo"` + IsIntl bool `mapstructure:"is_intl"` + Version string `mapstructure:"version"` + InstallDir string `mapstructure:"install_dir"` + ChangeUserInfo string `mapstructure:"change_user_info"` + EncryptKey string `mapstructure:"encrypt_key"` +} + +type Conn struct { + Port string `mapstructure:"port"` + BindAddress string `mapstructure:"bindAddress"` + Ipv6 string `mapstructure:"ipv6"` + SSL string `mapstructure:"ssl"` + Entrance string `mapstructure:"entrance"` +} + +type ApiInterface struct { + ApiKey string `mapstructure:"api_key"` + ApiInterfaceStatus string `mapstructure:"api_interface_status"` + IpWhiteList string `mapstructure:"ip_white_list"` + ApiKeyValidityTime string `mapstructure:"api_key_validity_time"` +} + +type RemoteURL struct { + RepoUrl string `mapstructure:"repo_url"` + ResourceUrl string `mapstructure:"resource_url"` +} + +type LogConfig struct { + Level string `mapstructure:"level"` + TimeZone string `mapstructure:"timeZone"` + LogName string `mapstructure:"log_name"` + LogSuffix string `mapstructure:"log_suffix"` + MaxBackup int `mapstructure:"max_backup"` +} diff --git a/core/global/global.go b/core/global/global.go index 1defcf957..b01c4ec22 100644 --- a/core/global/global.go +++ b/core/global/global.go @@ -1,7 +1,6 @@ package global import ( - "github.com/1Panel-dev/1Panel/core/configs" "github.com/1Panel-dev/1Panel/core/init/session/psession" "github.com/go-playground/validator/v10" "github.com/nicksnyder/go-i18n/v2/i18n" @@ -15,7 +14,8 @@ var ( DB *gorm.DB TaskDB *gorm.DB LOG *logrus.Logger - CONF configs.ServerConfig + CONF ServerConfig + Api ApiInterface VALID *validator.Validate SESSION *psession.PSession Viper *viper.Viper diff --git a/core/i18n/lang/zh.yaml b/core/i18n/lang/zh.yaml index f0e305cd5..c5c339583 100644 --- a/core/i18n/lang/zh.yaml +++ b/core/i18n/lang/zh.yaml @@ -21,10 +21,11 @@ ErrCmdTimeout: "命令执行超时!" ErrEntrance: "安全入口信息错误,请检查后重试!" ErrGroupIsDefault: "默认分组,无法删除" ErrLocalDelete: "无法删除本地节点!" +ErrPortInUsed: "{{ .name }} 端口已被占用!" #backup ErrBackupInUsed: "该备份账号已在计划任务中使用,无法删除" -ErrBackupCheck: "备份账号测试连接失败 {{ .err}}" +ErrBackupCheck: "备份账号测试连接失败 {{ .err }}" ErrBackupLocal: "本地服务器备份账号暂不支持该操作!" ErrBackupPublic: "检测到该备份账号为非公用,请检查后重试!" ErrOSSConn: "无法获取最新版本,请确认服务器是否能够连接外部网络。" @@ -51,12 +52,12 @@ ErrNodeBind: "检测到该节点已绑定许可证,请检查后重试!" ErrAlertSync: "告警信息同步错误,请检查后重试!" #task -TaskStart: "{{.name}} 任务开始 [START]" -TaskEnd: "{{.name}} 任务结束 [COMPLETED]" -TaskFailed: "{{.name}} 任务失败" -TaskTimeout: "{{.name}} 超时" -TaskSuccess: "{{.name}} 任务成功" -TaskRetry: "开始第 {{.name}} 次重试" +TaskStart: "{{ .name }} 任务开始 [START]" +TaskEnd: "{{ .name }} 任务结束 [COMPLETED]" +TaskFailed: "{{ .name }} 任务失败" +TaskTimeout: "{{ .name }} 超时" +TaskSuccess: "{{ .name }} 任务成功" +TaskRetry: "开始第 {{ .name }} 次重试" SubTaskSuccess: "{{ .name }} 成功" SubTaskFailed: "{{ .name }} 失败: {{ .err }}" TaskInstall: "安装" @@ -76,7 +77,7 @@ Stop: "停止" SubTask: "子任务" #upgrade node -NodeUpgrade: "升级节点 {name}" +NodeUpgrade: "升级节点 {{ .name }}" NewSSHClient: "初始化 SSH 连接" BackupBeforeUpgrade: "升级前备份数据" UploadUpgradeFile: "下发升级所需文件" diff --git a/core/init/db/db.go b/core/init/db/db.go index 1e218539b..5614781f4 100644 --- a/core/init/db/db.go +++ b/core/init/db/db.go @@ -8,6 +8,6 @@ import ( ) func Init() { - global.DB = common.LoadDBConnByPath(path.Join(global.CONF.System.BaseDir, "1panel/db/core.db"), "core") - global.TaskDB = common.LoadDBConnByPath(path.Join(global.CONF.System.BaseDir, "1panel/db/task.db"), "task") + global.DB = common.LoadDBConnByPath(path.Join(global.CONF.Base.InstallDir, "1panel/db/core.db"), "core") + global.TaskDB = common.LoadDBConnByPath(path.Join(global.CONF.Base.InstallDir, "1panel/db/task.db"), "task") } diff --git a/core/init/hook/hook.go b/core/init/hook/hook.go index d4ab6f4fc..1a3ce114c 100644 --- a/core/init/hook/hook.go +++ b/core/init/hook/hook.go @@ -13,62 +13,22 @@ import ( func Init() { settingRepo := repo.NewISettingRepo() - portSetting, err := settingRepo.Get(repo.WithByKey("ServerPort")) - if err != nil { - global.LOG.Errorf("load service port from setting failed, err: %v", err) - } - global.CONF.System.Port = portSetting.Value - ipv6Setting, err := settingRepo.Get(repo.WithByKey("Ipv6")) - if err != nil { - global.LOG.Errorf("load ipv6 status from setting failed, err: %v", err) - } - global.CONF.System.Ipv6 = ipv6Setting.Value - apiInterfaceStatusSetting, err := settingRepo.Get(repo.WithByKey("ApiInterfaceStatus")) - if err != nil { - global.LOG.Errorf("load service api interface from setting failed, err: %v", err) - } - global.CONF.System.ApiInterfaceStatus = apiInterfaceStatusSetting.Value - if apiInterfaceStatusSetting.Value == constant.StatusEnable { - apiKeySetting, err := settingRepo.Get(repo.WithByKey("ApiKey")) - if err != nil { - global.LOG.Errorf("load service api key from setting failed, err: %v", err) - } - global.CONF.System.ApiKey = apiKeySetting.Value - ipWhiteListSetting, err := settingRepo.Get(repo.WithByKey("IpWhiteList")) - if err != nil { - global.LOG.Errorf("load service ip white list from setting failed, err: %v", err) - } - global.CONF.System.IpWhiteList = ipWhiteListSetting.Value - apiKeyValidityTimeSetting, err := settingRepo.Get(repo.WithByKey("ApiKeyValidityTime")) - if err != nil { - global.LOG.Errorf("load service api key validity time from setting failed, err: %v", err) - } - global.CONF.System.ApiKeyValidityTime = apiKeyValidityTimeSetting.Value - } - bindAddressSetting, err := settingRepo.Get(repo.WithByKey("BindAddress")) - if err != nil { - global.LOG.Errorf("load bind address from setting failed, err: %v", err) - } - global.CONF.System.BindAddress = bindAddressSetting.Value - sslSetting, err := settingRepo.Get(repo.WithByKey("SSL")) - if err != nil { - global.LOG.Errorf("load service ssl from setting failed, err: %v", err) - } - global.CONF.System.SSL = sslSetting.Value - versionSetting, err := settingRepo.Get(repo.WithByKey("SystemVersion")) - if err != nil { - global.LOG.Errorf("load version from setting failed, err: %v", err) - } - global.CONF.System.Version = versionSetting.Value - - if _, err := settingRepo.Get(repo.WithByKey("SystemStatus")); err != nil { - _ = settingRepo.Create("SystemStatus", "Free") + global.CONF.Conn.Port, _ = settingRepo.GetValueByKey("ServerPort") + global.CONF.Conn.Ipv6, _ = settingRepo.GetValueByKey("Ipv6") + global.Api.ApiInterfaceStatus, _ = settingRepo.GetValueByKey("ApiInterfaceStatus") + if global.Api.ApiInterfaceStatus == constant.StatusEnable { + global.Api.ApiKey, _ = settingRepo.GetValueByKey("ApiKey") + global.Api.IpWhiteList, _ = settingRepo.GetValueByKey("IpWhiteList") + global.Api.ApiKeyValidityTime, _ = settingRepo.GetValueByKey("ApiKeyValidityTime") } + global.CONF.Conn.BindAddress, _ = settingRepo.GetValueByKey("BindAddress") + global.CONF.Conn.SSL, _ = settingRepo.GetValueByKey("SSL") + global.CONF.Base.Version, _ = settingRepo.GetValueByKey("SystemVersion") if err := settingRepo.Update("SystemStatus", "Free"); err != nil { global.LOG.Fatalf("init service before start failed, err: %v", err) } - handleUserInfo(global.CONF.System.ChangeUserInfo, settingRepo) + handleUserInfo(global.CONF.Base.ChangeUserInfo, settingRepo) } func handleUserInfo(tags string, settingRepo repo.ISettingRepo) { @@ -88,23 +48,23 @@ func handleUserInfo(tags string, settingRepo repo.ISettingRepo) { } return } - if strings.Contains(global.CONF.System.ChangeUserInfo, "username") { + if strings.Contains(global.CONF.Base.ChangeUserInfo, "username") { if err := settingRepo.Update("UserName", common.RandStrAndNum(10)); err != nil { global.LOG.Fatalf("init username before start failed, err: %v", err) } } - if strings.Contains(global.CONF.System.ChangeUserInfo, "password") { + if strings.Contains(global.CONF.Base.ChangeUserInfo, "password") { pass, _ := encrypt.StringEncrypt(common.RandStrAndNum(10)) if err := settingRepo.Update("Password", pass); err != nil { global.LOG.Fatalf("init password before start failed, err: %v", err) } } - if strings.Contains(global.CONF.System.ChangeUserInfo, "entrance") { + if strings.Contains(global.CONF.Base.ChangeUserInfo, "entrance") { if err := settingRepo.Update("SecurityEntrance", common.RandStrAndNum(10)); err != nil { global.LOG.Fatalf("init entrance before start failed, err: %v", err) } } sudo := cmd.SudoHandleCmd() - _, _ = cmd.Execf("%s sed -i '/CHANGE_USER_INFO=%v/d' /usr/local/bin/1pctl", sudo, global.CONF.System.ChangeUserInfo) + _, _ = cmd.Execf("%s sed -i '/CHANGE_USER_INFO=%v/d' /usr/local/bin/1pctl", sudo, global.CONF.Base.ChangeUserInfo) } diff --git a/core/init/lang/lang.go b/core/init/lang/lang.go index 6e64ef49d..976e60964 100644 --- a/core/init/lang/lang.go +++ b/core/init/lang/lang.go @@ -17,13 +17,13 @@ func Init() { } func initLang() { - geoPath := path.Join(global.CONF.System.BaseDir, "1panel/geo/GeoIP.mmdb") + geoPath := path.Join(global.CONF.Base.InstallDir, "1panel/geo/GeoIP.mmdb") isLangExist := fileUtils.Stat("/usr/local/bin/lang/zh.sh") isGeoExist := fileUtils.Stat(geoPath) if isLangExist && isGeoExist { return } - upgradePath := path.Join(global.CONF.System.BaseDir, "1panel/tmp/upgrade") + upgradePath := path.Join(global.CONF.Base.InstallDir, "1panel/tmp/upgrade") tmpPath, err := loadRestorePath(upgradePath) upgradeDir := path.Join(upgradePath, tmpPath, "downloads") if err != nil || len(tmpPath) == 0 || !fileUtils.Stat(upgradeDir) { @@ -106,7 +106,7 @@ func loadRestorePath(upgradeDir string) (string, error) { } func downloadLangFromRemote() { - path := fmt.Sprintf("%s/language/lang.tar.gz", global.CONF.System.RepoUrl) + path := fmt.Sprintf("%s/language/lang.tar.gz", global.CONF.RemoteURL.RepoUrl) if err := fileUtils.DownloadFile(path, "/usr/local/bin/lang.tar.gz"); err != nil { global.LOG.Errorf("download lang.tar.gz failed, err: %v", err) return @@ -125,7 +125,7 @@ func downloadLangFromRemote() { } func downloadGeoFromRemote(targetPath string) { _ = os.MkdirAll(path.Dir(targetPath), os.ModePerm) - pathItem := fmt.Sprintf("%s/geo/GeoIP.mmdb", global.CONF.System.RepoUrl) + pathItem := fmt.Sprintf("%s/geo/GeoIP.mmdb", global.CONF.RemoteURL.RepoUrl) if err := fileUtils.DownloadFile(pathItem, targetPath); err != nil { global.LOG.Errorf("download geo ip failed, err: %v", err) return diff --git a/core/init/log/log.go b/core/init/log/log.go index a22ece668..5640e46aa 100644 --- a/core/init/log/log.go +++ b/core/init/log/log.go @@ -8,7 +8,6 @@ import ( "strings" "time" - "github.com/1Panel-dev/1Panel/core/configs" "github.com/1Panel-dev/1Panel/core/global" "github.com/1Panel-dev/1Panel/core/log" @@ -28,9 +27,9 @@ func Init() { global.LOG.Info("init logger successfully") } -func setOutput(logger *logrus.Logger, config configs.LogConfig) { +func setOutput(logger *logrus.Logger, config global.LogConfig) { writer, err := log.NewWriterFromConfig(&log.Config{ - LogPath: path.Join(global.CONF.System.BaseDir, "1panel/log"), + LogPath: path.Join(global.CONF.Base.InstallDir, "1panel/log"), FileName: config.LogName, TimeTagFormat: FileTImeFormat, MaxRemain: config.MaxBackup, diff --git a/core/init/migration/migrations/init.go b/core/init/migration/migrations/init.go index aad4ca9ff..b5678e832 100644 --- a/core/init/migration/migrations/init.go +++ b/core/init/migration/migrations/init.go @@ -34,13 +34,13 @@ var InitSetting = &gormigrate.Migration{ ID: "20200908-add-table-setting", Migrate: func(tx *gorm.DB) error { encryptKey := common.RandStr(16) - if err := tx.Create(&model.Setting{Key: "UserName", Value: global.CONF.System.Username}).Error; err != nil { + if err := tx.Create(&model.Setting{Key: "UserName", Value: global.CONF.Base.Username}).Error; err != nil { return err } - global.CONF.System.EncryptKey = encryptKey - pass, _ := encrypt.StringEncrypt(global.CONF.System.Password) + global.CONF.Base.EncryptKey = encryptKey + pass, _ := encrypt.StringEncrypt(global.CONF.Base.Password) language := "en" - if global.CONF.System.Language == "zh" { + if global.CONF.Base.Language == "zh" { language = "zh" } if err := tx.Create(&model.Setting{Key: "Password", Value: pass}).Error; err != nil { @@ -98,10 +98,10 @@ var InitSetting = &gormigrate.Migration{ return err } - if err := tx.Create(&model.Setting{Key: "ServerPort", Value: global.CONF.System.Port}).Error; err != nil { + if err := tx.Create(&model.Setting{Key: "ServerPort", Value: global.CONF.Conn.Port}).Error; err != nil { return err } - if err := tx.Create(&model.Setting{Key: "SecurityEntrance", Value: global.CONF.System.Entrance}).Error; err != nil { + if err := tx.Create(&model.Setting{Key: "SecurityEntrance", Value: global.CONF.Conn.Entrance}).Error; err != nil { return err } if err := tx.Create(&model.Setting{Key: "JWTSigningKey", Value: common.RandStr(16)}).Error; err != nil { @@ -125,7 +125,7 @@ var InitSetting = &gormigrate.Migration{ if err := tx.Create(&model.Setting{Key: "MFASecret", Value: ""}).Error; err != nil { return err } - if err := tx.Create(&model.Setting{Key: "SystemVersion", Value: global.CONF.System.Version}).Error; err != nil { + if err := tx.Create(&model.Setting{Key: "SystemVersion", Value: global.CONF.Base.Version}).Error; err != nil { return err } if err := tx.Create(&model.Setting{Key: "SystemStatus", Value: "Free"}).Error; err != nil { @@ -203,7 +203,7 @@ var InitOneDrive = &gormigrate.Migration{ if err := tx.Create(&model.BackupAccount{ Name: "localhost", Type: "LOCAL", - Vars: fmt.Sprintf("{\"dir\":\"%s\"}", path.Join(global.CONF.System.BaseDir, "1panel/backup")), + Vars: fmt.Sprintf("{\"dir\":\"%s\"}", path.Join(global.CONF.Base.InstallDir, "1panel/backup")), }).Error; err != nil { return err } diff --git a/core/init/router/proxy.go b/core/init/router/proxy.go index c61510ff5..b51d8d991 100644 --- a/core/init/router/proxy.go +++ b/core/init/router/proxy.go @@ -9,7 +9,6 @@ import ( "strings" "github.com/1Panel-dev/1Panel/core/app/api/v2/helper" - "github.com/1Panel-dev/1Panel/core/constant" "github.com/1Panel-dev/1Panel/core/utils/xpack" "github.com/gin-gonic/gin" ) @@ -29,7 +28,7 @@ func Proxy() gin.HandlerFunc { if !strings.HasPrefix(c.Request.URL.Path, "/api/v2/core") && (currentNode == "local" || len(currentNode) == 0 || currentNode == "127.0.0.1") { sockPath := "/etc/1panel/agent.sock" if _, err := os.Stat(sockPath); err != nil { - helper.ErrorWithDetail(c, constant.CodeErrBadRequest, constant.ErrProxy, err) + helper.ErrorWithDetail(c, http.StatusBadRequest, "ErrProxy", err) return } dialUnix := func() (conn net.Conn, err error) { diff --git a/core/init/router/router.go b/core/init/router/router.go index 65ccad618..a3461f067 100644 --- a/core/init/router/router.go +++ b/core/init/router/router.go @@ -158,7 +158,7 @@ func Routers() *gin.Engine { } Router.Use(middleware.OperationLog()) - if global.CONF.System.IsDemo { + if global.CONF.Base.IsDemo { Router.Use(middleware.DemoHandle()) } Router.Use(Proxy()) diff --git a/core/init/session/session.go b/core/init/session/session.go index 90ad4e187..be040619d 100644 --- a/core/init/session/session.go +++ b/core/init/session/session.go @@ -1,12 +1,13 @@ package session import ( + "path" + "github.com/1Panel-dev/1Panel/core/global" "github.com/1Panel-dev/1Panel/core/init/session/psession" - "path" ) func Init() { - global.SESSION = psession.NewPSession(path.Join(global.CONF.System.BaseDir, "1panel/db/session.db")) + global.SESSION = psession.NewPSession(path.Join(global.CONF.Base.InstallDir, "1panel/db/session.db")) global.LOG.Info("init session successfully") } diff --git a/core/init/viper/viper.go b/core/init/viper/viper.go index 058b80d62..f209c1775 100644 --- a/core/init/viper/viper.go +++ b/core/init/viper/viper.go @@ -8,7 +8,6 @@ import ( "strings" "github.com/1Panel-dev/1Panel/core/cmd/server/conf" - "github.com/1Panel-dev/1Panel/core/configs" "github.com/1Panel-dev/1Panel/core/global" "github.com/1Panel-dev/1Panel/core/utils/cmd" "github.com/fsnotify/fsnotify" @@ -25,12 +24,12 @@ func Init() { v := viper.NewWithOptions() v.SetConfigType("yaml") - config := configs.ServerConfig{} + config := global.ServerConfig{} if err := yaml.Unmarshal(conf.AppYaml, &config); err != nil { panic(err) } - if config.System.Mode != "" { - mode = config.System.Mode + if config.Base.Mode != "" { + mode = config.Base.Mode } _, err := os.Stat("/opt/1panel/conf/app.yaml") if mode == "dev" && err == nil { @@ -58,46 +57,46 @@ func Init() { panic(err) } }) - serverConfig := configs.ServerConfig{} + serverConfig := global.ServerConfig{} if err := v.Unmarshal(&serverConfig); err != nil { panic(err) } _, err = os.Stat("/opt/1panel/conf/app.yaml") if mode == "dev" && err == nil { - if serverConfig.System.BaseDir != "" { - baseDir = serverConfig.System.BaseDir + if serverConfig.Base.InstallDir != "" { + baseDir = serverConfig.Base.InstallDir } - if serverConfig.System.Port != "" { - port = serverConfig.System.Port + if serverConfig.Conn.Port != "" { + port = serverConfig.Conn.Port } - if serverConfig.System.Version != "" { - version = serverConfig.System.Version + if serverConfig.Base.Version != "" { + version = serverConfig.Base.Version } - if serverConfig.System.Username != "" { - username = serverConfig.System.Username + if serverConfig.Base.Username != "" { + username = serverConfig.Base.Username } - if serverConfig.System.Password != "" { - password = serverConfig.System.Password + if serverConfig.Base.Password != "" { + password = serverConfig.Base.Password } - if serverConfig.System.Entrance != "" { - entrance = serverConfig.System.Entrance + if serverConfig.Conn.Entrance != "" { + entrance = serverConfig.Conn.Entrance } - if serverConfig.System.IsIntl { + if serverConfig.Base.IsIntl { language = "en" } } global.CONF = serverConfig - global.CONF.System.BaseDir = baseDir - global.CONF.System.IsDemo = v.GetBool("system.is_demo") - global.CONF.System.IsIntl = v.GetBool("system.is_intl") - global.CONF.System.Port = port - global.CONF.System.Version = version - global.CONF.System.Username = username - global.CONF.System.Password = password - global.CONF.System.Entrance = entrance - global.CONF.System.Language = language - global.CONF.System.ChangeUserInfo = loadChangeInfo() + global.CONF.Base.InstallDir = baseDir + global.CONF.Base.IsDemo = v.GetBool("system.is_demo") + global.CONF.Base.IsIntl = v.GetBool("system.is_intl") + global.CONF.Base.Version = version + global.CONF.Base.Username = username + global.CONF.Base.Password = password + global.CONF.Base.Language = language + global.CONF.Base.ChangeUserInfo = loadChangeInfo() + global.CONF.Conn.Entrance = entrance + global.CONF.Conn.Port = port global.Viper = v } diff --git a/core/middleware/bind_domain.go b/core/middleware/bind_domain.go index 8c5cda8de..5ba7f1ed8 100644 --- a/core/middleware/bind_domain.go +++ b/core/middleware/bind_domain.go @@ -6,7 +6,6 @@ import ( "github.com/1Panel-dev/1Panel/core/app/api/v2/helper" "github.com/1Panel-dev/1Panel/core/app/repo" - "github.com/1Panel-dev/1Panel/core/constant" "github.com/gin-gonic/gin" ) @@ -15,7 +14,7 @@ func BindDomain() gin.HandlerFunc { settingRepo := repo.NewISettingRepo() status, err := settingRepo.Get(repo.WithByKey("BindDomain")) if err != nil { - helper.ErrorWithDetail(c, constant.CodeErrInternalServer, constant.ErrTypeInternalServer, err) + helper.InternalServer(c, err) return } if len(status.Value) == 0 { @@ -33,7 +32,7 @@ func BindDomain() gin.HandlerFunc { helper.ErrResponse(c, LoadErrCode()) return } - helper.ErrorWithDetail(c, constant.CodeErrDomain, constant.ErrTypeInternalServer, errors.New("domain not allowed")) + helper.ErrorWithDetail(c, 311, "ErrInternalServer", errors.New("domain not allowed")) return } c.Next() diff --git a/core/middleware/demo_handle.go b/core/middleware/demo_handle.go index 11ec0aa27..1a4710a44 100644 --- a/core/middleware/demo_handle.go +++ b/core/middleware/demo_handle.go @@ -6,7 +6,6 @@ import ( "github.com/1Panel-dev/1Panel/core/app/dto" "github.com/1Panel-dev/1Panel/core/buserr" - "github.com/1Panel-dev/1Panel/core/constant" "github.com/gin-gonic/gin" ) @@ -50,7 +49,7 @@ func DemoHandle() gin.HandlerFunc { c.JSON(http.StatusInternalServerError, dto.Response{ Code: http.StatusInternalServerError, - Message: buserr.New(constant.ErrDemoEnvironment).Error(), + Message: buserr.New("ErrDemoEnvironment").Error(), }) c.Abort() } diff --git a/core/middleware/ip_limit.go b/core/middleware/ip_limit.go index 078af16ed..c829fb627 100644 --- a/core/middleware/ip_limit.go +++ b/core/middleware/ip_limit.go @@ -7,7 +7,6 @@ import ( "github.com/1Panel-dev/1Panel/core/app/api/v2/helper" "github.com/1Panel-dev/1Panel/core/app/repo" - "github.com/1Panel-dev/1Panel/core/constant" "github.com/1Panel-dev/1Panel/core/global" "github.com/gin-gonic/gin" ) @@ -17,7 +16,7 @@ func WhiteAllow() gin.HandlerFunc { settingRepo := repo.NewISettingRepo() status, err := settingRepo.Get(repo.WithByKey("AllowIPs")) if err != nil { - helper.ErrorWithDetail(c, constant.CodeErrInternalServer, constant.ErrTypeInternalServer, err) + helper.InternalServer(c, err) return } @@ -39,7 +38,7 @@ func WhiteAllow() gin.HandlerFunc { helper.ErrResponse(c, LoadErrCode()) return } - helper.ErrorWithDetail(c, constant.CodeErrIP, constant.ErrTypeInternalServer, errors.New("IP address not allowed")) + helper.ErrorWithDetail(c, 310, "ErrInternalServer", errors.New("IP address not allowed")) } } diff --git a/core/middleware/jwt.go b/core/middleware/jwt.go index 1b20ed211..85336ba26 100644 --- a/core/middleware/jwt.go +++ b/core/middleware/jwt.go @@ -25,7 +25,7 @@ func JwtAuth() gin.HandlerFunc { j := jwtUtils.NewJWT() claims, err := j.ParseToken(token) if err != nil { - helper.ErrorWithDetail(c, constant.CodeErrUnauthorized, constant.ErrTypeInternalServer, err) + helper.BadAuth(c, "ErrInternalServer", err) return } if claims.BaseClaims.IsAgent { @@ -35,12 +35,12 @@ func JwtAuth() gin.HandlerFunc { c.Next() return } else { - helper.ErrorWithDetail(c, constant.CodeErrUnauthorized, constant.ErrTypeInternalServer, fmt.Errorf("err token from request")) + helper.BadAuth(c, "ErrInternalServer", fmt.Errorf("err token from request")) return } } if strings.HasPrefix(c.Request.URL.Path, "/api/v2/agent/") { - helper.ErrorWithDetail(c, constant.CodeErrUnauthorized, constant.ErrTypeInternalServer, fmt.Errorf("err token from request")) + helper.BadAuth(c, "ErrInternalServer", fmt.Errorf("err token from request")) return } c.Set("claims", claims) diff --git a/core/middleware/loading.go b/core/middleware/loading.go index df177d111..afa14a648 100644 --- a/core/middleware/loading.go +++ b/core/middleware/loading.go @@ -3,7 +3,6 @@ package middleware import ( "github.com/1Panel-dev/1Panel/core/app/api/v2/helper" "github.com/1Panel-dev/1Panel/core/app/repo" - "github.com/1Panel-dev/1Panel/core/constant" "github.com/gin-gonic/gin" ) @@ -12,11 +11,11 @@ func GlobalLoading() gin.HandlerFunc { settingRepo := repo.NewISettingRepo() status, err := settingRepo.Get(repo.WithByKey("SystemStatus")) if err != nil { - helper.ErrorWithDetail(c, constant.CodeErrInternalServer, constant.ErrTypeInternalServer, err) + helper.InternalServer(c, err) return } if status.Value != "Free" { - helper.ErrorWithDetail(c, constant.CodeGlobalLoading, status.Value, err) + helper.ErrorWithDetail(c, 407, status.Value, err) return } c.Next() diff --git a/core/middleware/operation.go b/core/middleware/operation.go index 12231202a..b1fccf507 100644 --- a/core/middleware/operation.go +++ b/core/middleware/operation.go @@ -209,11 +209,11 @@ func newDB(pathItem string) (*gorm.DB, error) { dbFile := "" switch { case strings.HasPrefix(pathItem, "/core"): - dbFile = path.Join(global.CONF.System.BaseDir, "1panel/db/core.db") + dbFile = path.Join(global.CONF.Base.InstallDir, "1panel/db/core.db") case strings.HasPrefix(pathItem, "/xpack"): - dbFile = path.Join(global.CONF.System.BaseDir, "1panel/db/xpack.db") + dbFile = path.Join(global.CONF.Base.InstallDir, "1panel/db/xpack.db") default: - dbFile = path.Join(global.CONF.System.BaseDir, "1panel/db/agent.db") + dbFile = path.Join(global.CONF.Base.InstallDir, "1panel/db/agent.db") } db, _ := gorm.Open(sqlite.Open(dbFile), &gorm.Config{ diff --git a/core/middleware/password_expired.go b/core/middleware/password_expired.go index 2a2dc9c50..ebd8e0bcd 100644 --- a/core/middleware/password_expired.go +++ b/core/middleware/password_expired.go @@ -1,6 +1,7 @@ package middleware import ( + "net/http" "strconv" "strings" "time" @@ -23,7 +24,7 @@ func PasswordExpired() gin.HandlerFunc { settingRepo := repo.NewISettingRepo() setting, err := settingRepo.Get(repo.WithByKey("ExpirationDays")) if err != nil { - helper.ErrorWithDetail(c, constant.CodeErrInternalServer, constant.ErrTypePasswordExpired, err) + helper.ErrorWithDetail(c, http.StatusInternalServerError, "ErrPasswordExpired", err) return } expiredDays, _ := strconv.Atoi(setting.Value) @@ -34,17 +35,17 @@ func PasswordExpired() gin.HandlerFunc { extime, err := settingRepo.Get(repo.WithByKey("ExpirationTime")) if err != nil { - helper.ErrorWithDetail(c, constant.CodeErrInternalServer, constant.ErrTypePasswordExpired, err) + helper.ErrorWithDetail(c, http.StatusInternalServerError, "ErrPasswordExpired", err) return } loc, _ := time.LoadLocation(common.LoadTimeZoneByCmd()) expiredTime, err := time.ParseInLocation(constant.DateTimeLayout, extime.Value, loc) if err != nil { - helper.ErrorWithDetail(c, constant.CodePasswordExpired, constant.ErrTypePasswordExpired, err) + helper.ErrorWithDetail(c, 313, "ErrPasswordExpired", err) return } if time.Now().After(expiredTime) { - helper.ErrorWithDetail(c, constant.CodePasswordExpired, constant.ErrTypePasswordExpired, err) + helper.ErrorWithDetail(c, 313, "ErrPasswordExpired", err) return } c.Next() diff --git a/core/middleware/session.go b/core/middleware/session.go index d2a72bd0c..298e6aabc 100644 --- a/core/middleware/session.go +++ b/core/middleware/session.go @@ -29,32 +29,32 @@ func SessionAuth() gin.HandlerFunc { panelToken := c.GetHeader("1Panel-Token") panelTimestamp := c.GetHeader("1Panel-Timestamp") if panelToken != "" || panelTimestamp != "" { - if global.CONF.System.ApiInterfaceStatus == constant.StatusEnable { + if global.Api.ApiInterfaceStatus == constant.StatusEnable { clientIP := c.ClientIP() if !isValid1PanelTimestamp(panelTimestamp) { - helper.ErrorWithDetail(c, constant.CodeErrUnauthorized, constant.ErrApiConfigKeyTimeInvalid, nil) + helper.BadAuth(c, "ErrApiConfigKeyTimeInvalid", nil) return } if !isValid1PanelToken(panelToken, panelTimestamp) { - helper.ErrorWithDetail(c, constant.CodeErrUnauthorized, constant.ErrApiConfigKeyInvalid, nil) + helper.BadAuth(c, "ErrApiConfigKeyInvalid", nil) return } if !isIPInWhiteList(clientIP) { - helper.ErrorWithDetail(c, constant.CodeErrUnauthorized, constant.ErrApiConfigIPInvalid, nil) + helper.BadAuth(c, "ErrApiConfigIPInvalid", nil) return } c.Next() return } else { - helper.ErrorWithDetail(c, constant.CodeErrUnauthorized, constant.ErrApiConfigStatusInvalid, nil) + helper.BadAuth(c, "ErrApiConfigStatusInvalid", nil) return } } psession, err := global.SESSION.Get(c) if err != nil { - helper.ErrorWithDetail(c, constant.CodeErrUnauthorized, constant.ErrTypeNotLogin, err) + helper.BadAuth(c, "ErrNotLogin", err) return } settingRepo := repo.NewISettingRepo() @@ -75,7 +75,7 @@ func SessionAuth() gin.HandlerFunc { } func isValid1PanelTimestamp(panelTimestamp string) bool { - apiKeyValidityTime := global.CONF.System.ApiKeyValidityTime + apiKeyValidityTime := global.Api.ApiKeyValidityTime apiTime, err := strconv.Atoi(apiKeyValidityTime) if err != nil { return false @@ -92,12 +92,12 @@ func isValid1PanelTimestamp(panelTimestamp string) bool { } func isValid1PanelToken(panelToken string, panelTimestamp string) bool { - system1PanelToken := global.CONF.System.ApiKey + system1PanelToken := global.Api.ApiKey return panelToken == GenerateMD5("1panel"+system1PanelToken+panelTimestamp) } func isIPInWhiteList(clientIP string) bool { - ipWhiteString := global.CONF.System.IpWhiteList + ipWhiteString := global.Api.IpWhiteList ipWhiteList := strings.Split(ipWhiteString, "\n") for _, cidr := range ipWhiteList { if cidr == "0.0.0.0" { diff --git a/core/server/server.go b/core/server/server.go index 96be44198..55cb1a3d3 100644 --- a/core/server/server.go +++ b/core/server/server.go @@ -45,12 +45,12 @@ func Start() { rootRouter := router.Routers() tcpItem := "tcp4" - if global.CONF.System.Ipv6 == constant.StatusEnable { + if global.CONF.Conn.Ipv6 == constant.StatusEnable { tcpItem = "tcp" - global.CONF.System.BindAddress = fmt.Sprintf("[%s]", global.CONF.System.BindAddress) + global.CONF.Conn.BindAddress = fmt.Sprintf("[%s]", global.CONF.Conn.BindAddress) } server := &http.Server{ - Addr: global.CONF.System.BindAddress + ":" + global.CONF.System.Port, + Addr: global.CONF.Conn.BindAddress + ":" + global.CONF.Conn.Port, Handler: rootRouter, } ln, err := net.Listen(tcpItem, server.Addr) @@ -60,9 +60,9 @@ func Start() { type tcpKeepAliveListener struct { *net.TCPListener } - if global.CONF.System.SSL == constant.StatusEnable { - certPath := path.Join(global.CONF.System.BaseDir, "1panel/secret/server.crt") - keyPath := path.Join(global.CONF.System.BaseDir, "1panel/secret/server.key") + if global.CONF.Conn.SSL == constant.StatusEnable { + certPath := path.Join(global.CONF.Base.InstallDir, "1panel/secret/server.crt") + keyPath := path.Join(global.CONF.Base.InstallDir, "1panel/secret/server.key") certificate, err := os.ReadFile(certPath) if err != nil { panic(err) @@ -82,13 +82,13 @@ func Start() { return constant.CertStore.Load().(*tls.Certificate), nil }, } - global.LOG.Infof("listen at https://%s:%s [%s]", global.CONF.System.BindAddress, global.CONF.System.Port, tcpItem) + global.LOG.Infof("listen at https://%s:%s [%s]", global.CONF.Conn.BindAddress, global.CONF.Conn.Port, tcpItem) if err := server.ServeTLS(tcpKeepAliveListener{ln.(*net.TCPListener)}, "", ""); err != nil { panic(err) } } else { - global.LOG.Infof("listen at http://%s:%s [%s]", global.CONF.System.BindAddress, global.CONF.System.Port, tcpItem) + global.LOG.Infof("listen at http://%s:%s [%s]", global.CONF.Conn.BindAddress, global.CONF.Conn.Port, tcpItem) if err := server.Serve(tcpKeepAliveListener{ln.(*net.TCPListener)}); err != nil { panic(err) } diff --git a/core/utils/captcha/captcha.go b/core/utils/captcha/captcha.go index c0a60bc01..9d0afe0a1 100644 --- a/core/utils/captcha/captcha.go +++ b/core/utils/captcha/captcha.go @@ -4,7 +4,7 @@ import ( "strings" "github.com/1Panel-dev/1Panel/core/app/dto" - "github.com/1Panel-dev/1Panel/core/constant" + "github.com/1Panel-dev/1Panel/core/buserr" "github.com/mojocn/base64Captcha" ) @@ -12,7 +12,7 @@ var store = base64Captcha.DefaultMemStore func VerifyCode(codeID string, code string) error { if codeID == "" { - return constant.ErrCaptchaCode + return buserr.New("ErrCaptchaCode") } vv := store.Get(codeID, true) vv = strings.TrimSpace(vv) @@ -21,7 +21,7 @@ func VerifyCode(codeID string, code string) error { if strings.EqualFold(vv, code) { return nil } - return constant.ErrCaptchaCode + return buserr.New("ErrCaptchaCode") } func CreateCaptcha() (*dto.CaptchaResponse, error) { diff --git a/core/utils/cloud_storage/client/minio.go b/core/utils/cloud_storage/client/minio.go index 56dc5dcfd..9b16ff851 100644 --- a/core/utils/cloud_storage/client/minio.go +++ b/core/utils/cloud_storage/client/minio.go @@ -3,11 +3,12 @@ package client import ( "context" "crypto/tls" + "fmt" "net/http" "os" "strings" - "github.com/1Panel-dev/1Panel/core/constant" + "github.com/1Panel-dev/1Panel/core/buserr" "github.com/minio/minio-go/v7" "github.com/minio/minio-go/v7/pkg/credentials" ) @@ -24,7 +25,7 @@ func NewMinIoClient(vars map[string]interface{}) (*minIoClient, error) { bucket := loadParamFromVars("bucket", vars) ssl := strings.Split(endpoint, ":")[0] if len(ssl) == 0 || (ssl != "https" && ssl != "http") { - return nil, constant.ErrInvalidParams + return nil, buserr.WithErr("ErrInvalidParams", fmt.Errorf("no such proto in ssl: %s", ssl)) } secure := false diff --git a/core/utils/cloud_storage/cloud_storage_client.go b/core/utils/cloud_storage/cloud_storage_client.go index f1a3193df..0292d87d2 100644 --- a/core/utils/cloud_storage/cloud_storage_client.go +++ b/core/utils/cloud_storage/cloud_storage_client.go @@ -1,6 +1,7 @@ package cloud_storage import ( + "github.com/1Panel-dev/1Panel/core/buserr" "github.com/1Panel-dev/1Panel/core/constant" "github.com/1Panel-dev/1Panel/core/utils/cloud_storage/client" ) @@ -38,6 +39,6 @@ func NewCloudStorageClient(backupType string, vars map[string]interface{}) (Clou case constant.GoogleDrive: return client.NewGoogleDriveClient(vars) default: - return nil, constant.ErrNotSupportType + return nil, buserr.New("ErrNotSupportType") } } diff --git a/core/utils/cmd/cmd.go b/core/utils/cmd/cmd.go index 1af39d077..45e255366 100644 --- a/core/utils/cmd/cmd.go +++ b/core/utils/cmd/cmd.go @@ -8,7 +8,6 @@ import ( "time" "github.com/1Panel-dev/1Panel/core/buserr" - "github.com/1Panel-dev/1Panel/core/constant" ) func Exec(cmdStr string) (string, error) { @@ -59,7 +58,7 @@ func ExecWithTimeOut(cmdStr string, timeout time.Duration) (string, error) { select { case <-after: _ = cmd.Process.Kill() - return "", buserr.New(constant.ErrCmdTimeout) + return "", buserr.New("ErrCmdTimeout") case err := <-done: if err != nil { return handleErr(stdout, stderr, err) diff --git a/core/utils/encrypt/encrypt.go b/core/utils/encrypt/encrypt.go index 10aaec350..82e92e0c8 100644 --- a/core/utils/encrypt/encrypt.go +++ b/core/utils/encrypt/encrypt.go @@ -37,14 +37,14 @@ func StringEncrypt(text string) (string, error) { if len(text) == 0 { return "", nil } - if len(global.CONF.System.EncryptKey) == 0 { + if len(global.CONF.Base.EncryptKey) == 0 { var encryptSetting model.Setting if err := global.DB.Where("key = ?", "EncryptKey").First(&encryptSetting).Error; err != nil { return "", err } - global.CONF.System.EncryptKey = encryptSetting.Value + global.CONF.Base.EncryptKey = encryptSetting.Value } - key := global.CONF.System.EncryptKey + key := global.CONF.Base.EncryptKey return StringEncryptWithKey(text, key) } @@ -65,14 +65,14 @@ func StringDecrypt(text string) (string, error) { if len(text) == 0 { return "", nil } - if len(global.CONF.System.EncryptKey) == 0 { + if len(global.CONF.Base.EncryptKey) == 0 { var encryptSetting model.Setting if err := global.DB.Where("key = ?", "EncryptKey").First(&encryptSetting).Error; err != nil { return "", err } - global.CONF.System.EncryptKey = encryptSetting.Value + global.CONF.Base.EncryptKey = encryptSetting.Value } - key := global.CONF.System.EncryptKey + key := global.CONF.Base.EncryptKey return StringDecryptWithKey(text, key) } diff --git a/core/utils/geo/geo.go b/core/utils/geo/geo.go index 252aa39f0..c390a61b4 100644 --- a/core/utils/geo/geo.go +++ b/core/utils/geo/geo.go @@ -1,10 +1,11 @@ package geo import ( - "github.com/1Panel-dev/1Panel/core/global" - "github.com/oschwald/maxminddb-golang" "net" "path" + + "github.com/1Panel-dev/1Panel/core/global" + "github.com/oschwald/maxminddb-golang" ) type Location struct { @@ -21,7 +22,7 @@ type LocationRes struct { } func NewGeo() (*maxminddb.Reader, error) { - geoPath := path.Join(global.CONF.System.BaseDir, "1panel", "geo", "GeoIP.mmdb") + geoPath := path.Join(global.CONF.Base.InstallDir, "1panel", "geo", "GeoIP.mmdb") return maxminddb.Open(geoPath) } @@ -29,7 +30,7 @@ func GetIPLocation(reader *maxminddb.Reader, ip, lang string) (string, error) { var err error var geoLocation LocationRes if reader == nil { - geoPath := path.Join(global.CONF.System.BaseDir, "1panel", "geo", "GeoIP.mmdb") + geoPath := path.Join(global.CONF.Base.InstallDir, "1panel", "geo", "GeoIP.mmdb") reader, err = maxminddb.Open(geoPath) if err != nil { return "", err diff --git a/core/utils/jwt/jwt.go b/core/utils/jwt/jwt.go index 5c2480d86..4dd7a79b2 100644 --- a/core/utils/jwt/jwt.go +++ b/core/utils/jwt/jwt.go @@ -4,6 +4,7 @@ import ( "time" "github.com/1Panel-dev/1Panel/core/app/repo" + "github.com/1Panel-dev/1Panel/core/buserr" "github.com/1Panel-dev/1Panel/core/constant" "github.com/golang-jwt/jwt/v4" @@ -55,10 +56,10 @@ func (j *JWT) ParseToken(tokenStr string) (*CustomClaims, error) { return j.SigningKey, nil }) if err != nil || token == nil { - return nil, constant.ErrTokenParse + return nil, buserr.WithDetail("ErrTokenParse", "", err) } if claims, ok := token.Claims.(*CustomClaims); ok && token.Valid { return claims, nil } - return nil, constant.ErrTokenParse + return nil, buserr.New("ErrTokenParse") }