memos/server/service/backup.go
boojack 18fb02a1ec
chore: update swag docs (#2178)
* chore: update swag docs

* chore: update
2023-08-26 08:07:43 +08:00

59 lines
1.4 KiB
Go

package service
import (
"context"
"fmt"
"strconv"
"time"
apiv1 "github.com/usememos/memos/api/v1"
"github.com/usememos/memos/common/log"
"github.com/usememos/memos/store"
"go.uber.org/zap"
)
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:
}
filename := r.Store.Profile.DSN + t.Format("-20060102-150405.bak")
log.Info(fmt.Sprintf("create backup to %s", filename))
err := r.Store.BackupTo(ctx, filename)
if err != nil {
log.Error("fail to create backup", zap.Error(err))
}
}
}