style:fit some code style (#5601)

This commit is contained in:
yonwoo9 2024-06-28 14:04:08 +08:00 committed by GitHub
parent 4504a8b188
commit 3adf1aebb8
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
37 changed files with 105 additions and 100 deletions

View file

@ -139,7 +139,7 @@ type MysqlVariables struct {
MaxConnections string `json:"max_connections"` MaxConnections string `json:"max_connections"`
MaxHeapTableSize string `json:"max_heap_table_size"` MaxHeapTableSize string `json:"max_heap_table_size"`
QueryCacheSize string `json:"query_cache_size"` QueryCacheSize string `json:"query_cache_size"`
QueryCache_type string `json:"query_cache_type"` QueryCacheType string `json:"query_cache_type"`
ReadBufferSize string `json:"read_buffer_size"` ReadBufferSize string `json:"read_buffer_size"`
ReadRndBufferSize string `json:"read_rnd_buffer_size"` ReadRndBufferSize string `json:"read_rnd_buffer_size"`
SortBufferSize string `json:"sort_buffer_size"` SortBufferSize string `json:"sort_buffer_size"`
@ -207,8 +207,8 @@ type RedisStatus struct {
UptimeInDays string `json:"uptime_in_days"` UptimeInDays string `json:"uptime_in_days"`
ConnectedClients string `json:"connected_clients"` ConnectedClients string `json:"connected_clients"`
UsedMemory string `json:"used_memory"` UsedMemory string `json:"used_memory"`
UsedMemory_rss string `json:"used_memory_rss"` UsedMemoryRss string `json:"used_memory_rss"`
UsedMemory_peak string `json:"used_memory_peak"` UsedMemoryPeak string `json:"used_memory_peak"`
MemFragmentationRatio string `json:"mem_fragmentation_ratio"` MemFragmentationRatio string `json:"mem_fragmentation_ratio"`
TotalConnectionsReceived string `json:"total_connections_received"` TotalConnectionsReceived string `json:"total_connections_received"`
TotalCommandsProcessed string `json:"total_commands_processed"` TotalCommandsProcessed string `json:"total_commands_processed"`

View file

@ -782,7 +782,7 @@ func updateInstallInfoInDB(appKey, appName, param string, value interface{}) err
} }
case "port": case "port":
envKey = "PANEL_APP_PORT_HTTP=" envKey = "PANEL_APP_PORT_HTTP="
case "user-password": default:
envKey = "PANEL_DB_USER_PASSWORD=" envKey = "PANEL_DB_USER_PASSWORD="
} }
files := strings.Split(string(lineBytes), "\n") files := strings.Split(string(lineBytes), "\n")

View file

