Skip to content

Commit

Permalink
refactor: 重构 tools.Exec 函数
Browse files Browse the repository at this point in the history
  • Loading branch information
devhaozi committed Nov 13, 2023
1 parent 1c5b32a commit 2b1b58e
Show file tree
Hide file tree
Showing 39 changed files with 1,840 additions and 1,329 deletions.
66 changes: 54 additions & 12 deletions app/console/commands/panel.go
Original file line number Diff line number Diff line change
Expand Up @@ -125,23 +125,39 @@ func (receiver *Panel) Handle(ctx console.Context) error {
return nil
}

port := tools.Exec(`cat /www/panel/panel.conf | grep APP_PORT | awk -F '=' '{print $2}' | tr -d '\n'`)
port, err := tools.Exec(`cat /www/panel/panel.conf | grep APP_PORT | awk -F '=' '{print $2}' | tr -d '\n'`)
if err != nil {
color.Redln("获取面板端口失败")
return nil
}

color.Greenln("用户名: " + user.Username)
color.Greenln("密码: " + password)
color.Greenln("面板端口: " + port)
color.Greenln("面板入口: " + facades.Config().GetString("http.entrance"))

case "getPort":
port := tools.Exec("cat /www/panel/panel.conf | grep APP_PORT | awk -F '=' '{print $2}'")
port, err := tools.Exec(`cat /www/panel/panel.conf | grep APP_PORT | awk -F '=' '{print $2}' | tr -d '\n'`)
if err != nil {
color.Redln("获取面板端口失败")
return nil
}

color.Greenln("面板端口: " + port)

case "getEntrance":
color.Greenln("面板入口: " + facades.Config().GetString("http.entrance"))

case "deleteEntrance":
oldEntrance := tools.Exec(`cat /www/panel/panel.conf | grep APP_ENTRANCE | awk -F '=' '{print $2}' | tr -d '\n'`)
tools.Exec("sed -i 's!APP_ENTRANCE=" + oldEntrance + "!APP_ENTRANCE=/!g' /www/panel/panel.conf")
oldEntrance, err := tools.Exec(`cat /www/panel/panel.conf | grep APP_ENTRANCE | awk -F '=' '{print $2}' | tr -d '\n'`)
if err != nil {
color.Redln("获取面板入口失败")
return nil
}
if _, err = tools.Exec("sed -i 's!APP_ENTRANCE=" + oldEntrance + "!APP_ENTRANCE=/!g' /www/panel/panel.conf"); err != nil {
color.Redln("删除面板入口失败")
return nil
}

color.Greenln("删除面板入口成功")

Expand Down Expand Up @@ -245,7 +261,10 @@ func (receiver *Panel) Handle(ctx console.Context) error {
}

backupFile := path + "/" + website.Name + "_" + carbon.Now().ToShortDateTimeString() + ".zip"
tools.Exec(`cd '` + website.Path + `' && zip -r '` + backupFile + `' .`)
if _, err := tools.Exec(`cd '` + website.Path + `' && zip -r '` + backupFile + `' .`); err != nil {
color.Redln("|-备份失败: " + err.Error())
return nil
}
color.Greenln("|-备份成功")

