Skip to content

Commit 154fc83

Browse files
committed
feat: 统一备份文件大小获取接口
1 parent 86e7716 commit 154fc83

File tree

22 files changed

+255
-180
lines changed

22 files changed

+255
-180
lines changed

agent/app/api/v2/backup.go

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -205,6 +205,29 @@ func (b *BaseApi) GetLocalDir(c *gin.Context) {
205205
helper.SuccessWithData(c, dir)
206206
}
207207

208+
// @Tags Backup Account
209+
// @Summary Page backup records
210+
// @Description 获取备份记录列表分页
211+
// @Accept json
212+
// @Param request body dto.SearchForSize true "request"
213+
// @Success 200 {object} dto.RecordFileSize
214+
// @Security ApiKeyAuth
215+
// @Router /backups/record/size [post]
216+
func (b *BaseApi) LoadBackupRecordSize(c *gin.Context) {
217+
var req dto.SearchForSize
218+
if err := helper.CheckBindAndValidate(&req, c); err != nil {
219+
return
220+
}
221+
222+
list, err := backupRecordService.LoadRecordSize(req)
223+
if err != nil {
224+
helper.InternalServer(c, err)
225+
return
226+
}
227+
228+
helper.SuccessWithData(c, list)
229+
}
230+
208231
// @Tags Backup Account
209232
// @Summary Page backup records
210233
// @Description 获取备份记录列表分页

agent/app/api/v2/snapshot.go

Lines changed: 0 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -134,28 +134,6 @@ func (b *BaseApi) SearchSnapshot(c *gin.Context) {
134134
})
135135
}
136136

137-
// @Tags System Setting
138-
// @Summary Load system snapshot size
139-
// @Description 获取系统快照文件大小
140-
// @Accept json
141-
// @Param request body dto.SearchWithPage true "request"
142-
// @Success 200
143-
// @Security ApiKeyAuth
144-
// @Router /settings/snapshot/size [post]
145-
func (b *BaseApi) LoadSnapshotSize(c *gin.Context) {
146-
var req dto.SearchWithPage
147-
if err := helper.CheckBindAndValidate(&req, c); err != nil {
148-
return
149-
}
150-
151-
accounts, err := snapshotService.LoadSize(req)
152-
if err != nil {
153-
helper.InternalServer(c, err)
154-
return
155-
}
156-
helper.SuccessWithData(c, accounts)
157-
}
158-
159137
// @Tags System Setting
160138
// @Summary Recover system backup
161139
// @Description 从系统快照恢复

agent/app/dto/backup.go

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -92,11 +92,24 @@ type BackupRecords struct {
9292
DownloadAccountID uint `json:"downloadAccountID"`
9393
FileDir string `json:"fileDir"`
9494
FileName string `json:"fileName"`
95-
Size int64 `json:"size"`
9695
}
9796

9897
type DownloadRecord struct {
9998
DownloadAccountID uint `json:"downloadAccountID" validate:"required"`
10099
FileDir string `json:"fileDir" validate:"required"`
101100
FileName string `json:"fileName" validate:"required"`
102101
}
102+
103+
type SearchForSize struct {
104+
PageInfo
105+
Type string `json:"type" validate:"required"`
106+
Name string `json:"name"`
107+
DetailName string `json:"detailName"`
108+
Info string `json:"info"`
109+
CronjobID uint `json:"cronjobID"`
110+
}
111+
type RecordFileSize struct {
112+
ID uint `json:"id"`
113+
Name string `json:"name"`
114+
Size int64 `json:"size"`
115+
}

agent/app/dto/cronjob.go