@ -364,7 +364,7 @@ func (u *BackupService) Update(req dto.BackupOperate) error {
dirStr = dirStr[:strings.LastIndex(dirStr, "/")] dirStr = dirStr[:strings.LastIndex(dirStr, "/")]
} }
if err := copyDir(oldDir, dirStr); err != nil { if err := copyDir(oldDir, dirStr); err != nil {
_ = backupRepo.Update(req.ID, (map[string]interface{}{"vars": oldVars})) _ = backupRepo.Update(req.ID, map[string]interface{}{"vars": oldVars})
return err return err
} }
global.CONF.System.Backup = dirStr global.CONF.System.Backup = dirStr
@ -460,7 +460,7 @@ func (u *BackupService) loadAccessToken(backup *model.BackupAccount) error {
delete(varMap, "code") delete(varMap, "code")
backup.Credential = token backup.Credential = token
varMap["refresh_status"] = constant.StatusSuccess varMap["refresh_status"] = constant.StatusSuccess
varMap["refresh_time"] = time.Now().Format("2006-01-02 15:04:05") varMap["refresh_time"] = time.Now().Format(constant.DateTimeLayout)
varMap["refresh_token"] = refreshToken varMap["refresh_token"] = refreshToken
itemVars, err := json.Marshal(varMap) itemVars, err := json.Marshal(varMap)
if err != nil { if err != nil {
@ -587,10 +587,10 @@ func (u *BackupService) checkBackupConn(backup *model.BackupAccount) (bool, erro
} }
defer file.Close() defer file.Close()
write := bufio.NewWriter(file) write := bufio.NewWriter(file)
_, _ = write.WriteString(string("1Panel 备份账号测试文件。\n")) _, _ = write.WriteString("1Panel 备份账号测试文件。\n")
_, _ = write.WriteString(string("1Panel 備份賬號測試文件。\n")) _, _ = write.WriteString("1Panel 備份賬號測試文件。\n")
_, _ = write.WriteString(string("1Panel Backs up account test files.\n")) _, _ = write.WriteString("1Panel Backs up account test files.\n")
_, _ = write.WriteString(string("1Panelアカウントのテストファイルをバックアップします。\n")) _, _ = write.WriteString("1Panelアカウントのテストファイルをバックアップします。\n")
write.Flush() write.Flush()
targetPath := strings.TrimPrefix(path.Join(backup.BackupPath, "test/1panel"), "/") targetPath := strings.TrimPrefix(path.Join(backup.BackupPath, "test/1panel"), "/")
@ -625,7 +625,7 @@ func (u *BackupService) Run() {
} }
token, refreshToken, err := client.RefreshToken("refresh_token", varMap) token, refreshToken, err := client.RefreshToken("refresh_token", varMap)
varMap["refresh_status"] = constant.StatusSuccess varMap["refresh_status"] = constant.StatusSuccess
varMap["refresh_time"] = time.Now().Format("2006-01-02 15:04:05") varMap["refresh_time"] = time.Now().Format(constant.DateTimeLayout)
if err != nil { if err != nil {
varMap["refresh_status"] = constant.StatusFailed varMap["refresh_status"] = constant.StatusFailed
varMap["refresh_msg"] = err.Error() varMap["refresh_msg"] = err.Error()

View file

@ -35,7 +35,7 @@ func (u *BackupService) AppBackup(req dto.CommonBackup) (*model.BackupRecord, er
if err != nil { if err != nil {
return nil, err return nil, err
} }
timeNow := time.Now().Format("20060102150405") 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(localDir, itemDir) backupDir := path.Join(localDir, itemDir)
@ -163,7 +163,7 @@ func handleAppRecover(install *model.AppInstall, recoverFile string, isRollback
} }
if !isRollback { if !isRollback {
rollbackFile := path.Join(global.CONF.System.TmpDir, fmt.Sprintf("app/%s_%s.tar.gz", install.Name, time.Now().Format("20060102150405"))) rollbackFile := path.Join(global.CONF.System.TmpDir, fmt.Sprintf("app/%s_%s.tar.gz", install.Name, time.Now().Format(constant.DateTimeSlimLayout)))
if err := handleAppBackup(install, path.Dir(rollbackFile), path.Base(rollbackFile), "", ""); err != nil { if err := handleAppBackup(install, path.Dir(rollbackFile), path.Base(rollbackFile), "", ""); err != nil {
return fmt.Errorf("backup app %s for rollback before recover failed, err: %v", install.Name, err) return fmt.Errorf("backup app %s for rollback before recover failed, err: %v", install.Name, err)
} }

View file

@ -2,6 +2,7 @@ package service
import ( import (
"fmt" "fmt"
"github.com/1Panel-dev/1Panel/backend/constant"
"os" "os"
"path" "path"
"path/filepath" "path/filepath"
@ -24,7 +25,7 @@ func (u *BackupService) MysqlBackup(req dto.CommonBackup) error {
return err return err
} }
timeNow := time.Now().Format("20060102150405") 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(localDir, itemDir) targetDir := path.Join(localDir, 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))
@ -59,7 +60,7 @@ func (u *BackupService) MysqlRecoverByUpload(req dto.CommonRecover) error {
file := req.File file := req.File
fileName := path.Base(req.File) fileName := path.Base(req.File)
if strings.HasSuffix(fileName, ".tar.gz") { if strings.HasSuffix(fileName, ".tar.gz") {
fileNameItem := time.Now().Format("20060102150405") fileNameItem := time.Now().Format(constant.DateTimeSlimLayout)
dstDir := fmt.Sprintf("%s/%s", path.Dir(req.File), fileNameItem) dstDir := fmt.Sprintf("%s/%s", path.Dir(req.File), fileNameItem)
if _, err := os.Stat(dstDir); err != nil && os.IsNotExist(err) { if _, err := os.Stat(dstDir); err != nil && os.IsNotExist(err) {
if err = os.MkdirAll(dstDir, os.ModePerm); err != nil { if err = os.MkdirAll(dstDir, os.ModePerm); err != nil {
@ -142,7 +143,7 @@ func handleMysqlRecover(req dto.CommonRecover, isRollback bool) error {
} }
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("20060102150405"))) rollbackFile := path.Join(global.CONF.System.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,6 +2,7 @@ package service
import ( import (
"fmt" "fmt"
"github.com/1Panel-dev/1Panel/backend/constant"
"os" "os"
"path" "path"
"path/filepath" "path/filepath"
@ -25,7 +26,7 @@ func (u *BackupService) PostgresqlBackup(req dto.CommonBackup) error {
return err return err
} }
timeNow := time.Now().Format("20060102150405") 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(localDir, itemDir) targetDir := path.Join(localDir, 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))
@ -59,7 +60,7 @@ func (u *BackupService) PostgresqlRecoverByUpload(req dto.CommonRecover) error {
file := req.File file := req.File
fileName := path.Base(req.File) fileName := path.Base(req.File)
if strings.HasSuffix(fileName, ".tar.gz") { if strings.HasSuffix(fileName, ".tar.gz") {
fileNameItem := time.Now().Format("20060102150405") fileNameItem := time.Now().Format(constant.DateTimeSlimLayout)
dstDir := fmt.Sprintf("%s/%s", path.Dir(req.File), fileNameItem) dstDir := fmt.Sprintf("%s/%s", path.Dir(req.File), fileNameItem)
if _, err := os.Stat(dstDir); err != nil && os.IsNotExist(err) { if _, err := os.Stat(dstDir); err != nil && os.IsNotExist(err) {
if err = os.MkdirAll(dstDir, os.ModePerm); err != nil { if err = os.MkdirAll(dstDir, os.ModePerm); err != nil {
@ -136,7 +137,7 @@ func handlePostgresqlRecover(req dto.CommonRecover, isRollback bool) error {
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("20060102150405"))) rollbackFile := path.Join(global.CONF.System.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

@ -35,7 +35,7 @@ func (u *BackupService) RedisBackup(db dto.CommonBackup) error {
} }
global.LOG.Infof("appendonly in redis conf is %s", appendonly) global.LOG.Infof("appendonly in redis conf is %s", appendonly)
timeNow := time.Now().Format("20060102150405") + common.RandStrAndNum(5) timeNow := time.Now().Format(constant.DateTimeSlimLayout) + common.RandStrAndNum(5)
fileName := fmt.Sprintf("%s.rdb", timeNow) fileName := fmt.Sprintf("%s.rdb", timeNow)
if appendonly == "yes" { if appendonly == "yes" {
if strings.HasPrefix(redisInfo.Version, "6.") { if strings.HasPrefix(redisInfo.Version, "6.") {
@ -146,7 +146,7 @@ func handleRedisRecover(redisInfo *repo.RootInfo, recoverFile string, isRollback
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("20060102150405"), suffix)) rollbackFile := path.Join(global.CONF.System.TmpDir, fmt.Sprintf("database/redis/%s_%s.%s", redisInfo.Name, time.Now().Format(constant.DateTimeSlimLayout), suffix))
if err := handleRedisBackup(redisInfo, path.Dir(rollbackFile), path.Base(rollbackFile), secret); err != nil { if err := handleRedisBackup(redisInfo, 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)
} }

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("20060102150405"))) rollbackFile := path.Join(global.CONF.System.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)
} }

View file

@ -31,7 +31,7 @@ func (u *BackupService) WebsiteBackup(req dto.CommonBackup) error {
return err return err
} }
timeNow := time.Now().Format("20060102150405") timeNow := time.Now().Format(constant.DateTimeSlimLayout)
itemDir := fmt.Sprintf("website/%s", req.Name) itemDir := fmt.Sprintf("website/%s", req.Name)
backupDir := path.Join(localDir, itemDir) backupDir := path.Join(localDir, itemDir)
fileName := fmt.Sprintf("%s_%s.tar.gz", website.PrimaryDomain, timeNow+common.RandStrAndNum(5)) fileName := fmt.Sprintf("%s_%s.tar.gz", website.PrimaryDomain, timeNow+common.RandStrAndNum(5))
@ -106,7 +106,7 @@ func handleWebsiteRecover(website *model.Website, recoverFile string, isRollback
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("20060102150405"))) rollbackFile := path.Join(global.CONF.System.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)
} }

View file

@ -115,11 +115,11 @@ func (f *ClamService) SearchWithPage(req dto.SearchWithPage) (int64, interface{}
return logPaths[i] > logPaths[j] return logPaths[i] > logPaths[j]
}) })
if len(logPaths) != 0 { if len(logPaths) != 0 {
t1, err := time.ParseInLocation("20060102150405", logPaths[0], nyc) t1, err := time.ParseInLocation(constant.DateTimeSlimLayout, logPaths[0], nyc)
if err != nil { if err != nil {
continue continue
} }
datas[i].LastHandleDate = t1.Format("2006-01-02 15:04:05") datas[i].LastHandleDate = t1.Format(constant.DateTimeLayout)
} }
} }
return total, datas, err return total, datas, err
@ -173,7 +173,7 @@ func (u *ClamService) HandleOnce(req dto.OperateByID) error {
if cmd.CheckIllegal(clam.Path) { if cmd.CheckIllegal(clam.Path) {
return buserr.New(constant.ErrCmdIllegal) return buserr.New(constant.ErrCmdIllegal)
} }
logFile := path.Join(global.CONF.System.DataDir, scanDir, clam.Name, time.Now().Format("20060102150405")) logFile := path.Join(global.CONF.System.DataDir, scanDir, clam.Name, time.Now().Format(constant.DateTimeSlimLayout))
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)
} }
@ -197,7 +197,7 @@ func (u *ClamService) LoadRecords(req dto.ClamLogSearch) (int64, interface{}, er
var filterFiles []string var filterFiles []string
nyc, _ := time.LoadLocation(common.LoadTimeZone()) nyc, _ := time.LoadLocation(common.LoadTimeZone())
for _, item := range logPaths { for _, item := range logPaths {
t1, err := time.ParseInLocation("20060102150405", item, nyc) t1, err := time.ParseInLocation(constant.DateTimeSlimLayout, item, nyc)
if err != nil { if err != nil {
continue continue
} }

View file

@ -190,7 +190,7 @@ func (u *ContainerService) Page(req dto.PageContainer) (int64, interface{}, erro
ports := loadContainerPort(item.Ports) ports := loadContainerPort(item.Ports)
info := dto.ContainerInfo{ info := dto.ContainerInfo{
ContainerID: item.ID, ContainerID: item.ID,
CreateTime: time.Unix(item.Created, 0).Format("2006-01-02 15:04:05"), CreateTime: time.Unix(item.Created, 0).Format(constant.DateTimeLayout),
Name: item.Names[0][1:], Name: item.Names[0][1:],
ImageId: strings.Split(item.ImageID, ":")[1], ImageId: strings.Split(item.ImageID, ":")[1],
ImageName: item.Image, ImageName: item.Image,
@ -1147,7 +1147,7 @@ func loadConfigInfo(isCreate bool, req dto.ContainerOperate, oldContainer *types
} }
} else { } else {
if req.Ipv4 != "" || req.Ipv6 != "" { if req.Ipv4 != "" || req.Ipv6 != "" {
return nil, nil, nil, fmt.Errorf("Please set up the network") return nil, nil, nil, fmt.Errorf("please set up the network")
} }
networkConf = network.NetworkingConfig{} networkConf = network.NetworkingConfig{}
} }

View file

@ -59,7 +59,7 @@ func (u *ContainerService) PageCompose(req dto.SearchWithPage) (int64, interface
ContainerID: container.ID, ContainerID: container.ID,
Name: container.Names[0][1:], Name: container.Names[0][1:],
State: container.State, State: container.State,
CreateTime: time.Unix(container.Created, 0).Format("2006-01-02 15:04:05"), CreateTime: time.Unix(container.Created, 0).Format(constant.DateTimeLayout),
} }
if compose, has := composeMap[name]; has { if compose, has := composeMap[name]; has {
compose.ContainerNumber++ compose.ContainerNumber++
@ -70,7 +70,7 @@ func (u *ContainerService) PageCompose(req dto.SearchWithPage) (int64, interface
workdir := container.Labels[composeWorkdirLabel] workdir := container.Labels[composeWorkdirLabel]
composeItem := dto.ComposeInfo{ composeItem := dto.ComposeInfo{
ContainerNumber: 1, ContainerNumber: 1,
CreatedAt: time.Unix(container.Created, 0).Format("2006-01-02 15:04:05"), CreatedAt: time.Unix(container.Created, 0).Format(constant.DateTimeLayout),
ConfigFile: config, ConfigFile: config,
Workdir: workdir, Workdir: workdir,
Containers: []dto.ComposeContainer{containerItem}, Containers: []dto.ComposeContainer{containerItem},
@ -168,7 +168,7 @@ func (u *ContainerService) CreateCompose(req dto.ComposeCreate) (string, error)
return "", err return "", err
} }
} }
logItem := fmt.Sprintf("%s/compose_create_%s_%s.log", dockerLogDir, req.Name, time.Now().Format("20060102150405")) logItem := fmt.Sprintf("%s/compose_create_%s_%s.log", dockerLogDir, req.Name, time.Now().Format(constant.DateTimeSlimLayout))
file, err := os.OpenFile(logItem, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0666) file, err := os.OpenFile(logItem, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0666)
if err != nil { if err != nil {
return "", err return "", err

View file

@ -49,7 +49,7 @@ func (u *CronjobService) SearchWithPage(search dto.PageCronjob) (int64, interfac
} }
record, _ := cronjobRepo.RecordFirst(cronjob.ID) record, _ := cronjobRepo.RecordFirst(cronjob.ID)
if record.ID != 0 { if record.ID != 0 {
item.LastRecordTime = record.StartTime.Format("2006-01-02 15:04:05") item.LastRecordTime = record.StartTime.Format(constant.DateTimeLayout)
} else { } else {
item.LastRecordTime = "-" item.LastRecordTime = "-"
} }
@ -71,7 +71,7 @@ func (u *CronjobService) SearchRecords(search dto.SearchRecord) (int64, interfac
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, errors.WithMessage(constant.ErrStructTransform, err.Error())
} }
item.StartTime = record.StartTime.Format("2006-01-02 15:04:05") item.StartTime = record.StartTime.Format(constant.DateTimeLayout)
dtoCronjobs = append(dtoCronjobs, item) dtoCronjobs = append(dtoCronjobs, item)
} }
return total, dtoCronjobs, err return total, dtoCronjobs, err
@ -330,7 +330,7 @@ func mkdirAndWriteFile(cronjob *model.Cronjob, startTime time.Time, msg []byte)
} }
} }
path := fmt.Sprintf("%s/%s.log", dir, startTime.Format("20060102150405")) path := fmt.Sprintf("%s/%s.log", dir, startTime.Format(constant.DateTimeSlimLayout))
global.LOG.Infof("cronjob %s has generated some logs %s", cronjob.Name, path) global.LOG.Infof("cronjob %s has generated some logs %s", cronjob.Name, path)
file, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE, 0666) file, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE, 0666)
if err != nil { if err != nil {

View file

@ -20,7 +20,7 @@ func (u *CronjobService) handleApp(cronjob model.Cronjob, startTime time.Time) e
if cronjob.AppID == "all" { if cronjob.AppID == "all" {
apps, _ = appInstallRepo.ListBy() apps, _ = appInstallRepo.ListBy()
} else { } else {
itemID, _ := (strconv.Atoi(cronjob.AppID)) itemID, _ := strconv.Atoi(cronjob.AppID)
app, err := appInstallRepo.GetFirst(commonRepo.WithByID(uint(itemID))) app, err := appInstallRepo.GetFirst(commonRepo.WithByID(uint(itemID)))
if err != nil { if err != nil {
return err return err
@ -40,7 +40,7 @@ func (u *CronjobService) handleApp(cronjob model.Cronjob, startTime time.Time) e
record.DetailName = app.Name record.DetailName = app.Name
record.Source, record.BackupType = loadRecordPath(cronjob, accountMap) record.Source, record.BackupType = loadRecordPath(cronjob, accountMap)
backupDir := path.Join(global.CONF.System.TmpDir, fmt.Sprintf("app/%s/%s", app.App.Key, app.Name)) backupDir := path.Join(global.CONF.System.TmpDir, fmt.Sprintf("app/%s/%s", app.App.Key, app.Name))
record.FileName = fmt.Sprintf("app_%s_%s.tar.gz", app.Name, startTime.Format("20060102150405")+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, backupDir, record.FileName, cronjob.ExclusionRules, cronjob.Secret); err != nil { if err := handleAppBackup(&app, backupDir, record.FileName, cronjob.ExclusionRules, cronjob.Secret); err != nil {
return err return err
} }
@ -73,7 +73,7 @@ func (u *CronjobService) handleWebsite(cronjob model.Cronjob, startTime time.Tim
record.DetailName = web.Alias record.DetailName = web.Alias
record.Source, record.BackupType = loadRecordPath(cronjob, accountMap) record.Source, record.BackupType = loadRecordPath(cronjob, accountMap)
backupDir := path.Join(global.CONF.System.TmpDir, fmt.Sprintf("website/%s", web.PrimaryDomain)) backupDir := path.Join(global.CONF.System.TmpDir, fmt.Sprintf("website/%s", web.PrimaryDomain))
record.FileName = fmt.Sprintf("website_%s_%s.tar.gz", web.PrimaryDomain, startTime.Format("20060102150405")+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); err != nil { if err := handleWebsiteBackup(&web, backupDir, record.FileName, cronjob.ExclusionRules, cronjob.Secret); err != nil {
return err return err
} }
@ -107,7 +107,7 @@ func (u *CronjobService) handleDatabase(cronjob model.Cronjob, startTime time.Ti
record.Source, record.BackupType = loadRecordPath(cronjob, accountMap) record.Source, record.BackupType = loadRecordPath(cronjob, accountMap)
backupDir := path.Join(global.CONF.System.TmpDir, fmt.Sprintf("database/%s/%s/%s", dbInfo.DBType, record.Name, dbInfo.Name)) backupDir := path.Join(global.CONF.System.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("20060102150405")+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.Database, dbInfo.DBType, dbInfo.Name, backupDir, record.FileName); err != nil { if err := handleMysqlBackup(dbInfo.Database, dbInfo.DBType, dbInfo.Name, backupDir, record.FileName); err != nil {
return err return err
@ -136,7 +136,7 @@ func (u *CronjobService) handleDirectory(cronjob model.Cronjob, startTime time.T
if err != nil { if err != nil {
return err return err
} }
fileName := fmt.Sprintf("directory%s_%s.tar.gz", strings.ReplaceAll(cronjob.SourceDir, "/", "_"), startTime.Format("20060102150405")+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.CONF.System.TmpDir, fmt.Sprintf("%s/%s", cronjob.Type, cronjob.Name))
if err := handleTar(cronjob.SourceDir, backupDir, fileName, cronjob.ExclusionRules, cronjob.Secret); err != nil { if err := handleTar(cronjob.SourceDir, backupDir, fileName, cronjob.ExclusionRules, cronjob.Secret); err != nil {
return err return err
@ -166,7 +166,7 @@ func (u *CronjobService) handleSystemLog(cronjob model.Cronjob, startTime time.T
if err != nil { if err != nil {
return err return err
} }
nameItem := startTime.Format("20060102150405") + 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.CONF.System.TmpDir, "log", nameItem)
if err := handleBackupLogs(backupDir, fileName, cronjob.Secret); err != nil { if err := handleBackupLogs(backupDir, fileName, cronjob.Secret); err != nil {
@ -210,7 +210,7 @@ func (u *CronjobService) handleSnapshot(cronjob model.Cronjob, startTime time.Ti
From: record.BackupType, From: record.BackupType,
DefaultDownload: cronjob.DefaultDownload, DefaultDownload: cronjob.DefaultDownload,
} }
name, err := NewISnapshotService().HandleSnapshot(true, logPath, req, startTime.Format("20060102150405")+common.RandStrAndNum(5), cronjob.Secret) name, err := NewISnapshotService().HandleSnapshot(true, logPath, req, startTime.Format(constant.DateTimeSlimLayout)+common.RandStrAndNum(5), cronjob.Secret)
if err != nil { if err != nil {
return err return err
} }
@ -254,7 +254,7 @@ func loadDbsForJob(cronjob model.Cronjob) []databaseHelper {
} }
return dbs return dbs
} }
itemID, _ := (strconv.Atoi(cronjob.DBName)) itemID, _ := strconv.Atoi(cronjob.DBName)
if cronjob.DBType == "mysql" || cronjob.DBType == "mariadb" { if cronjob.DBType == "mysql" || cronjob.DBType == "mariadb" {
mysqlItem, _ := mysqlRepo.Get(commonRepo.WithByID(uint(itemID))) mysqlItem, _ := mysqlRepo.Get(commonRepo.WithByID(uint(itemID)))
dbs = append(dbs, databaseHelper{ dbs = append(dbs, databaseHelper{
@ -279,7 +279,7 @@ func loadWebsForJob(cronjob model.Cronjob) []model.Website {
weblist, _ = websiteRepo.List() weblist, _ = websiteRepo.List()
return weblist return weblist
} }
itemID, _ := (strconv.Atoi(cronjob.Website)) itemID, _ := strconv.Atoi(cronjob.Website)
webItem, _ := websiteRepo.GetFirst(commonRepo.WithByID(uint(itemID))) webItem, _ := websiteRepo.GetFirst(commonRepo.WithByID(uint(itemID)))
if webItem.ID != 0 { if webItem.ID != 0 {
weblist = append(weblist, webItem) weblist = append(weblist, webItem)

View file

@ -124,7 +124,7 @@ func (u *CronjobService) handleNtpSync() error {
if err != nil { if err != nil {
return err return err
} }
if err := ntp.UpdateSystemTime(ntime.Format("2006-01-02 15:04:05")); err != nil { if err := ntp.UpdateSystemTime(ntime.Format(constant.DateTimeLayout)); err != nil {
return err return err
} }
return nil return nil
@ -224,7 +224,7 @@ func (u *CronjobService) handleCutWebsiteLog(cronjob *model.Cronjob, startTime t
_ = os.MkdirAll(dstLogDir, 0755) _ = os.MkdirAll(dstLogDir, 0755)
} }
dstName := fmt.Sprintf("%s_log_%s.gz", website.PrimaryDomain, startTime.Format("20060102150405")) dstName := fmt.Sprintf("%s_log_%s.gz", website.PrimaryDomain, startTime.Format(constant.DateTimeSlimLayout))
dstFilePath := path.Join(dstLogDir, dstName) dstFilePath := path.Join(dstLogDir, dstName)
filePaths = append(filePaths, dstFilePath) filePaths = append(filePaths, dstFilePath)
@ -384,7 +384,7 @@ func (u *CronjobService) generateLogsPath(cronjob model.Cronjob, startTime time.
_ = os.MkdirAll(dir, os.ModePerm) _ = os.MkdirAll(dir, os.ModePerm)
} }
path := fmt.Sprintf("%s/%s.log", dir, startTime.Format("20060102150405")) path := fmt.Sprintf("%s/%s.log", dir, startTime.Format(constant.DateTimeSlimLayout))
return path return path
} }

View file

@ -135,7 +135,7 @@ func (u *DashboardService) LoadCurrentInfo(ioOption string, netOption string) *d
var currentInfo dto.DashboardCurrent var currentInfo dto.DashboardCurrent
hostInfo, _ := host.Info() hostInfo, _ := host.Info()
currentInfo.Uptime = hostInfo.Uptime currentInfo.Uptime = hostInfo.Uptime
currentInfo.TimeSinceUptime = time.Now().Add(-time.Duration(hostInfo.Uptime) * time.Second).Format("2006-01-02 15:04:05") currentInfo.TimeSinceUptime = time.Now().Add(-time.Duration(hostInfo.Uptime) * time.Second).Format(constant.DateTimeLayout)
currentInfo.Procs = hostInfo.Procs currentInfo.Procs = hostInfo.Procs
currentInfo.CPUTotal, _ = cpu.Counts(true) currentInfo.CPUTotal, _ = cpu.Counts(true)

View file

@ -7,8 +7,8 @@ import (
"path" "path"
"github.com/1Panel-dev/1Panel/backend/utils/postgresql" "github.com/1Panel-dev/1Panel/backend/utils/postgresql"
pg_client "github.com/1Panel-dev/1Panel/backend/utils/postgresql/client" pgclient "github.com/1Panel-dev/1Panel/backend/utils/postgresql/client"
redis_client "github.com/1Panel-dev/1Panel/backend/utils/redis" redisclient "github.com/1Panel-dev/1Panel/backend/utils/redis"
"github.com/1Panel-dev/1Panel/backend/app/dto" "github.com/1Panel-dev/1Panel/backend/app/dto"
"github.com/1Panel-dev/1Panel/backend/buserr" "github.com/1Panel-dev/1Panel/backend/buserr"
@ -118,7 +118,7 @@ func (u *DatabaseService) LoadItems(dbType string) ([]dto.DatabaseItem, error) {
func (u *DatabaseService) CheckDatabase(req dto.DatabaseCreate) bool { func (u *DatabaseService) CheckDatabase(req dto.DatabaseCreate) bool {
switch req.Type { switch req.Type {
case constant.AppPostgresql: case constant.AppPostgresql:
_, err := postgresql.NewPostgresqlClient(pg_client.DBInfo{ _, err := postgresql.NewPostgresqlClient(pgclient.DBInfo{
From: "remote", From: "remote",
Address: req.Address, Address: req.Address,
Port: req.Port, Port: req.Port,
@ -128,7 +128,7 @@ func (u *DatabaseService) CheckDatabase(req dto.DatabaseCreate) bool {
}) })
return err == nil return err == nil
case constant.AppRedis: case constant.AppRedis:
_, err := redis_client.NewRedisClient(redis_client.DBInfo{ _, err := redisclient.NewRedisClient(redisclient.DBInfo{
Address: req.Address, Address: req.Address,
Port: req.Port, Port: req.Port,
Password: req.Password, Password: req.Password,
@ -165,7 +165,7 @@ func (u *DatabaseService) Create(req dto.DatabaseCreate) error {
} }
switch req.Type { switch req.Type {
case constant.AppPostgresql: case constant.AppPostgresql:
if _, err := postgresql.NewPostgresqlClient(pg_client.DBInfo{ if _, err := postgresql.NewPostgresqlClient(pgclient.DBInfo{
From: "remote", From: "remote",
Address: req.Address, Address: req.Address,
Port: req.Port, Port: req.Port,
@ -176,7 +176,7 @@ func (u *DatabaseService) Create(req dto.DatabaseCreate) error {
return err return err
} }
case constant.AppRedis: case constant.AppRedis:
if _, err := redis_client.NewRedisClient(redis_client.DBInfo{ if _, err := redisclient.NewRedisClient(redisclient.DBInfo{
Address: req.Address, Address: req.Address,
Port: req.Port, Port: req.Port,
Password: req.Password, Password: req.Password,
@ -269,7 +269,7 @@ func (u *DatabaseService) Delete(req dto.DatabaseDelete) error {
func (u *DatabaseService) Update(req dto.DatabaseUpdate) error { func (u *DatabaseService) Update(req dto.DatabaseUpdate) error {
switch req.Type { switch req.Type {
case constant.AppPostgresql: case constant.AppPostgresql:
if _, err := postgresql.NewPostgresqlClient(pg_client.DBInfo{ if _, err := postgresql.NewPostgresqlClient(pgclient.DBInfo{
From: "remote", From: "remote",
Address: req.Address, Address: req.Address,
Port: req.Port, Port: req.Port,
@ -280,7 +280,7 @@ func (u *DatabaseService) Update(req dto.DatabaseUpdate) error {
return err return err
} }
case constant.AppRedis: case constant.AppRedis:
if _, err := redis_client.NewRedisClient(redis_client.DBInfo{ if _, err := redisclient.NewRedisClient(redisclient.DBInfo{
Address: req.Address, Address: req.Address,
Port: req.Port, Port: req.Port,
Password: req.Password, Password: req.Password,

View file

@ -518,11 +518,11 @@ func (u *MysqlService) LoadStatus(req dto.OperationWithNameAndType) (*dto.MysqlS
if value, ok := statusMap["Run"]; ok { if value, ok := statusMap["Run"]; ok {
uptime, _ := strconv.Atoi(value) uptime, _ := strconv.Atoi(value)
info.Run = time.Unix(time.Now().Unix()-int64(uptime), 0).Format("2006-01-02 15:04:05") info.Run = time.Unix(time.Now().Unix()-int64(uptime), 0).Format(constant.DateTimeLayout)
} else { } else {
if value, ok := statusMap["Uptime"]; ok { if value, ok := statusMap["Uptime"]; ok {
uptime, _ := strconv.Atoi(value) uptime, _ := strconv.Atoi(value)
info.Run = time.Unix(time.Now().Unix()-int64(uptime), 0).Format("2006-01-02 15:04:05") info.Run = time.Unix(time.Now().Unix()-int64(uptime), 0).Format(constant.DateTimeLayout)
} }
} }

View file

@ -158,7 +158,7 @@ func (u *DeviceService) Update(key, value string) error {
if err != nil { if err != nil {
return err return err
} }
ts := ntime.Format("2006-01-02 15:04:05") ts := ntime.Format(constant.DateTimeLayout)
if err := ntp.UpdateSystemTime(ts); err != nil { if err := ntp.UpdateSystemTime(ts); err != nil {
return err return err
} }

View file

@ -72,7 +72,7 @@ func (u *DeviceService) Scan() dto.CleanData {
snapTree := loadSnapshotTree(fileOp) snapTree := loadSnapshotTree(fileOp)
snapSize := uint64(0) snapSize := uint64(0)
for _, snap := range snapTree { for _, snap := range snapTree {
snapSize += uint64(snap.Size) snapSize += snap.Size
} }
treeData = append(treeData, dto.CleanTree{ treeData = append(treeData, dto.CleanTree{
ID: uuid.NewString(), ID: uuid.NewString(),
@ -87,7 +87,7 @@ func (u *DeviceService) Scan() dto.CleanData {
rollBackTree := loadRollBackTree(fileOp) rollBackTree := loadRollBackTree(fileOp)
rollbackSize := uint64(0) rollbackSize := uint64(0)
for _, rollback := range rollBackTree { for _, rollback := range rollBackTree {
rollbackSize += uint64(rollback.Size) rollbackSize += rollback.Size
} }
treeData = append(treeData, dto.CleanTree{ treeData = append(treeData, dto.CleanTree{
ID: uuid.NewString(), ID: uuid.NewString(),
@ -113,7 +113,7 @@ func (u *DeviceService) Scan() dto.CleanData {
unusedTree := loadUnusedFile(fileOp) unusedTree := loadUnusedFile(fileOp)
unusedSize := uint64(0) unusedSize := uint64(0)
for _, unused := range unusedTree { for _, unused := range unusedTree {
unusedSize += uint64(unused.Size) unusedSize += unused.Size
} }
treeData = append(treeData, dto.CleanTree{ treeData = append(treeData, dto.CleanTree{
ID: uuid.NewString(), ID: uuid.NewString(),
@ -278,7 +278,7 @@ func (u *DeviceService) Clean(req []dto.Clean) {
} }
} }
_ = settingRepo.Update("LastCleanTime", time.Now().Format("2006-01-02 15:04:05")) _ = settingRepo.Update("LastCleanTime", time.Now().Format(constant.DateTimeLayout))
_ = settingRepo.Update("LastCleanSize", fmt.Sprintf("%v", size)) _ = settingRepo.Update("LastCleanSize", fmt.Sprintf("%v", size))
_ = settingRepo.Update("LastCleanData", fmt.Sprintf("%v", len(req))) _ = settingRepo.Update("LastCleanData", fmt.Sprintf("%v", len(req)))
@ -342,7 +342,7 @@ func (u *DeviceService) CleanForCronjob() (string, error) {
} }
} }
} }
timeNow := time.Now().Format("2006-01-02 15:04:05") timeNow := time.Now().Format(constant.DateTimeLayout)
dropFileOrDirWithLog(path.Join(global.CONF.System.BaseDir, dockerLogPath), &logs, &size, &fileCount) dropFileOrDirWithLog(path.Join(global.CONF.System.BaseDir, dockerLogPath), &logs, &size, &fileCount)
logs += fmt.Sprintf("\n%s: total clean: %s, total count: %d", timeNow, common.LoadSizeUnit2F(float64(size)), fileCount) logs += fmt.Sprintf("\n%s: total clean: %s, total count: %d", timeNow, common.LoadSizeUnit2F(float64(size)), fileCount)

View file

@ -79,7 +79,7 @@ func (f *FileService) SearchUploadWithPage(req request.SearchUploadWithPage) (in
} }
if !info.IsDir() { if !info.IsDir() {
files = append(files, response.UploadInfo{ files = append(files, response.UploadInfo{
CreatedAt: info.ModTime().Format("2006-01-02 15:04:05"), CreatedAt: info.ModTime().Format(constant.DateTimeLayout),
Size: int(info.Size()), Size: int(info.Size()),
Name: info.Name(), Name: info.Name(),
}) })

View file

@ -199,7 +199,7 @@ func (u *ImageService) ImageBuild(req dto.ImageBuild) (string, error) {
return "", err return "", err
} }
} }
logItem := fmt.Sprintf("%s/image_build_%s_%s.log", dockerLogDir, strings.ReplaceAll(req.Name, ":", "_"), time.Now().Format("20060102150405")) logItem := fmt.Sprintf("%s/image_build_%s_%s.log", dockerLogDir, strings.ReplaceAll(req.Name, ":", "_"), time.Now().Format(constant.DateTimeSlimLayout))
file, err := os.OpenFile(logItem, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0666) file, err := os.OpenFile(logItem, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0666)
if err != nil { if err != nil {
return "", err return "", err
@ -249,7 +249,7 @@ func (u *ImageService) ImagePull(req dto.ImagePull) (string, error) {
} }
} }
imageItemName := strings.ReplaceAll(path.Base(req.ImageName), ":", "_") imageItemName := strings.ReplaceAll(path.Base(req.ImageName), ":", "_")
logItem := fmt.Sprintf("%s/image_pull_%s_%s.log", dockerLogDir, imageItemName, time.Now().Format("20060102150405")) logItem := fmt.Sprintf("%s/image_pull_%s_%s.log", dockerLogDir, imageItemName, time.Now().Format(constant.DateTimeSlimLayout))
file, err := os.OpenFile(logItem, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0666) file, err := os.OpenFile(logItem, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0666)
if err != nil { if err != nil {
return "", err return "", err
@ -403,7 +403,7 @@ func (u *ImageService) ImagePush(req dto.ImagePush) (string, error) {
} }
} }
imageItemName := strings.ReplaceAll(path.Base(req.Name), ":", "_") imageItemName := strings.ReplaceAll(path.Base(req.Name), ":", "_")
logItem := fmt.Sprintf("%s/image_push_%s_%s.log", dockerLogDir, imageItemName, time.Now().Format("20060102150405")) logItem := fmt.Sprintf("%s/image_push_%s_%s.log", dockerLogDir, imageItemName, time.Now().Format(constant.DateTimeSlimLayout))
file, err := os.OpenFile(logItem, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0666) file, err := os.OpenFile(logItem, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0666)
if err != nil { if err != nil {
return "", err return "", err

View file

@ -118,7 +118,7 @@ func (u *SettingService) Update(key, value string) error {
if err != nil { if err != nil {
return err return err
} }
if err := settingRepo.Update("ExpirationTime", time.Now().AddDate(0, 0, timeout).Format("2006-01-02 15:04:05")); err != nil { if err := settingRepo.Update("ExpirationTime", time.Now().AddDate(0, 0, timeout).Format(constant.DateTimeLayout)); err != nil {
return err return err
} }
case "BindDomain": case "BindDomain":
@ -382,7 +382,7 @@ func (u *SettingService) LoadFromCert() (*dto.SSLInfo, error) {
} }
data.Domain = ssl.Domains data.Domain = ssl.Domains
data.SSLID = uint(id) data.SSLID = uint(id)
data.Timeout = ssl.ExpireDate.Format("2006-01-02 15:04:05") data.Timeout = ssl.ExpireDate.Format(constant.DateTimeLayout)
} }
return &data, nil return &data, nil
} }
@ -410,7 +410,7 @@ func (u *SettingService) HandlePasswordExpired(c *gin.Context, old, new string)
return err return err
} }
timeout, _ := strconv.Atoi(expiredSetting.Value) timeout, _ := strconv.Atoi(expiredSetting.Value)
if err := settingRepo.Update("ExpirationTime", time.Now().AddDate(0, 0, timeout).Format("2006-01-02 15:04:05")); err != nil { if err := settingRepo.Update("ExpirationTime", time.Now().AddDate(0, 0, timeout).Format(constant.DateTimeLayout)); err != nil {
return err return err
} }
return nil return nil
@ -455,7 +455,7 @@ func loadInfoFromCert() (dto.SSLInfo, error) {
} }
return dto.SSLInfo{ return dto.SSLInfo{
Domain: strings.Join(domains, ","), Domain: strings.Join(domains, ","),
Timeout: certObj.NotAfter.Format("2006-01-02 15:04:05"), Timeout: certObj.NotAfter.Format(constant.DateTimeLayout),
RootPath: path.Join(global.CONF.System.BaseDir, "1panel/secret/server.crt"), RootPath: path.Join(global.CONF.System.BaseDir, "1panel/secret/server.crt"),
}, nil }, nil
} }

View file

@ -119,7 +119,7 @@ type SnapshotJson struct {
} }
func (u *SnapshotService) SnapshotCreate(req dto.SnapshotCreate) error { func (u *SnapshotService) SnapshotCreate(req dto.SnapshotCreate) error {
if _, err := u.HandleSnapshot(false, "", req, time.Now().Format("20060102150405"), req.Secret); err != nil { if _, err := u.HandleSnapshot(false, "", req, time.Now().Format(constant.DateTimeSlimLayout), req.Secret); err != nil {
return err return err
} }
return nil return nil
@ -132,7 +132,7 @@ func (u *SnapshotService) SnapshotRecover(req dto.SnapshotRecover) error {
return err return err
} }
if hasOs(snap.Name) && !strings.Contains(snap.Name, loadOs()) { if hasOs(snap.Name) && !strings.Contains(snap.Name, loadOs()) {
return fmt.Errorf("Restoring snapshots(%s) between different server architectures(%s) is not supported.", snap.Name, loadOs()) return fmt.Errorf("restoring snapshots(%s) between different server architectures(%s) is not supported", snap.Name, loadOs())
} }
if !req.IsNew && len(snap.InterruptStep) != 0 && len(snap.RollbackStatus) != 0 { if !req.IsNew && len(snap.InterruptStep) != 0 && len(snap.RollbackStatus) != 0 {
return fmt.Errorf("the snapshot has been rolled back and cannot be restored again") return fmt.Errorf("the snapshot has been rolled back and cannot be restored again")
@ -350,7 +350,7 @@ func updateRecoverStatus(id uint, isRecover bool, interruptStep, status, message
"interrupt_step": interruptStep, "interrupt_step": interruptStep,
"recover_status": status, "recover_status": status,
"recover_message": message, "recover_message": message,
"last_recovered_at": time.Now().Format("2006-01-02 15:04:05"), "last_recovered_at": time.Now().Format(constant.DateTimeLayout),
}); err != nil { }); err != nil {
global.LOG.Errorf("update snap recover status failed, err: %v", err) global.LOG.Errorf("update snap recover status failed, err: %v", err)
} }
@ -365,7 +365,7 @@ func updateRecoverStatus(id uint, isRecover bool, interruptStep, status, message
"interrupt_step": "", "interrupt_step": "",
"rollback_status": "", "rollback_status": "",
"rollback_message": "", "rollback_message": "",
"last_rollbacked_at": time.Now().Format("2006-01-02 15:04:05"), "last_rollbacked_at": time.Now().Format(constant.DateTimeLayout),
}); err != nil { }); err != nil {
global.LOG.Errorf("update snap recover status failed, err: %v", err) global.LOG.Errorf("update snap recover status failed, err: %v", err)
} }
@ -375,7 +375,7 @@ func updateRecoverStatus(id uint, isRecover bool, interruptStep, status, message
if err := snapshotRepo.Update(id, map[string]interface{}{ if err := snapshotRepo.Update(id, map[string]interface{}{
"rollback_status": status, "rollback_status": status,
"rollback_message": message, "rollback_message": message,
"last_rollbacked_at": time.Now().Format("2006-01-02 15:04:05"), "last_rollbacked_at": time.Now().Format(constant.DateTimeLayout),
}); err != nil { }); err != nil {
global.LOG.Errorf("update snap recover status failed, err: %v", err) global.LOG.Errorf("update snap recover status failed, err: %v", err)
} }

View file

@ -62,7 +62,9 @@ func (u *SSHService) GetSSHInfo() (*dto.SSHInfo, error) {
active, err := systemctl.IsActive(serviceName) active, err := systemctl.IsActive(serviceName)
if !active { if !active {
data.Status = constant.StatusDisable data.Status = constant.StatusDisable
if err != nil {
data.Message = err.Error() data.Message = err.Error()
}
} else { } else {
data.Status = constant.StatusEnable data.Status = constant.StatusEnable
} }
@ -549,14 +551,14 @@ func loadDate(currentYear int, DateStr string, nyc *time.Location) time.Time {
} }
func analyzeDateStr(parts []string) (int, string) { func analyzeDateStr(parts []string) (int, string) {
t, err := time.Parse("2006-01-02T15:04:05.999999-07:00", parts[0]) t, err := time.Parse(time.RFC3339Nano, parts[0])
if err == nil { if err == nil {
if len(parts) < 12 { if len(parts) < 12 {
return 0, "" return 0, ""
} }
return 0, t.Format("2006 Jan 2 15:04:05") return 0, t.Format("2006 Jan 2 15:04:05")
} }
t, err = time.Parse("2006-01-02 15:04:05", fmt.Sprintf("%s %s", parts[0], parts[1])) t, err = time.Parse(constant.DateTimeLayout, fmt.Sprintf("%s %s", parts[0], parts[1]))
if err == nil { if err == nil {
if len(parts) < 14 { if len(parts) < 14 {
return 0, "" return 0, ""

View file

@ -83,7 +83,7 @@ func (u *UpgradeService) LoadNotes(req dto.Upgrade) (string, error) {
func (u *UpgradeService) Upgrade(req dto.Upgrade) error { func (u *UpgradeService) Upgrade(req dto.Upgrade) error {
global.LOG.Info("start to upgrade now...") global.LOG.Info("start to upgrade now...")
fileOp := files.NewFileOp() fileOp := files.NewFileOp()
timeStr := time.Now().Format("20060102150405") timeStr := time.Now().Format(constant.DateTimeSlimLayout)
rootDir := path.Join(global.CONF.System.TmpDir, fmt.Sprintf("upgrade/upgrade_%s/downloads", timeStr)) rootDir := path.Join(global.CONF.System.TmpDir, fmt.Sprintf("upgrade/upgrade_%s/downloads", timeStr))
originalDir := path.Join(global.CONF.System.TmpDir, fmt.Sprintf("upgrade/upgrade_%s/original", timeStr)) originalDir := path.Join(global.CONF.System.TmpDir, fmt.Sprintf("upgrade/upgrade_%s/original", timeStr))
if err := os.MkdirAll(rootDir, os.ModePerm); err != nil { if err := os.MkdirAll(rootDir, os.ModePerm); err != nil {

View file

@ -17,4 +17,9 @@ const (
TimeOut5s = 5 TimeOut5s = 5
TimeOut20s = 20 TimeOut20s = 20
TimeOut5m = 300 TimeOut5m = 300
DateLayout = "2006-01-02" // or use time.DateOnly while go version >= 1.20
DefaultDate = "1970-01-01"
DateTimeLayout = "2006-01-02 15:04:05" // or use time.DateTime while go version >= 1.20
DateTimeSlimLayout = "20060102150405"
) )

View file

@ -4,10 +4,6 @@ const (
WebRunning = "Running" WebRunning = "Running"
WebStopped = "Stopped" WebStopped = "Stopped"
DateLayout = "2006-01-02"
DateTimeLayout = "2006-01-02 15:04:05"
DefaultDate = "1970-01-01"
ProtocolHTTP = "HTTP" ProtocolHTTP = "HTTP"
ProtocolHTTPS = "HTTPS" ProtocolHTTPS = "HTTPS"

View file

@ -94,7 +94,7 @@ func syncBeforeStart() {
global.LOG.Errorf("load remote time with [%s] failed, err: %v", ntpSite.Value, err) global.LOG.Errorf("load remote time with [%s] failed, err: %v", ntpSite.Value, err)
return return
} }
ts := ntime.Format("2006-01-02 15:04:05") ts := ntime.Format(constant.DateTimeLayout)
if err := ntp.UpdateSystemTime(ts); err != nil { if err := ntp.UpdateSystemTime(ts); err != nil {
global.LOG.Errorf("failed to synchronize system time with [%s], err: %v", ntpSite.Value, err) global.LOG.Errorf("failed to synchronize system time with [%s], err: %v", ntpSite.Value, err)
} }

View file

@ -109,7 +109,7 @@ var AddTableSetting = &gormigrate.Migration{
return err return err
} }
if err := tx.Create(&model.Setting{Key: "ExpirationTime", Value: time.Now().AddDate(0, 0, 10).Format("2006-01-02 15:04:05")}).Error; err != nil { if err := tx.Create(&model.Setting{Key: "ExpirationTime", Value: time.Now().AddDate(0, 0, 10).Format(constant.DateTimeLayout)}).Error; err != nil {
return err return err
} }
if err := tx.Create(&model.Setting{Key: "ExpirationDays", Value: "0"}).Error; err != nil { if err := tx.Create(&model.Setting{Key: "ExpirationDays", Value: "0"}).Error; err != nil {

View file

@ -251,7 +251,7 @@ var UpdateOneDriveToken = &gormigrate.Migration{
varMap["refresh_token"] = backup.Credential varMap["refresh_token"] = backup.Credential
token, refreshToken, err := client.RefreshToken("refresh_token", varMap) token, refreshToken, err := client.RefreshToken("refresh_token", varMap)
varMap["refresh_status"] = constant.StatusSuccess varMap["refresh_status"] = constant.StatusSuccess
varMap["refresh_time"] = time.Now().Format("2006-01-02 15:04:05") varMap["refresh_time"] = time.Now().Format(constant.DateTimeLayout)
if err != nil { if err != nil {
varMap["refresh_msg"] = err.Error() varMap["refresh_msg"] = err.Error()
varMap["refresh_status"] = constant.StatusFailed varMap["refresh_status"] = constant.StatusFailed

View file

@ -31,7 +31,7 @@ func PasswordExpired() gin.HandlerFunc {
return return
} }
loc, _ := time.LoadLocation(common.LoadTimeZone()) loc, _ := time.LoadLocation(common.LoadTimeZone())
expiredTime, err := time.ParseInLocation("2006-01-02 15:04:05", extime.Value, loc) expiredTime, err := time.ParseInLocation(constant.DateTimeLayout, extime.Value, loc)
if err != nil { if err != nil {
helper.ErrorWithDetail(c, constant.CodePasswordExpired, constant.ErrTypePasswordExpired, err) helper.ErrorWithDetail(c, constant.CodePasswordExpired, constant.ErrTypePasswordExpired, err)
return return

View file

@ -114,7 +114,7 @@ func (o oneDriveClient) Upload(src, target string) (bool, error) {
return false, err return false, err
} }
if fileInfo.IsDir() { if fileInfo.IsDir() {
return false, errors.New("Only file is allowed to be uploaded here.") return false, errors.New("only file is allowed to be uploaded here")
} }
var isOk bool var isOk bool
if fileInfo.Size() < 4*1024*1024 { if fileInfo.Size() < 4*1024*1024 {

View file

@ -26,7 +26,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("20060102150405"))) tmpFile := path.Join(global.CONF.System.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

@ -46,10 +46,10 @@ func WithWriter(writer io.Writer) DumpOption {
func Dump(dns string, opts ...DumpOption) error { func Dump(dns string, opts ...DumpOption) error {
start := time.Now() start := time.Now()
global.LOG.Infof("dump start at %s\n", start.Format("2006-01-02 15:04:05")) global.LOG.Infof("dump start at %s\n", start.Format(constant.DateTimeLayout))
defer func() { defer func() {
end := time.Now() end := time.Now()
global.LOG.Infof("dump end at %s, cost %s\n", end.Format("2006-01-02 15:04:05"), end.Sub(start)) global.LOG.Infof("dump end at %s, cost %s\n", end.Format(constant.DateTimeLayout), end.Sub(start))
}() }()
var err error var err error
@ -75,7 +75,7 @@ func Dump(dns string, opts ...DumpOption) error {
itemFile += "-- ----------------------------\n" itemFile += "-- ----------------------------\n"
itemFile += "-- MySQL Database Dump\n" itemFile += "-- MySQL Database Dump\n"
itemFile += "-- Start Time: " + start.Format("2006-01-02 15:04:05") + "\n" itemFile += "-- Start Time: " + start.Format(constant.DateTimeLayout) + "\n"
itemFile += "-- ----------------------------\n\n\n" itemFile += "-- ----------------------------\n\n\n"
db, err := sql.Open("mysql", dns) db, err := sql.Open("mysql", dns)
@ -252,14 +252,14 @@ func loadDataSql(row []interface{}, columnTypes []*sql.ColumnType, table string)
global.LOG.Errorf("the DATETIME type conversion failed, err value: %v", col) global.LOG.Errorf("the DATETIME type conversion failed, err value: %v", col)
return "" return ""
} }
ssql += fmt.Sprintf("'%s'", t.Format("2006-01-02 15:04:05")) ssql += fmt.Sprintf("'%s'", t.Format(constant.DateTimeLayout))
case "TIMESTAMP": case "TIMESTAMP":
t, ok := col.(time.Time) t, ok := col.(time.Time)
if !ok { if !ok {
global.LOG.Errorf("the TIMESTAMP type conversion failed, err value: %v", col) global.LOG.Errorf("the TIMESTAMP type conversion failed, err value: %v", col)
return "" return ""
} }
ssql += fmt.Sprintf("'%s'", t.Format("2006-01-02 15:04:05")) ssql += fmt.Sprintf("'%s'", t.Format(constant.DateTimeLayout))
case "TIME": case "TIME":
t, ok := col.([]byte) t, ok := col.([]byte)
if !ok { if !ok {

View file

@ -53,10 +53,10 @@ func (db *dbWrapper) Exec(query string, args ...interface{}) (sql.Result, error)
func Source(dns string, reader io.Reader, opts ...SourceOption) error { func Source(dns string, reader io.Reader, opts ...SourceOption) error {
start := time.Now() start := time.Now()
global.LOG.Infof("source start at %s", start.Format("2006-01-02 15:04:05")) global.LOG.Infof("source start at %s", start.Format(constant.DateTimeLayout))
defer func() { defer func() {
end := time.Now() end := time.Now()
global.LOG.Infof("source end at %s, cost %s", end.Format("2006-01-02 15:04:05"), end.Sub(start)) global.LOG.Infof("source end at %s, cost %s", end.Format(constant.DateTimeLayout), end.Sub(start))
}() }()
var err error var err error

View file

@ -246,7 +246,7 @@ func loadLogsByFiles(fileList []string, user, operation string) []FtpLog {
timeStr = strings.ReplaceAll(timeStr, "]", "") timeStr = strings.ReplaceAll(timeStr, "]", "")
timeItem, err := time.Parse(layout, timeStr) timeItem, err := time.Parse(layout, timeStr)
if err == nil { if err == nil {
timeStr = timeItem.Format("2006-01-02 15:04:05") timeStr = timeItem.Format(constant.DateTimeLayout)
} }
operateStr := parts[5] + parts[6] operateStr := parts[5] + parts[6]
logs = append(logs, FtpLog{ logs = append(logs, FtpLog{