1
0
mirror of https://github.com/1Panel-dev/1Panel.git synced 2025-02-08 01:20:07 +08:00

feat: adjust internationalization errors and the positions of global … (#7767)

This commit is contained in:
ssongliu 2025-01-24 11:00:07 +08:00 committed by GitHub
parent d6b21f4ab5
commit 8283cd7d02
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
159 changed files with 1110 additions and 1438 deletions

View File

@ -5,7 +5,6 @@ import (
"github.com/1Panel-dev/1Panel/agent/app/api/v2/helper" "github.com/1Panel-dev/1Panel/agent/app/api/v2/helper"
"github.com/1Panel-dev/1Panel/agent/app/dto" "github.com/1Panel-dev/1Panel/agent/app/dto"
"github.com/1Panel-dev/1Panel/agent/constant"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
) )
@ -35,7 +34,7 @@ func (b *BaseApi) LoadDashboardOsInfo(c *gin.Context) {
func (b *BaseApi) LoadAppLauncher(c *gin.Context) { func (b *BaseApi) LoadAppLauncher(c *gin.Context) {
data, err := dashboardService.LoadAppLauncher() data, err := dashboardService.LoadAppLauncher()
if err != nil { if err != nil {
helper.ErrorWithDetail(c, constant.CodeErrInternalServer, constant.ErrTypeInternalServer, err) helper.InternalServer(c, err)
return return
} }
helper.SuccessWithData(c, data) helper.SuccessWithData(c, data)
@ -56,7 +55,7 @@ func (b *BaseApi) LoadAppLauncherOption(c *gin.Context) {
} }
data, err := dashboardService.ListLauncherOption(req.Filter) data, err := dashboardService.ListLauncherOption(req.Filter)
if err != nil { if err != nil {
helper.ErrorWithDetail(c, constant.CodeErrInternalServer, constant.ErrTypeInternalServer, err) helper.InternalServer(c, err)
return return
} }
helper.SuccessWithData(c, data) helper.SuccessWithData(c, data)

View File

@ -314,7 +314,7 @@ func (b *BaseApi) UploadFiles(c *gin.Context) {
} }
if len(paths) == 0 || !strings.Contains(paths[0], "/") { 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 return
} }
dir := path.Dir(paths[0]) dir := path.Dir(paths[0])
@ -327,7 +327,7 @@ func (b *BaseApi) UploadFiles(c *gin.Context) {
return return
} }
if err = os.MkdirAll(dir, mode); err != nil { 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 return
} }
} }
@ -390,7 +390,7 @@ func (b *BaseApi) UploadFiles(c *gin.Context) {
success++ success++
} }
if success == 0 { if success == 0 {
helper.ErrorWithDetail(c, constant.CodeErrInternalServer, constant.ErrTypeInternalServer, failures) helper.InternalServer(c, failures)
} else { } else {
helper.SuccessWithMsg(c, fmt.Sprintf("%d files upload success", success)) helper.SuccessWithMsg(c, fmt.Sprintf("%d files upload success", success))
} }
@ -518,7 +518,7 @@ func (b *BaseApi) DownloadChunkFiles(c *gin.Context) {
} }
fileOp := files.NewFileOp() fileOp := files.NewFileOp()
if !fileOp.Stat(req.Path) { if !fileOp.Stat(req.Path) {
helper.ErrorWithDetail(c, constant.CodeErrInternalServer, constant.ErrPathNotFound, nil) helper.ErrorWithDetail(c, http.StatusInternalServerError, "ErrPathNotFound", nil)
return return
} }
filePath := req.Path filePath := req.Path
@ -533,7 +533,7 @@ func (b *BaseApi) DownloadChunkFiles(c *gin.Context) {
return return
} }
if info.IsDir() { if info.IsDir() {
helper.ErrorWithDetail(c, constant.CodeErrInternalServer, constant.ErrFileDownloadDir, err) helper.ErrorWithDetail(c, http.StatusInternalServerError, "ErrFileDownloadDir", err)
return return
} }
@ -679,7 +679,7 @@ func (b *BaseApi) UploadChunkFiles(c *gin.Context) {
return return
} }
fileOp := files.NewFileOp() fileOp := files.NewFileOp()
tmpDir := path.Join(global.CONF.System.TmpDir, "upload") tmpDir := path.Join(global.Dir.TmpDir, "upload")
if !fileOp.Stat(tmpDir) { if !fileOp.Stat(tmpDir) {
if err := fileOp.CreateDir(tmpDir, constant.DirPerm); err != nil { if err := fileOp.CreateDir(tmpDir, constant.DirPerm); err != nil {
helper.BadRequest(c, err) helper.BadRequest(c, err)
@ -715,14 +715,14 @@ func (b *BaseApi) UploadChunkFiles(c *gin.Context) {
chunkData, err = io.ReadAll(uploadFile) chunkData, err = io.ReadAll(uploadFile)
if err != nil { 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 return
} }
chunkPath := filepath.Join(fileDir, fmt.Sprintf("%s.%d", filename, chunkIndex)) chunkPath := filepath.Join(fileDir, fmt.Sprintf("%s.%d", filename, chunkIndex))
err = os.WriteFile(chunkPath, chunkData, constant.DirPerm) err = os.WriteFile(chunkPath, chunkData, constant.DirPerm)
if err != nil { 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 return
} }
@ -733,7 +733,7 @@ func (b *BaseApi) UploadChunkFiles(c *gin.Context) {
} }
err = mergeChunks(filename, fileDir, c.PostForm("path"), chunkCount, overwrite) err = mergeChunks(filename, fileDir, c.PostForm("path"), chunkCount, overwrite)
if err != nil { 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 return
} }
helper.SuccessWithData(c, true) helper.SuccessWithData(c, true)

View File

@ -5,7 +5,6 @@ import (
"github.com/1Panel-dev/1Panel/agent/app/api/v2/helper" "github.com/1Panel-dev/1Panel/agent/app/api/v2/helper"
"github.com/1Panel-dev/1Panel/agent/app/dto" "github.com/1Panel-dev/1Panel/agent/app/dto"
"github.com/1Panel-dev/1Panel/agent/constant"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
) )
@ -41,7 +40,7 @@ func (b *BaseApi) LoadFtpLogInfo(c *gin.Context) {
total, list, err := ftpService.LoadLog(req) total, list, err := ftpService.LoadLog(req)
if err != nil { if err != nil {
helper.ErrorWithDetail(c, constant.CodeErrInternalServer, constant.ErrTypeInternalServer, err) helper.InternalServer(c, err)
return return
} }
@ -66,7 +65,7 @@ func (b *BaseApi) OperateFtp(c *gin.Context) {
} }
if err := ftpService.Operate(req.Operation); err != nil { if err := ftpService.Operate(req.Operation); err != nil {
helper.ErrorWithDetail(c, constant.CodeErrInternalServer, constant.ErrTypeInternalServer, err) helper.InternalServer(c, err)
return return
} }
@ -89,7 +88,7 @@ func (b *BaseApi) SearchFtp(c *gin.Context) {
total, list, err := ftpService.SearchWithPage(req) total, list, err := ftpService.SearchWithPage(req)
if err != nil { if err != nil {
helper.ErrorWithDetail(c, constant.CodeErrInternalServer, constant.ErrTypeInternalServer, err) helper.InternalServer(c, err)
return return
} }
@ -123,7 +122,7 @@ func (b *BaseApi) CreateFtp(c *gin.Context) {
req.Password = string(pass) req.Password = string(pass)
} }
if _, err := ftpService.Create(req); err != nil { if _, err := ftpService.Create(req); err != nil {
helper.ErrorWithDetail(c, constant.CodeErrInternalServer, constant.ErrTypeInternalServer, err) helper.InternalServer(c, err)
return return
} }
helper.SuccessWithOutData(c) helper.SuccessWithOutData(c)
@ -145,7 +144,7 @@ func (b *BaseApi) DeleteFtp(c *gin.Context) {
} }
if err := ftpService.Delete(req); err != nil { if err := ftpService.Delete(req); err != nil {
helper.ErrorWithDetail(c, constant.CodeErrInternalServer, constant.ErrTypeInternalServer, err) helper.InternalServer(c, err)
return return
} }
helper.SuccessWithOutData(c) 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"} // @x-panel-log {"bodyKeys":[],"paramKeys":[],"BeforeFunctions":[],"formatZH":"同步 FTP 账户","formatEN":"sync FTP users"}
func (b *BaseApi) SyncFtp(c *gin.Context) { func (b *BaseApi) SyncFtp(c *gin.Context) {
if err := ftpService.Sync(); err != nil { if err := ftpService.Sync(); err != nil {
helper.ErrorWithDetail(c, constant.CodeErrInternalServer, constant.ErrTypeInternalServer, err) helper.InternalServer(c, err)
return return
} }
helper.SuccessWithOutData(c) helper.SuccessWithOutData(c)
@ -192,7 +191,7 @@ func (b *BaseApi) UpdateFtp(c *gin.Context) {
req.Password = string(pass) req.Password = string(pass)
} }
if err := ftpService.Update(req); err != nil { if err := ftpService.Update(req); err != nil {
helper.ErrorWithDetail(c, constant.CodeErrInternalServer, constant.ErrTypeInternalServer, err) helper.InternalServer(c, err)
return return
} }
helper.SuccessWithOutData(c) helper.SuccessWithOutData(c)

View File

@ -10,7 +10,6 @@ import (
"gorm.io/gorm" "gorm.io/gorm"
"github.com/1Panel-dev/1Panel/agent/app/dto" "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/constant"
"github.com/1Panel-dev/1Panel/agent/i18n" "github.com/1Panel-dev/1Panel/agent/i18n"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
@ -22,34 +21,17 @@ func ErrorWithDetail(ctx *gin.Context, code int, msgKey string, err error) {
Code: code, Code: code,
Message: "", 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()) res.Message = i18n.GetMsgWithDetail(msgKey, err.Error())
}
} else {
res.Message = i18n.GetMsgWithDetail(msgKey, err.Error())
}
ctx.JSON(http.StatusOK, res) ctx.JSON(http.StatusOK, res)
ctx.Abort() ctx.Abort()
} }
func InternalServer(ctx *gin.Context, err error) { 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) { 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{}) { func SuccessWithData(ctx *gin.Context, data interface{}) {
@ -57,7 +39,7 @@ func SuccessWithData(ctx *gin.Context, data interface{}) {
data = gin.H{} data = gin.H{}
} }
res := dto.Response{ res := dto.Response{
Code: constant.CodeSuccess, Code: http.StatusOK,
Data: data, Data: data,
} }
ctx.JSON(http.StatusOK, res) ctx.JSON(http.StatusOK, res)
@ -66,7 +48,7 @@ func SuccessWithData(ctx *gin.Context, data interface{}) {
func SuccessWithOutData(ctx *gin.Context) { func SuccessWithOutData(ctx *gin.Context) {
res := dto.Response{ res := dto.Response{
Code: constant.CodeSuccess, Code: http.StatusOK,
Message: "success", Message: "success",
} }
ctx.JSON(http.StatusOK, res) ctx.JSON(http.StatusOK, res)
@ -75,7 +57,7 @@ func SuccessWithOutData(ctx *gin.Context) {
func SuccessWithMsg(ctx *gin.Context, msg string) { func SuccessWithMsg(ctx *gin.Context, msg string) {
res := dto.Response{ res := dto.Response{
Code: constant.CodeSuccess, Code: http.StatusOK,
Message: msg, Message: msg,
} }
ctx.JSON(http.StatusOK, res) 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 { func CheckBindAndValidate(req interface{}, c *gin.Context) error {
if err := c.ShouldBindJSON(req); err != nil { if err := c.ShouldBindJSON(req); err != nil {
ErrorWithDetail(c, constant.CodeErrBadRequest, constant.ErrTypeInvalidParams, err) ErrorWithDetail(c, http.StatusBadRequest, "ErrInvalidParams", err)
return err return err
} }
if err := global.VALID.Struct(req); err != nil { if err := global.VALID.Struct(req); err != nil {
ErrorWithDetail(c, constant.CodeErrBadRequest, constant.ErrTypeInvalidParams, err) ErrorWithDetail(c, http.StatusBadRequest, "ErrInvalidParams", err)
return err return err
} }
return nil return nil
@ -128,7 +110,7 @@ func CheckBindAndValidate(req interface{}, c *gin.Context) error {
func CheckBind(req interface{}, c *gin.Context) error { func CheckBind(req interface{}, c *gin.Context) error {
if err := c.ShouldBindJSON(&req); err != nil { if err := c.ShouldBindJSON(&req); err != nil {
ErrorWithDetail(c, constant.CodeErrBadRequest, constant.ErrTypeInvalidParams, err) ErrorWithDetail(c, http.StatusBadRequest, "ErrInvalidParams", err)
return err return err
} }
return nil return nil

View File

@ -61,7 +61,7 @@ func (b *BaseApi) UpdateSetting(c *gin.Context) {
// @Security Timestamp // @Security Timestamp
// @Router /settings/basedir [get] // @Router /settings/basedir [get]
func (b *BaseApi) LoadBaseDir(c *gin.Context) { 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) { func (b *BaseApi) ReloadConn(c *gin.Context) {

View File

@ -26,7 +26,7 @@ func (b *BaseApi) RedisWsSsh(c *gin.Context) {
} }
defer wsConn.Close() defer wsConn.Close()
if global.CONF.System.IsDemo { if global.CONF.Base.IsDemo {
if wshandleError(wsConn, errors.New(" demo server, prohibit this operation!")) { if wshandleError(wsConn, errors.New(" demo server, prohibit this operation!")) {
return return
} }
@ -99,7 +99,7 @@ func (b *BaseApi) ContainerWsSsh(c *gin.Context) {
} }
defer wsConn.Close() defer wsConn.Close()
if global.CONF.System.IsDemo { if global.CONF.Base.IsDemo {
if wshandleError(wsConn, errors.New(" demo server, prohibit this operation!")) { if wshandleError(wsConn, errors.New(" demo server, prohibit this operation!")) {
return return
} }

View File

@ -5,6 +5,7 @@ import (
"strings" "strings"
"github.com/1Panel-dev/1Panel/agent/constant" "github.com/1Panel-dev/1Panel/agent/constant"
"github.com/1Panel-dev/1Panel/agent/global"
) )
type App struct { type App struct {
@ -43,7 +44,7 @@ func (i *App) IsLocalApp() bool {
func (i *App) GetAppResourcePath() string { func (i *App) GetAppResourcePath() string {
if i.IsLocalApp() { if i.IsLocalApp() {
//这里要去掉本地应用的local前缀 //这里要去掉本地应用的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)
} }

View File

@ -5,6 +5,7 @@ import (
"strings" "strings"
"github.com/1Panel-dev/1Panel/agent/constant" "github.com/1Panel-dev/1Panel/agent/constant"
"github.com/1Panel-dev/1Panel/agent/global"
) )
type AppInstall struct { type AppInstall struct {
@ -41,8 +42,8 @@ func (i *AppInstall) GetEnvPath() string {
func (i *AppInstall) GetAppPath() string { func (i *AppInstall) GetAppPath() string {
if i.App.Resource == constant.AppResourceLocal { 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 { } else {
return path.Join(constant.AppInstallDir, i.App.Key) return path.Join(global.Dir.AppInstallDir, i.App.Key)
} }
} }

View File

@ -3,7 +3,7 @@ package model
import ( import (
"path" "path"
"github.com/1Panel-dev/1Panel/agent/constant" "github.com/1Panel-dev/1Panel/agent/global"
) )
type Runtime struct { type Runtime struct {
@ -34,15 +34,15 @@ func (r *Runtime) GetEnvPath() string {
} }
func (r *Runtime) GetPath() 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 { 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 { 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 { func (r *Runtime) GetLogPath() string {

View File

@ -5,7 +5,7 @@ import (
"path" "path"
"time" "time"
"github.com/1Panel-dev/1Panel/agent/constant" "github.com/1Panel-dev/1Panel/agent/global"
) )
type WebsiteSSL struct { type WebsiteSSL struct {
@ -47,5 +47,5 @@ func (w WebsiteSSL) TableName() string {
} }
func (w WebsiteSSL) GetLogPath() 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))
} }

View File

@ -218,7 +218,7 @@ func (a AppService) GetAppDetail(appID uint, version, appType string) (response.
case constant.RuntimePHP: case constant.RuntimePHP:
paramsPath := filepath.Join(versionPath, "data.yml") paramsPath := filepath.Join(versionPath, "data.yml")
if !fileOp.Stat(paramsPath) { if !fileOp.Stat(paramsPath) {
return appDetailDTO, buserr.WithDetail(constant.ErrFileNotExist, paramsPath, nil) return appDetailDTO, buserr.WithDetail("ErrFileNotExist", paramsPath, nil)
} }
param, err := fileOp.GetContent(paramsPath) param, err := fileOp.GetContent(paramsPath)
if err != nil { if err != nil {
@ -231,7 +231,7 @@ func (a AppService) GetAppDetail(appID uint, version, appType string) (response.
appDetailDTO.Params = paramMap["additionalProperties"] appDetailDTO.Params = paramMap["additionalProperties"]
composePath := filepath.Join(versionPath, "docker-compose.yml") composePath := filepath.Join(versionPath, "docker-compose.yml")
if !fileOp.Stat(composePath) { if !fileOp.Stat(composePath) {
return appDetailDTO, buserr.WithDetail(constant.ErrFileNotExist, composePath, nil) return appDetailDTO, buserr.WithDetail("ErrFileNotExist", composePath, nil)
} }
compose, err := fileOp.GetContent(composePath) compose, err := fileOp.GetContent(composePath)
if err != nil { 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) { func (a AppService) Install(req request.AppInstallCreate) (appInstall *model.AppInstall, err error) {
if err = docker.CreateDefaultDockerNetwork(); err != nil { if err = docker.CreateDefaultDockerNetwork(); err != nil {
err = buserr.WithDetail(constant.Err1PanelNetworkFailed, err.Error(), nil) err = buserr.WithDetail("Err1PanelNetworkFailed", err.Error(), nil)
return return
} }
if list, _ := appInstallRepo.ListBy(repo.WithByName(req.Name)); len(list) > 0 { if list, _ := appInstallRepo.ListBy(repo.WithByName(req.Name)); len(list) > 0 {
err = buserr.New(constant.ErrAppNameExist) err = buserr.New("ErrAppNameExist")
return return
} }
var ( var (
@ -347,7 +347,7 @@ func (a AppService) Install(req request.AppInstallCreate) (appInstall *model.App
} }
if DatabaseKeys[app.Key] > 0 { if DatabaseKeys[app.Key] > 0 {
if existDatabases, _ := databaseRepo.GetList(repo.WithByName(req.Name)); len(existDatabases) > 0 { if existDatabases, _ := databaseRepo.GetList(repo.WithByName(req.Name)); len(existDatabases) > 0 {
err = buserr.New(constant.ErrRemoteExist) err = buserr.New("ErrRemoteExist")
return return
} }
} }
@ -355,7 +355,7 @@ func (a AppService) Install(req request.AppInstallCreate) (appInstall *model.App
if dir, ok := req.Params["WEBSITE_DIR"]; ok { if dir, ok := req.Params["WEBSITE_DIR"]; ok {
siteDir := dir.(string) siteDir := dir.(string)
if siteDir == "" || !strings.HasPrefix(siteDir, "/") { 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 req.Params["WEBSITE_DIR"] = siteDir
oldWebStePath, _ := settingRepo.GetValueByKey("WEBSITE_DIR") oldWebStePath, _ := settingRepo.GetValueByKey("WEBSITE_DIR")
@ -416,7 +416,7 @@ func (a AppService) Install(req request.AppInstallCreate) (appInstall *model.App
value, ok := composeMap["services"] value, ok := composeMap["services"]
if !ok || value == nil { if !ok || value == nil {
err = buserr.New(constant.ErrFileParse) err = buserr.New("ErrFileParse")
return return
} }
servicesMap := value.(map[string]interface{}) servicesMap := value.(map[string]interface{})
@ -425,7 +425,7 @@ func (a AppService) Install(req request.AppInstallCreate) (appInstall *model.App
containerName = req.ContainerName containerName = req.ContainerName
appInstalls, _ := appInstallRepo.ListBy(appInstallRepo.WithContainerName(containerName)) appInstalls, _ := appInstallRepo.ListBy(appInstallRepo.WithContainerName(containerName))
if len(appInstalls) > 0 { if len(appInstalls) > 0 {
err = buserr.New(constant.ErrContainerName) err = buserr.New("ErrContainerName")
return return
} }
containerExist := false containerExist := false
@ -434,7 +434,7 @@ func (a AppService) Install(req request.AppInstallCreate) (appInstall *model.App
return return
} }
if containerExist { if containerExist {
err = buserr.New(constant.ErrContainerName) err = buserr.New("ErrContainerName")
return 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) { syncTask.AddSubTask(task.GetTaskName(i18n.GetMsgByKey("LocalApp"), task.TaskSync, task.TaskScopeAppStore), func(t *task.Task) (err error) {
fileOp := files.NewFileOp() fileOp := files.NewFileOp()
localAppDir := constant.LocalAppResourceDir localAppDir := global.Dir.LocalAppResourceDir
if !fileOp.Stat(localAppDir) { if !fileOp.Stat(localAppDir) {
return nil return nil
} }
@ -771,7 +771,7 @@ func (a AppService) GetAppUpdate() (*response.AppUpdateRes, error) {
CanUpdate: false, 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) _, versionRes, err := req_helper.HandleRequest(versionUrl, http.MethodGet, constant.TimeOut20s)
if err != nil { if err != nil {
return nil, err return nil, err
@ -820,11 +820,11 @@ func getAppFromRepo(downloadPath string) error {
downloadUrl := downloadPath downloadUrl := downloadPath
global.LOG.Infof("[AppStore] download file from %s", downloadUrl) global.LOG.Infof("[AppStore] download file from %s", downloadUrl)
fileOp := files.NewFileOp() 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 { if err := fileOp.DownloadFile(downloadUrl, packagePath); err != nil {
return err 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 return err
} }
defer func() { defer func() {
@ -835,10 +835,10 @@ func getAppFromRepo(downloadPath string) error {
func getAppList() (*dto.AppList, error) { func getAppList() (*dto.AppList, error) {
list := &dto.AppList{} 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 return nil, err
} }
listFile := filepath.Join(constant.ResourceDir, "1panel.json") listFile := filepath.Join(global.Dir.ResourceDir, "1panel.json")
content, err := os.ReadFile(listFile) content, err := os.ReadFile(listFile)
if err != nil { if err != nil {
return nil, err return nil, err
@ -935,7 +935,7 @@ func (a AppService) SyncAppListFromRemote(taskID string) (err error) {
oldAppIds = append(oldAppIds, old.ID) 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) appsMap := getApps(oldApps, list.Apps, setting.SystemVersion, t)

View File

@ -163,7 +163,7 @@ func (a *AppInstallService) CheckExist(req request.AppInstalledInfo) (*response.
res.Status = appInstall.Status res.Status = appInstall.Status
res.AppInstallID = appInstall.ID res.AppInstallID = appInstall.ID
res.IsExist = true 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.HttpPort = appInstall.HttpPort
res.HttpsPort = appInstall.HttpsPort res.HttpsPort = appInstall.HttpsPort
@ -245,7 +245,7 @@ func (a *AppInstallService) Operate(req request.AppInstalledOperate) error {
return err return err
} }
if !req.ForceDelete && !files.NewFileOp().Stat(install.GetPath()) { if !req.ForceDelete && !files.NewFileOp().Stat(install.GetPath()) {
return buserr.New(constant.ErrInstallDirNotFound) return buserr.New("ErrInstallDirNotFound")
} }
dockerComposePath := install.GetComposePath() dockerComposePath := install.GetComposePath()
switch req.Operate { switch req.Operate {
@ -370,14 +370,14 @@ func (a *AppInstallService) Update(req request.AppInstalledUpdate) error {
if installed.ContainerName != req.ContainerName { if installed.ContainerName != req.ContainerName {
exist, _ := appInstallRepo.GetFirst(appInstallRepo.WithContainerName(req.ContainerName), appInstallRepo.WithIDNotIs(installed.ID)) exist, _ := appInstallRepo.GetFirst(appInstallRepo.WithContainerName(req.ContainerName), appInstallRepo.WithIDNotIs(installed.ID))
if exist.ID > 0 { if exist.ID > 0 {
return buserr.New(constant.ErrContainerName) return buserr.New("ErrContainerName")
} }
containerExist, err := checkContainerNameIsExist(req.ContainerName, installed.GetPath()) containerExist, err := checkContainerNameIsExist(req.ContainerName, installed.GetPath())
if err != nil { if err != nil {
return err return err
} }
if containerExist { if containerExist {
return buserr.New(constant.ErrContainerName) return buserr.New("ErrContainerName")
} }
installed.ContainerName = req.ContainerName installed.ContainerName = req.ContainerName
} }
@ -414,13 +414,13 @@ func (a *AppInstallService) Update(req request.AppInstalledUpdate) error {
go func() { go func() {
nginxInstall, err := getNginxFull(&website) nginxInstall, err := getNginxFull(&website)
if err != nil { if err != nil {
global.LOG.Error(buserr.WithErr(constant.ErrUpdateBuWebsite, err).Error()) global.LOG.Error(buserr.WithErr("ErrUpdateBuWebsite", err).Error())
return return
} }
config := nginxInstall.SiteConfig.Config config := nginxInstall.SiteConfig.Config
servers := config.FindServers() servers := config.FindServers()
if len(servers) == 0 { 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 return
} }
server := servers[0] server := servers[0]
@ -428,11 +428,11 @@ func (a *AppInstallService) Update(req request.AppInstalledUpdate) error {
server.UpdateRootProxy([]string{proxy}) server.UpdateRootProxy([]string{proxy})
if err := nginx.WriteConfig(config, nginx.IndentedStyle); err != nil { 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 return
} }
if err := nginxCheckAndReload(nginxInstall.SiteConfig.OldContent, config.FilePath, nginxInstall.Install.ContainerName); err != nil { 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 return
} }
}() }()
@ -588,7 +588,7 @@ func (a *AppInstallService) GetUpdateVersions(req request.AppUpdateVersion) ([]d
func (a *AppInstallService) ChangeAppPort(req request.PortUpdate) error { func (a *AppInstallService) ChangeAppPort(req request.PortUpdate) error {
if common.ScanPort(int(req.Port)) { 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) appInstall, err := appInstallRepo.LoadBaseInfo(req.Key, req.Name)
@ -606,7 +606,7 @@ func (a *AppInstallService) ChangeAppPort(req request.PortUpdate) error {
if err != nil { if err != nil {
return err 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) 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() 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) { 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) { if !fileOp.Stat(filePath) {
return "", buserr.New(constant.ErrPathNotFound) return "", buserr.New("ErrPathNotFound")
} }
if key == constant.AppMysql || key == constant.AppMariaDB { if key == constant.AppMysql || key == constant.AppMariaDB {
@ -877,7 +877,7 @@ func updateInstallInfoInDB(appKey, appName, param string, value interface{}) err
}, repo.WithByID(appInstall.ID)) }, 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) stdout, err := compose.Down(ComposeFile)
if err != nil { if err != nil {
return errors.New(stdout) return errors.New(stdout)

View File

@ -84,10 +84,10 @@ func checkPort(key string, params map[string]interface{}) (int, error) {
for _, install := range oldInstalled { for _, install := range oldInstalled {
apps = append(apps, install.App.Name) 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) { if common.ScanPort(portN) {
return portN, buserr.WithDetail(constant.ErrPortInUsed, portN, nil) return portN, buserr.WithDetail("ErrPortInUsed", portN, nil)
} else { } else {
return portN, nil return portN, nil
} }
@ -117,7 +117,7 @@ func checkPortExist(port int) error {
return buserr.WithMap("ErrPortExist", errMap, nil) return buserr.WithMap("ErrPortExist", errMap, nil)
} }
if common.ScanPort(port) { if common.ScanPort(port) {
return buserr.WithDetail(constant.ErrPortInUsed, port, nil) return buserr.WithDetail("ErrPortInUsed", port, nil)
} }
return nil return nil
} }
@ -264,7 +264,7 @@ func createLink(ctx context.Context, installTask *task.Task, app model.App, appI
resourceId = oldPostgresqlDb.ID resourceId = oldPostgresqlDb.ID
if oldPostgresqlDb.ID > 0 { if oldPostgresqlDb.ID > 0 {
if oldPostgresqlDb.Username != dbConfig.DbUser || oldPostgresqlDb.Password != dbConfig.Password { if oldPostgresqlDb.Username != dbConfig.DbUser || oldPostgresqlDb.Password != dbConfig.Password {
return buserr.New(constant.ErrDbUserNotValid) return buserr.New("ErrDbUserNotValid")
} }
} else { } else {
var createPostgresql dto.PostgresqlDBCreate var createPostgresql dto.PostgresqlDBCreate
@ -286,7 +286,7 @@ func createLink(ctx context.Context, installTask *task.Task, app model.App, appI
resourceId = oldMysqlDb.ID resourceId = oldMysqlDb.ID
if oldMysqlDb.ID > 0 { if oldMysqlDb.ID > 0 {
if oldMysqlDb.Username != dbConfig.DbUser || oldMysqlDb.Password != dbConfig.Password { if oldMysqlDb.Username != dbConfig.DbUser || oldMysqlDb.Password != dbConfig.Password {
return buserr.New(constant.ErrDbUserNotValid) return buserr.New("ErrDbUserNotValid")
} }
} else { } else {
var createMysql dto.MysqlDBCreate 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)) _ = 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 { if _, err := os.Stat(uploadDir); err == nil {
_ = os.RemoveAll(uploadDir) _ = os.RemoveAll(uploadDir)
} }
if deleteReq.DeleteBackup { 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 { if _, err = os.Stat(backupDir); err == nil {
t.LogWithOps(task.TaskDelete, i18n.GetMsgByKey("TaskBackup")) t.LogWithOps(task.TaskDelete, i18n.GetMsgByKey("TaskBackup"))
_ = os.RemoveAll(backupDir) _ = os.RemoveAll(backupDir)
@ -494,7 +494,7 @@ func getUpgradeCompose(install model.AppInstall, detail model.AppDetail) (string
} }
value, ok := composeMap["services"] value, ok := composeMap["services"]
if !ok || value == nil { if !ok || value == nil {
return "", buserr.New(constant.ErrFileParse) return "", buserr.New("ErrFileParse")
} }
servicesMap := value.(map[string]interface{}) servicesMap := value.(map[string]interface{})
if len(servicesMap) == 1 { if len(servicesMap) == 1 {
@ -576,7 +576,7 @@ func upgradeInstall(req request.AppInstallUpgrade) error {
} }
_ = backupRecordService.BatchDeleteRecord(deleteIDs) _ = 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 { } else {
return buserr.WithNameAndErr("ErrAppBackup", install.Name, err) return buserr.WithNameAndErr("ErrAppBackup", install.Name, err)
} }
@ -587,7 +587,7 @@ func upgradeInstall(req request.AppInstallUpgrade) error {
upgradeApp := func(t *task.Task) error { upgradeApp := func(t *task.Task) error {
fileOp := files.NewFileOp() 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 install.App.Resource == constant.AppResourceRemote {
if err = downloadApp(install.App, detail, &install, t.Logger); err != nil { if err = downloadApp(install.App, detail, &install, t.Logger); err != nil {
return err return err
@ -605,7 +605,7 @@ func upgradeInstall(req request.AppInstallUpgrade) error {
}() }()
} }
if install.App.Resource == constant.AppResourceLocal { 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()) content, err := fileOp.GetContent(install.GetEnvPath())
@ -673,15 +673,15 @@ func upgradeInstall(req request.AppInstallUpgrade) error {
handleMap(envs, envParams) handleMap(envs, envParams)
if install.App.Key == "openresty" && install.App.Resource == "remote" && !common.CompareVersion(install.Version, "1.25.3.2-0-1") { if install.App.Key == "openresty" && install.App.Resource == "remote" && !common.CompareVersion(install.Version, "1.25.3.2-0-1") {
t.Log(i18n.GetMsgByKey("MoveSiteDir")) t.Log(i18n.GetMsgByKey("MoveSiteDir"))
siteDir := path.Join(constant.DataDir, "www") siteDir := path.Join(global.Dir.DataDir, "www")
envParams["WEBSITE_DIR"] = siteDir envParams["WEBSITE_DIR"] = siteDir
oldSiteDir := path.Join(install.GetPath(), "www") oldSiteDir := path.Join(install.GetPath(), "www")
t.Log(i18n.GetWithName("MoveSiteToDir", siteDir)) 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")) t.Log(i18n.GetMsgByKey("ErrMoveSiteDir"))
return err return err
} }
newConfDir := path.Join(constant.DataDir, "www", "conf.d") newConfDir := path.Join(global.Dir.DataDir, "www", "conf.d")
_ = fileOp.CreateDir(newConfDir, constant.DirPerm) _ = fileOp.CreateDir(newConfDir, constant.DirPerm)
oldConfDir := path.Join(install.GetPath(), "conf/conf.d") oldConfDir := path.Join(install.GetPath(), "conf/conf.d")
items, err := os.ReadDir(oldConfDir) 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"}) httpDirective.UpdateDirective("include", []string{"/usr/local/openresty/nginx/conf/default/*.conf"})
if err = nginx.WriteConfig(config, nginx.IndentedStyle); err != nil { 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")) 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")) websites, _ := websiteRepo.List(repo.WithByType("runtime"))
for _, website := range websites { for _, website := range websites {
runtime, _ := runtimeRepo.GetFirst(repo.WithByID(website.RuntimeID)) runtime, _ := runtimeRepo.GetFirst(repo.WithByID(website.RuntimeID))
@ -827,7 +827,7 @@ func checkLimit(app model.App) error {
return err return err
} }
if len(installs) >= app.Limit { if len(installs) >= app.Limit {
return buserr.New(constant.ErrAppLimit) return buserr.New("ErrAppLimit")
} }
} }
return nil return nil
@ -867,7 +867,7 @@ func downloadApp(app model.App, appDetail model.AppDetail, appInstall *model.App
if app.IsLocalApp() { if app.IsLocalApp() {
return nil return nil
} }
appResourceDir := path.Join(constant.AppResourceDir, app.Resource) appResourceDir := path.Join(global.Dir.AppResourceDir, app.Resource)
appDownloadDir := app.GetAppResourcePath() appDownloadDir := app.GetAppResourcePath()
appVersionDir := path.Join(appDownloadDir, appDetail.Version) appVersionDir := path.Join(appDownloadDir, appDetail.Version)
fileOp := files.NewFileOp() 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) { func copyData(task *task.Task, app model.App, appDetail model.AppDetail, appInstall *model.AppInstall, req request.AppInstallCreate) (err error) {
fileOp := files.NewFileOp() fileOp := files.NewFileOp()
appResourceDir := path.Join(constant.AppResourceDir, app.Resource) appResourceDir := path.Join(global.Dir.AppResourceDir, app.Resource)
if app.Resource == constant.AppResourceRemote { if app.Resource == constant.AppResourceRemote {
err = downloadApp(app, appDetail, appInstall, task.Logger) 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 appKey := app.Key
installAppDir := path.Join(constant.AppInstallDir, app.Key) installAppDir := path.Join(global.Dir.AppInstallDir, app.Key)
if app.Resource == constant.AppResourceLocal { if app.Resource == constant.AppResourceLocal {
appResourceDir = constant.LocalAppResourceDir appResourceDir = global.Dir.LocalAppResourceDir
appKey = strings.TrimPrefix(app.Key, "local") appKey = strings.TrimPrefix(app.Key, "local")
installAppDir = path.Join(constant.LocalAppInstallDir, appKey) installAppDir = path.Join(global.Dir.LocalAppInstallDir, appKey)
} }
if app.Resource == constant.AppResourceCustom { 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) resourceDir := path.Join(appResourceDir, appKey, appDetail.Version)
@ -1205,43 +1205,43 @@ func handleLocalAppDetail(versionDir string, appDetail *model.AppDetail) error {
fileOp := files.NewFileOp() fileOp := files.NewFileOp()
dockerComposePath := path.Join(versionDir, "docker-compose.yml") dockerComposePath := path.Join(versionDir, "docker-compose.yml")
if !fileOp.Stat(dockerComposePath) { if !fileOp.Stat(dockerComposePath) {
return buserr.WithName(constant.ErrFileNotFound, "docker-compose.yml") return buserr.WithName("ErrFileNotFound", "docker-compose.yml")
} }
dockerComposeByte, _ := fileOp.GetContent(dockerComposePath) dockerComposeByte, _ := fileOp.GetContent(dockerComposePath)
if dockerComposeByte == nil { if dockerComposeByte == nil {
return buserr.WithName(constant.ErrFileParseApp, "docker-compose.yml") return buserr.WithName("ErrFileParseApp", "docker-compose.yml")
} }
appDetail.DockerCompose = string(dockerComposeByte) appDetail.DockerCompose = string(dockerComposeByte)
paramPath := path.Join(versionDir, "data.yml") paramPath := path.Join(versionDir, "data.yml")
if !fileOp.Stat(paramPath) { if !fileOp.Stat(paramPath) {
return buserr.WithName(constant.ErrFileNotFound, "data.yml") return buserr.WithName("ErrFileNotFound", "data.yml")
} }
paramByte, _ := fileOp.GetContent(paramPath) paramByte, _ := fileOp.GetContent(paramPath)
if paramByte == nil { if paramByte == nil {
return buserr.WithName(constant.ErrFileNotFound, "data.yml") return buserr.WithName("ErrFileNotFound", "data.yml")
} }
appParamConfig := dto.LocalAppParam{} appParamConfig := dto.LocalAppParam{}
if err := yaml.Unmarshal(paramByte, &appParamConfig); err != nil { 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) dataJson, err := json.Marshal(appParamConfig.AppParams)
if err != nil { 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 var appParam dto.AppForm
if err = json.Unmarshal(dataJson, &appParam); err != nil { 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 { for _, formField := range appParam.FormFields {
if strings.Contains(formField.EnvKey, " ") { if strings.Contains(formField.EnvKey, " ") {
return buserr.WithName(constant.ErrAppParamKey, formField.EnvKey) return buserr.WithName("ErrAppParamKey", formField.EnvKey)
} }
} }
var dataMap map[string]interface{} var dataMap map[string]interface{}
err = yaml.Unmarshal(paramByte, &dataMap) err = yaml.Unmarshal(paramByte, &dataMap)
if err != nil { 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{}) additionalProperties, _ := dataMap["additionalProperties"].(map[string]interface{})
@ -1249,13 +1249,13 @@ func handleLocalAppDetail(versionDir string, appDetail *model.AppDetail) error {
if ok { if ok {
formFields, ok := formFieldsInterface.([]interface{}) formFields, ok := formFieldsInterface.([]interface{})
if !ok { if !ok {
return buserr.WithName(constant.ErrAppParamKey, "formFields") return buserr.WithName("ErrAppParamKey", "formFields")
} }
for _, item := range formFields { for _, item := range formFields {
field := item.(map[string]interface{}) field := item.(map[string]interface{})
for key, value := range field { for key, value := range field {
if value == nil { 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() fileOp := files.NewFileOp()
configYamlPath := path.Join(appDir, "data.yml") configYamlPath := path.Join(appDir, "data.yml")
if !fileOp.Stat(configYamlPath) { if !fileOp.Stat(configYamlPath) {
err = buserr.WithName(constant.ErrFileNotFound, "data.yml") err = buserr.WithName("ErrFileNotFound", "data.yml")
return return
} }
iconPath := path.Join(appDir, "logo.png") iconPath := path.Join(appDir, "logo.png")
if !fileOp.Stat(iconPath) { if !fileOp.Stat(iconPath) {
err = buserr.WithName(constant.ErrFileNotFound, "logo.png") err = buserr.WithName("ErrFileNotFound", "logo.png")
return return
} }
configYamlByte, err := fileOp.GetContent(configYamlPath) configYamlByte, err := fileOp.GetContent(configYamlPath)
if err != nil { 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 return
} }
localAppDefine := dto.LocalAppAppDefine{} localAppDefine := dto.LocalAppAppDefine{}
if err = yaml.Unmarshal(configYamlByte, &localAppDefine); err != nil { 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 return
} }
app = &localAppDefine.AppProperty 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 { func addDockerComposeCommonParam(composeMap map[string]interface{}, serviceName string, req request.AppContainerConfig, params map[string]interface{}) error {
services, serviceValid := composeMap["services"].(map[string]interface{}) services, serviceValid := composeMap["services"].(map[string]interface{})
if !serviceValid { if !serviceValid {
return buserr.New(constant.ErrFileParse) return buserr.New("ErrFileParse")
} }
imagePreFix := xpack.GetImagePrefix() imagePreFix := xpack.GetImagePrefix()
if imagePreFix != "" { if imagePreFix != "" {
@ -1598,7 +1598,7 @@ func addDockerComposeCommonParam(composeMap map[string]interface{}, serviceName
service, serviceExist := services[serviceName] service, serviceExist := services[serviceName]
if !serviceExist { if !serviceExist {
return buserr.New(constant.ErrFileParse) return buserr.New("ErrFileParse")
} }
serviceValue := service.(map[string]interface{}) serviceValue := service.(map[string]interface{})

View File

@ -23,7 +23,6 @@ import (
"github.com/1Panel-dev/1Panel/agent/utils/encrypt" "github.com/1Panel-dev/1Panel/agent/utils/encrypt"
"github.com/1Panel-dev/1Panel/agent/utils/files" "github.com/1Panel-dev/1Panel/agent/utils/files"
"github.com/jinzhu/copier" "github.com/jinzhu/copier"
"github.com/pkg/errors"
) )
type BackupService struct{} type BackupService struct{}
@ -125,17 +124,17 @@ func (u *BackupService) SearchWithPage(req dto.SearchPageWithType) (int64, inter
func (u *BackupService) Create(req dto.BackupOperate) error { func (u *BackupService) Create(req dto.BackupOperate) error {
if req.Type == constant.Local { if req.Type == constant.Local {
return buserr.New(constant.ErrBackupLocalCreate) return buserr.New("ErrBackupLocalCreate")
} }
if req.Type != constant.Sftp && req.BackupPath != "/" { if req.Type != constant.Sftp && req.BackupPath != "/" {
req.BackupPath = strings.TrimPrefix(req.BackupPath, "/") req.BackupPath = strings.TrimPrefix(req.BackupPath, "/")
} }
backup, _ := backupRepo.Get(repo.WithByName(req.Name)) backup, _ := backupRepo.Get(repo.WithByName(req.Name))
if backup.ID != 0 { if backup.ID != 0 {
return constant.ErrRecordExist return buserr.New("ErrRecordExist")
} }
if err := copier.Copy(&backup, &req); err != nil { 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) itemAccessKey, err := base64.StdEncoding.DecodeString(backup.AccessKey)
if err != nil { if err != nil {
@ -156,7 +155,7 @@ func (u *BackupService) Create(req dto.BackupOperate) error {
if req.Type != "LOCAL" { if req.Type != "LOCAL" {
isOk, err := u.checkBackupConn(&backup) isOk, err := u.checkBackupConn(&backup)
if err != nil || !isOk { 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 { func (u *BackupService) Delete(id uint) error {
backup, _ := backupRepo.Get(repo.WithByID(id)) backup, _ := backupRepo.Get(repo.WithByID(id))
if backup.ID == 0 { if backup.ID == 0 {
return constant.ErrRecordNotFound return buserr.New("ErrRecordNotFound")
} }
if backup.Type == constant.Local { if backup.Type == constant.Local {
return buserr.New(constant.ErrBackupLocalDelete) return buserr.New("ErrBackupLocalDelete")
} }
return backupRepo.Delete(repo.WithByID(id)) 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 { func (u *BackupService) Update(req dto.BackupOperate) error {
backup, _ := backupRepo.Get(repo.WithByID(req.ID)) backup, _ := backupRepo.Get(repo.WithByID(req.ID))
if backup.ID == 0 { if backup.ID == 0 {
return constant.ErrRecordNotFound return buserr.New("ErrRecordNotFound")
} }
if req.Type != constant.Sftp && req.Type != constant.Local && req.BackupPath != "/" { if req.Type != constant.Sftp && req.Type != constant.Local && req.BackupPath != "/" {
req.BackupPath = strings.TrimPrefix(req.BackupPath, "/") req.BackupPath = strings.TrimPrefix(req.BackupPath, "/")
} }
var newBackup model.BackupAccount var newBackup model.BackupAccount
if err := copier.Copy(&newBackup, &req); err != nil { 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) itemAccessKey, err := base64.StdEncoding.DecodeString(newBackup.AccessKey)
if err != nil { if err != nil {
@ -281,7 +280,7 @@ func (u *BackupService) Update(req dto.BackupOperate) error {
func (u *BackupService) RefreshToken(req dto.OperateByID) error { func (u *BackupService) RefreshToken(req dto.OperateByID) error {
backup, _ := backupRepo.Get(repo.WithByID(req.ID)) backup, _ := backupRepo.Get(repo.WithByID(req.ID))
if backup.ID == 0 { if backup.ID == 0 {
return constant.ErrRecordNotFound return buserr.New("ErrRecordNotFound")
} }
varMap := make(map[string]interface{}) varMap := make(map[string]interface{})
if err := json.Unmarshal([]byte(backup.Vars), &varMap); err != nil { 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 { if err != nil {
return false, err 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.Stat(path.Dir(fileItem)); err != nil && os.IsNotExist(err) {
if err = os.MkdirAll(path.Dir(fileItem), os.ModePerm); err != nil { if err = os.MkdirAll(path.Dir(fileItem), os.ModePerm); err != nil {
return false, err return false, err
@ -365,12 +364,12 @@ func (u *BackupService) Sync(req dto.SyncFromMaster) error {
return backupRepo.Create(&accountItem) return backupRepo.Create(&accountItem)
case "delete": case "delete":
if account.ID == 0 { if account.ID == 0 {
return constant.ErrRecordNotFound return buserr.New("ErrRecordNotFound")
} }
return backupRepo.Delete(repo.WithByID(account.ID)) return backupRepo.Delete(repo.WithByID(account.ID))
case "update": case "update":
if account.ID == 0 { if account.ID == 0 {
return constant.ErrRecordNotFound return buserr.New("ErrRecordNotFound")
} }
accountItem.ID = account.ID accountItem.ID = account.ID
return backupRepo.Save(&accountItem) return backupRepo.Save(&accountItem)
@ -399,12 +398,12 @@ func (u *BackupService) CheckUsed(id uint) error {
cronjobs, _ := cronjobRepo.List() cronjobs, _ := cronjobRepo.List()
for _, job := range cronjobs { for _, job := range cronjobs {
if job.DownloadAccountID == id { if job.DownloadAccountID == id {
return buserr.New(constant.ErrBackupInUsed) return buserr.New("ErrBackupInUsed")
} }
ids := strings.Split(job.SourceAccountIDs, ",") ids := strings.Split(job.SourceAccountIDs, ",")
for _, idItem := range ids { for _, idItem := range ids {
if idItem == fmt.Sprintf("%v", id) { if idItem == fmt.Sprintf("%v", id) {
return buserr.New(constant.ErrBackupInUsed) return buserr.New("ErrBackupInUsed")
} }
} }
} }

View File

@ -4,13 +4,14 @@ import (
"context" "context"
"encoding/json" "encoding/json"
"fmt" "fmt"
"github.com/1Panel-dev/1Panel/agent/app/repo"
"io/fs" "io/fs"
"os" "os"
"path" "path"
"strings" "strings"
"time" "time"
"github.com/1Panel-dev/1Panel/agent/app/repo"
"github.com/1Panel-dev/1Panel/agent/app/task" "github.com/1Panel-dev/1Panel/agent/app/task"
"github.com/1Panel-dev/1Panel/agent/i18n" "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) timeNow := time.Now().Format(constant.DateTimeSlimLayout)
itemDir := fmt.Sprintf("app/%s/%s", req.Name, req.DetailName) 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 fileName := req.FileName
if req.FileName == "" { if req.FileName == "" {
@ -226,7 +227,7 @@ func handleAppRecover(install *model.AppInstall, parentTask *task.Task, recoverF
} }
if !isRollback { 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 { 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)) t.Log(fmt.Sprintf("backup app %s for rollback before recover failed, err: %v", install.Name, err))
} }

View File

@ -2,13 +2,14 @@ package service
import ( import (
"fmt" "fmt"
"github.com/1Panel-dev/1Panel/agent/app/repo"
"os" "os"
"path" "path"
"path/filepath" "path/filepath"
"strings" "strings"
"time" "time"
"github.com/1Panel-dev/1Panel/agent/app/repo"
"github.com/1Panel-dev/1Panel/agent/constant" "github.com/1Panel-dev/1Panel/agent/constant"
"github.com/1Panel-dev/1Panel/agent/i18n" "github.com/1Panel-dev/1Panel/agent/i18n"
@ -26,7 +27,7 @@ import (
func (u *BackupService) MysqlBackup(req dto.CommonBackup) error { func (u *BackupService) MysqlBackup(req dto.CommonBackup) error {
timeNow := time.Now().Format(constant.DateTimeSlimLayout) timeNow := time.Now().Format(constant.DateTimeSlimLayout)
itemDir := fmt.Sprintf("database/%s/%s/%s", req.Type, req.Name, req.DetailName) 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)) fileName := fmt.Sprintf("%s_%s.sql.gz", req.DetailName, timeNow+common.RandStrAndNum(5))
databaseHelper := DatabaseHelper{Database: req.Name, DBType: req.Type, Name: req.DetailName} 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 { 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{ if err := cli.Backup(client.BackupInfo{
Name: req.DetailName, Name: req.DetailName,
Type: req.Type, Type: req.Type,

View File

@ -2,13 +2,14 @@ package service
import ( import (
"fmt" "fmt"
"github.com/1Panel-dev/1Panel/agent/app/repo"
"os" "os"
"path" "path"
"path/filepath" "path/filepath"
"strings" "strings"
"time" "time"
"github.com/1Panel-dev/1Panel/agent/app/repo"
"github.com/1Panel-dev/1Panel/agent/constant" "github.com/1Panel-dev/1Panel/agent/constant"
"github.com/1Panel-dev/1Panel/agent/i18n" "github.com/1Panel-dev/1Panel/agent/i18n"
@ -27,7 +28,7 @@ import (
func (u *BackupService) PostgresqlBackup(req dto.CommonBackup) error { func (u *BackupService) PostgresqlBackup(req dto.CommonBackup) error {
timeNow := time.Now().Format(constant.DateTimeSlimLayout) timeNow := time.Now().Format(constant.DateTimeSlimLayout)
itemDir := fmt.Sprintf("database/%s/%s/%s", req.Type, req.Name, req.DetailName) 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)) fileName := fmt.Sprintf("%s_%s.sql.gz", req.DetailName, timeNow+common.RandStrAndNum(5))
databaseHelper := DatabaseHelper{Database: req.Name, DBType: req.Type, Name: req.DetailName} 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() defer cli.Close()
if !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{ if err := cli.Backup(client.BackupInfo{
Name: req.DetailName, Name: req.DetailName,
TargetDir: path.Dir(rollbackFile), TargetDir: path.Dir(rollbackFile),

View File

@ -10,7 +10,6 @@ import (
"github.com/1Panel-dev/1Panel/agent/app/dto" "github.com/1Panel-dev/1Panel/agent/app/dto"
"github.com/1Panel-dev/1Panel/agent/app/model" "github.com/1Panel-dev/1Panel/agent/app/model"
"github.com/1Panel-dev/1Panel/agent/app/repo" "github.com/1Panel-dev/1Panel/agent/app/repo"
"github.com/1Panel-dev/1Panel/agent/constant"
"github.com/1Panel-dev/1Panel/agent/global" "github.com/1Panel-dev/1Panel/agent/global"
"github.com/jinzhu/copier" "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) return "", fmt.Errorf("new cloud storage client failed, err: %v", err)
} }
if account.Type == "LOCAL" { 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.Stat(path.Dir(targetPath)); err != nil && os.IsNotExist(err) {
if err = os.MkdirAll(path.Dir(targetPath), os.ModePerm); err != nil { if err = os.MkdirAll(path.Dir(targetPath), os.ModePerm); err != nil {
global.LOG.Errorf("mkdir %s failed, err: %v", path.Dir(targetPath), err) global.LOG.Errorf("mkdir %s failed, err: %v", path.Dir(targetPath), err)

View File

@ -43,7 +43,7 @@ func (u *BackupService) RedisBackup(req dto.CommonBackup) error {
} }
} }
itemDir := fmt.Sprintf("database/redis/%s", redisInfo.Name) 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 { if err := handleRedisBackup(redisInfo, nil, backupDir, fileName, req.Secret, req.TaskID); err != nil {
return err return err
} }
@ -101,7 +101,7 @@ func handleRedisBackup(redisInfo *repo.RootInfo, parentTask *task.Task, backupDi
} }
if strings.HasSuffix(fileName, ".tar.gz") { 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 { if err := fileOp.TarGzCompressPro(true, redisDataDir, path.Join(backupDir, fileName), secret, ""); err != nil {
return err return err
} }
@ -155,14 +155,14 @@ func handleRedisRecover(redisInfo *repo.RootInfo, parentTask *task.Task, recover
if appendonly == "yes" { if appendonly == "yes" {
if strings.HasPrefix(redisInfo.Version, "6.") && !strings.HasSuffix(recoverFile, ".aof") { 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") { if strings.HasPrefix(redisInfo.Version, "7.") && !strings.HasSuffix(recoverFile, ".tar.gz") {
return buserr.New(constant.ErrTypeOfRedis) return buserr.New("ErrTypeOfRedis")
} }
} else { } else {
if !strings.HasSuffix(recoverFile, ".rdb") { 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" 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 { 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) 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 { if _, err := compose.Down(composeDir + "/docker-compose.yml"); err != nil {
return err return err
} }
if appendonly == "yes" && strings.HasPrefix(redisInfo.Version, "7.") { 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 { if err := fileOp.TarGzExtractPro(recoverFile, redisDataDir, secret); err != nil {
return err return err
} }

View File

@ -72,7 +72,7 @@ func handleRuntimeRecover(runtime *model.Runtime, recoverFile string, isRollback
} }
if !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 { 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) 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.Rename(runtimeDir, backPath)
_ = fileOp.CreateDir(runtimeDir, constant.DirPerm) _ = 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) global.LOG.Errorf("handle recover from runtime.tar.gz failed, err: %v", err)
_ = fileOp.DeleteDir(runtimeDir) _ = fileOp.DeleteDir(runtimeDir)
_ = fileOp.Rename(backPath, runtimeDir) _ = fileOp.Rename(backPath, runtimeDir)
@ -109,7 +109,7 @@ func handleRuntimeRecover(runtime *model.Runtime, recoverFile string, isRollback
_ = fileOp.DeleteDir(backPath) _ = fileOp.DeleteDir(backPath)
if len(newEnvFile) != 0 { 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) file, err := os.OpenFile(envPath, os.O_WRONLY|os.O_TRUNC, 0640)
if err != nil { if err != nil {
return err return err

View File

@ -3,13 +3,14 @@ package service
import ( import (
"encoding/json" "encoding/json"
"fmt" "fmt"
"github.com/1Panel-dev/1Panel/agent/app/repo"
"io/fs" "io/fs"
"os" "os"
"path" "path"
"strings" "strings"
"time" "time"
"github.com/1Panel-dev/1Panel/agent/app/repo"
"github.com/1Panel-dev/1Panel/agent/app/task" "github.com/1Panel-dev/1Panel/agent/app/task"
"github.com/1Panel-dev/1Panel/agent/i18n" "github.com/1Panel-dev/1Panel/agent/i18n"
"github.com/1Panel-dev/1Panel/agent/utils/cmd" "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) timeNow := time.Now().Format(constant.DateTimeSlimLayout)
itemDir := fmt.Sprintf("website/%s", req.Name) 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)) fileName := fmt.Sprintf("%s_%s.tar.gz", website.Alias, timeNow+common.RandStrAndNum(5))
go func() { go func() {
@ -103,17 +104,17 @@ func handleWebsiteRecover(website *model.Website, recoverFile string, isRollback
temPathWithName := tmpPath + "/" + website.Alias temPathWithName := tmpPath + "/" + website.Alias
if !fileOp.Stat(tmpPath+"/website.json") || !fileOp.Stat(temPathWithName+".conf") || !fileOp.Stat(temPathWithName+".web.tar.gz") { 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 website.Type == constant.Deployment {
if !fileOp.Stat(temPathWithName + ".app.tar.gz") { 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 isOk := false
if !isRollback { 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 { 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) 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 return err
} }
t.LogSuccess(taskName) 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) t.LogFailedWithErr("Run", err)
return err return err
} }
@ -278,22 +279,22 @@ func handleWebsiteBackup(website *model.Website, backupDir, fileName, excludes,
func checkValidOfWebsite(oldWebsite, website *model.Website) error { func checkValidOfWebsite(oldWebsite, website *model.Website) error {
if oldWebsite.Alias != website.Alias || oldWebsite.Type != website.Type { 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 { if oldWebsite.AppInstallID != 0 {
_, err := appInstallRepo.GetFirst(repo.WithByID(oldWebsite.AppInstallID)) _, err := appInstallRepo.GetFirst(repo.WithByID(oldWebsite.AppInstallID))
if err != nil { if err != nil {
return buserr.WithDetail(constant.ErrBackupMatch, "app", nil) return buserr.WithDetail("ErrBackupMatch", "app", nil)
} }
} }
if oldWebsite.RuntimeID != 0 { if oldWebsite.RuntimeID != 0 {
if _, err := runtimeRepo.GetFirst(repo.WithByID(oldWebsite.RuntimeID)); err != nil { 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 oldWebsite.WebsiteSSLID != 0 {
if _, err := websiteSSLRepo.GetFirst(repo.WithByID(oldWebsite.WebsiteSSLID)); err != nil { 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 return nil

View File

@ -25,8 +25,6 @@ import (
"github.com/1Panel-dev/1Panel/agent/utils/xpack" "github.com/1Panel-dev/1Panel/agent/utils/xpack"
"github.com/jinzhu/copier" "github.com/jinzhu/copier"
"github.com/robfig/cron/v3" "github.com/robfig/cron/v3"
"github.com/pkg/errors"
) )
const ( const (
@ -139,7 +137,7 @@ func (c *ClamService) SearchWithPage(req dto.SearchClamWithPage) (int64, interfa
for _, command := range commands { for _, command := range commands {
var item dto.ClamInfo var item dto.ClamInfo
if err := copier.Copy(&item, &command); err != nil { 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 = "-" item.LastHandleDate = "-"
datas = append(datas, item) 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 { func (c *ClamService) Create(req dto.ClamCreate) error {
clam, _ := clamRepo.Get(repo.WithByName(req.Name)) clam, _ := clamRepo.Get(repo.WithByName(req.Name))
if clam.ID != 0 { if clam.ID != 0 {
return constant.ErrRecordExist return buserr.New("ErrRecordExist")
} }
if err := copier.Copy(&clam, &req); err != nil { 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" { if clam.InfectedStrategy == "none" || clam.InfectedStrategy == "remove" {
clam.InfectedDir = "" clam.InfectedDir = ""
@ -211,14 +209,14 @@ func (c *ClamService) Create(req dto.ClamCreate) error {
func (c *ClamService) Update(req dto.ClamUpdate) error { func (c *ClamService) Update(req dto.ClamUpdate) error {
clam, _ := clamRepo.Get(repo.WithByName(req.Name)) clam, _ := clamRepo.Get(repo.WithByName(req.Name))
if clam.ID == 0 { if clam.ID == 0 {
return constant.ErrRecordNotFound return buserr.New("ErrRecordNotFound")
} }
if req.InfectedStrategy == "none" || req.InfectedStrategy == "remove" { if req.InfectedStrategy == "none" || req.InfectedStrategy == "remove" {
req.InfectedDir = "" req.InfectedDir = ""
} }
var clamItem model.Clam var clamItem model.Clam
if err := copier.Copy(&clamItem, &req); err != nil { 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 clamItem.EntryID = clam.EntryID
upMap := map[string]interface{}{} 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 { func (c *ClamService) UpdateStatus(id uint, status string) error {
clam, _ := clamRepo.Get(repo.WithByID(id)) clam, _ := clamRepo.Get(repo.WithByID(id))
if clam.ID == 0 { if clam.ID == 0 {
return constant.ErrRecordNotFound return buserr.New("ErrRecordNotFound")
} }
var ( var (
entryID int entryID int
@ -292,7 +290,7 @@ func (c *ClamService) Delete(req dto.ClamDelete) error {
continue continue
} }
if req.RemoveRecord { 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 { if req.RemoveInfected {
_ = os.RemoveAll(path.Join(clam.InfectedDir, "1panel-infected", clam.Name)) _ = 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)) clam, _ := clamRepo.Get(repo.WithByID(req.ID))
if clam.ID == 0 { if clam.ID == 0 {
return constant.ErrRecordNotFound return buserr.New("ErrRecordNotFound")
} }
if cmd.CheckIllegal(clam.Path) { if cmd.CheckIllegal(clam.Path) {
return buserr.New(constant.ErrCmdIllegal) return buserr.New("ErrCmdIllegal")
} }
timeNow := time.Now().Format(constant.DateTimeSlimLayout) 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 { if _, err := os.Stat(path.Dir(logFile)); err != nil {
_ = os.MkdirAll(path.Dir(logFile), os.ModePerm) _ = 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) { func (c *ClamService) LoadRecords(req dto.ClamLogSearch) (int64, interface{}, error) {
clam, _ := clamRepo.Get(repo.WithByID(req.ClamID)) clam, _ := clamRepo.Get(repo.WithByID(req.ClamID))
if clam.ID == 0 { if clam.ID == 0 {
return 0, nil, constant.ErrRecordNotFound return 0, nil, buserr.New("ErrRecordNotFound")
} }
logPaths := loadFileByName(clam.Name) logPaths := loadFileByName(clam.Name)
if len(logPaths) == 0 { if len(logPaths) == 0 {
@ -398,13 +396,13 @@ func (c *ClamService) LoadRecords(req dto.ClamLogSearch) (int64, interface{}, er
var datas []dto.ClamLog var datas []dto.ClamLog
for i := 0; i < len(records); i++ { 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) datas = append(datas, item)
} }
return int64(total), datas, nil return int64(total), datas, nil
} }
func (c *ClamService) LoadRecordLog(req dto.ClamLogReq) (string, error) { 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 var tail string
if req.Tail != "0" { if req.Tail != "0" {
tail = req.Tail tail = req.Tail
@ -422,9 +420,9 @@ func (c *ClamService) LoadRecordLog(req dto.ClamLogReq) (string, error) {
func (c *ClamService) CleanRecord(req dto.OperateByID) error { func (c *ClamService) CleanRecord(req dto.OperateByID) error {
clam, _ := clamRepo.Get(repo.WithByID(req.ID)) clam, _ := clamRepo.Get(repo.WithByID(req.ID))
if clam.ID == 0 { 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) _ = os.RemoveAll(pathItem)
return nil return nil
} }
@ -544,7 +542,7 @@ func StopAllCronJob(withCheck bool) bool {
func loadFileByName(name string) []string { func loadFileByName(name string) []string {
var logPaths []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 { _ = filepath.Walk(pathItem, func(path string, info os.FileInfo, err error) error {
if err != nil { if err != nil {
return nil return nil

View File

@ -3,9 +3,8 @@ package service
import ( import (
"github.com/1Panel-dev/1Panel/agent/app/dto" "github.com/1Panel-dev/1Panel/agent/app/dto"
"github.com/1Panel-dev/1Panel/agent/app/repo" "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/jinzhu/copier"
"github.com/pkg/errors"
) )
type ComposeTemplateService struct{} type ComposeTemplateService struct{}
@ -25,13 +24,13 @@ func NewIComposeTemplateService() IComposeTemplateService {
func (u *ComposeTemplateService) List() ([]dto.ComposeTemplateInfo, error) { func (u *ComposeTemplateService) List() ([]dto.ComposeTemplateInfo, error) {
composes, err := composeRepo.List() composes, err := composeRepo.List()
if err != nil { if err != nil {
return nil, constant.ErrRecordNotFound return nil, buserr.New("ErrRecordNotFound")
} }
var dtoLists []dto.ComposeTemplateInfo var dtoLists []dto.ComposeTemplateInfo
for _, compose := range composes { for _, compose := range composes {
var item dto.ComposeTemplateInfo var item dto.ComposeTemplateInfo
if err := copier.Copy(&item, &compose); err != nil { 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) dtoLists = append(dtoLists, item)
} }
@ -44,7 +43,7 @@ func (u *ComposeTemplateService) SearchWithPage(req dto.SearchWithPage) (int64,
for _, compose := range composes { for _, compose := range composes {
var item dto.ComposeTemplateInfo var item dto.ComposeTemplateInfo
if err := copier.Copy(&item, &compose); err != nil { 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) dtoComposeTemplates = append(dtoComposeTemplates, item)
} }
@ -54,10 +53,10 @@ func (u *ComposeTemplateService) SearchWithPage(req dto.SearchWithPage) (int64,
func (u *ComposeTemplateService) Create(composeDto dto.ComposeTemplateCreate) error { func (u *ComposeTemplateService) Create(composeDto dto.ComposeTemplateCreate) error {
compose, _ := composeRepo.Get(repo.WithByName(composeDto.Name)) compose, _ := composeRepo.Get(repo.WithByName(composeDto.Name))
if compose.ID != 0 { if compose.ID != 0 {
return constant.ErrRecordExist return buserr.New("ErrRecordExist")
} }
if err := copier.Copy(&compose, &composeDto); err != nil { 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 { if err := composeRepo.Create(&compose); err != nil {
return err return err
@ -69,7 +68,7 @@ func (u *ComposeTemplateService) Delete(ids []uint) error {
if len(ids) == 1 { if len(ids) == 1 {
compose, _ := composeRepo.Get(repo.WithByID(ids[0])) compose, _ := composeRepo.Get(repo.WithByID(ids[0]))
if compose.ID == 0 { if compose.ID == 0 {
return constant.ErrRecordNotFound return buserr.New("ErrRecordNotFound")
} }
return composeRepo.Delete(repo.WithByID(ids[0])) return composeRepo.Delete(repo.WithByID(ids[0]))
} }

View File

@ -317,7 +317,7 @@ func (u *ContainerService) ContainerListStats() ([]dto.ContainerListStats, error
func (u *ContainerService) ContainerCreateByCommand(req dto.ContainerCreateByCommand) error { func (u *ContainerService) ContainerCreateByCommand(req dto.ContainerCreateByCommand) error {
if cmd.CheckIllegal(req.Command) { if cmd.CheckIllegal(req.Command) {
return buserr.New(constant.ErrCmdIllegal) return buserr.New("ErrCmdIllegal")
} }
if !strings.HasPrefix(strings.TrimSpace(req.Command), "docker run ") { if !strings.HasPrefix(strings.TrimSpace(req.Command), "docker run ") {
return errors.New("error command format") return errors.New("error command format")
@ -343,7 +343,7 @@ func (u *ContainerService) ContainerCreateByCommand(req dto.ContainerCreateByCom
} }
go func() { go func() {
taskItem.AddSubTask(i18n.GetWithName("ContainerCreate", containerName), func(t *task.Task) error { 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) return cmd.ExecShell(logPath, 5*time.Minute, "bash", "-c", req.Command)
}, nil) }, nil)
_ = taskItem.Execute() _ = taskItem.Execute()
@ -466,7 +466,7 @@ func (u *ContainerService) ContainerCreate(req dto.ContainerOperate) error {
ctx := context.Background() ctx := context.Background()
newContainer, _ := client.ContainerInspect(ctx, req.Name) newContainer, _ := client.ContainerInspect(ctx, req.Name)
if newContainer.ContainerJSONBase != nil { 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) 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() ctx := context.Background()
newContainer, _ := client.ContainerInspect(ctx, req.Name) newContainer, _ := client.ContainerInspect(ctx, req.Name)
if newContainer.ContainerJSONBase != nil && newContainer.ID != req.ContainerID { if newContainer.ContainerJSONBase != nil && newContainer.ID != req.ContainerID {
return buserr.New(constant.ErrContainerName) return buserr.New("ErrContainerName")
} }
oldContainer, err := client.ContainerInspect(ctx, req.ContainerID) 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) newContainer, _ := client.ContainerInspect(ctx, req.NewName)
if newContainer.ContainerJSONBase != nil { if newContainer.ContainerJSONBase != nil {
return buserr.New(constant.ErrContainerName) return buserr.New("ErrContainerName")
} }
return client.ContainerRename(ctx, req.Name, req.NewName) 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 { func (u *ContainerService) DownloadContainerLogs(containerType, container, since, tail string, c *gin.Context) error {
if cmd.CheckIllegal(container, since, tail) { if cmd.CheckIllegal(container, since, tail) {
return buserr.New(constant.ErrCmdIllegal) return buserr.New("ErrCmdIllegal")
} }
commandName := "docker" commandName := "docker"
commandArg := []string{"logs", container} commandArg := []string{"logs", container}
@ -1192,17 +1192,17 @@ func checkPortStats(ports []dto.PortHelper) (nat.PortMap, error) {
for _, port := range ports { for _, port := range ports {
if strings.Contains(port.ContainerPort, "-") { if strings.Contains(port.ContainerPort, "-") {
if !strings.Contains(port.HostPort, "-") { if !strings.Contains(port.HostPort, "-") {
return portMap, buserr.New(constant.ErrPortRules) return portMap, buserr.New("ErrPortRules")
} }
hostStart, _ := strconv.Atoi(strings.Split(port.HostPort, "-")[0]) hostStart, _ := strconv.Atoi(strings.Split(port.HostPort, "-")[0])
hostEnd, _ := strconv.Atoi(strings.Split(port.HostPort, "-")[1]) hostEnd, _ := strconv.Atoi(strings.Split(port.HostPort, "-")[1])
containerStart, _ := strconv.Atoi(strings.Split(port.ContainerPort, "-")[0]) containerStart, _ := strconv.Atoi(strings.Split(port.ContainerPort, "-")[0])
containerEnd, _ := strconv.Atoi(strings.Split(port.ContainerPort, "-")[1]) containerEnd, _ := strconv.Atoi(strings.Split(port.ContainerPort, "-")[1])
if (hostEnd-hostStart) <= 0 || (containerEnd-containerStart) <= 0 { if (hostEnd-hostStart) <= 0 || (containerEnd-containerStart) <= 0 {
return portMap, buserr.New(constant.ErrPortRules) return portMap, buserr.New("ErrPortRules")
} }
if (containerEnd - containerStart) != (hostEnd - hostStart) { if (containerEnd - containerStart) != (hostEnd - hostStart) {
return portMap, buserr.New(constant.ErrPortRules) return portMap, buserr.New("ErrPortRules")
} }
for i := 0; i <= hostEnd-hostStart; i++ { for i := 0; i <= hostEnd-hostStart; i++ {
bindItem := nat.PortBinding{HostPort: strconv.Itoa(hostStart + i), HostIP: port.HostIP} 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++ { for i := hostStart; i <= hostEnd; i++ {
if common.ScanPort(i) { if common.ScanPort(i) {
return portMap, buserr.WithDetail(constant.ErrPortInUsed, i, nil) return portMap, buserr.WithDetail("ErrPortInUsed", i, nil)
} }
} }
} else { } else {
@ -1221,7 +1221,7 @@ func checkPortStats(ports []dto.PortHelper) (nat.PortMap, error) {
portItem, _ = strconv.Atoi(port.HostPort) portItem, _ = strconv.Atoi(port.HostPort)
} }
if common.ScanPort(portItem) { 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} bindItem := nat.PortBinding{HostPort: strconv.Itoa(portItem), HostIP: port.HostIP}
portMap[nat.Port(fmt.Sprintf("%s/%s", port.ContainerPort, port.Protocol))] = []nat.PortBinding{bindItem} portMap[nat.Port(fmt.Sprintf("%s/%s", port.ContainerPort, port.Protocol))] = []nat.PortBinding{bindItem}

View File

@ -4,7 +4,6 @@ import (
"bufio" "bufio"
"errors" "errors"
"fmt" "fmt"
"github.com/1Panel-dev/1Panel/agent/app/repo"
"os" "os"
"os/exec" "os/exec"
"path" "path"
@ -12,6 +11,8 @@ import (
"strings" "strings"
"time" "time"
"github.com/1Panel-dev/1Panel/agent/app/repo"
"github.com/docker/docker/api/types/container" "github.com/docker/docker/api/types/container"
"github.com/1Panel-dev/1Panel/agent/app/dto" "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) { func (u *ContainerService) TestCompose(req dto.ComposeCreate) (bool, error) {
if cmd.CheckIllegal(req.Path) { if cmd.CheckIllegal(req.Path) {
return false, buserr.New(constant.ErrCmdIllegal) return false, buserr.New("ErrCmdIllegal")
} }
composeItem, _ := composeRepo.GetRecord(repo.WithByName(req.Name)) composeItem, _ := composeRepo.GetRecord(repo.WithByName(req.Name))
if composeItem.ID != 0 { if composeItem.ID != 0 {
return false, constant.ErrRecordExist return false, buserr.New("ErrRecordExist")
} }
if err := u.loadPath(&req); err != nil { if err := u.loadPath(&req); err != nil {
return false, err return false, err
@ -183,7 +184,7 @@ func (u *ContainerService) TestCompose(req dto.ComposeCreate) (bool, error) {
func (u *ContainerService) CreateCompose(req dto.ComposeCreate) error { func (u *ContainerService) CreateCompose(req dto.ComposeCreate) error {
if cmd.CheckIllegal(req.Name, req.Path) { if cmd.CheckIllegal(req.Name, req.Path) {
return buserr.New(constant.ErrCmdIllegal) return buserr.New("ErrCmdIllegal")
} }
if err := u.loadPath(&req); err != nil { if err := u.loadPath(&req); err != nil {
return err return err
@ -222,7 +223,7 @@ func (u *ContainerService) ComposeOperation(req dto.ComposeOperation) error {
return nil return nil
} }
if cmd.CheckIllegal(req.Path, req.Operation) { if cmd.CheckIllegal(req.Path, req.Operation) {
return buserr.New(constant.ErrCmdIllegal) return buserr.New("ErrCmdIllegal")
} }
if _, err := os.Stat(req.Path); err != nil { if _, err := os.Stat(req.Path); err != nil {
return fmt.Errorf("load file with path %s failed, %v", req.Path, err) 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 { func (u *ContainerService) ComposeUpdate(req dto.ComposeUpdate) error {
if cmd.CheckIllegal(req.Name, req.Path) { if cmd.CheckIllegal(req.Name, req.Path) {
return buserr.New(constant.ErrCmdIllegal) return buserr.New("ErrCmdIllegal")
} }
oldFile, err := os.ReadFile(req.Path) oldFile, err := os.ReadFile(req.Path)
if err != nil { if err != nil {
@ -291,7 +292,7 @@ func (u *ContainerService) ComposeUpdate(req dto.ComposeUpdate) error {
func (u *ContainerService) loadPath(req *dto.ComposeCreate) error { func (u *ContainerService) loadPath(req *dto.ComposeCreate) error {
if req.From == "template" || req.From == "edit" { 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.Stat(dir); err != nil && os.IsNotExist(err) {
if err = os.MkdirAll(dir, os.ModePerm); err != nil { if err = os.MkdirAll(dir, os.ModePerm); err != nil {
return err return err

View File

@ -8,7 +8,6 @@ import (
"github.com/1Panel-dev/1Panel/agent/app/dto" "github.com/1Panel-dev/1Panel/agent/app/dto"
"github.com/1Panel-dev/1Panel/agent/buserr" "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/docker"
"github.com/docker/docker/api/types/network" "github.com/docker/docker/api/types/network"
) )
@ -105,7 +104,7 @@ func (u *ContainerService) DeleteNetwork(req dto.BatchDelete) error {
for _, id := range req.Names { for _, id := range req.Names {
if err := client.NetworkRemove(context.TODO(), id); err != nil { if err := client.NetworkRemove(context.TODO(), id); err != nil {
if strings.Contains(err.Error(), "has active endpoints") { if strings.Contains(err.Error(), "has active endpoints") {
return buserr.WithDetail(constant.ErrInUsed, id, nil) return buserr.WithDetail("ErrInUsed", id, nil)
} }
return err return err
} }

View File

@ -8,7 +8,6 @@ import (
"github.com/1Panel-dev/1Panel/agent/app/dto" "github.com/1Panel-dev/1Panel/agent/app/dto"
"github.com/1Panel-dev/1Panel/agent/buserr" "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/common"
"github.com/1Panel-dev/1Panel/agent/utils/docker" "github.com/1Panel-dev/1Panel/agent/utils/docker"
"github.com/docker/docker/api/types/filters" "github.com/docker/docker/api/types/filters"
@ -107,7 +106,7 @@ func (u *ContainerService) DeleteVolume(req dto.BatchDelete) error {
for _, id := range req.Names { for _, id := range req.Names {
if err := client.VolumeRemove(context.TODO(), id, true); err != nil { if err := client.VolumeRemove(context.TODO(), id, true); err != nil {
if strings.Contains(err.Error(), "volume is in use") { if strings.Contains(err.Error(), "volume is in use") {
return buserr.WithDetail(constant.ErrInUsed, id, nil) return buserr.WithDetail("ErrInUsed", id, nil)
} }
return err return err
} }
@ -126,7 +125,7 @@ func (u *ContainerService) CreateVolume(req dto.VolumeCreate) error {
if len(vos.Volumes) != 0 { if len(vos.Volumes) != 0 {
for _, v := range vos.Volumes { for _, v := range vos.Volumes {
if v.Name == req.Name { if v.Name == req.Name {
return constant.ErrRecordExist return buserr.New("ErrRecordExist")
} }
} }
} }

View File

@ -10,6 +10,7 @@ import (
"time" "time"
"github.com/1Panel-dev/1Panel/agent/app/repo" "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/utils/xpack"
"github.com/1Panel-dev/1Panel/agent/app/dto" "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 { for _, cronjob := range cronjobs {
var item dto.CronjobInfo var item dto.CronjobInfo
if err := copier.Copy(&item, &cronjob); err != nil { 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) record, _ := cronjobRepo.RecordFirst(cronjob.ID)
if record.ID != 0 { if record.ID != 0 {
@ -85,7 +86,7 @@ func (u *CronjobService) SearchRecords(search dto.SearchRecord) (int64, interfac
for _, record := range records { for _, record := range records {
var item dto.Record var item dto.Record
if err := copier.Copy(&item, &record); err != nil { 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) item.StartTime = record.StartTime.Format(constant.DateTimeLayout)
dtoCronjobs = append(dtoCronjobs, item) 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) { func (u *CronjobService) Download(req dto.CronjobDownload) (string, error) {
record, _ := cronjobRepo.GetRecord(repo.WithByID(req.RecordID)) record, _ := cronjobRepo.GetRecord(repo.WithByID(req.RecordID))
if record.ID == 0 { if record.ID == 0 {
return "", constant.ErrRecordNotFound return "", buserr.New("ErrRecordNotFound")
} }
account, client, err := NewBackupClientWithID(req.BackupAccountID) account, client, err := NewBackupClientWithID(req.BackupAccountID)
if err != nil { if err != nil {
@ -177,7 +178,7 @@ func (u *CronjobService) Download(req dto.CronjobDownload) (string, error) {
} }
return record.File, nil 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) { if _, err := os.Stat(tempPath); err != nil && os.IsNotExist(err) {
_ = os.MkdirAll(path.Dir(tempPath), os.ModePerm) _ = os.MkdirAll(path.Dir(tempPath), os.ModePerm)
isOK, err := client.Download(record.File, tempPath) 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 { func (u *CronjobService) HandleOnce(id uint) error {
cronjob, _ := cronjobRepo.Get(repo.WithByID(id)) cronjob, _ := cronjobRepo.Get(repo.WithByID(id))
if cronjob.ID == 0 { if cronjob.ID == 0 {
return constant.ErrRecordNotFound return buserr.New("ErrRecordNotFound")
} }
u.HandleJob(&cronjob) u.HandleJob(&cronjob)
return nil return nil
@ -200,11 +201,11 @@ func (u *CronjobService) HandleOnce(id uint) error {
func (u *CronjobService) Create(req dto.CronjobCreate) error { func (u *CronjobService) Create(req dto.CronjobCreate) error {
cronjob, _ := cronjobRepo.Get(repo.WithByName(req.Name)) cronjob, _ := cronjobRepo.Get(repo.WithByName(req.Name))
if cronjob.ID != 0 { if cronjob.ID != 0 {
return constant.ErrRecordExist return buserr.New("ErrRecordExist")
} }
cronjob.Secret = req.Secret cronjob.Secret = req.Secret
if err := copier.Copy(&cronjob, &req); err != nil { 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 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 { func (u *CronjobService) Update(id uint, req dto.CronjobUpdate) error {
var cronjob model.Cronjob var cronjob model.Cronjob
if err := copier.Copy(&cronjob, &req); err != nil { 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)) cronModel, err := cronjobRepo.Get(repo.WithByID(id))
if err != nil { if err != nil {
return constant.ErrRecordNotFound return buserr.New("ErrRecordNotFound")
} }
upMap := make(map[string]interface{}) upMap := make(map[string]interface{})
cronjob.EntryIDs = cronModel.EntryIDs 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 { func (u *CronjobService) UpdateStatus(id uint, status string) error {
cronjob, _ := cronjobRepo.Get(repo.WithByID(id)) cronjob, _ := cronjobRepo.Get(repo.WithByID(id))
if cronjob.ID == 0 { if cronjob.ID == 0 {
return errors.WithMessage(constant.ErrRecordNotFound, "record not found") return errors.WithMessage(buserr.New("ErrRecordNotFound"), "record not found")
} }
var ( var (
entryIDs string 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) { 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.Stat(dir); err != nil && os.IsNotExist(err) {
if err = os.MkdirAll(dir, os.ModePerm); err != nil { if err = os.MkdirAll(dir, os.ModePerm); err != nil {
return "", err return "", err

View File

@ -2,13 +2,14 @@ package service
import ( import (
"fmt" "fmt"
"github.com/1Panel-dev/1Panel/agent/app/repo"
"os" "os"
"path" "path"
"strconv" "strconv"
"strings" "strings"
"time" "time"
"github.com/1Panel-dev/1Panel/agent/app/repo"
"github.com/1Panel-dev/1Panel/agent/app/dto" "github.com/1Panel-dev/1Panel/agent/app/dto"
"github.com/1Panel-dev/1Panel/agent/app/model" "github.com/1Panel-dev/1Panel/agent/app/model"
"github.com/1Panel-dev/1Panel/agent/constant" "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.Name = app.App.Key
record.DetailName = app.Name record.DetailName = app.Name
record.DownloadAccountID, record.SourceAccountIDs = cronjob.DownloadAccountID, cronjob.SourceAccountIDs 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)) 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 { if err := handleAppBackup(&app, nil, backupDir, record.FileName, cronjob.ExclusionRules, cronjob.Secret, taskID); err != nil {
return err return err
@ -81,7 +82,7 @@ func (u *CronjobService) handleWebsite(cronjob model.Cronjob, startTime time.Tim
record.Name = web.PrimaryDomain record.Name = web.PrimaryDomain
record.DetailName = web.Alias record.DetailName = web.Alias
record.DownloadAccountID, record.SourceAccountIDs = cronjob.DownloadAccountID, cronjob.SourceAccountIDs 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)) 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 { if err := handleWebsiteBackup(&web, backupDir, record.FileName, cronjob.ExclusionRules, cronjob.Secret, taskID); err != nil {
return err return err
@ -118,7 +119,7 @@ func (u *CronjobService) handleDatabase(cronjob model.Cronjob, startTime time.Ti
record.DetailName = dbInfo.Name record.DetailName = dbInfo.Name
record.DownloadAccountID, record.SourceAccountIDs = cronjob.DownloadAccountID, cronjob.SourceAccountIDs 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)) 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 cronjob.DBType == "mysql" || cronjob.DBType == "mariadb" {
if err := handleMysqlBackup(dbInfo, nil, backupDir, record.FileName, taskID); err != nil { 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 return err
} }
fileName := fmt.Sprintf("directory%s_%s.tar.gz", strings.ReplaceAll(cronjob.SourceDir, "/", "_"), startTime.Format(constant.DateTimeSlimLayout)+common.RandStrAndNum(5)) 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() fileOp := files.NewFileOp()
if cronjob.IsDir { 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) nameItem := startTime.Format(constant.DateTimeSlimLayout) + common.RandStrAndNum(5)
fileName := fmt.Sprintf("system_log_%s.tar.gz", nameItem) 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 { if err := handleBackupLogs(backupDir, fileName, cronjob.Secret); err != nil {
return err 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) logFiles2, _ := os.ReadDir(itemDir2)
if len(logFiles2) != 0 { if len(logFiles2) != 0 {
for i := 0; i < len(logFiles2); i++ { 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!") global.LOG.Debug("backup website log successful!")
} }
systemLogDir := path.Join(global.CONF.System.BaseDir, "1panel/log")
systemDir := path.Join(targetDir, "system") systemDir := path.Join(targetDir, "system")
if _, err := os.Stat(systemDir); err != nil && os.IsNotExist(err) { if _, err := os.Stat(systemDir); err != nil && os.IsNotExist(err) {
if err = os.MkdirAll(systemDir, os.ModePerm); err != nil { if err = os.MkdirAll(systemDir, os.ModePerm); err != nil {
return err return err
} }
} }
systemLogFiles, _ := os.ReadDir(systemLogDir) systemLogFiles, _ := os.ReadDir(global.Dir.LogDir)
if len(systemLogFiles) != 0 { if len(systemLogFiles) != 0 {
for i := 0; i < len(systemLogFiles); i++ { for i := 0; i < len(systemLogFiles); i++ {
if !systemLogFiles[i].IsDir() { if !systemLogFiles[i].IsDir() {
_ = fileOp.CopyFile(path.Join(systemLogDir, systemLogFiles[i].Name()), systemDir) _ = fileOp.CopyFile(path.Join(global.Dir.LogDir, systemLogFiles[i].Name()), systemDir)
} }
} }
} }

View File

@ -104,7 +104,7 @@ func (u *CronjobService) handleShell(cronjob model.Cronjob, taskID string) error
cronjob.Executor = "bash" cronjob.Executor = "bash"
} }
if cronjob.ScriptMode == "input" { 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) _ = os.MkdirAll(pathUtils.Dir(fileItem), os.ModePerm)
shellFile, err := os.OpenFile(fileItem, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, constant.FilePerm) shellFile, err := os.OpenFile(fileItem, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, constant.FilePerm)
if err != nil { if err != nil {
@ -192,7 +192,7 @@ func (u *CronjobService) handleCutWebsiteLog(cronjob *model.Cronjob, startTime t
websiteLogDir := pathUtils.Join(baseDir, website.Alias, "log") websiteLogDir := pathUtils.Join(baseDir, website.Alias, "log")
srcAccessLogPath := pathUtils.Join(websiteLogDir, "access.log") srcAccessLogPath := pathUtils.Join(websiteLogDir, "access.log")
srcErrorLogPath := pathUtils.Join(websiteLogDir, "error.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) { if !fileOp.Stat(dstLogDir) {
_ = os.MkdirAll(dstLogDir, constant.DirPerm) _ = os.MkdirAll(dstLogDir, constant.DirPerm)
} }
@ -251,7 +251,7 @@ func (u *CronjobService) uploadCronjobBackFile(cronjob model.Cronjob, accountMap
_ = os.Remove(file) _ = os.Remove(file)
}() }()
accounts := strings.Split(cronjob.SourceAccountIDs, ",") accounts := strings.Split(cronjob.SourceAccountIDs, ",")
cloudSrc := strings.TrimPrefix(file, global.CONF.System.TmpDir+"/") cloudSrc := strings.TrimPrefix(file, global.Dir.TmpDir+"/")
for _, account := range accounts { for _, account := range accounts {
if len(account) != 0 { if len(account) != 0 {
global.LOG.Debugf("start upload file to %s, dir: %s", accountMap[account].name, pathUtils.Join(accountMap[account].backupPath, cloudSrc)) global.LOG.Debugf("start upload file to %s, dir: %s", accountMap[account].name, pathUtils.Join(accountMap[account].backupPath, cloudSrc))

View File

@ -11,6 +11,7 @@ import (
"time" "time"
"github.com/1Panel-dev/1Panel/agent/app/repo" "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/dto"
"github.com/1Panel-dev/1Panel/agent/app/model" "github.com/1Panel-dev/1Panel/agent/app/model"
@ -62,12 +63,12 @@ func (u *DashboardService) Sync(req dto.SyncFromMaster) error {
return launcherRepo.Create(&launcherItem) return launcherRepo.Create(&launcherItem)
case "delete": case "delete":
if launcher.ID == 0 { if launcher.ID == 0 {
return constant.ErrRecordNotFound return buserr.New("ErrRecordNotFound")
} }
return launcherRepo.Delete(repo.WithByID(launcher.ID)) return launcherRepo.Delete(repo.WithByID(launcher.ID))
case "update": case "update":
if launcher.ID == 0 { if launcher.ID == 0 {
return constant.ErrRecordNotFound return buserr.New("ErrRecordNotFound")
} }
launcherItem.ID = launcher.ID launcherItem.ID = launcher.ID
return launcherRepo.Save(&launcherItem) return launcherRepo.Save(&launcherItem)
@ -105,7 +106,7 @@ func (u *DashboardService) LoadOsInfo() (*dto.OsInfo, error) {
baseInfo.KernelArch = hostInfo.KernelArch baseInfo.KernelArch = hostInfo.KernelArch
baseInfo.KernelVersion = hostInfo.KernelVersion baseInfo.KernelVersion = hostInfo.KernelVersion
diskInfo, err := disk.Usage(global.CONF.System.BaseDir) diskInfo, err := disk.Usage(global.Dir.BaseDir)
if err == nil { if err == nil {
baseInfo.DiskSize = int64(diskInfo.Free) baseInfo.DiskSize = int64(diskInfo.Free)
} }

View File

@ -3,10 +3,11 @@ package service
import ( import (
"context" "context"
"fmt" "fmt"
"github.com/1Panel-dev/1Panel/agent/app/repo"
"os" "os"
"path" "path"
"github.com/1Panel-dev/1Panel/agent/app/repo"
"github.com/1Panel-dev/1Panel/agent/utils/postgresql" "github.com/1Panel-dev/1Panel/agent/utils/postgresql"
pgclient "github.com/1Panel-dev/1Panel/agent/utils/postgresql/client" pgclient "github.com/1Panel-dev/1Panel/agent/utils/postgresql/client"
redisclient "github.com/1Panel-dev/1Panel/agent/utils/redis" 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 { for _, db := range dbs {
var item dto.DatabaseInfo var item dto.DatabaseInfo
if err := copier.Copy(&item, &db); err != nil { 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) datas = append(datas, item)
} }
@ -65,7 +66,7 @@ func (u *DatabaseService) Get(name string) (dto.DatabaseInfo, error) {
return data, err return data, err
} }
if err := copier.Copy(&data, &remote); err != nil { 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 return data, nil
} }
@ -79,7 +80,7 @@ func (u *DatabaseService) List(dbType string) ([]dto.DatabaseOption, error) {
for _, db := range dbs { for _, db := range dbs {
var item dto.DatabaseOption var item dto.DatabaseOption
if err := copier.Copy(&item, &db); err != nil { 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 item.Database = db.Name
datas = append(datas, item) datas = append(datas, item)
@ -160,9 +161,9 @@ func (u *DatabaseService) Create(req dto.DatabaseCreate) error {
db, _ := databaseRepo.Get(repo.WithByName(req.Name)) db, _ := databaseRepo.Get(repo.WithByName(req.Name))
if db.ID != 0 { if db.ID != 0 {
if db.From == "local" { if db.From == "local" {
return buserr.New(constant.ErrLocalExist) return buserr.New("ErrLocalExist")
} }
return constant.ErrRecordExist return buserr.New("ErrRecordExist")
} }
switch req.Type { switch req.Type {
case constant.AppPostgresql: case constant.AppPostgresql:
@ -206,7 +207,7 @@ func (u *DatabaseService) Create(req dto.DatabaseCreate) error {
} }
if err := copier.Copy(&db, &req); err != nil { 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 { if err := databaseRepo.Create(context.Background(), &db); err != nil {
return err return err
@ -230,15 +231,15 @@ func (u *DatabaseService) DeleteCheck(id uint) ([]string, error) {
func (u *DatabaseService) Delete(req dto.DatabaseDelete) error { func (u *DatabaseService) Delete(req dto.DatabaseDelete) error {
db, _ := databaseRepo.Get(repo.WithByID(req.ID)) db, _ := databaseRepo.Get(repo.WithByID(req.ID))
if db.ID == 0 { if db.ID == 0 {
return constant.ErrRecordNotFound return buserr.New("ErrRecordNotFound")
} }
if req.DeleteBackup { 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 { if _, err := os.Stat(uploadDir); err == nil {
_ = os.RemoveAll(uploadDir) _ = 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 { if _, err := os.Stat(backupDir); err == nil {
_ = os.RemoveAll(backupDir) _ = os.RemoveAll(backupDir)
} }

View File

@ -43,17 +43,17 @@ func (u *DBCommonService) LoadDatabaseFile(req dto.OperationWithNameAndType) (st
filePath := "" filePath := ""
switch req.Type { switch req.Type {
case "mysql-conf": 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": 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": 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": 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": 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": 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 { if _, err := os.Stat(filePath); err != nil {
return "", buserr.New("ErrHttpReqNotFound") return "", buserr.New("ErrHttpReqNotFound")
@ -73,11 +73,11 @@ func (u *DBCommonService) UpdateConfByFile(req dto.DBConfUpdateByFile) error {
path := "" path := ""
switch req.Type { switch req.Type {
case constant.AppMariaDB, constant.AppMysql: 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: 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: 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) file, err := os.OpenFile(path, os.O_WRONLY|os.O_TRUNC, 0640)
if err != nil { if err != nil {
@ -87,7 +87,7 @@ func (u *DBCommonService) UpdateConfByFile(req dto.DBConfUpdateByFile) error {
write := bufio.NewWriter(file) write := bufio.NewWriter(file)
_, _ = write.WriteString(req.File) _, _ = write.WriteString(req.File)
write.Flush() 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 err
} }
return nil return nil

View File

@ -4,7 +4,6 @@ import (
"context" "context"
"encoding/json" "encoding/json"
"fmt" "fmt"
"github.com/1Panel-dev/1Panel/agent/app/repo"
"os" "os"
"os/exec" "os/exec"
"path" "path"
@ -13,6 +12,8 @@ import (
"strings" "strings"
"time" "time"
"github.com/1Panel-dev/1Panel/agent/app/repo"
"github.com/1Panel-dev/1Panel/agent/app/dto" "github.com/1Panel-dev/1Panel/agent/app/dto"
"github.com/1Panel-dev/1Panel/agent/app/model" "github.com/1Panel-dev/1Panel/agent/app/model"
"github.com/1Panel-dev/1Panel/agent/buserr" "github.com/1Panel-dev/1Panel/agent/buserr"
@ -63,7 +64,7 @@ func (u *MysqlService) SearchWithPage(search dto.MysqlDBSearch) (int64, interfac
for _, mysql := range mysqls { for _, mysql := range mysqls {
var item dto.MysqlDBInfo var item dto.MysqlDBInfo
if err := copier.Copy(&item, &mysql); err != nil { 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) dtoMysqls = append(dtoMysqls, item)
} }
@ -84,7 +85,7 @@ func (u *MysqlService) ListDBOption() ([]dto.MysqlOption, error) {
for _, mysql := range mysqls { for _, mysql := range mysqls {
var item dto.MysqlOption var item dto.MysqlOption
if err := copier.Copy(&item, &mysql); err != nil { 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 item.Database = mysql.MysqlName
for _, database := range databases { 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) { 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) { 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)) mysql, _ := mysqlRepo.Get(repo.WithByName(req.Name), mysqlRepo.WithByMysqlName(req.Database), repo.WithByFrom(req.From))
if mysql.ID != 0 { if mysql.ID != 0 {
return nil, constant.ErrRecordExist return nil, buserr.New("ErrRecordExist")
} }
var createItem model.DatabaseMysql var createItem model.DatabaseMysql
if err := copier.Copy(&createItem, &req); err != nil { 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" { 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 { func (u *MysqlService) BindUser(req dto.BindUser) error {
if cmd.CheckIllegal(req.Username, req.Password, req.Permission) { 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)) 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 { if !hasOld {
var createItem model.DatabaseMysql var createItem model.DatabaseMysql
if err := copier.Copy(&createItem, &data); err != nil { 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 { if err := mysqlRepo.Create(context.Background(), &createItem); err != nil {
return err return err
@ -281,11 +282,11 @@ func (u *MysqlService) Delete(ctx context.Context, req dto.MysqlDBDelete) error
} }
if req.DeleteBackup { 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 { if _, err := os.Stat(uploadDir); err == nil {
_ = os.RemoveAll(uploadDir) _ = 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 { if _, err := os.Stat(backupDir); err == nil {
_ = os.RemoveAll(backupDir) _ = 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 { func (u *MysqlService) ChangePassword(req dto.ChangeDBInfo) error {
if cmd.CheckIllegal(req.Value) { if cmd.CheckIllegal(req.Value) {
return buserr.New(constant.ErrCmdIllegal) return buserr.New("ErrCmdIllegal")
} }
cli, version, err := LoadMysqlClientByFrom(req.Database) cli, version, err := LoadMysqlClientByFrom(req.Database)
if err != nil { if err != nil {
@ -383,7 +384,7 @@ func (u *MysqlService) ChangePassword(req dto.ChangeDBInfo) error {
func (u *MysqlService) ChangeAccess(req dto.ChangeDBInfo) error { func (u *MysqlService) ChangeAccess(req dto.ChangeDBInfo) error {
if cmd.CheckIllegal(req.Value) { if cmd.CheckIllegal(req.Value) {
return buserr.New(constant.ErrCmdIllegal) return buserr.New("ErrCmdIllegal")
} }
cli, version, err := LoadMysqlClientByFrom(req.Database) cli, version, err := LoadMysqlClientByFrom(req.Database)
if err != nil { if err != nil {
@ -428,7 +429,7 @@ func (u *MysqlService) UpdateVariables(req dto.MysqlVariablesUpdate) error {
} }
var files []string 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) lineBytes, err := os.ReadFile(path)
if err != nil { if err != nil {
return err return err
@ -459,7 +460,7 @@ func (u *MysqlService) UpdateVariables(req dto.MysqlVariablesUpdate) error {
return err 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 return err
} }

View File

@ -3,15 +3,15 @@ package service
import ( import (
"context" "context"
"fmt" "fmt"
"github.com/1Panel-dev/1Panel/agent/app/repo"
"os" "os"
"path" "path"
"strings" "strings"
"github.com/1Panel-dev/1Panel/agent/app/repo"
"github.com/1Panel-dev/1Panel/agent/app/dto" "github.com/1Panel-dev/1Panel/agent/app/dto"
"github.com/1Panel-dev/1Panel/agent/app/model" "github.com/1Panel-dev/1Panel/agent/app/model"
"github.com/1Panel-dev/1Panel/agent/buserr" "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/global"
"github.com/1Panel-dev/1Panel/agent/utils/cmd" "github.com/1Panel-dev/1Panel/agent/utils/cmd"
"github.com/1Panel-dev/1Panel/agent/utils/encrypt" "github.com/1Panel-dev/1Panel/agent/utils/encrypt"
@ -51,7 +51,7 @@ func (u *PostgresqlService) SearchWithPage(search dto.PostgresqlDBSearch) (int64
for _, pg := range postgresqls { for _, pg := range postgresqls {
var item dto.PostgresqlDBInfo var item dto.PostgresqlDBInfo
if err := copier.Copy(&item, &pg); err != nil { 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) dtoPostgresqls = append(dtoPostgresqls, item)
} }
@ -72,7 +72,7 @@ func (u *PostgresqlService) ListDBOption() ([]dto.PostgresqlOption, error) {
for _, pg := range postgresqls { for _, pg := range postgresqls {
var item dto.PostgresqlOption var item dto.PostgresqlOption
if err := copier.Copy(&item, &pg); err != nil { 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 item.Database = pg.PostgresqlName
for _, database := range databases { for _, database := range databases {
@ -87,7 +87,7 @@ func (u *PostgresqlService) ListDBOption() ([]dto.PostgresqlOption, error) {
func (u *PostgresqlService) BindUser(req dto.PostgresqlBindUser) error { func (u *PostgresqlService) BindUser(req dto.PostgresqlBindUser) error {
if cmd.CheckIllegal(req.Name, req.Username, req.Password) { 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)) dbItem, err := postgresqlRepo.Get(postgresqlRepo.WithByPostgresqlName(req.Database), repo.WithByName(req.Name))
if err != nil { 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) { func (u *PostgresqlService) Create(ctx context.Context, req dto.PostgresqlDBCreate) (*model.DatabasePostgresql, error) {
if cmd.CheckIllegal(req.Name, req.Username, req.Password, req.Format) { 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)) pgsql, _ := postgresqlRepo.Get(repo.WithByName(req.Name), postgresqlRepo.WithByPostgresqlName(req.Database), repo.WithByFrom(req.From))
if pgsql.ID != 0 { if pgsql.ID != 0 {
return nil, constant.ErrRecordExist return nil, buserr.New("ErrRecordExist")
} }
var createItem model.DatabasePostgresql var createItem model.DatabasePostgresql
if err := copier.Copy(&createItem, &req); err != nil { 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" { if req.From == "local" && req.Username == "root" {
@ -233,7 +233,7 @@ func (u *PostgresqlService) LoadFromRemote(database string) error {
if !hasOld { if !hasOld {
var createItem model.DatabasePostgresql var createItem model.DatabasePostgresql
if err := copier.Copy(&createItem, &data); err != nil { 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 { if err := postgresqlRepo.Create(context.Background(), &createItem); err != nil {
return err return err
@ -302,11 +302,11 @@ func (u *PostgresqlService) Delete(ctx context.Context, req dto.PostgresqlDBDele
} }
if req.DeleteBackup { 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 { if _, err := os.Stat(uploadDir); err == nil {
_ = os.RemoveAll(uploadDir) _ = 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 { if _, err := os.Stat(backupDir); err == nil {
_ = os.RemoveAll(backupDir) _ = 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 { func (u *PostgresqlService) ChangePrivileges(req dto.PostgresqlPrivileges) error {
if cmd.CheckIllegal(req.Database, req.Username) { 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)) dbItem, err := postgresqlRepo.Get(postgresqlRepo.WithByPostgresqlName(req.Database), repo.WithByName(req.Name))
if err != nil { if err != nil {
@ -345,7 +345,7 @@ func (u *PostgresqlService) ChangePrivileges(req dto.PostgresqlPrivileges) error
func (u *PostgresqlService) ChangePassword(req dto.ChangeDBInfo) error { func (u *PostgresqlService) ChangePassword(req dto.ChangeDBInfo) error {
if cmd.CheckIllegal(req.Value) { if cmd.CheckIllegal(req.Value) {
return buserr.New(constant.ErrCmdIllegal) return buserr.New("ErrCmdIllegal")
} }
cli, err := LoadPostgresqlClientByFrom(req.Database) cli, err := LoadPostgresqlClientByFrom(req.Database)
if err != nil { if err != nil {

View File

@ -5,11 +5,13 @@ import (
"encoding/json" "encoding/json"
"errors" "errors"
"fmt" "fmt"
"github.com/1Panel-dev/1Panel/agent/app/repo"
"os" "os"
"os/exec" "os/exec"
"strings" "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/app/dto"
"github.com/1Panel-dev/1Panel/agent/constant" "github.com/1Panel-dev/1Panel/agent/constant"
"github.com/1Panel-dev/1Panel/agent/utils/compose" "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 { if err := confSet(redisInfo.Name, "", confs); err != nil {
return err 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 return err
} }
@ -120,7 +122,7 @@ func (u *RedisService) UpdatePersistenceConf(req dto.RedisConfPersistenceUpdate)
if err := confSet(redisInfo.Name, req.Type, confs); err != nil { if err := confSet(redisInfo.Name, req.Type, confs); err != nil {
return err 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 return err
} }
@ -213,7 +215,7 @@ type redisConfig struct {
} }
func confSet(redisName string, updateType string, changeConf []redisConfig) error { 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) lineBytes, err := os.ReadFile(path)
if err != nil { if err != nil {
return err return err

View File

@ -115,7 +115,7 @@ func (u *DeviceService) Update(key, value string) error {
switch key { switch key {
case "TimeZone": case "TimeZone":
if cmd.CheckIllegal(value) { if cmd.CheckIllegal(value) {
return buserr.New(constant.ErrCmdIllegal) return buserr.New("ErrCmdIllegal")
} }
if err := ntp.UpdateSystemTimeZone(value); err != nil { if err := ntp.UpdateSystemTimeZone(value); err != nil {
return err return err
@ -132,7 +132,7 @@ func (u *DeviceService) Update(key, value string) error {
} }
case "Hostname": case "Hostname":
if cmd.CheckIllegal(value) { 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) std, err := cmd.Execf("%s hostnamectl set-hostname %s", cmd.SudoHandleCmd(), value)
if err != nil { if err != nil {
@ -140,7 +140,7 @@ func (u *DeviceService) Update(key, value string) error {
} }
case "Ntp", "LocalTime": case "Ntp", "LocalTime":
if cmd.CheckIllegal(value) { if cmd.CheckIllegal(value) {
return buserr.New(constant.ErrCmdIllegal) return buserr.New("ErrCmdIllegal")
} }
ntpValue := value ntpValue := value
if key == "LocalTime" { if key == "LocalTime" {
@ -223,12 +223,12 @@ func (u *DeviceService) UpdateHosts(req []dto.HostHelper) error {
func (u *DeviceService) UpdatePasswd(req dto.ChangePasswd) error { func (u *DeviceService) UpdatePasswd(req dto.ChangePasswd) error {
if cmd.CheckIllegal(req.User, req.Passwd) { 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()) std, err := cmd.Execf("%s echo '%s:%s' | %s chpasswd", cmd.SudoHandleCmd(), req.User, req.Passwd, cmd.SudoHandleCmd())
if err != nil { if err != nil {
if strings.Contains(err.Error(), "does not exist") { if strings.Contains(err.Error(), "does not exist") {
return buserr.New(constant.ErrNotExistUser) return buserr.New("ErrNotExistUser")
} }
return errors.New(std) return errors.New(std)
} }
@ -237,7 +237,7 @@ func (u *DeviceService) UpdatePasswd(req dto.ChangePasswd) error {
func (u *DeviceService) UpdateSwap(req dto.SwapHelper) error { func (u *DeviceService) UpdateSwap(req dto.SwapHelper) error {
if cmd.CheckIllegal(req.Path) { if cmd.CheckIllegal(req.Path) {
return buserr.New(constant.ErrCmdIllegal) return buserr.New("ErrCmdIllegal")
} }
if !req.IsNew { if !req.IsNew {
std, err := cmd.Execf("%s swapoff %s", cmd.SudoHandleCmd(), req.Path) 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.Size == 0 {
if req.Path == path.Join(global.CONF.System.BaseDir, ".1panel_swap") { if req.Path == path.Join(global.Dir.BaseDir, ".1panel_swap") {
_ = os.Remove(path.Join(global.CONF.System.BaseDir, ".1panel_swap")) _ = os.Remove(path.Join(global.Dir.BaseDir, ".1panel_swap"))
} }
return operateSwapWithFile(true, req) return operateSwapWithFile(true, req)
} }

View File

@ -47,7 +47,7 @@ func (u *DeviceService) Scan() dto.CleanData {
) )
fileOp := fileUtils.NewFileOp() fileOp := fileUtils.NewFileOp()
originalPath := path.Join(global.CONF.System.BaseDir, "1panel_original") originalPath := path.Join(global.Dir.BaseDir, "1panel_original")
originalSize, _ := fileOp.GetDirSize(originalPath) originalSize, _ := fileOp.GetDirSize(originalPath)
treeData = append(treeData, dto.CleanTree{ treeData = append(treeData, dto.CleanTree{
ID: uuid.NewString(), ID: uuid.NewString(),
@ -59,7 +59,7 @@ func (u *DeviceService) Scan() dto.CleanData {
Children: loadTreeWithDir(true, "1panel_original", originalPath, fileOp), 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) upgradeSize, _ := fileOp.GetDirSize(upgradePath)
treeData = append(treeData, dto.CleanTree{ treeData = append(treeData, dto.CleanTree{
ID: uuid.NewString(), ID: uuid.NewString(),
@ -101,7 +101,7 @@ func (u *DeviceService) Scan() dto.CleanData {
Children: rollBackTree, Children: rollBackTree,
}) })
cachePath := path.Join(global.CONF.System.BaseDir, cachePath) cachePath := path.Join(global.Dir.BaseDir, cachePath)
cacheSize, _ := fileOp.GetDirSize(cachePath) cacheSize, _ := fileOp.GetDirSize(cachePath)
treeData = append(treeData, dto.CleanTree{ treeData = append(treeData, dto.CleanTree{
ID: uuid.NewString(), ID: uuid.NewString(),
@ -150,97 +150,97 @@ func (u *DeviceService) Clean(req []dto.Clean) {
size += item.Size size += item.Size
switch item.TreeType { switch item.TreeType {
case "1panel_original": 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": case "upgrade":
dropFileOrDir(path.Join(global.CONF.System.BaseDir, upgradePath, item.Name)) dropFileOrDir(path.Join(global.Dir.BaseDir, upgradePath, item.Name))
case "snapshot": case "snapshot":
dropFileOrDir(path.Join(global.CONF.System.BaseDir, snapshotTmpPath, item.Name)) dropFileOrDir(path.Join(global.Dir.BaseDir, snapshotTmpPath, item.Name))
dropFileOrDir(path.Join(global.CONF.System.Backup, "system", item.Name)) dropFileOrDir(path.Join(global.Dir.LocalBackupDir, "system", item.Name))
case "snapshot_tmp": 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": case "snapshot_local":
dropFileOrDir(path.Join(global.CONF.System.Backup, "system", item.Name)) dropFileOrDir(path.Join(global.Dir.LocalBackupDir, "system", item.Name))
case "rollback": case "rollback":
dropFileOrDir(path.Join(global.CONF.System.BaseDir, rollbackPath, "app")) dropFileOrDir(path.Join(global.Dir.BaseDir, rollbackPath, "app"))
dropFileOrDir(path.Join(global.CONF.System.BaseDir, rollbackPath, "database")) dropFileOrDir(path.Join(global.Dir.BaseDir, rollbackPath, "database"))
dropFileOrDir(path.Join(global.CONF.System.BaseDir, rollbackPath, "website")) dropFileOrDir(path.Join(global.Dir.BaseDir, rollbackPath, "website"))
case "rollback_app": 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": 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": 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": case "cache":
dropFileOrDir(path.Join(global.CONF.System.BaseDir, cachePath, item.Name)) dropFileOrDir(path.Join(global.Dir.BaseDir, cachePath, item.Name))
restart = true restart = true
case "unused": case "unused":
dropFileOrDir(path.Join(global.CONF.System.BaseDir, oldOriginalPath)) dropFileOrDir(path.Join(global.Dir.BaseDir, oldOriginalPath))
dropFileOrDir(path.Join(global.CONF.System.BaseDir, oldAppBackupPath)) dropFileOrDir(path.Join(global.Dir.BaseDir, oldAppBackupPath))
dropFileOrDir(path.Join(global.CONF.System.BaseDir, oldDownloadPath)) dropFileOrDir(path.Join(global.Dir.BaseDir, oldDownloadPath))
files, _ := os.ReadDir(path.Join(global.CONF.System.BaseDir, oldUpgradePath)) files, _ := os.ReadDir(path.Join(global.Dir.BaseDir, oldUpgradePath))
if len(files) == 0 { if len(files) == 0 {
continue continue
} }
for _, file := range files { for _, file := range files {
if strings.HasPrefix(file.Name(), "upgrade_") { 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": 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": 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": 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": case "old_upgrade":
if len(item.Name) == 0 { 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 { if len(files) == 0 {
continue continue
} }
for _, file := range files { for _, file := range files {
if strings.HasPrefix(file.Name(), "upgrade_") { 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 { } else {
dropFileOrDir(path.Join(global.CONF.System.BaseDir, oldUpgradePath, item.Name)) dropFileOrDir(path.Join(global.Dir.BaseDir, oldUpgradePath, item.Name))
} }
case "upload": 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 { if len(item.Name) == 0 {
dropFileOrDir(path.Join(global.CONF.System.BaseDir, tmpUploadPath)) dropFileOrDir(path.Join(global.Dir.BaseDir, tmpUploadPath))
} }
case "upload_tmp": 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": 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": 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": 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": 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": case "download":
dropFileOrDir(path.Join(global.CONF.System.BaseDir, downloadPath, item.Name)) dropFileOrDir(path.Join(global.Dir.BaseDir, downloadPath, item.Name))
case "download_app": 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": 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": 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": 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": case "system_log":
if len(item.Name) == 0 { 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 { if len(files) == 0 {
continue continue
} }
@ -248,14 +248,14 @@ func (u *DeviceService) Clean(req []dto.Clean) {
if file.Name() == "1Panel.log" || file.IsDir() { if file.Name() == "1Panel.log" || file.IsDir() {
continue continue
} }
dropFileOrDir(path.Join(global.CONF.System.BaseDir, logPath, file.Name())) dropFileOrDir(path.Join(global.Dir.BaseDir, logPath, file.Name()))
} }
} else { } else {
dropFileOrDir(path.Join(global.CONF.System.BaseDir, logPath, item.Name)) dropFileOrDir(path.Join(global.Dir.BaseDir, logPath, item.Name))
} }
case "task_log": case "task_log":
pathItem := path.Join(global.CONF.System.BaseDir, taskPath, item.Name) pathItem := path.Join(global.Dir.BaseDir, taskPath, item.Name)
dropFileOrDir(path.Join(global.CONF.System.BaseDir, taskPath, item.Name)) dropFileOrDir(path.Join(global.Dir.BaseDir, taskPath, item.Name))
if len(item.Name) == 0 { if len(item.Name) == 0 {
files, _ := os.ReadDir(pathItem) files, _ := os.ReadDir(pathItem)
if len(files) == 0 { if len(files) == 0 {
@ -296,9 +296,9 @@ func systemClean(taskItem *task.Task) error {
taskItem.AddSubTask(i18n.GetMsgByKey("HandleSystemClean"), func(t *task.Task) error { taskItem.AddSubTask(i18n.GetMsgByKey("HandleSystemClean"), func(t *task.Task) error {
size := int64(0) size := int64(0)
fileCount := 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) upgradeFiles, _ := os.ReadDir(upgradePath)
if len(upgradeFiles) != 0 { if len(upgradeFiles) != 0 {
sort.Slice(upgradeFiles, func(i, j int) bool { 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.Dir.BaseDir, snapshotTmpPath), taskItem, &size, &fileCount)
dropWithTask(path.Join(global.CONF.System.Backup, "system"), 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.Dir.BaseDir, rollbackPath, "app"), taskItem, &size, &fileCount)
dropWithTask(path.Join(global.CONF.System.BaseDir, rollbackPath, "website"), taskItem, &size, &fileCount) dropWithTask(path.Join(global.Dir.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, "database"), taskItem, &size, &fileCount)
dropWithTask(path.Join(global.CONF.System.BaseDir, oldOriginalPath), taskItem, &size, &fileCount) dropWithTask(path.Join(global.Dir.BaseDir, oldOriginalPath), taskItem, &size, &fileCount)
dropWithTask(path.Join(global.CONF.System.BaseDir, oldAppBackupPath), taskItem, &size, &fileCount) dropWithTask(path.Join(global.Dir.BaseDir, oldAppBackupPath), taskItem, &size, &fileCount)
dropWithTask(path.Join(global.CONF.System.BaseDir, oldDownloadPath), taskItem, &size, &fileCount) dropWithTask(path.Join(global.Dir.BaseDir, oldDownloadPath), taskItem, &size, &fileCount)
oldUpgradePath := path.Join(global.CONF.System.BaseDir, oldUpgradePath) oldUpgradePath := path.Join(global.Dir.BaseDir, oldUpgradePath)
oldUpgradeFiles, _ := os.ReadDir(oldUpgradePath) oldUpgradeFiles, _ := os.ReadDir(oldUpgradePath)
if len(oldUpgradeFiles) != 0 { if len(oldUpgradeFiles) != 0 {
for i := 0; i < len(oldUpgradeFiles); i++ { 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.Dir.BaseDir, tmpUploadPath), taskItem, &size, &fileCount)
dropWithTask(path.Join(global.CONF.System.BaseDir, uploadPath), taskItem, &size, &fileCount) dropWithTask(path.Join(global.Dir.BaseDir, uploadPath), taskItem, &size, &fileCount)
dropWithTask(path.Join(global.CONF.System.BaseDir, downloadPath), 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) logFiles, _ := os.ReadDir(logPath)
if len(logFiles) != 0 { if len(logFiles) != 0 {
for i := 0; i < len(logFiles); i++ { for i := 0; i < len(logFiles); i++ {
@ -361,14 +361,14 @@ func systemClean(taskItem *task.Task) error {
func loadSnapshotTree(fileOp fileUtils.FileOp) []dto.CleanTree { func loadSnapshotTree(fileOp fileUtils.FileOp) []dto.CleanTree {
var treeData []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) list1 := loadTreeWithAllFile(true, path1, "snapshot_tmp", path1, fileOp)
if len(list1) != 0 { if len(list1) != 0 {
size, _ := fileOp.GetDirSize(path1) 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}) 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) list2 := loadTreeWithAllFile(true, path2, "snapshot_local", path2, fileOp)
if len(list2) != 0 { if len(list2) != 0 {
size, _ := fileOp.GetDirSize(path2) size, _ := fileOp.GetDirSize(path2)
@ -379,17 +379,17 @@ func loadSnapshotTree(fileOp fileUtils.FileOp) []dto.CleanTree {
func loadRollBackTree(fileOp fileUtils.FileOp) []dto.CleanTree { func loadRollBackTree(fileOp fileUtils.FileOp) []dto.CleanTree {
var treeData []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) list1 := loadTreeWithAllFile(true, path1, "rollback_app", path1, fileOp)
size1, _ := fileOp.GetDirSize(path1) 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}) 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) list2 := loadTreeWithAllFile(true, path2, "rollback_website", path2, fileOp)
size2, _ := fileOp.GetDirSize(path2) 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}) 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) list3 := loadTreeWithAllFile(true, path3, "rollback_database", path3, fileOp)
size3, _ := fileOp.GetDirSize(path3) 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}) 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 { func loadUnusedFile(fileOp fileUtils.FileOp) []dto.CleanTree {
var treeData []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) list1 := loadTreeWithAllFile(true, path1, "old_original", path1, fileOp)
if len(list1) != 0 { if len(list1) != 0 {
size, _ := fileOp.GetDirSize(path1) size, _ := fileOp.GetDirSize(path1)
treeData = append(treeData, dto.CleanTree{ID: uuid.NewString(), Label: "old_original", Size: uint64(size), Children: list1, Type: "old_original"}) 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) list2 := loadTreeWithAllFile(true, path2, "old_apps_bak", path2, fileOp)
if len(list2) != 0 { if len(list2) != 0 {
size, _ := fileOp.GetDirSize(path2) 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"}) 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) list3 := loadTreeWithAllFile(true, path3, "old_download", path3, fileOp)
if len(list3) != 0 { if len(list3) != 0 {
size, _ := fileOp.GetDirSize(path3) size, _ := fileOp.GetDirSize(path3)
treeData = append(treeData, dto.CleanTree{ID: uuid.NewString(), Label: "old_download", Size: uint64(size), Children: list3, Type: "old_download"}) 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) list4 := loadTreeWithDir(true, "old_upgrade", path4, fileOp)
itemSize := uint64(0) itemSize := uint64(0)
for _, item := range list4 { for _, item := range list4 {
@ -435,32 +435,32 @@ func loadUnusedFile(fileOp fileUtils.FileOp) []dto.CleanTree {
func loadUploadTree(fileOp fileUtils.FileOp) []dto.CleanTree { func loadUploadTree(fileOp fileUtils.FileOp) []dto.CleanTree {
var treeData []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) list0 := loadTreeWithAllFile(true, path0, "upload_tmp", path0, fileOp)
size0, _ := fileOp.GetDirSize(path0) 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}) 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) list1 := loadTreeWithAllFile(true, path1, "upload_app", path1, fileOp)
size1, _ := fileOp.GetDirSize(path1) 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}) 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) list2 := loadTreeWithAllFile(true, path2, "upload_website", path2, fileOp)
size2, _ := fileOp.GetDirSize(path2) 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}) 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) list3 := loadTreeWithAllFile(true, path3, "upload_database", path3, fileOp)
size3, _ := fileOp.GetDirSize(path3) 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}) 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) list4 := loadTreeWithAllFile(true, path4, "upload_directory", path4, fileOp)
size4, _ := fileOp.GetDirSize(path4) 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}) 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) uploadTreeData := loadTreeWithAllFile(true, path5, "upload", path5, fileOp)
treeData = append(treeData, uploadTreeData...) treeData = append(treeData, uploadTreeData...)
@ -469,27 +469,27 @@ func loadUploadTree(fileOp fileUtils.FileOp) []dto.CleanTree {
func loadDownloadTree(fileOp fileUtils.FileOp) []dto.CleanTree { func loadDownloadTree(fileOp fileUtils.FileOp) []dto.CleanTree {
var treeData []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) list1 := loadTreeWithAllFile(true, path1, "download_app", path1, fileOp)
size1, _ := fileOp.GetDirSize(path1) 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}) 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) list2 := loadTreeWithAllFile(true, path2, "download_website", path2, fileOp)
size2, _ := fileOp.GetDirSize(path2) 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}) 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) list3 := loadTreeWithAllFile(true, path3, "download_database", path3, fileOp)
size3, _ := fileOp.GetDirSize(path3) 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}) 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) list4 := loadTreeWithAllFile(true, path4, "download_directory", path4, fileOp)
size4, _ := fileOp.GetDirSize(path4) 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}) 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) uploadTreeData := loadTreeWithAllFile(true, path5, "download", path5, fileOp)
treeData = append(treeData, uploadTreeData...) treeData = append(treeData, uploadTreeData...)
@ -498,7 +498,7 @@ func loadDownloadTree(fileOp fileUtils.FileOp) []dto.CleanTree {
func loadLogTree(fileOp fileUtils.FileOp) []dto.CleanTree { func loadLogTree(fileOp fileUtils.FileOp) []dto.CleanTree {
var treeData []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) list1 := loadTreeWithAllFile(true, path1, "system_log", path1, fileOp)
size := uint64(0) size := uint64(0)
for _, file := range list1 { 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}) 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) list2 := loadTreeWithAllFile(false, path2, "task_log", path2, fileOp)
size2, _ := fileOp.GetDirSize(path2) size2, _ := fileOp.GetDirSize(path2)
treeData = append(treeData, dto.CleanTree{ID: uuid.NewString(), Label: "task_log", Size: uint64(size2), Children: list2, Type: "task_log"}) treeData = append(treeData, dto.CleanTree{ID: uuid.NewString(), Label: "task_log", Size: uint64(size2), Children: list2, Type: "task_log"})

View File

@ -7,7 +7,6 @@ import (
"github.com/1Panel-dev/1Panel/agent/app/model" "github.com/1Panel-dev/1Panel/agent/app/model"
"github.com/1Panel-dev/1Panel/agent/app/repo" "github.com/1Panel-dev/1Panel/agent/app/repo"
"github.com/1Panel-dev/1Panel/agent/buserr" "github.com/1Panel-dev/1Panel/agent/buserr"
"github.com/1Panel-dev/1Panel/agent/constant"
"github.com/1Panel-dev/1Panel/agent/utils/files" "github.com/1Panel-dev/1Panel/agent/utils/files"
"github.com/spf13/afero" "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) { func (f *FavoriteService) Create(req request.FavoriteCreate) (*model.Favorite, error) {
exist, _ := favoriteRepo.GetFirst(favoriteRepo.WithByPath(req.Path)) exist, _ := favoriteRepo.GetFirst(favoriteRepo.WithByPath(req.Path))
if exist.ID > 0 { if exist.ID > 0 {
return nil, buserr.New(constant.ErrFavoriteExist) return nil, buserr.New("ErrFavoriteExist")
} }
op := files.NewFileOp() op := files.NewFileOp()
if !op.Stat(req.Path) { if !op.Stat(req.Path) {
return nil, buserr.New(constant.ErrLinkPathNotFound) return nil, buserr.New("ErrLinkPathNotFound")
} }
openFile, err := op.OpenFile(req.Path) openFile, err := op.OpenFile(req.Path)
if err != nil { if err != nil {

View File

@ -190,7 +190,7 @@ func (f *FileService) Create(op request.FileCreate) error {
} }
fo := files.NewFileOp() fo := files.NewFileOp()
if fo.Stat(op.Path) { if fo.Stat(op.Path) {
return buserr.New(constant.ErrFileIsExist) return buserr.New("ErrFileIsExist")
} }
mode := op.Mode mode := op.Mode
if mode == 0 { if mode == 0 {
@ -206,7 +206,7 @@ func (f *FileService) Create(op request.FileCreate) error {
} }
if op.IsLink { if op.IsLink {
if !fo.Stat(op.LinkPath) { if !fo.Stat(op.LinkPath) {
return buserr.New(constant.ErrLinkPathNotFound) return buserr.New("ErrLinkPathNotFound")
} }
return fo.LinkFile(op.LinkPath, op.Path, op.IsSymlink) 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 { func (f *FileService) Delete(op request.FileDelete) error {
if op.IsDir { if op.IsDir {
excludeDir := global.CONF.System.DataDir excludeDir := global.Dir.DataDir
if filepath.Base(op.Path) == ".1panel_clash" || op.Path == excludeDir { if filepath.Base(op.Path) == ".1panel_clash" || op.Path == excludeDir {
return buserr.New(constant.ErrPathNotDelete) return buserr.New("ErrPathNotDelete")
} }
} }
fo := files.NewFileOp() fo := files.NewFileOp()
@ -265,7 +265,7 @@ func (f *FileService) BatchChangeModeAndOwner(op request.FileRoleReq) error {
fo := files.NewFileOp() fo := files.NewFileOp()
for _, path := range op.Paths { for _, path := range op.Paths {
if !fo.Stat(path) { 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 { if err := fo.ChownR(path, op.User, op.Group, op.Sub); err != nil {
return err return err
@ -286,7 +286,7 @@ func (f *FileService) ChangeOwner(req request.FileRoleUpdate) error {
func (f *FileService) Compress(c request.FileCompress) error { func (f *FileService) Compress(c request.FileCompress) error {
fo := files.NewFileOp() fo := files.NewFileOp()
if !c.Replace && fo.Stat(filepath.Join(c.Dst, c.Name)) { 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) 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 { func (f *FileService) MvFile(m request.FileMove) error {
fo := files.NewFileOp() fo := files.NewFileOp()
if !fo.Stat(m.NewPath) { if !fo.Stat(m.NewPath) {
return buserr.New(constant.ErrPathNotFound) return buserr.New("ErrPathNotFound")
} }
for _, oldPath := range m.OldPaths { for _, oldPath := range m.OldPaths {
if !fo.Stat(oldPath) { 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)+"/") { if oldPath == m.NewPath || strings.Contains(m.NewPath, filepath.Clean(oldPath)+"/") {
return buserr.New(constant.ErrMovePathFailed) return buserr.New("ErrMovePathFailed")
} }
} }
if m.Type == "cut" { if m.Type == "cut" {
@ -451,9 +451,9 @@ func (f *FileService) ReadLogByLine(req request.FileReadByLineReq) (*response.Fi
} else { } else {
fileName = "1Panel-" + req.Name + ".log" 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 { 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 { if _, err := os.Stat(fileGzPath); err != nil {
return nil, buserr.New("ErrHttpReqNotFound") return nil, buserr.New("ErrHttpReqNotFound")
} }
@ -500,7 +500,7 @@ func (f *FileService) GetPathByType(pathType string) string {
if pathType == "websiteDir" { if pathType == "websiteDir" {
value, _ := settingRepo.GetValueByKey("WEBSITE_DIR") value, _ := settingRepo.GetValueByKey("WEBSITE_DIR")
if value == "" { if value == "" {
return path.Join(global.CONF.System.BaseDir, "www") return path.Join(global.Dir.BaseDir, "www")
} }
return value return value
} }

View File

@ -10,6 +10,7 @@ import (
"github.com/1Panel-dev/1Panel/agent/app/dto" "github.com/1Panel-dev/1Panel/agent/app/dto"
"github.com/1Panel-dev/1Panel/agent/app/model" "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/constant"
"github.com/1Panel-dev/1Panel/agent/global" "github.com/1Panel-dev/1Panel/agent/global"
"github.com/1Panel-dev/1Panel/agent/utils/cmd" "github.com/1Panel-dev/1Panel/agent/utils/cmd"
@ -17,7 +18,6 @@ import (
"github.com/1Panel-dev/1Panel/agent/utils/firewall" "github.com/1Panel-dev/1Panel/agent/utils/firewall"
fireClient "github.com/1Panel-dev/1Panel/agent/utils/firewall/client" fireClient "github.com/1Panel-dev/1Panel/agent/utils/firewall/client"
"github.com/jinzhu/copier" "github.com/jinzhu/copier"
"github.com/pkg/errors"
) )
const confPath = "/etc/sysctl.conf" const confPath = "/etc/sysctl.conf"
@ -347,7 +347,7 @@ func (u *FirewallService) OperateForwardRule(req dto.ForwardRuleOperate) error {
reqRule.TargetPort == rule.TargetPort && reqRule.TargetPort == rule.TargetPort &&
reqRule.TargetIP == rule.TargetIP && reqRule.TargetIP == rule.TargetIP &&
proto == rule.Protocol { 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 { func (u *FirewallService) UpdateDescription(req dto.UpdateFirewallDescription) error {
var firewall model.Firewall var firewall model.Firewall
if err := copier.Copy(&firewall, &req); err != nil { 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) return hostRepo.SaveFirewallRecord(&firewall)
} }

View File

@ -1,17 +1,18 @@
package service package service
import ( import (
"github.com/1Panel-dev/1Panel/agent/app/repo"
"os" "os"
"sort" "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/dto"
"github.com/1Panel-dev/1Panel/agent/app/model" "github.com/1Panel-dev/1Panel/agent/app/model"
"github.com/1Panel-dev/1Panel/agent/constant" "github.com/1Panel-dev/1Panel/agent/constant"
"github.com/1Panel-dev/1Panel/agent/utils/encrypt" "github.com/1Panel-dev/1Panel/agent/utils/encrypt"
"github.com/1Panel-dev/1Panel/agent/utils/toolbox" "github.com/1Panel-dev/1Panel/agent/utils/toolbox"
"github.com/jinzhu/copier" "github.com/jinzhu/copier"
"github.com/pkg/errors"
) )
type FtpService struct{} type FtpService struct{}
@ -83,7 +84,7 @@ func (f *FtpService) SearchWithPage(req dto.SearchWithPage) (int64, interface{},
for _, user := range lists { for _, user := range lists {
var item dto.FtpInfo var item dto.FtpInfo
if err := copier.Copy(&item, &user); err != nil { 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) item.Password, _ = encrypt.StringDecrypt(item.Password)
users = append(users, item) users = append(users, item)
@ -145,7 +146,7 @@ func (f *FtpService) Create(req dto.FtpCreate) (uint, error) {
} }
userInDB, _ := ftpRepo.Get(ftpRepo.WithByUser(req.User)) userInDB, _ := ftpRepo.Get(ftpRepo.WithByUser(req.User))
if userInDB.ID != 0 { if userInDB.ID != 0 {
return 0, constant.ErrRecordExist return 0, buserr.New("ErrRecordExist")
} }
client, err := toolbox.NewFtpClient() client, err := toolbox.NewFtpClient()
if err != nil { if err != nil {
@ -156,7 +157,7 @@ func (f *FtpService) Create(req dto.FtpCreate) (uint, error) {
} }
var ftp model.Ftp var ftp model.Ftp
if err := copier.Copy(&ftp, &req); err != nil { 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.Status = constant.StatusEnable
ftp.Password = pass ftp.Password = pass
@ -199,7 +200,7 @@ func (f *FtpService) Update(req dto.FtpUpdate) error {
} }
ftpItem, _ := ftpRepo.Get(repo.WithByID(req.ID)) ftpItem, _ := ftpRepo.Get(repo.WithByID(req.ID))
if ftpItem.ID == 0 { if ftpItem.ID == 0 {
return constant.ErrRecordNotFound return buserr.New("ErrRecordNotFound")
} }
passItem, err := encrypt.StringDecrypt(ftpItem.Password) passItem, err := encrypt.StringDecrypt(ftpItem.Password)
if err != nil { if err != nil {

View File

@ -154,7 +154,7 @@ func (h *HostToolService) CreateToolConfig(req request.HostToolCreate) error {
return err 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") includeDir := path.Join(supervisorDir, "supervisor.d")
if !fileOp.Stat(includeDir) { if !fileOp.Stat(includeDir) {
if err = fileOp.CreateDir(includeDir, constant.DirPerm); err != nil { 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 { func (h *HostToolService) OperateSupervisorProcess(req request.SupervisorProcessConfig) error {
var ( var (
supervisordDir = path.Join(global.CONF.System.BaseDir, "1panel", "tools", "supervisord") supervisordDir = path.Join(global.Dir.DataDir, "tools", "supervisord")
fileOp = files.NewFileOp() fileOp = files.NewFileOp()
) )
if req.Operate == "update" || req.Operate == "create" { 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) { 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, "") return handleProcessConfig(configDir, "")
} }
func (h *HostToolService) OperateSupervisorProcessFile(req request.SupervisorProcessFileReq) (string, error) { func (h *HostToolService) OperateSupervisorProcessFile(req request.SupervisorProcessFileReq) (string, error) {
var ( 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, "", "") return handleSupervisorFile(req, includeDir, "", "")
} }

View File

@ -19,6 +19,7 @@ import (
"github.com/1Panel-dev/1Panel/agent/app/task" "github.com/1Panel-dev/1Panel/agent/app/task"
"github.com/1Panel-dev/1Panel/agent/buserr" "github.com/1Panel-dev/1Panel/agent/buserr"
"github.com/1Panel-dev/1Panel/agent/constant" "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/i18n"
"github.com/1Panel-dev/1Panel/agent/utils/docker" "github.com/1Panel-dev/1Panel/agent/utils/docker"
"github.com/docker/docker/api/types" "github.com/docker/docker/api/types"
@ -162,7 +163,7 @@ func (u *ImageService) ImageBuild(req dto.ImageBuild) error {
defer client.Close() defer client.Close()
fileName := "Dockerfile" fileName := "Dockerfile"
if req.From == "edit" { 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.Stat(dir); err != nil && os.IsNotExist(err) {
if err = os.MkdirAll(dir, os.ModePerm); err != nil { if err = os.MkdirAll(dir, os.ModePerm); err != nil {
return err 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 _, 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(err.Error(), "image is being used") || strings.Contains(err.Error(), "is using") {
if strings.Contains(id, "sha256:") { 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") { if strings.Contains(err.Error(), "image has dependent") {
return report, buserr.New(constant.ErrObjectBeDependent) return report, buserr.New("ErrObjectBeDependent")
} }
return report, err return report, err
} }

View File

@ -4,11 +4,12 @@ import (
"context" "context"
"encoding/json" "encoding/json"
"fmt" "fmt"
"github.com/1Panel-dev/1Panel/agent/app/repo"
"os" "os"
"strings" "strings"
"time" "time"
"github.com/1Panel-dev/1Panel/agent/app/repo"
"github.com/1Panel-dev/1Panel/agent/app/dto" "github.com/1Panel-dev/1Panel/agent/app/dto"
"github.com/1Panel-dev/1Panel/agent/buserr" "github.com/1Panel-dev/1Panel/agent/buserr"
"github.com/1Panel-dev/1Panel/agent/constant" "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 { for _, op := range ops {
var item dto.ImageRepoInfo var item dto.ImageRepoInfo
if err := copier.Copy(&item, &op); err != nil { 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) dtoOps = append(dtoOps, item)
} }
@ -69,7 +70,7 @@ func (u *ImageRepoService) List() ([]dto.ImageRepoOption, error) {
if op.Status == constant.StatusSuccess { if op.Status == constant.StatusSuccess {
var item dto.ImageRepoOption var item dto.ImageRepoOption
if err := copier.Copy(&item, &op); err != nil { 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) dtoOps = append(dtoOps, item)
} }
@ -79,11 +80,11 @@ func (u *ImageRepoService) List() ([]dto.ImageRepoOption, error) {
func (u *ImageRepoService) Create(req dto.ImageRepoCreate) error { func (u *ImageRepoService) Create(req dto.ImageRepoCreate) error {
if cmd.CheckIllegal(req.Username, req.Password, req.DownloadUrl) { 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)) imageRepo, _ := imageRepoRepo.Get(repo.WithByName(req.Name))
if imageRepo.ID != 0 { if imageRepo.ID != 0 {
return constant.ErrRecordExist return buserr.New("ErrRecordExist")
} }
if req.Protocol == "http" { if req.Protocol == "http" {
@ -124,7 +125,7 @@ func (u *ImageRepoService) Create(req dto.ImageRepoCreate) error {
} }
if err := copier.Copy(&imageRepo, &req); err != nil { 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 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 !") return errors.New("The default value cannot be deleted !")
} }
if cmd.CheckIllegal(req.Username, req.Password, req.DownloadUrl) { 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)) repo, err := imageRepoRepo.Get(repo.WithByID(req.ID))
if err != nil { if err != nil {

View File

@ -25,9 +25,8 @@ func NewILogService() ILogService {
} }
func (u *LogService) ListSystemLogFile() ([]string, error) { func (u *LogService) ListSystemLogFile() ([]string, error) {
logDir := path.Join(global.CONF.System.BaseDir, "1panel/log")
var files []string 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 { if err != nil {
return err return err
} }
@ -63,9 +62,9 @@ func (u *LogService) LoadSystemLog(name string) (string, error) {
} else { } else {
name = "1Panel-" + name + ".log" 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 { 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 { if _, err := os.Stat(fileGzPath); err != nil {
return "", buserr.New("ErrHttpReqNotFound") return "", buserr.New("ErrHttpReqNotFound")
} }

View File

@ -8,10 +8,10 @@ import (
"time" "time"
"github.com/1Panel-dev/1Panel/agent/app/repo" "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/dto"
"github.com/1Panel-dev/1Panel/agent/app/model" "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/global"
"github.com/1Panel-dev/1Panel/agent/utils/common" "github.com/1Panel-dev/1Panel/agent/utils/common"
"github.com/robfig/cron/v3" "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) { func (m *MonitorService) LoadSetting() (*dto.MonitorSetting, error) {
setting, err := settingRepo.GetList() setting, err := settingRepo.GetList()
if err != nil { if err != nil {
return nil, constant.ErrRecordNotFound return nil, buserr.New("ErrRecordNotFound")
} }
settingMap := make(map[string]string) settingMap := make(map[string]string)
for _, set := range setting { for _, set := range setting {

View File

@ -4,10 +4,6 @@ import (
"bufio" "bufio"
"encoding/json" "encoding/json"
"fmt" "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" "io"
"net/http" "net/http"
"os" "os"
@ -16,6 +12,12 @@ import (
"strings" "strings"
"time" "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/utils/compose"
"github.com/1Panel-dev/1Panel/agent/app/dto/request" "github.com/1Panel-dev/1Panel/agent/app/dto/request"
@ -50,7 +52,7 @@ func (n NginxService) GetNginxConfig() (*response.NginxFile, error) {
if err != nil { if err != nil {
return nil, err 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) byteContent, err := files.NewFileOp().GetContent(configPath)
if err != nil { if err != nil {
return nil, err return nil, err
@ -131,7 +133,7 @@ func (n NginxService) UpdateConfigFile(req request.NginxConfigFileUpdate) error
if err != nil { if err != nil {
return err 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 { if req.Backup {
backupPath := path.Join(path.Dir(filePath), "bak") backupPath := path.Join(path.Dir(filePath), "bak")
if !fileOp.Stat(backupPath) { if !fileOp.Stat(backupPath) {

View File

@ -13,6 +13,7 @@ import (
"github.com/1Panel-dev/1Panel/agent/app/model" "github.com/1Panel-dev/1Panel/agent/app/model"
"github.com/1Panel-dev/1Panel/agent/cmd/server/nginx_conf" "github.com/1Panel-dev/1Panel/agent/cmd/server/nginx_conf"
"github.com/1Panel-dev/1Panel/agent/constant" "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/cmd"
"github.com/1Panel-dev/1Panel/agent/utils/files" "github.com/1Panel-dev/1Panel/agent/utils/files"
"github.com/1Panel-dev/1Panel/agent/utils/nginx" "github.com/1Panel-dev/1Panel/agent/utils/nginx"
@ -27,7 +28,7 @@ func getNginxFull(website *model.Website) (dto.NginxFull, error) {
return nginxFull, err return nginxFull, err
} }
nginxFull.Install = nginxInstall 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.ConfigDir = path.Join(nginxFull.Dir, "conf")
nginxFull.ConfigFile = "nginx.conf" nginxFull.ConfigFile = "nginx.conf"
nginxFull.SiteDir = path.Join(nginxFull.Dir, "www") nginxFull.SiteDir = path.Join(nginxFull.Dir, "www")

View File

@ -6,7 +6,6 @@ import (
"github.com/1Panel-dev/1Panel/agent/app/model" "github.com/1Panel-dev/1Panel/agent/app/model"
"github.com/1Panel-dev/1Panel/agent/app/repo" "github.com/1Panel-dev/1Panel/agent/app/repo"
"github.com/1Panel-dev/1Panel/agent/buserr" "github.com/1Panel-dev/1Panel/agent/buserr"
"github.com/1Panel-dev/1Panel/agent/constant"
) )
type PHPExtensionsService struct { type PHPExtensionsService struct {
@ -64,7 +63,7 @@ func (p PHPExtensionsService) List() ([]response.PHPExtensionsDTO, error) {
func (p PHPExtensionsService) Create(req request.PHPExtensionsCreate) error { func (p PHPExtensionsService) Create(req request.PHPExtensionsCreate) error {
exist, _ := phpExtensionsRepo.GetFirst(repo.WithByName(req.Name)) exist, _ := phpExtensionsRepo.GetFirst(repo.WithByName(req.Name))
if exist.ID > 0 { if exist.ID > 0 {
return buserr.New(constant.ErrNameIsExist) return buserr.New("ErrNameIsExist")
} }
extension := model.PHPExtensions{ extension := model.PHPExtensions{
Name: req.Name, Name: req.Name,

View File

@ -15,6 +15,7 @@ import (
"github.com/1Panel-dev/1Panel/agent/app/dto/response" "github.com/1Panel-dev/1Panel/agent/app/dto/response"
"github.com/1Panel-dev/1Panel/agent/buserr" "github.com/1Panel-dev/1Panel/agent/buserr"
"github.com/1Panel-dev/1Panel/agent/constant" "github.com/1Panel-dev/1Panel/agent/constant"
"github.com/1Panel-dev/1Panel/agent/global"
"github.com/1Panel-dev/1Panel/agent/utils/files" "github.com/1Panel-dev/1Panel/agent/utils/files"
"github.com/shirou/gopsutil/v3/disk" "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 { func (r RecycleBinService) Create(create request.RecycleBinCreate) error {
op := files.NewFileOp() op := files.NewFileOp()
if !op.Stat(create.SourcePath) { if !op.Stat(create.SourcePath) {
return buserr.New(constant.ErrLinkPathNotFound) return buserr.New("ErrLinkPathNotFound")
} }
clashDir, err := getClashDir(create.SourcePath) clashDir, err := getClashDir(create.SourcePath)
if err != nil { if err != nil {
@ -113,7 +114,7 @@ func (r RecycleBinService) Reduce(reduce request.RecycleBinReduce) error {
filePath := path.Join(reduce.From, reduce.RName) filePath := path.Join(reduce.From, reduce.RName)
op := files.NewFileOp() op := files.NewFileOp()
if !op.Stat(filePath) { if !op.Stat(filePath) {
return buserr.New(constant.ErrLinkPathNotFound) return buserr.New("ErrLinkPathNotFound")
} }
recycleBinDTO, err := getRecycleBinDTOFromName(reduce.RName) recycleBinDTO, err := getRecycleBinDTOFromName(reduce.RName)
if err != nil { if err != nil {
@ -169,7 +170,7 @@ func getClashDir(realPath string) (string, error) {
return clashDir, nil return clashDir, nil
} }
} }
return constant.RecycleBinDir, createClashDir(constant.RecycleBinDir) return global.Dir.RecycleBinDir, createClashDir(global.Dir.RecycleBinDir)
} }
func createClashDir(clashDir string) error { func createClashDir(clashDir string) error {

View File

@ -5,9 +5,6 @@ import (
"context" "context"
"encoding/json" "encoding/json"
"fmt" "fmt"
"github.com/1Panel-dev/1Panel/agent/app/task"
"github.com/1Panel-dev/1Panel/agent/cmd/server/nginx_conf"
"gopkg.in/ini.v1"
"os" "os"
"path" "path"
"path/filepath" "path/filepath"
@ -17,6 +14,10 @@ import (
"strings" "strings"
"time" "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"
"github.com/1Panel-dev/1Panel/agent/app/dto/request" "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/dto/response"
@ -82,11 +83,11 @@ func (r *RuntimeService) Create(create request.RuntimeCreate) (*model.Runtime, e
} }
exist, _ := runtimeRepo.GetFirst(opts...) exist, _ := runtimeRepo.GetFirst(opts...)
if exist != nil { if exist != nil {
return nil, buserr.New(constant.ErrNameIsExist) return nil, buserr.New("ErrNameIsExist")
} }
fileOp := files.NewFileOp() fileOp := files.NewFileOp()
runtimeDir := path.Join(constant.RuntimeDir, create.Type) runtimeDir := path.Join(global.Dir.RuntimeDir, create.Type)
if !fileOp.Stat(runtimeDir) { if !fileOp.Stat(runtimeDir) {
if err := fileOp.CreateDir(runtimeDir, constant.DirPerm); err != nil { if err := fileOp.CreateDir(runtimeDir, constant.DirPerm); err != nil {
return nil, err return nil, err
@ -107,11 +108,11 @@ func (r *RuntimeService) Create(create request.RuntimeCreate) (*model.Runtime, e
} }
exist, _ = runtimeRepo.GetFirst(runtimeRepo.WithImage(create.Image)) exist, _ = runtimeRepo.GetFirst(runtimeRepo.WithImage(create.Image))
if exist != nil { 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: case constant.RuntimeNode, constant.RuntimeJava, constant.RuntimeGo, constant.RuntimePython, constant.RuntimeDotNet:
if !fileOp.Stat(create.CodeDir) { if !fileOp.Stat(create.CodeDir) {
return nil, buserr.New(constant.ErrPathNotFound) return nil, buserr.New("ErrPathNotFound")
} }
create.Install = true create.Install = true
for _, export := range create.ExposedPorts { for _, export := range create.ExposedPorts {
@ -229,7 +230,7 @@ func (r *RuntimeService) Delete(runtimeDelete request.RuntimeDelete) error {
} }
website, _ := websiteRepo.GetFirst(websiteRepo.WithRuntimeID(runtimeDelete.ID)) website, _ := websiteRepo.GetFirst(websiteRepo.WithRuntimeID(runtimeDelete.ID))
if website.ID > 0 { if website.ID > 0 {
return buserr.New(constant.ErrDelWithWebsite) return buserr.New("ErrDelWithWebsite")
} }
if runtime.Resource != constant.ResourceAppstore { if runtime.Resource != constant.ResourceAppstore {
return runtimeRepo.DeleteBy(repo.WithByID(runtimeDelete.ID)) return runtimeRepo.DeleteBy(repo.WithByID(runtimeDelete.ID))
@ -441,7 +442,7 @@ func (r *RuntimeService) Update(req request.RuntimeUpdate) error {
case constant.RuntimePHP: case constant.RuntimePHP:
exist, _ := runtimeRepo.GetFirst(runtimeRepo.WithImage(req.Name), runtimeRepo.WithNotId(req.ID)) exist, _ := runtimeRepo.GetFirst(runtimeRepo.WithImage(req.Name), runtimeRepo.WithNotId(req.ID))
if exist != nil { if exist != nil {
return buserr.New(constant.ErrImageExist) return buserr.New("ErrImageExist")
} }
case constant.RuntimeNode, constant.RuntimeJava, constant.RuntimeGo, constant.RuntimePython, constant.RuntimeDotNet: case constant.RuntimeNode, constant.RuntimeJava, constant.RuntimeGo, constant.RuntimePython, constant.RuntimeDotNet:
if runtime.Port != port { if runtime.Port != port {
@ -465,7 +466,7 @@ func (r *RuntimeService) Update(req request.RuntimeUpdate) error {
return err return err
} }
fileOp := files.NewFileOp() 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 !fileOp.Stat(appVersionDir) || appDetail.Update {
if err := downloadApp(app, appDetail, nil, nil); err != nil { if err := downloadApp(app, appDetail, nil, nil); err != nil {
return err 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{ create := request.RuntimeCreate{
Image: req.Image, Image: req.Image,
Type: runtime.Type, 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) { func (r *RuntimeService) GetNodePackageRunScript(req request.NodePackageReq) ([]response.PackageScripts, error) {
fileOp := files.NewFileOp() fileOp := files.NewFileOp()
if !fileOp.Stat(req.CodeDir) { 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")) { 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")) content, err := fileOp.GetContent(path.Join(req.CodeDir, "package.json"))
if err != nil { if err != nil {
@ -548,7 +549,7 @@ func (r *RuntimeService) GetNodePackageRunScript(req request.NodePackageReq) ([]
} }
scripts, ok := packageMap["scripts"] scripts, ok := packageMap["scripts"]
if !ok { if !ok {
return nil, buserr.New(constant.ErrScriptsNotFound) return nil, buserr.New("ErrScriptsNotFound")
} }
var packageScripts []response.PackageScripts var packageScripts []response.PackageScripts
for k, v := range scripts.(map[string]interface{}) { for k, v := range scripts.(map[string]interface{}) {
@ -1050,7 +1051,7 @@ func (r *RuntimeService) GetSupervisorProcess(id uint) ([]response.SupervisorPro
if err != nil { if err != nil {
return nil, err 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) return handleProcessConfig(configDir, runtime.ContainerName)
} }
@ -1059,7 +1060,7 @@ func (r *RuntimeService) OperateSupervisorProcess(req request.PHPSupervisorProce
if err != nil { if err != nil {
return err 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) return handleProcess(configDir, req.SupervisorProcessConfig, runtime.ContainerName)
} }
@ -1068,7 +1069,7 @@ func (r *RuntimeService) OperateSupervisorProcessFile(req request.PHPSupervisorP
if err != nil { if err != nil {
return "", err 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") configDir := path.Join(supervisorDir, "supervisor.d")
logFile := path.Join(supervisorDir, "log", fmt.Sprintf("%s.out.log", req.SupervisorProcessFileReq.Name)) logFile := path.Join(supervisorDir, "log", fmt.Sprintf("%s.out.log", req.SupervisorProcessFileReq.Name))
return handleSupervisorFile(req.SupervisorProcessFileReq, configDir, runtime.ContainerName, logFile) return handleSupervisorFile(req.SupervisorProcessFileReq, configDir, runtime.ContainerName, logFile)

View File

@ -6,6 +6,14 @@ import (
"context" "context"
"encoding/json" "encoding/json"
"fmt" "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"
"github.com/1Panel-dev/1Panel/agent/app/dto/request" "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/dto/response"
@ -22,17 +30,10 @@ import (
"github.com/pkg/errors" "github.com/pkg/errors"
"github.com/subosito/gotenv" "github.com/subosito/gotenv"
"gopkg.in/yaml.v3" "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) { 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 { if err = fileOp.CopyDir(appVersionDir, runtimeDir); err != nil {
return 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) { 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 { if err = fileOp.CopyDirWithNewName(appVersionDir, runtimeDir, create.Name); err != nil {
return return
} }
@ -147,7 +148,7 @@ func runComposeCmdWithLog(operate string, composePath string, logPath string) er
err = cmd.Run() err = cmd.Run()
if err != nil { if err != nil {
return errors.New(buserr.New(constant.ErrRuntimeStart).Error() + ":" + err.Error()) return errors.New(buserr.New("ErrRuntimeStart").Error() + ":" + err.Error())
} }
return nil return nil
} }
@ -230,11 +231,11 @@ func buildRuntime(runtime *model.Runtime, oldImageID string, oldEnv string, rebu
err = cmd.Run() err = cmd.Run()
if err != nil { if err != nil {
runtime.Status = constant.RuntimeError 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) { 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 { } else {
runtime.Message = buserr.New(constant.ErrImageBuildErr).Error() + ":" + stderrBuf.String() runtime.Message = buserr.New("ErrImageBuildErr").Error() + ":" + stderrBuf.String()
} }
} else { } else {
if err = runComposeCmdWithLog(constant.RuntimeDown, runtime.GetComposePath(), runtime.GetLogPath()); err != nil { 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) err = cmd2.ExecWithLogFile(installCmd, 60*time.Minute, logPath)
if err != nil { if err != nil {
runtime.Status = constant.RuntimeError runtime.Status = constant.RuntimeError
runtime.Message = buserr.New(constant.ErrImageBuildErr).Error() + ":" + err.Error() runtime.Message = buserr.New("ErrImageBuildErr").Error() + ":" + err.Error()
_ = runtimeRepo.Save(runtime) _ = runtimeRepo.Save(runtime)
return return
} }
@ -422,7 +423,7 @@ func handleCompose(env gotenv.Env, composeContent []byte, create request.Runtime
} }
services, serviceValid := composeMap["services"].(map[string]interface{}) services, serviceValid := composeMap["services"].(map[string]interface{})
if !serviceValid { if !serviceValid {
err = buserr.New(constant.ErrFileParse) err = buserr.New("ErrFileParse")
return return
} }
serviceName := "" serviceName := ""
@ -500,7 +501,7 @@ func checkContainerName(name string) error {
return err return err
} }
if len(names) > 0 { if len(names) > 0 {
return buserr.New(constant.ErrContainerName) return buserr.New("ErrContainerName")
} }
return nil return nil
} }

View File

@ -6,7 +6,7 @@ import (
"time" "time"
"github.com/1Panel-dev/1Panel/agent/app/dto" "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/global"
"github.com/1Panel-dev/1Panel/agent/utils/encrypt" "github.com/1Panel-dev/1Panel/agent/utils/encrypt"
"github.com/1Panel-dev/1Panel/agent/utils/xpack" "github.com/1Panel-dev/1Panel/agent/utils/xpack"
@ -28,7 +28,7 @@ func NewISettingService() ISettingService {
func (u *SettingService) GetSettingInfo() (*dto.SettingInfo, error) { func (u *SettingService) GetSettingInfo() (*dto.SettingInfo, error) {
setting, err := settingRepo.GetList() setting, err := settingRepo.GetList()
if err != nil { if err != nil {
return nil, constant.ErrRecordNotFound return nil, buserr.New("ErrRecordNotFound")
} }
settingMap := make(map[string]string) settingMap := make(map[string]string)
for _, set := range setting { for _, set := range setting {
@ -92,11 +92,12 @@ func (u *SettingService) ReloadConn() error {
return nil return nil
} }
global.CONF.System.BaseDir = nodeInfo.BaseDir global.Dir.BaseDir = nodeInfo.BaseDir
global.CONF.System.Version = nodeInfo.Version global.CONF.Base.Version = nodeInfo.Version
global.CONF.System.Port = fmt.Sprintf("%v", nodeInfo.NodePort) global.CONF.Base.Port = fmt.Sprintf("%v", nodeInfo.NodePort)
if global.CONF.System.Port == "0" { global.CONF.Base.InstallDir = nodeInfo.BaseDir
global.CONF.System.Port = "9999" if global.CONF.Base.Port == "0" {
global.CONF.Base.Port = "9999"
} }
global.IsMaster = nodeInfo.Scope == "master" global.IsMaster = nodeInfo.Scope == "master"
return nil return nil

View File

@ -8,6 +8,7 @@ import (
"strings" "strings"
"github.com/1Panel-dev/1Panel/agent/app/repo" "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/dto"
"github.com/1Panel-dev/1Panel/agent/app/model" "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 { for _, snapName := range req.Names {
snap, _ := snapshotRepo.Get(repo.WithByName(strings.ReplaceAll(snapName, ".tar.gz", ""))) snap, _ := snapshotRepo.Get(repo.WithByName(strings.ReplaceAll(snapName, ".tar.gz", "")))
if snap.ID != 0 { if snap.ID != 0 {
return constant.ErrRecordExist return buserr.New("ErrRecordExist")
} }
} }
for _, snap := range req.Names { for _, snap := range req.Names {
@ -108,7 +109,7 @@ func (u *SnapshotService) LoadSnapshotData() (dto.SnapshotData, error) {
if err != nil { if err != nil {
return data, err return data, err
} }
itemBackups, err := loadFile(global.CONF.System.Backup, 8, fileOp) itemBackups, err := loadFile(global.Dir.LocalBackupDir, 8, fileOp)
if err != nil { if err != nil {
return data, err return data, err
} }
@ -220,7 +221,7 @@ func loadApps(fileOp fileUtils.FileOp) ([]dto.DataTree, error) {
Key: app.App.Key, Key: app.App.Key,
Name: app.Name, 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} 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 { if app.App.Key == constant.AppOpenresty && len(websites) != 0 {
itemAppData.IsDisable = true 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 { func loadAppBackup(list []dto.DataTree, fileOp fileUtils.FileOp) []dto.DataTree {
for i := 0; i < len(list); i++ { 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) itemAppBackupTree, err := loadFile(appBackupPath, 8, fileOp)
itemAppBackup := dto.DataTree{ID: uuid.NewString(), Label: "appBackup", IsCheck: true, Children: itemAppBackupTree, Path: appBackupPath} itemAppBackup := dto.DataTree{ID: uuid.NewString(), Label: "appBackup", IsCheck: true, Children: itemAppBackupTree, Path: appBackupPath}
if err == nil { if err == nil {
@ -286,7 +287,7 @@ func loadAppImage(list []dto.DataTree) []dto.DataTree {
for i := 0; i < len(list); i++ { for i := 0; i < len(list); i++ {
itemAppImage := dto.DataTree{ID: uuid.NewString(), Label: "appImage"} 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 { if err != nil {
list[i].Children = append(list[i].Children, itemAppImage) list[i].Children = append(list[i].Children, itemAppImage)
continue continue
@ -307,7 +308,7 @@ func loadAppImage(list []dto.DataTree) []dto.DataTree {
func loadPanelFile(fileOp fileUtils.FileOp) ([]dto.DataTree, error) { func loadPanelFile(fileOp fileUtils.FileOp) ([]dto.DataTree, error) {
var data []dto.DataTree 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 { if err != nil {
return data, err return data, err
} }
@ -316,19 +317,19 @@ func loadPanelFile(fileOp fileUtils.FileOp) ([]dto.DataTree, error) {
ID: uuid.NewString(), ID: uuid.NewString(),
Label: fileItem.Name(), Label: fileItem.Name(),
IsCheck: true, IsCheck: true,
Path: path.Join(global.CONF.System.BaseDir, "1panel", fileItem.Name()), Path: path.Join(global.Dir.DataDir, fileItem.Name()),
} }
switch itemData.Label { switch itemData.Label {
case "agent", "conf", "runtime", "docker", "secret", "task": case "agent", "conf", "runtime", "docker", "secret", "task":
itemData.IsDisable = true itemData.IsDisable = true
case "clamav": 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) itemData.Children, _ = loadFile(panelPath, 5, fileOp)
default: default:
continue continue
} }
if fileItem.IsDir() { 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 { if err != nil {
continue continue
} }

View File

@ -111,7 +111,7 @@ func (u *SnapshotService) SnapshotReCreate(id uint) error {
} }
func handleSnapshot(req dto.SnapshotCreate, taskItem *task.Task) { 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()} itemHelper := snapHelper{SnapID: req.ID, Task: *taskItem, FileOp: files.NewFileOp(), Ctx: context.Background()}
baseDir := path.Join(rootDir, "base") baseDir := path.Join(rootDir, "base")
_ = os.MkdirAll(baseDir, os.ModePerm) _ = os.MkdirAll(baseDir, os.ModePerm)
@ -204,7 +204,7 @@ type snapHelper struct {
func loadDbConn(snap *snapHelper, targetDir string, req dto.SnapshotCreate) error { func loadDbConn(snap *snapHelper, targetDir string, req dto.SnapshotCreate) error {
snap.Task.Log("---------------------- 1 / 8 ----------------------") snap.Task.Log("---------------------- 1 / 8 ----------------------")
snap.Task.LogStart(i18n.GetMsgByKey("SnapDBInfo")) 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) err := snap.FileOp.CopyDir(pathDB, targetDir)
snap.Task.LogWithStatus(i18n.GetWithName("SnapCopy", pathDB), err) snap.Task.LogWithStatus(i18n.GetWithName("SnapCopy", pathDB), err)
@ -296,8 +296,8 @@ func snapBaseData(snap snapHelper, targetDir string) error {
} }
remarkInfo, _ := json.MarshalIndent(SnapshotJson{ remarkInfo, _ := json.MarshalIndent(SnapshotJson{
BaseDir: global.CONF.System.BaseDir, BaseDir: global.Dir.BaseDir,
BackupDataDir: global.CONF.System.Backup, BackupDataDir: global.Dir.LocalBackupDir,
}, "", "\t") }, "", "\t")
err = os.WriteFile(path.Join(targetDir, "snapshot.json"), remarkInfo, 0640) err = os.WriteFile(path.Join(targetDir, "snapshot.json"), remarkInfo, 0640)
snap.Task.LogWithStatus(i18n.GetWithName("SnapCopy", path.Join(targetDir, "snapshot.json")), err) 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) snap.Task.LogWithStatus(i18n.GetMsgByKey("SnapCompressBackup"), err)
return err return err
@ -364,18 +364,18 @@ func loadBackupExcludes(snap snapHelper, req []dto.DataTree) []string {
if item.IsCheck { if item.IsCheck {
continue 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")) 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 { 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) snap.Task.LogWithStatus("delete snapshot from database", err)
} }
} else { } else {
fmt.Println(strings.TrimPrefix(path.Dir(item.Path), global.CONF.System.Backup+"/"), path.Base(item.Path)) 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.CONF.System.Backup+"/"), path.Base(item.Path)).Delete(&model.BackupRecord{}).Error; err != nil { 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) 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 { } else {
excludes = append(excludes, loadBackupExcludes(snap, item.Children)...) excludes = append(excludes, loadBackupExcludes(snap, item.Children)...)
} }
@ -387,7 +387,7 @@ func loadAppBackupExcludes(req []dto.DataTree) []string {
for _, item := range req { for _, item := range req {
if len(item.Children) == 0 { if len(item.Children) == 0 {
if !item.IsCheck { 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 { } else {
excludes = append(excludes, loadAppBackupExcludes(item.Children)...) 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") excludes = append(excludes, "./log/Website")
} }
rootDir := path.Join(global.CONF.System.BaseDir, "1panel") rootDir := global.Dir.DataDir
if strings.Contains(global.CONF.System.Backup, rootDir) { if strings.Contains(global.Dir.LocalBackupDir, rootDir) {
excludes = append(excludes, "."+strings.ReplaceAll(global.CONF.System.Backup, rootDir, "")) excludes = append(excludes, "."+strings.ReplaceAll(global.Dir.LocalBackupDir, rootDir, ""))
} }
ignoreVal, _ := settingRepo.Get(settingRepo.WithByKey("SnapshotIgnore")) ignoreVal, _ := settingRepo.Get(settingRepo.WithByKey("SnapshotIgnore"))
rules := strings.Split(ignoreVal.Value, ",") rules := strings.Split(ignoreVal.Value, ",")
@ -445,7 +445,7 @@ func loadPanelExcludes(req []dto.DataTree) []string {
for _, item := range req { for _, item := range req {
if len(item.Children) == 0 { if len(item.Children) == 0 {
if !item.IsCheck { 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 { } else {
excludes = append(excludes, loadPanelExcludes(item.Children)...) 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.Log("---------------------- 7 / 8 ----------------------")
snap.Task.LogStart(i18n.GetMsgByKey("SnapCompress")) 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)) fileName := fmt.Sprintf("%s.tar.gz", path.Base(rootDir))
err := snap.FileOp.TarGzCompressPro(true, rootDir, path.Join(tmpDir, fileName), secret, "") err := snap.FileOp.TarGzCompressPro(true, rootDir, path.Join(tmpDir, fileName), secret, "")
snap.Task.LogWithStatus(i18n.GetMsgByKey("SnapCompressFile"), err) 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.Log("---------------------- 8 / 8 ----------------------")
snap.Task.LogStart(i18n.GetMsgByKey("SnapUpload")) 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, ",")) accountMap, err := NewBackupClientMap(strings.Split(accounts, ","))
snap.Task.LogWithStatus(i18n.GetMsgByKey("SnapLoadBackup"), err) snap.Task.LogWithStatus(i18n.GetMsgByKey("SnapLoadBackup"), err)
if err != nil { if err != nil {

View File

@ -4,12 +4,13 @@ import (
"context" "context"
"encoding/json" "encoding/json"
"fmt" "fmt"
"github.com/1Panel-dev/1Panel/agent/app/repo"
"os" "os"
"path" "path"
"strings" "strings"
"sync" "sync"
"github.com/1Panel-dev/1Panel/agent/app/repo"
"github.com/1Panel-dev/1Panel/agent/app/dto" "github.com/1Panel-dev/1Panel/agent/app/dto"
"github.com/1Panel-dev/1Panel/agent/app/model" "github.com/1Panel-dev/1Panel/agent/app/model"
"github.com/1Panel-dev/1Panel/agent/app/task" "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) global.LOG.Errorf("new task for create snapshot failed, err: %v", err)
return 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) { if _, err := os.Stat(rootDir); err != nil && os.IsNotExist(err) {
_ = os.MkdirAll(rootDir, os.ModePerm) _ = os.MkdirAll(rootDir, os.ModePerm)
} }
@ -204,19 +205,19 @@ func backupBeforeRecover(name string, itemHelper *snapRecoverHelper) error {
itemHelper.Task.Log("---------------------- 3 / 10 ----------------------") itemHelper.Task.Log("---------------------- 3 / 10 ----------------------")
itemHelper.Task.LogStart(i18n.GetMsgByKey("BackupBeforeRecover")) 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") baseDir := path.Join(rootDir, "base")
if _, err := os.Stat(baseDir); err != nil { if _, err := os.Stat(baseDir); err != nil {
_ = os.MkdirAll(baseDir, os.ModePerm) _ = os.MkdirAll(baseDir, os.ModePerm)
} }
err := itemHelper.FileOp.CopyDirWithExclude(path.Join(global.CONF.System.BaseDir, "1panel"), rootDir, []string{"cache", "tmp"}) err := itemHelper.FileOp.CopyDirWithExclude(global.Dir.DataDir, rootDir, []string{"cache", "tmp"})
itemHelper.Task.LogWithStatus(i18n.GetWithName("SnapCopy", path.Join(global.CONF.System.BaseDir, "1panel")), err) itemHelper.Task.LogWithStatus(i18n.GetWithName("SnapCopy", global.Dir.DataDir), err)
if err != nil { if err != nil {
return err return err
} }
err = itemHelper.FileOp.CopyDirWithExclude(global.CONF.System.Backup, rootDir, []string{"system_snapshot"}) err = itemHelper.FileOp.CopyDirWithExclude(global.Dir.LocalBackupDir, rootDir, []string{"system_snapshot"})
itemHelper.Task.LogWithStatus(i18n.GetWithName("SnapCopy", global.CONF.System.Backup), err) itemHelper.Task.LogWithStatus(i18n.GetWithName("SnapCopy", global.Dir.LocalBackupDir), err)
if err != nil { if err != nil {
return err return err
} }
@ -369,7 +370,7 @@ func recoverBaseData(src string, itemHelper *snapRecoverHelper) error {
func recoverDBData(src string, itemHelper *snapRecoverHelper) error { func recoverDBData(src string, itemHelper *snapRecoverHelper) error {
itemHelper.Task.Log("---------------------- 7 / 10 ----------------------") itemHelper.Task.Log("---------------------- 7 / 10 ----------------------")
itemHelper.Task.LogStart(i18n.GetMsgByKey("RecoverDBData")) 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) itemHelper.Task.LogWithStatus(i18n.GetMsgByKey("RecoverDBData"), err)
return err return err

View File

@ -2,10 +2,11 @@ package service
import ( import (
"fmt" "fmt"
"github.com/1Panel-dev/1Panel/agent/app/repo"
"os" "os"
"path" "path"
"github.com/1Panel-dev/1Panel/agent/app/repo"
"github.com/1Panel-dev/1Panel/agent/app/dto" "github.com/1Panel-dev/1Panel/agent/app/dto"
"github.com/1Panel-dev/1Panel/agent/app/task" "github.com/1Panel-dev/1Panel/agent/app/task"
"github.com/1Panel-dev/1Panel/agent/constant" "github.com/1Panel-dev/1Panel/agent/constant"
@ -31,7 +32,7 @@ func (u *SnapshotService) SnapshotRollback(req dto.SnapshotRecover) error {
return err return err
} }
go func() { 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") baseDir := path.Join(rootDir, "base")
FileOp := files.NewFileOp() FileOp := files.NewFileOp()
@ -78,16 +79,16 @@ func (u *SnapshotService) SnapshotRollback(req dto.SnapshotRecover) error {
nil, nil,
) )
taskItem.AddSubTask( taskItem.AddSubTask(
i18n.GetWithName("SnapCopy", global.CONF.System.Backup), i18n.GetWithName("SnapCopy", global.Dir.LocalBackupDir),
func(t *task.Task) error { 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, nil,
) )
taskItem.AddSubTask( taskItem.AddSubTask(
i18n.GetWithName("SnapCopy", global.CONF.System.BaseDir), i18n.GetWithName("SnapCopy", global.Dir.BaseDir),
func(t *task.Task) error { 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, nil,
) )

View File

@ -2,8 +2,6 @@ package service
import ( import (
"fmt" "fmt"
"github.com/1Panel-dev/1Panel/agent/utils/geo"
"github.com/gin-gonic/gin"
"os" "os"
"os/user" "os/user"
"path" "path"
@ -12,6 +10,9 @@ import (
"strings" "strings"
"time" "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/app/dto"
"github.com/1Panel-dev/1Panel/agent/buserr" "github.com/1Panel-dev/1Panel/agent/buserr"
"github.com/1Panel-dev/1Panel/agent/constant" "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 { func (u *SSHService) GenerateSSH(req dto.GenerateSSH) error {
if cmd.CheckIllegal(req.EncryptionMode, req.Password) { if cmd.CheckIllegal(req.EncryptionMode, req.Password) {
return buserr.New(constant.ErrCmdIllegal) return buserr.New("ErrCmdIllegal")
} }
currentUser, err := user.Current() currentUser, err := user.Current()
if err != nil { if err != nil {

View File

@ -232,7 +232,7 @@ func (w WebsiteService) CreateWebsite(create request.WebsiteCreate) (err error)
} }
} }
if exist, _ := websiteRepo.GetBy(websiteRepo.WithAlias(alias)); len(exist) > 0 { if exist, _ := websiteRepo.GetBy(websiteRepo.WithAlias(alias)); len(exist) > 0 {
return buserr.New(constant.ErrAliasIsExist) return buserr.New("ErrAliasIsExist")
} }
if len(create.FtpPassword) != 0 { if len(create.FtpPassword) != 0 {
pass, err := base64.StdEncoding.DecodeString(create.FtpPassword) 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: case constant.AppPostgresql, constant.AppPostgres:
oldPostgresqlDb, _ := postgresqlRepo.Get(repo.WithByName(create.DbName), repo.WithByFrom(constant.ResourceLocal)) oldPostgresqlDb, _ := postgresqlRepo.Get(repo.WithByName(create.DbName), repo.WithByFrom(constant.ResourceLocal))
if oldPostgresqlDb.ID > 0 { if oldPostgresqlDb.ID > 0 {
return buserr.New(constant.ErrDbUserNotValid) return buserr.New("ErrDbUserNotValid")
} }
var createPostgresql dto.PostgresqlDBCreate var createPostgresql dto.PostgresqlDBCreate
createPostgresql.Name = dbConfig.DbName createPostgresql.Name = dbConfig.DbName
@ -316,7 +316,7 @@ func (w WebsiteService) CreateWebsite(create request.WebsiteCreate) (err error)
case constant.AppMysql, constant.AppMariaDB: case constant.AppMysql, constant.AppMariaDB:
oldMysqlDb, _ := mysqlRepo.Get(repo.WithByName(dbConfig.DbName), repo.WithByFrom(constant.ResourceLocal)) oldMysqlDb, _ := mysqlRepo.Get(repo.WithByName(dbConfig.DbName), repo.WithByFrom(constant.ResourceLocal))
if oldMysqlDb.ID > 0 { if oldMysqlDb.ID > 0 {
return buserr.New(constant.ErrDbUserNotValid) return buserr.New("ErrDbUserNotValid")
} }
var createMysql dto.MysqlDBCreate var createMysql dto.MysqlDBCreate
createMysql.Name = dbConfig.DbName createMysql.Name = dbConfig.DbName
@ -616,7 +616,7 @@ func (w WebsiteService) DeleteWebsite(req request.WebsiteDelete) error {
} }
tx.Commit() 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 { if _, err := os.Stat(uploadDir); err == nil {
_ = os.RemoveAll(uploadDir) _ = os.RemoveAll(uploadDir)
} }
@ -1130,7 +1130,7 @@ func (w WebsiteService) PreInstallCheck(req request.WebsiteInstallCheckReq) ([]r
res = append(res, response.WebsitePreInstallCheck{ res = append(res, response.WebsitePreInstallCheck{
Name: appInstall.Name, Name: appInstall.Name,
AppName: app.Name, AppName: app.Name,
Status: buserr.WithDetail(constant.ErrNotInstall, app.Name, nil).Error(), Status: buserr.WithDetail("ErrNotInstall", app.Name, nil).Error(),
Version: appInstall.Version, Version: appInstall.Version,
}) })
showErr = true showErr = true
@ -1473,7 +1473,7 @@ func (w WebsiteService) OperateCustomRewrite(req request.CustomRewriteOperate) e
switch req.Operate { switch req.Operate {
case "create": case "create":
if fileOp.Stat(rewriteFile) { if fileOp.Stat(rewriteFile) {
return buserr.New(constant.ErrNameIsExist) return buserr.New("ErrNameIsExist")
} }
return fileOp.WriteFile(rewriteFile, strings.NewReader(req.Content), constant.DirPerm) return fileOp.WriteFile(rewriteFile, strings.NewReader(req.Content), constant.DirPerm)
case "delete": case "delete":
@ -1562,7 +1562,7 @@ func (w WebsiteService) OperateProxy(req request.WebsiteProxyConfig) (err error)
backPath := path.Join(includeDir, backName) backPath := path.Join(includeDir, backName)
if req.Operate == "create" && (fileOp.Stat(includePath) || fileOp.Stat(backPath)) { if req.Operate == "create" && (fileOp.Stat(includePath) || fileOp.Stat(backPath)) {
err = buserr.New(constant.ErrNameIsExist) err = buserr.New("ErrNameIsExist")
return return
} }
@ -1642,7 +1642,7 @@ func (w WebsiteService) OperateProxy(req request.WebsiteProxyConfig) (err error)
location.UpdateDirective("proxy_ssl_server_name", []string{"off"}) location.UpdateDirective("proxy_ssl_server_name", []string{"off"})
} }
if err = nginx.WriteConfig(config, nginx.IndentedStyle); err != nil { 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) nginxInclude := fmt.Sprintf("/www/sites/%s/proxy/*.conf", website.Alias)
return updateNginxConfig(constant.NginxScopeServer, []dto.NginxParam{{Name: "include", Params: []string{nginxInclude}}}, &website) 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, ":") authParams := strings.Split(line, ":")
username := authParams[0] username := authParams[0]
if username == req.Username { if username == req.Username {
err = buserr.New(constant.ErrUsernameIsExist) err = buserr.New("ErrUsernameIsExist")
return return
} }
} }
@ -1969,7 +1969,7 @@ func (w WebsiteService) UpdateAuthBasic(req request.NginxAuthUpdate) (err error)
} }
} }
if !userExist { if !userExist {
err = buserr.New(constant.ErrUsernameIsNotExist) err = buserr.New("ErrUsernameIsNotExist")
return return
} }
case "delete": case "delete":
@ -2120,7 +2120,7 @@ func (w WebsiteService) UpdatePathAuthBasic(req request.NginxPathAuthUpdate) err
return err return err
} }
if fileOp.Stat(confPath) || fileOp.Stat(passPath) { if fileOp.Stat(confPath) || fileOp.Stat(passPath) {
return buserr.New(constant.ErrNameIsExist) return buserr.New("ErrNameIsExist")
} }
case "edit": case "edit":
par, err := parser.NewParser(confPath) par, err := parser.NewParser(confPath)
@ -2148,7 +2148,7 @@ func (w WebsiteService) UpdatePathAuthBasic(req request.NginxPathAuthUpdate) err
} }
_ = fileOp.SaveFile(passPath, line, constant.DirPerm) _ = fileOp.SaveFile(passPath, line, constant.DirPerm)
if err = nginx.WriteConfig(config, nginx.IndentedStyle); err != nil { 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) 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 { 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) backPath := path.Join(includeDir, backName)
if req.Operate == "create" && (fileOp.Stat(includePath) || fileOp.Stat(backPath)) { if req.Operate == "create" && (fileOp.Stat(includePath) || fileOp.Stat(backPath)) {
err = buserr.New(constant.ErrNameIsExist) err = buserr.New("ErrNameIsExist")
return return
} }
@ -2461,7 +2461,7 @@ func (w WebsiteService) OperateRedirect(req request.NginxRedirectReq) (err error
config.Block = block config.Block = block
if err = nginx.WriteConfig(config, nginx.IndentedStyle); err != nil { 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) 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)) filePath := path.Join(includeDir, fmt.Sprintf("%s.conf", req.Name))
if fileOp.Stat(filePath) { if fileOp.Stat(filePath) {
return buserr.New(constant.ErrNameIsExist) return buserr.New("ErrNameIsExist")
} }
config, err := parser.NewStringParser(string(nginx_conf.Upstream)).Parse() config, err := parser.NewStringParser(string(nginx_conf.Upstream)).Parse()
if err != nil { if err != nil {
@ -2926,7 +2926,7 @@ func (w WebsiteService) CreateLoadBalance(req request.WebsiteLBCreate) error {
}() }()
if err = nginx.WriteConfig(config, nginx.IndentedStyle); err != nil { 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) nginxInclude := fmt.Sprintf("/www/sites/%s/upstream/*.conf", website.Alias)
if err = updateNginxConfig("", []dto.NginxParam{{Name: "include", Params: []string{nginxInclude}}}, &website); err != nil { 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 { 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 { if err = opNginx(nginxInstall.ContainerName, constant.NginxReload); err != nil {
return err return err

View File

@ -7,7 +7,6 @@ import (
"github.com/1Panel-dev/1Panel/agent/app/model" "github.com/1Panel-dev/1Panel/agent/app/model"
"github.com/1Panel-dev/1Panel/agent/app/repo" "github.com/1Panel-dev/1Panel/agent/app/repo"
"github.com/1Panel-dev/1Panel/agent/buserr" "github.com/1Panel-dev/1Panel/agent/buserr"
"github.com/1Panel-dev/1Panel/agent/constant"
"github.com/1Panel-dev/1Panel/agent/utils/ssl" "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) { func (w WebsiteAcmeAccountService) Create(create request.WebsiteAcmeAccountCreate) (*response.WebsiteAcmeAccountDTO, error) {
exist, _ := websiteAcmeRepo.GetFirst(websiteAcmeRepo.WithEmail(create.Email), websiteAcmeRepo.WithType(create.Type)) exist, _ := websiteAcmeRepo.GetFirst(websiteAcmeRepo.WithEmail(create.Email), websiteAcmeRepo.WithType(create.Type))
if exist != nil { if exist != nil {
return nil, buserr.New(constant.ErrEmailIsExist) return nil, buserr.New("ErrEmailIsExist")
} }
acmeAccount := &model.WebsiteAcmeAccount{ acmeAccount := &model.WebsiteAcmeAccount{
Email: create.Email, Email: create.Email,
@ -48,7 +47,7 @@ func (w WebsiteAcmeAccountService) Create(create request.WebsiteAcmeAccountCreat
if create.Type == "google" { if create.Type == "google" {
if create.EabKid == "" || create.EabHmacKey == "" { if create.EabKid == "" || create.EabHmacKey == "" {
return nil, buserr.New(constant.ErrEabKidOrEabHmacKeyCannotBlank) return nil, buserr.New("ErrEabKidOrEabHmacKeyCannotBlank")
} }
acmeAccount.EabKid = create.EabKid acmeAccount.EabKid = create.EabKid
acmeAccount.EabHmacKey = create.EabHmacKey acmeAccount.EabHmacKey = create.EabHmacKey
@ -73,7 +72,7 @@ func (w WebsiteAcmeAccountService) Create(create request.WebsiteAcmeAccountCreat
func (w WebsiteAcmeAccountService) Delete(id uint) error { func (w WebsiteAcmeAccountService) Delete(id uint) error {
if ssls, _ := websiteSSLRepo.List(websiteSSLRepo.WithByAcmeAccountId(id)); len(ssls) > 0 { 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)) return websiteAcmeRepo.DeleteBy(repo.WithByID(id))
} }

View File

@ -10,8 +10,6 @@ import (
"crypto/x509/pkix" "crypto/x509/pkix"
"encoding/pem" "encoding/pem"
"fmt" "fmt"
"github.com/1Panel-dev/1Panel/agent/app/repo"
"github.com/1Panel-dev/1Panel/agent/utils/common"
"log" "log"
"math/big" "math/big"
"net" "net"
@ -20,6 +18,9 @@ import (
"strings" "strings"
"time" "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/request"
"github.com/1Panel-dev/1Panel/agent/app/dto/response" "github.com/1Panel-dev/1Panel/agent/app/dto/response"
"github.com/1Panel-dev/1Panel/agent/app/model" "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) { func (w WebsiteCAService) Create(create request.WebsiteCACreate) (*request.WebsiteCACreate, error) {
if exist, _ := websiteCARepo.GetFirst(repo.WithByName(create.Name)); exist.ID > 0 { 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{ ca := &model.WebsiteCA{
@ -212,7 +213,7 @@ func (w WebsiteCAService) ObtainSSL(req request.WebsiteCAObtain) (*model.Website
} }
if req.PushDir { if req.PushDir {
if !files.NewFileOp().Stat(req.Dir) { if !files.NewFileOp().Stat(req.Dir) {
return nil, buserr.New(constant.ErrLinkPathNotFound) return nil, buserr.New("ErrLinkPathNotFound")
} }
websiteSSL.Dir = req.Dir 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() defer logFile.Close()
logger := log.New(logFile, "", log.LstdFlags) logger := log.New(logFile, "", log.LstdFlags)
logger.Println(i18n.GetMsgWithMap("ApplySSLSuccess", map[string]interface{}{"domain": strings.Join(domains, ",")})) logger.Println(i18n.GetMsgWithMap("ApplySSLSuccess", map[string]interface{}{"domain": strings.Join(domains, ",")}))
saveCertificateFile(websiteSSL, logger) saveCertificateFile(websiteSSL, logger)
if websiteSSL.ExecShell { if websiteSSL.ExecShell {
workDir := constant.DataDir workDir := global.Dir.DataDir
if websiteSSL.PushDir { if websiteSSL.PushDir {
workDir = websiteSSL.Dir workDir = websiteSSL.Dir
} }
@ -425,7 +426,7 @@ func (w WebsiteCAService) DownloadFile(id uint) (*os.File, error) {
return nil, err return nil, err
} }
fileOp := files.NewFileOp() 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 fileOp.Stat(dir) {
if err = fileOp.DeleteDir(dir); err != nil { if err = fileOp.DeleteDir(dir); err != nil {
return nil, err return nil, err

View File

@ -2,6 +2,7 @@ package service
import ( import (
"encoding/json" "encoding/json"
"github.com/1Panel-dev/1Panel/agent/app/repo" "github.com/1Panel-dev/1Panel/agent/app/repo"
"github.com/1Panel-dev/1Panel/agent/app/dto" "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/dto/response"
"github.com/1Panel-dev/1Panel/agent/app/model" "github.com/1Panel-dev/1Panel/agent/app/model"
"github.com/1Panel-dev/1Panel/agent/buserr" "github.com/1Panel-dev/1Panel/agent/buserr"
"github.com/1Panel-dev/1Panel/agent/constant"
) )
type WebsiteDnsAccountService struct { 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) { func (w WebsiteDnsAccountService) Create(create request.WebsiteDnsAccountCreate) (request.WebsiteDnsAccountCreate, error) {
exist, _ := websiteDnsRepo.GetFirst(repo.WithByName(create.Name)) exist, _ := websiteDnsRepo.GetFirst(repo.WithByName(create.Name))
if exist != nil { if exist != nil {
return request.WebsiteDnsAccountCreate{}, buserr.New(constant.ErrNameIsExist) return request.WebsiteDnsAccountCreate{}, buserr.New("ErrNameIsExist")
} }
authorization, err := json.Marshal(create.Authorization) authorization, err := json.Marshal(create.Authorization)
@ -70,7 +70,7 @@ func (w WebsiteDnsAccountService) Update(update request.WebsiteDnsAccountUpdate)
exists, _ := websiteDnsRepo.List(repo.WithByName(update.Name)) exists, _ := websiteDnsRepo.List(repo.WithByName(update.Name))
for _, exist := range exists { for _, exist := range exists {
if exist.ID != update.ID { if exist.ID != update.ID {
return request.WebsiteDnsAccountUpdate{}, buserr.New(constant.ErrNameIsExist) return request.WebsiteDnsAccountUpdate{}, buserr.New("ErrNameIsExist")
} }
} }
if err := websiteDnsRepo.Save(model.WebsiteDnsAccount{ if err := websiteDnsRepo.Save(model.WebsiteDnsAccount{
@ -89,7 +89,7 @@ func (w WebsiteDnsAccountService) Update(update request.WebsiteDnsAccountUpdate)
func (w WebsiteDnsAccountService) Delete(id uint) error { func (w WebsiteDnsAccountService) Delete(id uint) error {
if ssls, _ := websiteSSLRepo.List(websiteSSLRepo.WithByDnsAccountId(id)); len(ssls) > 0 { 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)) return websiteDnsRepo.DeleteBy(repo.WithByID(id))
} }

View File

@ -64,7 +64,7 @@ func (w WebsiteSSLService) Page(search request.WebsiteSSLSearch) (int64, []respo
for _, model := range sslList { for _, model := range sslList {
result = append(result, response.WebsiteSSLDTO{ result = append(result, response.WebsiteSSLDTO{
WebsiteSSL: model, 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 return total, result, err
@ -194,8 +194,8 @@ func reloadSystemSSL(websiteSSL *model.WebsiteSSL, logger *log.Logger) {
systemSSLEnable, sslID := GetSystemSSL() systemSSLEnable, sslID := GetSystemSSL()
if systemSSLEnable && sslID == websiteSSL.ID { if systemSSLEnable && sslID == websiteSSL.ID {
fileOp := files.NewFileOp() fileOp := files.NewFileOp()
certPath := path.Join(global.CONF.System.BaseDir, "1panel/secret/server.crt") certPath := path.Join(global.Dir.DataDir, "secret/server.crt")
keyPath := path.Join(global.CONF.System.BaseDir, "1panel/secret/server.key") keyPath := path.Join(global.Dir.DataDir, "secret/server.key")
printSSLLog(logger, "StartUpdateSystemSSL", nil, logger == nil) printSSLLog(logger, "StartUpdateSystemSSL", nil, logger == nil)
if err := fileOp.WriteFile(certPath, strings.NewReader(websiteSSL.Pem), 0600); err != 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()) 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() { 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() defer logFile.Close()
logger := log.New(logFile, "", log.LstdFlags) logger := log.New(logFile, "", log.LstdFlags)
legoLogger.Logger = logger legoLogger.Logger = logger
@ -334,7 +334,7 @@ func (w WebsiteSSLService) ObtainSSL(apply request.WebsiteSSLApply) error {
saveCertificateFile(websiteSSL, logger) saveCertificateFile(websiteSSL, logger)
if websiteSSL.ExecShell { if websiteSSL.ExecShell {
workDir := constant.DataDir workDir := global.Dir.DataDir
if websiteSSL.PushDir { if websiteSSL.PushDir {
workDir = websiteSSL.Dir workDir = websiteSSL.Dir
} }
@ -364,7 +364,7 @@ func (w WebsiteSSLService) ObtainSSL(apply request.WebsiteSSLApply) error {
return return
} }
if err := opNginx(nginxInstall.ContainerName, constant.NginxReload); err != nil { if err := opNginx(nginxInstall.ContainerName, constant.NginxReload); err != nil {
printSSLLog(logger, constant.ErrSSLApply, nil, apply.DisableLog) printSSLLog(logger, "ErrSSLApply", nil, apply.DisableLog)
return return
} }
printSSLLog(logger, "ApplyWebSiteSSLSuccess", nil, apply.DisableLog) printSSLLog(logger, "ApplyWebSiteSSLSuccess", nil, apply.DisableLog)
@ -636,7 +636,7 @@ func (w WebsiteSSLService) DownloadFile(id uint) (*os.File, error) {
return nil, err return nil, err
} }
fileOp := files.NewFileOp() 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 fileOp.Stat(dir) {
if err = fileOp.DeleteDir(dir); err != nil { if err = fileOp.DeleteDir(dir); err != nil {
return nil, err return nil, err

View File

@ -3,7 +3,6 @@ package service
import ( import (
"encoding/json" "encoding/json"
"fmt" "fmt"
"github.com/1Panel-dev/1Panel/agent/app/repo"
"log" "log"
"os" "os"
"path" "path"
@ -12,6 +11,8 @@ import (
"strings" "strings"
"time" "time"
"github.com/1Panel-dev/1Panel/agent/app/repo"
"github.com/1Panel-dev/1Panel/agent/utils/xpack" "github.com/1Panel-dev/1Panel/agent/utils/xpack"
"github.com/1Panel-dev/1Panel/agent/app/dto/request" "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_pass", []string{website.Proxy})
location.UpdateDirective("proxy_set_header", []string{"Host", "$host"}) location.UpdateDirective("proxy_set_header", []string{"Host", "$host"})
if err := nginx.WriteConfig(config, nginx.IndentedStyle); err != nil { if err := nginx.WriteConfig(config, nginx.IndentedStyle); err != nil {
return buserr.WithErr(constant.ErrUpdateBuWebsite, err) return buserr.WithErr("ErrUpdateBuWebsite", err)
} }
return nil return nil
} }
@ -760,7 +761,7 @@ func toMapStr(m map[string]interface{}) map[string]string {
} }
func deleteWebsiteFolder(nginxInstall model.AppInstall, website *model.Website) error { 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) siteFolder := path.Join(nginxFolder, "www", "sites", website.Alias)
fileOp := files.NewFileOp() fileOp := files.NewFileOp()
if fileOp.Stat(siteFolder) { if fileOp.Stat(siteFolder) {
@ -965,7 +966,7 @@ func getWebsiteDomains(domains []request.WebsiteDomain, defaultPort int, website
for _, domain := range domainModels { for _, domain := range domainModels {
if exist, _ := websiteDomainRepo.GetFirst(websiteDomainRepo.WithDomain(domain.Domain), websiteDomainRepo.WithPort(domain.Port)); exist.ID > 0 { if exist, _ := websiteDomainRepo.GetFirst(websiteDomainRepo.WithDomain(domain.Domain), websiteDomainRepo.WithPort(domain.Port)); exist.ID > 0 {
website, _ := websiteRepo.GetFirst(repo.WithByID(exist.WebsiteID)) website, _ := websiteRepo.GetFirst(repo.WithByID(exist.WebsiteID))
err = buserr.WithName(constant.ErrDomainIsUsed, website.PrimaryDomain) err = buserr.WithName("ErrDomainIsUsed", website.PrimaryDomain)
return return
} }
} }
@ -993,7 +994,7 @@ func getWebsiteDomains(domains []request.WebsiteDomain, defaultPort int, website
return return
} }
if common.ScanPort(port) { if common.ScanPort(port) {
err = buserr.WithDetail(constant.ErrPortInUsed, port, nil) err = buserr.WithDetail("ErrPortInUsed", port, nil)
return return
} }
} }
@ -1057,13 +1058,13 @@ func UpdateSSLConfig(websiteSSL model.WebsiteSSL) error {
return err return err
} }
if err := opNginx(nginxInstall.ContainerName, constant.NginxReload); err != nil { if err := opNginx(nginxInstall.ContainerName, constant.NginxReload); err != nil {
return buserr.WithErr(constant.ErrSSLApply, err) return buserr.WithErr("ErrSSLApply", err)
} }
} }
enable, sslID := GetSystemSSL() enable, sslID := GetSystemSSL()
if enable && sslID == websiteSSL.ID { if enable && sslID == websiteSSL.ID {
fileOp := files.NewFileOp() 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 { 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()) global.LOG.Errorf("Failed to update the SSL certificate File for 1Panel System domain [%s] , err:%s", websiteSSL.PrimaryDomain, err.Error())
return err 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\""}) location.RemoveDirective("add_header", []string{"Strict-Transport-Security", "\"max-age=31536000\""})
} }
if err = nginx.WriteConfig(config, nginx.IndentedStyle); err != nil { 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")) siteSetting, _ := settingRepo.Get(settingRepo.WithByKey("WEBSITE_DIR"))
dir := siteSetting.Value dir := siteSetting.Value
if dir == "" { if dir == "" {
dir = path.Join(constant.DataDir, "www") dir = path.Join(global.Dir.DataDir, "www")
} }
return dir return dir
} }

View File

@ -10,6 +10,7 @@ import (
"time" "time"
"github.com/1Panel-dev/1Panel/agent/buserr" "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/model"
"github.com/1Panel-dev/1Panel/agent/app/repo" "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 == "" { if taskID == "" {
taskID = uuid.New().String() 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.Stat(logDir); os.IsNotExist(err) {
if err = os.MkdirAll(logDir, constant.DirPerm); err != nil { if err = os.MkdirAll(logDir, constant.DirPerm); err != nil {
return nil, fmt.Errorf("failed to create log directory: %w", err) 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) file, err := os.OpenFile(logPath, os.O_TRUNC|os.O_CREATE|os.O_WRONLY, constant.FilePerm)
if err != nil { if err != nil {
return nil, fmt.Errorf("failed to open log file: %w", err) return nil, fmt.Errorf("failed to open log file: %w", err)

View File

@ -1,6 +1,8 @@
system: base:
base_dir: /opt install_dir: /opt
mode: dev mode: dev
remote_rul:
repo_url: https://resource.fit2cloud.com/1panel/package repo_url: https://resource.fit2cloud.com/1panel/package
resource_url: https://resource.fit2cloud.com/1panel/resource resource_url: https://resource.fit2cloud.com/1panel/resource
app_repo: https://apps-assets.fit2cloud.com app_repo: https://apps-assets.fit2cloud.com

View File

@ -1,6 +0,0 @@
package configs
type ServerConfig struct {
System System `mapstructure:"system"`
LogConfig LogConfig `mapstructure:"log"`
}

View File

@ -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"`
}

View File

@ -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"`
}

View File

@ -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")
)

View File

@ -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"
)

51
agent/global/config.go Normal file
View File

@ -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"`
}

View File

@ -1,7 +1,6 @@
package global package global
import ( import (
"github.com/1Panel-dev/1Panel/agent/configs"
badger_db "github.com/1Panel-dev/1Panel/agent/init/cache/db" badger_db "github.com/1Panel-dev/1Panel/agent/init/cache/db"
"github.com/go-playground/validator/v10" "github.com/go-playground/validator/v10"
"github.com/nicksnyder/go-i18n/v2/i18n" "github.com/nicksnyder/go-i18n/v2/i18n"
@ -16,12 +15,15 @@ var (
MonitorDB *gorm.DB MonitorDB *gorm.DB
TaskDB *gorm.DB TaskDB *gorm.DB
CoreDB *gorm.DB CoreDB *gorm.DB
LOG *logrus.Logger LOG *logrus.Logger
CONF configs.ServerConfig CONF ServerConfig
VALID *validator.Validate VALID *validator.Validate
CACHE *badger_db.Cache CACHE *badger_db.Cache
Viper *viper.Viper Viper *viper.Viper
Dir SystemDir
Cron *cron.Cron Cron *cron.Cron
MonitorCronID cron.EntryID MonitorCronID cron.EntryID

View File

@ -4,10 +4,10 @@ ErrInitialPassword: "原密码错误"
ErrInternalServer: "服务内部错误: {{ .detail }}" ErrInternalServer: "服务内部错误: {{ .detail }}"
ErrRecordExist: "记录已存在" ErrRecordExist: "记录已存在"
ErrRecordNotFound: "记录未能找到" ErrRecordNotFound: "记录未能找到"
ErrStructTransform: "类型转换失败: {{ .detail }}" ErrStructTransform: "类型转换失败: {{ .err }}"
ErrNotLogin: "用户未登录: {{ .detail }}" ErrNotLogin: "用户未登录: {{ .detail }}"
ErrPasswordExpired: "当前密码已过期: {{ .detail }}" ErrPasswordExpired: "当前密码已过期: {{ .detail }}"
ErrNotSupportType: "系统暂不支持当前类型: {{ .detail }}" ErrNotSupportType: "系统暂不支持当前类型: {{ .name }}"
ErrProxy: "请求错误,请检查该节点状态: {{ .detail }}" ErrProxy: "请求错误,请检查该节点状态: {{ .detail }}"
ErrApiConfigStatusInvalid: "API 接口禁止访问: {{ .detail }}" ErrApiConfigStatusInvalid: "API 接口禁止访问: {{ .detail }}"
ErrApiConfigKeyInvalid: "API 接口密钥错误: {{ .detail }}" ErrApiConfigKeyInvalid: "API 接口密钥错误: {{ .detail }}"
@ -112,7 +112,6 @@ ErrPathNotDelete: "所选目录不可删除"
ErrDomainIsExist: "域名已存在" ErrDomainIsExist: "域名已存在"
ErrAliasIsExist: "代号已存在" ErrAliasIsExist: "代号已存在"
ErrAppDelete: '其他网站使用此应用,无法删除' ErrAppDelete: '其他网站使用此应用,无法删除'
ErrGroupIsUsed: '分组正在使用中,无法删除'
ErrBackupMatch: '该备份文件与当前网站部分数据不匹配 {{ .detail}}' ErrBackupMatch: '该备份文件与当前网站部分数据不匹配 {{ .detail}}'
ErrBackupExist: '该备份文件对应部分源数据不存在 {{ .detail}}' ErrBackupExist: '该备份文件对应部分源数据不存在 {{ .detail}}'
ErrPHPResource: '本地运行环境不支持切换!' ErrPHPResource: '本地运行环境不支持切换!'

View File

@ -1,43 +1,11 @@
package app package app
import ( import (
"path"
"github.com/1Panel-dev/1Panel/agent/utils/docker" "github.com/1Panel-dev/1Panel/agent/utils/docker"
"github.com/1Panel-dev/1Panel/agent/utils/firewall" "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() { 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() { go func() {
_ = docker.CreateDefaultDockerNetwork() _ = docker.CreateDefaultDockerNetwork()
@ -46,9 +14,3 @@ func Init() {
} }
}() }()
} }
func createDir(fileOp files.FileOp, dirPath string) {
if !fileOp.Stat(dirPath) {
_ = fileOp.CreateDir(dirPath, constant.DirPerm)
}
}

View File

@ -8,7 +8,7 @@ import (
) )
func Init() { func Init() {
global.DB = common.LoadDBConnByPath(path.Join(global.CONF.System.DbPath, "agent.db"), "agent") global.DB = common.LoadDBConnByPath(path.Join(global.Dir.DbDir, "agent.db"), "agent")
global.TaskDB = common.LoadDBConnByPath(path.Join(global.CONF.System.DbPath, "task.db"), "task") global.TaskDB = common.LoadDBConnByPath(path.Join(global.Dir.DbDir, "task.db"), "task")
global.MonitorDB = common.LoadDBConnByPath(path.Join(global.CONF.System.DbPath, "monitor.db"), "monitor") global.MonitorDB = common.LoadDBConnByPath(path.Join(global.Dir.DbDir, "monitor.db"), "monitor")
} }

44
agent/init/dir/dir.go Normal file
View File

@ -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
}

View File

@ -17,7 +17,6 @@ func Init() {
initGlobalData() initGlobalData()
handleCronjobStatus() handleCronjobStatus()
handleSnapStatus() handleSnapStatus()
loadLocalDir()
} }
func initGlobalData() { func initGlobalData() {
@ -28,10 +27,10 @@ func initGlobalData() {
if err := settingRepo.Update("SystemStatus", "Free"); err != nil { if err := settingRepo.Update("SystemStatus", "Free"); err != nil {
global.LOG.Fatalf("init service before start failed, err: %v", err) 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() _ = service.NewISettingService().ReloadConn()
if global.IsMaster { 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) { func handleCronJobAlert(cronjob *model.Cronjob) {
pushAlert := dto.PushAlert{ pushAlert := dto.PushAlert{
TaskName: cronjob.Name, TaskName: cronjob.Name,

View File

@ -9,7 +9,6 @@ import (
"github.com/1Panel-dev/1Panel/agent/log" "github.com/1Panel-dev/1Panel/agent/log"
"github.com/1Panel-dev/1Panel/agent/configs"
"github.com/1Panel-dev/1Panel/agent/global" "github.com/1Panel-dev/1Panel/agent/global"
"github.com/sirupsen/logrus" "github.com/sirupsen/logrus"
@ -23,14 +22,14 @@ const (
func Init() { func Init() {
l := logrus.New() l := logrus.New()
setOutput(l, global.CONF.LogConfig) setOutput(l, (global.CONF.Log))
global.LOG = l global.LOG = l
global.LOG.Info("init logger successfully") 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{ writer, err := log.NewWriterFromConfig(&log.Config{
LogPath: global.CONF.System.LogPath, LogPath: global.Dir.LogDir,
FileName: config.LogName, FileName: config.LogName,
TimeTagFormat: FileTImeFormat, TimeTagFormat: FileTImeFormat,
MaxRemain: config.MaxBackup, MaxRemain: config.MaxBackup,

View File

@ -75,7 +75,7 @@ var AddMonitorTable = &gormigrate.Migration{
var InitSetting = &gormigrate.Migration{ var InitSetting = &gormigrate.Migration{
ID: "20240722-init-setting", ID: "20240722-init-setting",
Migrate: func(tx *gorm.DB) error { Migrate: func(tx *gorm.DB) error {
global.CONF.System.EncryptKey = common.RandStr(16) global.CONF.Base.EncryptKey = common.RandStr(16)
_, nodeInfo, err := xpack.LoadNodeInfo() _, nodeInfo, err := xpack.LoadNodeInfo()
if err != nil { if err != nil {
return err return err
@ -238,7 +238,7 @@ var InitBackup = &gormigrate.Migration{
if err := tx.Create(&model.BackupAccount{ if err := tx.Create(&model.BackupAccount{
Name: "localhost", Name: "localhost",
Type: "LOCAL", Type: "LOCAL",
BackupPath: path.Join(global.CONF.System.BaseDir, "1panel/backup"), BackupPath: path.Join(global.Dir.DataDir, "backup"),
}).Error; err != nil { }).Error; err != nil {
return err return err
} }

View File

@ -6,7 +6,6 @@ import (
"path" "path"
"github.com/1Panel-dev/1Panel/agent/cmd/server/conf" "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/global"
"github.com/1Panel-dev/1Panel/agent/utils/files" "github.com/1Panel-dev/1Panel/agent/utils/files"
"github.com/1Panel-dev/1Panel/agent/utils/xpack" "github.com/1Panel-dev/1Panel/agent/utils/xpack"
@ -21,12 +20,12 @@ func Init() {
v := viper.NewWithOptions() v := viper.NewWithOptions()
v.SetConfigType("yaml") v.SetConfigType("yaml")
config := configs.ServerConfig{} config := global.ServerConfig{}
if err := yaml.Unmarshal(conf.AppYaml, &config); err != nil { if err := yaml.Unmarshal(conf.AppYaml, &config); err != nil {
panic(err) panic(err)
} }
if config.System.Mode != "" { if config.Base.Mode != "" {
mode = config.System.Mode mode = config.Base.Mode
} }
if mode == "dev" && fileOp.Stat("/opt/1panel/conf/app.yaml") { if mode == "dev" && fileOp.Stat("/opt/1panel/conf/app.yaml") {
v.SetConfigName("app") v.SetConfigName("app")
@ -45,30 +44,22 @@ func Init() {
panic(err) panic(err)
} }
}) })
serverConfig := configs.ServerConfig{} serverConfig := global.ServerConfig{}
if err := v.Unmarshal(&serverConfig); err != nil { if err := v.Unmarshal(&serverConfig); err != nil {
panic(err) panic(err)
} }
global.CONF = serverConfig 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 global.Viper = v
} }
func initDir() { func initInstallDir() {
_, nodeInfo, err := xpack.LoadNodeInfo() _, nodeInfo, err := xpack.LoadNodeInfo()
if err != nil { if err != nil {
panic(err) panic(err)
} }
global.CONF.System.BaseDir = nodeInfo.BaseDir global.CONF.Base.InstallDir = 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"))
} }

View File

@ -5,7 +5,6 @@ import (
"fmt" "fmt"
"github.com/1Panel-dev/1Panel/agent/app/api/v2/helper" "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/1Panel-dev/1Panel/agent/global"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
) )
@ -17,12 +16,12 @@ func Certificate() gin.HandlerFunc {
return return
} }
if !c.Request.TLS.HandshakeComplete || len(c.Request.TLS.PeerCertificates) == 0 { 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 return
} }
cert := c.Request.TLS.PeerCertificates[0] cert := c.Request.TLS.PeerCertificates[0]
if cert.Subject.CommonName != "panel_client" { 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 return
} }
c.Next() c.Next()

View File

@ -6,7 +6,6 @@ import (
"github.com/1Panel-dev/1Panel/agent/app/dto" "github.com/1Panel-dev/1Panel/agent/app/dto"
"github.com/1Panel-dev/1Panel/agent/buserr" "github.com/1Panel-dev/1Panel/agent/buserr"
"github.com/1Panel-dev/1Panel/agent/constant"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
) )
@ -51,7 +50,7 @@ func DemoHandle() gin.HandlerFunc {
c.JSON(http.StatusInternalServerError, dto.Response{ c.JSON(http.StatusInternalServerError, dto.Response{
Code: http.StatusInternalServerError, Code: http.StatusInternalServerError,
Message: buserr.New(constant.ErrDemoEnvironment).Error(), Message: buserr.New("ErrDemoEnvironment").Error(),
}) })
c.Abort() c.Abort()
} }

View File

@ -1,9 +1,10 @@
package middleware package middleware
import ( import (
"net/http"
"github.com/1Panel-dev/1Panel/agent/app/api/v2/helper" "github.com/1Panel-dev/1Panel/agent/app/api/v2/helper"
"github.com/1Panel-dev/1Panel/agent/app/repo" "github.com/1Panel-dev/1Panel/agent/app/repo"
"github.com/1Panel-dev/1Panel/agent/constant"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
) )
@ -12,11 +13,11 @@ func GlobalLoading() gin.HandlerFunc {
settingRepo := repo.NewISettingRepo() settingRepo := repo.NewISettingRepo()
status, err := settingRepo.Get(settingRepo.WithByKey("SystemStatus")) status, err := settingRepo.Get(settingRepo.WithByKey("SystemStatus"))
if err != nil { if err != nil {
helper.ErrorWithDetail(c, constant.CodeErrInternalServer, constant.ErrTypeInternalServer, err) helper.InternalServer(c, err)
return return
} }
if status.Value != "Free" { if status.Value != "Free" {
helper.ErrorWithDetail(c, constant.CodeGlobalLoading, status.Value, err) helper.ErrorWithDetail(c, http.StatusProxyAuthRequired, status.Value, err)
return return
} }
c.Next() c.Next()

View File

@ -17,6 +17,7 @@ import (
"github.com/1Panel-dev/1Panel/agent/init/business" "github.com/1Panel-dev/1Panel/agent/init/business"
"github.com/1Panel-dev/1Panel/agent/init/cache" "github.com/1Panel-dev/1Panel/agent/init/cache"
"github.com/1Panel-dev/1Panel/agent/init/db" "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/hook"
"github.com/1Panel-dev/1Panel/agent/init/log" "github.com/1Panel-dev/1Panel/agent/init/log"
"github.com/1Panel-dev/1Panel/agent/init/migration" "github.com/1Panel-dev/1Panel/agent/init/migration"
@ -32,6 +33,7 @@ import (
func Start() { func Start() {
viper.Init() viper.Init()
dir.Init()
i18n.Init() i18n.Init()
log.Init() log.Init()
db.Init() db.Init()
@ -65,7 +67,7 @@ func Start() {
_ = server.Serve(listener) _ = server.Serve(listener)
return return
} else { } 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() settingRepo := repo.NewISettingRepo()
certItem, err := settingRepo.Get(settingRepo.WithByKey("ServerCrt")) certItem, err := settingRepo.Get(settingRepo.WithByKey("ServerCrt"))
if err != nil { if err != nil {
@ -87,7 +89,7 @@ func Start() {
ClientAuth: tls.RequireAnyClientCert, ClientAuth: tls.RequireAnyClientCert,
} }
business.Init() 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 { if err := server.ListenAndServeTLS("", ""); err != nil {
panic(err) panic(err)
} }

View File

@ -3,12 +3,13 @@ package client
import ( import (
"context" "context"
"crypto/tls" "crypto/tls"
"fmt"
"io" "io"
"net/http" "net/http"
"os" "os"
"strings" "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"
"github.com/minio/minio-go/v7/pkg/credentials" "github.com/minio/minio-go/v7/pkg/credentials"
) )
@ -25,7 +26,7 @@ func NewMinIoClient(vars map[string]interface{}) (*minIoClient, error) {
bucket := loadParamFromVars("bucket", vars) bucket := loadParamFromVars("bucket", vars)
ssl := strings.Split(endpoint, ":")[0] ssl := strings.Split(endpoint, ":")[0]
if len(ssl) == 0 || (ssl != "https" && ssl != "http") { 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 secure := false

View File

@ -1,6 +1,7 @@
package cloud_storage package cloud_storage
import ( import (
"github.com/1Panel-dev/1Panel/agent/buserr"
"github.com/1Panel-dev/1Panel/agent/constant" "github.com/1Panel-dev/1Panel/agent/constant"
"github.com/1Panel-dev/1Panel/agent/utils/cloud_storage/client" "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: case constant.ALIYUN:
return client.NewALIClient(vars) return client.NewALIClient(vars)
default: default:
return nil, constant.ErrNotSupportType return nil, buserr.WithName("ErrNotSupportType", backupType)
} }
} }

View File

@ -51,7 +51,7 @@ func ExecWithTimeOut(cmdStr string, timeout time.Duration) (string, error) {
select { select {
case <-after: case <-after:
_ = cmd.Process.Kill() _ = cmd.Process.Kill()
return "", buserr.New(constant.ErrCmdTimeout) return "", buserr.New("ErrCmdTimeout")
case err := <-done: case err := <-done:
if err != nil { if err != nil {
return handleErr(stdout, stderr, err) return handleErr(stdout, stderr, err)
@ -86,7 +86,7 @@ func ExecWithLogFile(cmdStr string, timeout time.Duration, outputFile string) er
select { select {
case <-after: case <-after:
_ = cmd.Process.Kill() _ = cmd.Process.Kill()
return buserr.New(constant.ErrCmdTimeout) return buserr.New("ErrCmdTimeout")
case err := <-done: case err := <-done:
if err != nil { if err != nil {
return err return err
@ -129,7 +129,7 @@ func ExecShell(outPath string, timeout time.Duration, name string, arg ...string
select { select {
case <-after: case <-after:
_ = cmd.Process.Kill() _ = cmd.Process.Kill()
return buserr.New(constant.ErrCmdTimeout) return buserr.New("ErrCmdTimeout")
case err := <-done: case err := <-done:
if err != nil { if err != nil {
return err return err
@ -162,7 +162,7 @@ func ExecShellWithTask(taskItem *task.Task, timeout time.Duration, name string,
select { select {
case <-after: case <-after:
_ = cmd.Process.Kill() _ = cmd.Process.Kill()
return buserr.New(constant.ErrCmdTimeout) return buserr.New("ErrCmdTimeout")
case err := <-done: case err := <-done:
if err != nil { if err != nil {
return err return err
@ -212,7 +212,7 @@ func ExecScript(scriptPath, workDir string) (string, error) {
select { select {
case <-after: case <-after:
_ = cmd.Process.Kill() _ = cmd.Process.Kill()
return "", buserr.New(constant.ErrCmdTimeout) return "", buserr.New("ErrCmdTimeout")
case err := <-done: case err := <-done:
if err != nil { if err != nil {
return handleErr(stdout, stderr, err) return handleErr(stdout, stderr, err)
@ -291,7 +291,7 @@ func ExecShellWithTimeOut(cmdStr, workdir string, logger *log.Logger, timeout ti
} }
err := cmd.Wait() err := cmd.Wait()
if errors.Is(ctx.Err(), context.DeadlineExceeded) { if errors.Is(ctx.Err(), context.DeadlineExceeded) {
return buserr.New(constant.ErrCmdTimeout) return buserr.New("ErrCmdTimeout")
} }
return err return err
} }

View File

@ -29,14 +29,14 @@ func StringEncrypt(text string) (string, error) {
if len(text) == 0 { if len(text) == 0 {
return "", nil return "", nil
} }
if len(global.CONF.System.EncryptKey) == 0 { if len(global.CONF.Base.EncryptKey) == 0 {
var encryptSetting model.Setting var encryptSetting model.Setting
if err := global.DB.Where("key = ?", "EncryptKey").First(&encryptSetting).Error; err != nil { if err := global.DB.Where("key = ?", "EncryptKey").First(&encryptSetting).Error; err != nil {
return "", err 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) pass := []byte(text)
xpass, err := aesEncryptWithSalt([]byte(key), pass) xpass, err := aesEncryptWithSalt([]byte(key), pass)
if err == nil { if err == nil {
@ -75,14 +75,14 @@ func StringDecrypt(text string) (string, error) {
if len(text) == 0 { if len(text) == 0 {
return "", nil return "", nil
} }
if len(global.CONF.System.EncryptKey) == 0 { if len(global.CONF.Base.EncryptKey) == 0 {
var encryptSetting model.Setting var encryptSetting model.Setting
if err := global.DB.Where("key = ?", "EncryptKey").First(&encryptSetting).Error; err != nil { if err := global.DB.Where("key = ?", "EncryptKey").First(&encryptSetting).Error; err != nil {
return "", err 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) return StringDecryptWithKey(text, key)
} }

View File

@ -2,7 +2,6 @@ package files
import ( import (
"github.com/1Panel-dev/1Panel/agent/buserr" "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/cmd"
) )
@ -34,5 +33,5 @@ func checkCmdAvailability(cmdStr string) error {
if cmd.Which(cmdStr) { if cmd.Which(cmdStr) {
return nil return nil
} }
return buserr.WithName(constant.ErrCmdNotFound, cmdStr) return buserr.WithName("ErrCmdNotFound", cmdStr)
} }

View File

@ -17,7 +17,6 @@ import (
"github.com/1Panel-dev/1Panel/agent/app/repo" "github.com/1Panel-dev/1Panel/agent/app/repo"
"github.com/1Panel-dev/1Panel/agent/buserr" "github.com/1Panel-dev/1Panel/agent/buserr"
"github.com/1Panel-dev/1Panel/agent/constant"
"github.com/spf13/afero" "github.com/spf13/afero"
) )
@ -74,7 +73,7 @@ func NewFileInfo(op FileOption) (*FileInfo, error) {
info, err := appFs.Stat(op.Path) info, err := appFs.Stat(op.Path)
if err != nil { if err != nil {
if os.IsNotExist(err) { if os.IsNotExist(err) {
return nil, buserr.New(constant.ErrLinkPathNotFound) return nil, buserr.New("ErrLinkPathNotFound")
} }
return nil, err return nil, err
} }
@ -411,7 +410,7 @@ func (f *FileInfo) checkSymlink(df FileSearchInfo) (bool, bool) {
func (f *FileInfo) getContent() error { func (f *FileInfo) getContent() error {
if IsBlockDevice(f.FileMode) { if IsBlockDevice(f.FileMode) {
return buserr.New(constant.ErrFileCanNotRead) return buserr.New("ErrFileCanNotRead")
} }
if f.Size > 10*1024*1024 { if f.Size > 10*1024*1024 {
return buserr.New("ErrFileToLarge") return buserr.New("ErrFileToLarge")
@ -422,7 +421,7 @@ func (f *FileInfo) getContent() error {
return nil return nil
} }
if len(cByte) > 0 && DetectBinary(cByte) { if len(cByte) > 0 && DetectBinary(cByte) {
return buserr.New(constant.ErrFileCanNotRead) return buserr.New("ErrFileCanNotRead")
} }
f.Content = string(cByte) f.Content = string(cByte)
return nil return nil

View File

@ -28,7 +28,7 @@ func (z ZipArchiver) Extract(filePath, dstDir string, secret string) error {
func (z ZipArchiver) Compress(sourcePaths []string, dstFile string, _ string) error { func (z ZipArchiver) Compress(sourcePaths []string, dstFile string, _ string) error {
var err 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() op := NewFileOp()
defer func() { defer func() {
_ = op.DeleteFile(tmpFile) _ = op.DeleteFile(tmpFile)

View File

@ -2,7 +2,6 @@ package firewall
import ( import (
"github.com/1Panel-dev/1Panel/agent/buserr" "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/cmd"
"github.com/1Panel-dev/1Panel/agent/utils/firewall/client" "github.com/1Panel-dev/1Panel/agent/utils/firewall/client"
) )
@ -32,7 +31,7 @@ func NewFirewallClient() (FirewallClient, error) {
ufw := cmd.Which("ufw") ufw := cmd.Which("ufw")
if firewalld && ufw { if firewalld && ufw {
return nil, buserr.New(constant.ErrFirewallBoth) return nil, buserr.New("ErrFirewallBoth")
} }
if firewalld { if firewalld {
@ -41,5 +40,5 @@ func NewFirewallClient() (FirewallClient, error) {
if ufw { if ufw {
return client.NewUfw() return client.NewUfw()
} }
return nil, buserr.New(constant.ErrFirewallNone) return nil, buserr.New("ErrFirewallNone")
} }

View File

@ -7,7 +7,6 @@ import (
"sync" "sync"
"github.com/1Panel-dev/1Panel/agent/buserr" "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/global"
"github.com/1Panel-dev/1Panel/agent/utils/cmd" "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 { func (f *Firewall) Port(port FireInfo, operation string) error {
if cmd.CheckIllegal(operation, port.Protocol, port.Port) { 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) 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 { func (f *Firewall) RichRules(rule FireInfo, operation string) error {
if cmd.CheckIllegal(operation, rule.Address, rule.Protocol, rule.Port, rule.Strategy) { 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 " ruleStr := "rule family=ipv4 "
if strings.Contains(rule.Address, ":") { if strings.Contains(rule.Address, ":") {

View File

@ -5,7 +5,6 @@ import (
"strings" "strings"
"github.com/1Panel-dev/1Panel/agent/buserr" "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/global"
"github.com/1Panel-dev/1Panel/agent/utils/cmd" "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) return fmt.Errorf("unsupported strategy %s", port.Strategy)
} }
if cmd.CheckIllegal(port.Protocol, port.Port) { 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) 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) { 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) ruleStr := fmt.Sprintf("%s insert 1 %s ", f.CmdStr, rule.Strategy)

View File

@ -1,10 +1,11 @@
package geo package geo
import ( import (
"github.com/1Panel-dev/1Panel/agent/global"
"github.com/oschwald/maxminddb-golang"
"net" "net"
"path" "path"
"github.com/1Panel-dev/1Panel/agent/global"
"github.com/oschwald/maxminddb-golang"
) )
type Location struct { type Location struct {
@ -21,7 +22,7 @@ type LocationRes struct {
} }
func NewGeo() (*maxminddb.Reader, error) { 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) return maxminddb.Open(geoPath)
} }
@ -29,7 +30,7 @@ func GetIPLocation(reader *maxminddb.Reader, ip, lang string) (string, error) {
var err error var err error
var geoLocation LocationRes var geoLocation LocationRes
if reader == nil { 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) reader, err = maxminddb.Open(geoPath)
if err != nil { if err != nil {
return "", err return "", err

View File

@ -9,7 +9,6 @@ import (
"time" "time"
"github.com/1Panel-dev/1Panel/agent/buserr" "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/global"
"github.com/1Panel-dev/1Panel/agent/utils/mysql/client" "github.com/1Panel-dev/1Panel/agent/utils/mysql/client"
) )
@ -56,7 +55,7 @@ func NewMysqlClient(conn client.DBInfo) (MysqlClient, error) {
return nil, err return nil, err
} }
if errors.Is(ctx.Err(), context.DeadlineExceeded) { if errors.Is(ctx.Err(), context.DeadlineExceeded) {
return nil, buserr.New(constant.ErrExecTimeOut) return nil, buserr.New("ErrExecTimeOut")
} }
return client.NewRemote(client.Remote{ return client.NewRemote(client.Remote{

View File

@ -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]) 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 err := r.ExecSQL(createSql, info.Timeout); err != nil {
if strings.Contains(strings.ToLower(err.Error()), "error 1007") { if strings.Contains(strings.ToLower(err.Error()), "error 1007") {
return buserr.New(constant.ErrDatabaseIsExist) return buserr.New("ErrDatabaseIsExist")
} }
return err return err
} }
@ -63,7 +63,7 @@ func (r *Local) CreateUser(info CreateInfo, withDeleteDB bool) error {
for _, user := range userlist { for _, user := range userlist {
if err := r.ExecSQL(fmt.Sprintf("create user %s identified by '%s';", user, info.Password), info.Timeout); err != nil { 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") { if strings.Contains(strings.ToLower(err.Error()), "error 1396") {
return buserr.New(constant.ErrUserIsExist) return buserr.New("ErrUserIsExist")
} }
if withDeleteDB { if withDeleteDB {
_ = r.Delete(DeleteInfo{ _ = r.Delete(DeleteInfo{
@ -354,7 +354,7 @@ func (r *Local) ExecSQL(command string, timeout uint) error {
cmd := exec.CommandContext(ctx, "docker", itemCommand...) cmd := exec.CommandContext(ctx, "docker", itemCommand...)
stdout, err := cmd.CombinedOutput() stdout, err := cmd.CombinedOutput()
if errors.Is(ctx.Err(), context.DeadlineExceeded) { 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", "") 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 ") { 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...) cmd := exec.CommandContext(ctx, "docker", itemCommand...)
stdout, err := cmd.CombinedOutput() stdout, err := cmd.CombinedOutput()
if errors.Is(ctx.Err(), context.DeadlineExceeded) { 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", "") 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 ") { if err != nil || strings.HasPrefix(string(stdStr), "ERROR ") {

View File

@ -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]) 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 err := r.ExecSQL(createSql, info.Timeout); err != nil {
if strings.Contains(strings.ToLower(err.Error()), "error 1007") { if strings.Contains(strings.ToLower(err.Error()), "error 1007") {
return buserr.New(constant.ErrDatabaseIsExist) return buserr.New("ErrDatabaseIsExist")
} }
return err return err
} }
@ -74,7 +74,7 @@ func (r *Remote) CreateUser(info CreateInfo, withDeleteDB bool) error {
for _, user := range userlist { for _, user := range userlist {
if err := r.ExecSQL(fmt.Sprintf("create user %s identified by '%s';", user, info.Password), info.Timeout); err != nil { 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") { if strings.Contains(strings.ToLower(err.Error()), "error 1396") {
return buserr.New(constant.ErrUserIsExist) return buserr.New("ErrUserIsExist")
} }
if withDeleteDB { if withDeleteDB {
_ = r.Delete(DeleteInfo{ _ = r.Delete(DeleteInfo{
@ -391,7 +391,7 @@ func (r *Remote) ExecSQL(command string, timeout uint) error {
return err return err
} }
if errors.Is(ctx.Err(), context.DeadlineExceeded) { if errors.Is(ctx.Err(), context.DeadlineExceeded) {
return buserr.New(constant.ErrExecTimeOut) return buserr.New("ErrExecTimeOut")
} }
return nil return nil
@ -406,7 +406,7 @@ func (r *Remote) ExecSQLForHosts(timeout uint) ([]string, error) {
return nil, err return nil, err
} }
if errors.Is(ctx.Err(), context.DeadlineExceeded) { if errors.Is(ctx.Err(), context.DeadlineExceeded) {
return nil, buserr.New(constant.ErrExecTimeOut) return nil, buserr.New("ErrExecTimeOut")
} }
var rows []string var rows []string
for results.Next() { for results.Next() {

Some files were not shown because too many files have changed in this diff Show More