case "mysql":
Expand All @@ -261,10 +280,16 @@ func (receiver *Panel) Handle(ctx console.Context) error {

color.Greenln("|-目标MySQL数据库: " + name)
color.Greenln("|-开始导出")
tools.Exec(`mysqldump -uroot ` + name + ` > /tmp/` + backupFile + ` 2>&1`)
if _, err = tools.Exec(`mysqldump -uroot ` + name + ` > /tmp/` + backupFile + ` 2>&1`); err != nil {
color.Redln("|-导出失败: " + err.Error())
return nil
}
color.Greenln("|-导出成功")
color.Greenln("|-开始压缩")
tools.Exec("cd /tmp && zip -r " + backupFile + ".zip " + backupFile)
if _, err = tools.Exec("cd /tmp && zip -r " + backupFile + ".zip " + backupFile); err != nil {
color.Redln("|-压缩失败: " + err.Error())
return nil
}
tools.Remove("/tmp/" + backupFile)
color.Greenln("|-压缩成功")
color.Greenln("|-开始移动")
Expand All @@ -278,7 +303,12 @@ func (receiver *Panel) Handle(ctx console.Context) error {

case "postgresql":
backupFile := name + "_" + carbon.Now().ToShortDateTimeString() + ".sql"
check := tools.Exec(`su - postgres -c "psql -l" 2>&1`)
check, err := tools.Exec(`su - postgres -c "psql -l" 2>&1`)
if err != nil {
color.Redln("|-获取数据库失败: " + err.Error())
color.Greenln(hr)
return nil
}
if strings.Contains(check, name) {
color.Redln("|-数据库不存在")
color.Greenln(hr)
Expand All @@ -287,10 +317,16 @@ func (receiver *Panel) Handle(ctx console.Context) error {

color.Greenln("|-目标PostgreSQL数据库: " + name)
color.Greenln("|-开始导出")
tools.Exec(`su - postgres -c "pg_dump '` + name + `'" > /tmp/` + backupFile + ` 2>&1`)
if _, err = tools.Exec(`su - postgres -c "pg_dump '` + name + `'" > /tmp/` + backupFile + ` 2>&1`); err != nil {
color.Redln("|-导出失败: " + err.Error())
return nil
}
color.Greenln("|-导出成功")
color.Greenln("|-开始压缩")
tools.Exec("cd /tmp && zip -r " + backupFile + ".zip " + backupFile)
if _, err = tools.Exec("cd /tmp && zip -r " + backupFile + ".zip " + backupFile); err != nil {
color.Redln("|-压缩失败: " + err.Error())
return nil
}
tools.Remove("/tmp/" + backupFile)
color.Greenln("|-压缩成功")
color.Greenln("|-开始移动")
Expand Down Expand Up @@ -360,8 +396,14 @@ func (receiver *Panel) Handle(ctx console.Context) error {
}

backupPath := "/www/wwwlogs/" + website.Name + "_" + carbon.Now().ToShortDateTimeString() + ".log.zip"
tools.Exec(`cd /www/wwwlogs && zip -r ` + backupPath + ` ` + website.Name + ".log")
tools.Exec(`echo "" > ` + logPath)
if _, err := tools.Exec(`cd /www/wwwlogs && zip -r ` + backupPath + ` ` + website.Name + ".log"); err != nil {
color.Redln("|-备份失败: " + err.Error())
return nil
}
if _, err := tools.Exec(`echo "" > ` + logPath); err != nil {
color.Redln("|-清空失败: " + err.Error())
return nil
}
color.Greenln("|-切割成功")

color.Greenln(hr)
Expand Down
2 changes: 1 addition & 1 deletion app/http/controllers/controller.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ func Success(ctx http.Context, data any) http.Response {
func Error(ctx http.Context, code int, message string) http.Response {
return ctx.Response().Json(http.StatusOK, &ErrorResponse{
Code: code,
Message: message,
Message: "错误: " + message,
})
}

Expand Down
90 changes: 56 additions & 34 deletions app/http/controllers/cron_controller.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,15 +26,17 @@ func NewCronController() *CronController {
}

// List 获取计划任务列表
func (c *CronController) List(ctx http.Context) http.Response {
func (r *CronController) List(ctx http.Context) http.Response {
limit := ctx.Request().QueryInt("limit", 10)
page := ctx.Request().QueryInt("page", 1)

var crons []models.Cron
var total int64
err := facades.Orm().Query().Paginate(page, limit, &crons, &total)
if err != nil {
facades.Log().Info("[面板][CronController] 查询计划任务列表失败 ", err)
facades.Log().Request(ctx.Request()).Tags("面板", "计划任务").With(map[string]any{
"error": err.Error(),
}).Info("查询计划任务列表失败")
return ErrorSystem(ctx)
}

Expand All @@ -45,7 +47,7 @@ func (c *CronController) List(ctx http.Context) http.Response {
}

// Add 添加计划任务
func (c *CronController) Add(ctx http.Context) http.Response {
func (r *CronController) Add(ctx http.Context) http.Response {
validator, err := ctx.Request().Validate(map[string]string{
"name": "required|min_len:1|max_len:255",
"time": "required",
Expand Down Expand Up @@ -75,7 +77,7 @@ func (c *CronController) Add(ctx http.Context) http.Response {
}
backupPath := ctx.Request().Input("backup_path")
if len(backupPath) == 0 {
backupPath = c.setting.Get(models.SettingKeyBackupPath) + "/" + backupType
backupPath = r.setting.Get(models.SettingKeyBackupPath) + "/" + backupType
}
backupSave := ctx.Request().InputInt("save", 10)
shell = `#!/bin/bash
Expand Down Expand Up @@ -111,19 +113,18 @@ panel cutoff ${name} ${save} 2>&1
shellDir := "/www/server/cron/"
shellLogDir := "/www/server/cron/logs/"
if !tools.Exists(shellDir) {
facades.Log().Info("[面板][CronController] 计划任务目录不存在")
return Error(ctx, http.StatusInternalServerError, "计划任务目录不存在")
}
if !tools.Exists(shellLogDir) {
facades.Log().Info("[面板][CronController] 计划任务日志目录不存在")
return Error(ctx, http.StatusInternalServerError, "计划任务日志目录不存在")
}
shellFile := strconv.Itoa(int(carbon.Now().Timestamp())) + tools.RandomString(16)
if err = tools.Write(shellDir+shellFile+".sh", shell, 0700); err != nil {
facades.Log().Info("[面板][CronController] 创建计划任务脚本失败 ", err)
return ErrorSystem(ctx)
return Error(ctx, http.StatusInternalServerError, err.Error())
}
if out, err := tools.Exec("dos2unix " + shellDir + shellFile + ".sh"); err != nil {
return Error(ctx, http.StatusInternalServerError, out)
}
tools.Exec("dos2unix " + shellDir + shellFile + ".sh")

var cron models.Cron
cron.Name = ctx.Request().Input("name")
Expand All @@ -135,19 +136,23 @@ panel cutoff ${name} ${save} 2>&1

err = facades.Orm().Query().Create(&cron)
if err != nil {
facades.Log().Info("[面板][CronController] 创建计划任务失败 ", err)
facades.Log().Request(ctx.Request()).Tags("面板", "计划任务").With(map[string]any{
"error": err.Error(),
}).Info("保存计划任务失败")
return ErrorSystem(ctx)
}

c.cron.AddToSystem(cron)
if err := r.cron.AddToSystem(cron); err != nil {
return Error(ctx, http.StatusInternalServerError, err.Error())
}

return Success(ctx, http.Json{
"id": cron.ID,
})
}

// Script 获取脚本内容
func (c *CronController) Script(ctx http.Context) http.Response {
func (r *CronController) Script(ctx http.Context) http.Response {
var cron models.Cron
err := facades.Orm().Query().Where("id", ctx.Request().Input("id")).FirstOrFail(&cron)
if err != nil {
Expand All @@ -158,7 +163,7 @@ func (c *CronController) Script(ctx http.Context) http.Response {
}

// Update 更新计划任务
func (c *CronController) Update(ctx http.Context) http.Response {
func (r *CronController) Update(ctx http.Context) http.Response {
validator, err := ctx.Request().Validate(map[string]string{
"name": "required|min_len:1|max_len:255",
"time": "required",
Expand Down Expand Up @@ -190,46 +195,55 @@ func (c *CronController) Update(ctx http.Context) http.Response {
cron.Name = ctx.Request().Input("name")
err = facades.Orm().Query().Save(&cron)
if err != nil {
facades.Log().Info("[面板][CronController] 更新计划任务失败 ", err)
facades.Log().Request(ctx.Request()).Tags("面板", "计划任务").With(map[string]any{
"error": err.Error(),
}).Info("更新计划任务失败")
return ErrorSystem(ctx)
}

if err = tools.Write(cron.Shell, ctx.Request().Input("script"), 0644); err != nil {
facades.Log().Info("[面板][CronController] 更新计划任务脚本失败 ", err)
return ErrorSystem(ctx)
return Error(ctx, http.StatusInternalServerError, err.Error())
}
if out, err := tools.Exec("dos2unix " + cron.Shell); err != nil {
return Error(ctx, http.StatusInternalServerError, out)
}
tools.Exec("dos2unix " + cron.Shell)

c.cron.DeleteFromSystem(cron)
if err := r.cron.DeleteFromSystem(cron); err != nil {
return Error(ctx, http.StatusInternalServerError, err.Error())
}
if cron.Status {
c.cron.AddToSystem(cron)
if err := r.cron.AddToSystem(cron); err != nil {
return Error(ctx, http.StatusInternalServerError, err.Error())
}
}

return Success(ctx, nil)
}

// Delete 删除计划任务
func (c *CronController) Delete(ctx http.Context) http.Response {
func (r *CronController) Delete(ctx http.Context) http.Response {
var cron models.Cron
err := facades.Orm().Query().Where("id", ctx.Request().Input("id")).FirstOrFail(&cron)
if err != nil {
if err := facades.Orm().Query().Where("id", ctx.Request().Input("id")).FirstOrFail(&cron); err != nil {
return Error(ctx, http.StatusUnprocessableEntity, "计划任务不存在")
}

c.cron.DeleteFromSystem(cron)
if err := r.cron.DeleteFromSystem(cron); err != nil {
return Error(ctx, http.StatusInternalServerError, err.Error())
}
tools.Remove(cron.Shell)

_, err = facades.Orm().Query().Delete(&cron)
if err != nil {
facades.Log().Info("[面板][CronController] 删除计划任务失败 ", err)
if _, err := facades.Orm().Query().Delete(&cron); err != nil {
facades.Log().Request(ctx.Request()).Tags("面板", "计划任务").With(map[string]any{
"error": err.Error(),
}).Info("删除计划任务失败")
return ErrorSystem(ctx)
}

return Success(ctx, nil)
}

// Status 更新计划任务状态
func (c *CronController) Status(ctx http.Context) http.Response {
func (r *CronController) Status(ctx http.Context) http.Response {
validator, err := ctx.Request().Validate(map[string]string{
"status": "bool",
})
Expand All @@ -249,31 +263,39 @@ func (c *CronController) Status(ctx http.Context) http.Response {
cron.Status = ctx.Request().InputBool("status")
err = facades.Orm().Query().Save(&cron)
if err != nil {
facades.Log().Info("[面板][CronController] 更新计划任务状态失败 ", err)
facades.Log().Request(ctx.Request()).Tags("面板", "计划任务").With(map[string]any{
"error": err.Error(),
}).Info("更新计划任务状态失败")
return ErrorSystem(ctx)
}

c.cron.DeleteFromSystem(cron)
if err := r.cron.DeleteFromSystem(cron); err != nil {
return Error(ctx, http.StatusInternalServerError, err.Error())
}
if cron.Status {
c.cron.AddToSystem(cron)
if err := r.cron.AddToSystem(cron); err != nil {
return Error(ctx, http.StatusInternalServerError, err.Error())
}
}

return Success(ctx, nil)
}

// Log 获取计划任务日志
func (c *CronController) Log(ctx http.Context) http.Response {
func (r *CronController) Log(ctx http.Context) http.Response {
var cron models.Cron
err := facades.Orm().Query().Where("id", ctx.Request().Input("id")).FirstOrFail(&cron)
if err != nil {
if err := facades.Orm().Query().Where("id", ctx.Request().Input("id")).FirstOrFail(&cron); err != nil {
return Error(ctx, http.StatusUnprocessableEntity, "计划任务不存在")
}

if !tools.Exists(cron.Log) {
return Error(ctx, http.StatusUnprocessableEntity, "日志文件不存在")
}

log := tools.Exec("tail -n 1000 " + cron.Log)
log, err := tools.Exec("tail -n 1000 " + cron.Log)
if err != nil {
return Error(ctx, http.StatusInternalServerError, err.Error())
}

return Success(ctx, log)
}
Loading

0 comments on commit 2b1b58e

Please sign in to comment.