Lines changed: 11 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -106,17 +106,17 @@ type CronjobInfo struct {
106106
ContainerName string `json:"containerName"`
107107
User string `json:"user"`
108108

109-
AppID string `json:"appID"`
110-
Website string `json:"website"`
111-
ExclusionRules string `json:"exclusionRules"`
112-
DBType string `json:"dbType"`
113-
DBName string `json:"dbName"`
114-
URL string `json:"url"`
115-
IsDir bool `json:"isDir"`
116-
SourceDir string `json:"sourceDir"`
117-
SourceAccountIDs string `json:"sourceAccountIDs"`
118-
DownloadAccountID uint `json:"downloadAccountID"`
119-
RetainCopies int `json:"retainCopies"`
109+
AppID string `json:"appID"`
110+
Website string `json:"website"`
111+
ExclusionRules string `json:"exclusionRules"`
112+
DBType string `json:"dbType"`
113+
DBName string `json:"dbName"`
114+
URL string `json:"url"`
115+
IsDir bool `json:"isDir"`
116+
SourceDir string `json:"sourceDir"`
117+
SourceAccounts []string `json:"sourceAccounts"`
118+
DownloadAccount string `json:"downloadAccount"`
119+
RetainCopies int `json:"retainCopies"`
120120

121121
LastRecordStatus string `json:"lastRecordStatus"`
122122
LastRecordTime string `json:"lastRecordTime"`

agent/app/dto/snapshot.go

Lines changed: 2 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -88,8 +88,8 @@ type SnapshotInfo struct {
8888
ID uint `json:"id"`
8989
Name string `json:"name"`
9090
Description string `json:"description" validate:"max=256"`
91-
From string `json:"from"`
92-
DefaultDownload string `json:"defaultDownload"`
91+
SourceAccounts []string `json:"sourceAccounts"`
92+
DownloadAccount string `json:"downloadAccount"`
9393
Status string `json:"status"`
9494
Message string `json:"message"`
9595
CreatedAt time.Time `json:"createdAt"`
@@ -108,11 +108,3 @@ type SnapshotInfo struct {
108108
RollbackMessage string `json:"rollbackMessage"`
109109
LastRollbackedAt string `json:"lastRollbackedAt"`
110110
}
111-
112-
type SnapshotFile struct {
113-
ID uint `json:"id"`
114-
Name string `json:"name"`
115-
From string `json:"from"`
116-
DefaultDownload string `json:"defaultDownload"`
117-
Size int64 `json:"size"`
118-
}

agent/app/service/backup.go

Lines changed: 35 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -88,6 +88,9 @@ func (u *BackupService) SearchWithPage(req dto.SearchPageWithType) (int64, inter
8888
if err := copier.Copy(&item, &account); err != nil {
8989
global.LOG.Errorf("copy backup account to dto backup info failed, err: %v", err)
9090
}
91+
if item.Type != constant.Sftp && item.Type != constant.Local {
92+
item.BackupPath = path.Join("/", strings.TrimPrefix(item.BackupPath, "/"))
93+
}
9194
if !item.RememberAuth {
9295
item.AccessKey = ""
9396
item.Credential = ""
@@ -124,6 +127,9 @@ func (u *BackupService) Create(req dto.BackupOperate) error {
124127
if req.Type == constant.Local {
125128
return buserr.New(constant.ErrBackupLocalCreate)
126129
}
130+
if req.Type != constant.Sftp && req.BackupPath != "/" {
131+
req.BackupPath = strings.TrimPrefix(req.BackupPath, "/")
132+
}
127133
backup, _ := backupRepo.Get(repo.WithByName(req.Name))
128134
if backup.ID != 0 {
129135
return constant.ErrRecordExist
@@ -215,6 +221,9 @@ func (u *BackupService) Update(req dto.BackupOperate) error {
215221
if backup.ID == 0 {
216222
return constant.ErrRecordNotFound
217223
}
224+
if req.Type != constant.Sftp && req.Type != constant.Local && req.BackupPath != "/" {
225+
req.BackupPath = strings.TrimPrefix(req.BackupPath, "/")
226+
}
218227
var newBackup model.BackupAccount
219228
if err := copier.Copy(&newBackup, &req); err != nil {
220229
return errors.WithMessage(constant.ErrStructTransform, err.Error())
@@ -428,14 +437,10 @@ func NewBackupClientMap(ids []string) (map[string]backupClientHelper, error) {
428437
if err != nil {
429438
return nil, err
430439
}
431-
pathItem := item.BackupPath
432-
if item.Type != constant.Sftp && item.Type != constant.Local && pathItem != "/" {
433-
pathItem = strings.TrimPrefix(item.BackupPath, "/")
434-
}
435440
clientMap[fmt.Sprintf("%v", item.ID)] = backupClientHelper{
436441
client: backClient,
437442
name: item.Name,
438-
backupPath: pathItem,
443+
backupPath: item.BackupPath,
439444
accountType: item.Type,
440445
id: item.ID,
441446
}
@@ -502,3 +507,28 @@ func loadRefreshTokenByCode(backup *model.BackupAccount) error {
502507
backup.Vars = string(itemVars)
503508
return nil
504509
}
510+
511+
func loadBackupNamesByID(accountIDs string, downloadID uint) ([]string, string, error) {
512+
accountIDList := strings.Split(accountIDs, ",")
513+
var ids []uint
514+
for _, item := range accountIDList {
515+
if len(item) != 0 {
516+
itemID, _ := strconv.Atoi(item)
517+
ids = append(ids, uint(itemID))
518+
}
519+
}
520+
list, err := backupRepo.List(repo.WithByIDs(ids))
521+
if err != nil {
522+
return nil, "", err
523+
}
524+
var accounts []string
525+
var downloadAccount string
526+
for _, item := range list {
527+
itemName := fmt.Sprintf("%s - %s", item.Type, item.Name)
528+
accounts = append(accounts, itemName)
529+
if item.ID == downloadID {
530+
downloadAccount = itemName
531+
}
532+
}
533+
return accounts, downloadAccount, nil
534+
}

agent/app/service/backup_record.go

Lines changed: 67 additions & 46 deletions
Original file line numberDiff line numberDiff line change
@@ -5,18 +5,14 @@ import (
55
"fmt"
66
"os"
77
"path"
8-
"sort"
9-
"strings"
108
"sync"
119

1210
"github.com/1Panel-dev/1Panel/agent/app/dto"
1311
"github.com/1Panel-dev/1Panel/agent/app/model"
1412
"github.com/1Panel-dev/1Panel/agent/app/repo"
1513
"github.com/1Panel-dev/1Panel/agent/constant"
1614
"github.com/1Panel-dev/1Panel/agent/global"
17-
"github.com/1Panel-dev/1Panel/agent/utils/cloud_storage"
1815
"github.com/jinzhu/copier"
19-
"github.com/pkg/errors"
2016
)
2117

2218
type BackupRecordService struct{}
@@ -30,6 +26,7 @@ type IBackupRecordService interface {
3026
ListAppRecords(name, detailName, fileName string) ([]model.BackupRecord, error)
3127

3228
ListFiles(req dto.OperateByID) []string
29+
LoadRecordSize(req dto.SearchForSize) ([]dto.RecordFileSize, error)
3330
}
3431

3532
func NewIBackupRecordService() IBackupRecordService {
@@ -47,15 +44,15 @@ func (u *BackupRecordService) SearchRecordsWithPage(search dto.RecordSearch) (in
4744
if err != nil {
4845
return 0, nil, err
4946
}
50-
51-
if total == 0 {
52-
return 0, nil, nil
47+
var data []dto.BackupRecords
48+
for _, account := range records {
49+
var item dto.BackupRecords
50+
if err := copier.Copy(&item, &account); err != nil {
51+
global.LOG.Errorf("copy backup account to dto backup info failed, err: %v", err)
52+
}
53+
data = append(data, item)
5354
}
54-
datas, err := u.loadRecordSize(records)
55-
sort.Slice(datas, func(i, j int) bool {
56-
return datas[i].CreatedAt.After(datas[j].CreatedAt)
57-
})
58-
return total, datas, err
55+
return total, data, err
5956
}
6057

6158
func (u *BackupRecordService) SearchRecordsByCronjobWithPage(search dto.RecordSearchByCronjob) (int64, []dto.BackupRecords, error) {
@@ -67,15 +64,15 @@ func (u *BackupRecordService) SearchRecordsByCronjobWithPage(search dto.RecordSe
6764
if err != nil {
6865
return 0, nil, err
6966
}
70-
71-
if total == 0 {
72-
return 0, nil, nil
67+
var data []dto.BackupRecords
68+
for _, account := range records {
69+
var item dto.BackupRecords
70+
if err := copier.Copy(&item, &account); err != nil {
71+
global.LOG.Errorf("copy backup account to dto backup info failed, err: %v", err)
72+
}
73+
data = append(data, item)
7374
}
74-
datas, err := u.loadRecordSize(records)
75-
sort.Slice(datas, func(i, j int) bool {
76-
return datas[i].CreatedAt.After(datas[j].CreatedAt)
77-
})
78-
return total, datas, err
75+
return total, data, err
7976
}
8077

8178
func (u *BackupRecordService) DownloadRecord(info dto.DownloadRecord) (string, error) {
@@ -94,7 +91,7 @@ func (u *BackupRecordService) DownloadRecord(info dto.DownloadRecord) (string, e
9491
}
9592
srcPath := fmt.Sprintf("%s/%s", info.FileDir, info.FileName)
9693
if len(account.BackupPath) != 0 {
97-
srcPath = path.Join(strings.TrimPrefix(account.BackupPath, "/"), srcPath)
94+
srcPath = path.Join(account.BackupPath, srcPath)
9895
}
9996
if exist, _ := client.Exist(srcPath); exist {
10097
isOK, err := client.Download(srcPath, targetPath)
@@ -181,36 +178,67 @@ func (u *BackupRecordService) ListFiles(req dto.OperateByID) []string {
181178
return datas
182179
}
183180

184-
func (u *BackupRecordService) loadRecordSize(records []model.BackupRecord) ([]dto.BackupRecords, error) {
181+
type backupSizeHelper struct {
182+
ID uint `json:"id"`
183+
DownloadID uint `json:"downloadID"`
184+
FilePath string `json:"filePath"`
185+
Size uint `json:"size"`
186+
}
187+
188+
func (u *BackupRecordService) LoadRecordSize(req dto.SearchForSize) ([]dto.RecordFileSize, error) {
189+
var list []backupSizeHelper
190+
switch req.Type {
191+
case "snapshot":
192+
_, records, err := snapshotRepo.Page(req.Page, req.PageSize, repo.WithByLikeName(req.Info))
193+
if err != nil {
194+
return nil, err
195+
}
196+
for _, item := range records {
197+
list = append(list, backupSizeHelper{ID: item.ID, DownloadID: item.DownloadAccountID, FilePath: fmt.Sprintf("system_snapshot/%s.tar.gz", item.Name)})
198+
}
199+
case "cronjob":
200+
_, records, err := backupRepo.PageRecord(req.Page, req.PageSize, backupRepo.WithByCronID(req.CronjobID))
201+
if err != nil {
202+
return nil, err
203+
}
204+
for _, item := range records {
205+
list = append(list, backupSizeHelper{ID: item.ID, DownloadID: item.DownloadAccountID, FilePath: path.Join(item.FileDir, item.FileName)})
206+
}
207+
default:
208+
_, records, err := backupRepo.PageRecord(
209+
req.Page, req.PageSize,
210+
repo.WithByName(req.Name),
211+
repo.WithByType(req.Type),
212+
repo.WithByDetailName(req.DetailName),
213+
)
214+
if err != nil {
215+
return nil, err
216+
}
217+
for _, item := range records {
218+
list = append(list, backupSizeHelper{ID: item.ID, DownloadID: item.DownloadAccountID, FilePath: path.Join(item.FileDir, item.FileName)})
219+
}
220+
}
185221
recordMap := make(map[uint]struct{})
186222
var recordIds []string
187-
for _, record := range records {
188-
if _, ok := recordMap[record.DownloadAccountID]; !ok {
189-
recordMap[record.DownloadAccountID] = struct{}{}
190-
recordIds = append(recordIds, fmt.Sprintf("%v", record.DownloadAccountID))
223+
for _, record := range list {
224+
if _, ok := recordMap[record.DownloadID]; !ok {
225+
recordMap[record.DownloadID] = struct{}{}
226+
recordIds = append(recordIds, fmt.Sprintf("%v", record.DownloadID))
191227
}
192228
}
193229
clientMap, err := NewBackupClientMap(recordIds)
194230
if err != nil {
195231
return nil, err
196232
}
197233

198-
var datas []dto.BackupRecords
234+
var datas []dto.RecordFileSize
199235
var wg sync.WaitGroup
200-
for i := 0; i < len(records); i++ {
201-
var item dto.BackupRecords
202-
if err := copier.Copy(&item, &records[i]); err != nil {
203-
return nil, errors.WithMessage(constant.ErrStructTransform, err.Error())
204-
}
205-
206-
itemPath := path.Join(records[i].FileDir, records[i].FileName)
207-
if val, ok := clientMap[fmt.Sprintf("%v", records[i].DownloadAccountID)]; ok {
208-
item.AccountName = val.name
209-
item.AccountType = val.accountType
210-
item.DownloadAccountID = val.id
236+
for i := 0; i < len(list); i++ {
237+
item := dto.RecordFileSize{ID: list[i].ID}
238+
if val, ok := clientMap[fmt.Sprintf("%v", list[i].DownloadID)]; ok {
211239
wg.Add(1)
212240
go func(index int) {
213-
item.Size, _ = val.client.Size(path.Join(strings.TrimLeft(val.backupPath, "/"), itemPath))
241+
item.Size, _ = val.client.Size(path.Join(val.backupPath, list[i].FilePath))
214242
datas = append(datas, item)
215243
wg.Done()
216244
}(i)
@@ -221,10 +249,3 @@ func (u *BackupRecordService) loadRecordSize(records []model.BackupRecord) ([]dt
221249
wg.Wait()
222250
return datas, nil
223251
}
224-
225-
type loadSizeHelper struct {
226-
isOk bool
227-
backupName string
228-
backupPath string
229-
client cloud_storage.CloudStorageClient
230-
}

0 commit comments

Comments
 (0)