memos/server/service/backup.go

60 lines
1.4 KiB
Go
Raw Normal View History

package service
import (
"context"
"fmt"
"strconv"
"time"
2023-09-17 17:55:13 +03:00
"go.uber.org/zap"
apiv1 "github.com/usememos/memos/api/v1"
"github.com/usememos/memos/common/log"
"github.com/usememos/memos/store"
)
2023-07-30 04:53:24 +03:00
type BackupRunner struct {
Store *store.Store
}
func NewBackupRunner(store *store.Store) *BackupRunner {
return &BackupRunner{
Store: store,
}
}
func (r *BackupRunner) Run(ctx context.Context) {
intervalStr := r.Store.GetSystemSettingValueWithDefault(&ctx, apiv1.SystemSettingAutoBackupIntervalName.String(), "")
if intervalStr == "" {
log.Debug("no SystemSettingAutoBackupIntervalName setting, disable auto backup")
return
}
interval, err := strconv.Atoi(intervalStr)
if err != nil || interval <= 0 {
log.Error(fmt.Sprintf("invalid SystemSettingAutoBackupIntervalName value %s, disable auto backup", intervalStr), zap.Error(err))
return
}
log.Info("enable auto backup every " + intervalStr + " seconds")
ticker := time.NewTicker(time.Duration(interval) * time.Second)
defer ticker.Stop()
var t time.Time
for {
select {
case <-ctx.Done():
log.Info("stop auto backup graceful.")
return
case t = <-ticker.C:
}
2023-07-30 04:53:24 +03:00
filename := r.Store.Profile.DSN + t.Format("-20060102-150405.bak")
log.Info(fmt.Sprintf("create backup to %s", filename))
2023-07-30 04:53:24 +03:00
err := r.Store.BackupTo(ctx, filename)
if err != nil {
log.Error("fail to create backup", zap.Error(err))
}
}
}