2023-08-26 03:07:43 +03:00
|
|
|
package service
|
2023-07-14 15:05:07 +03:00
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"fmt"
|
|
|
|
"strconv"
|
|
|
|
"time"
|
|
|
|
|
2023-09-17 17:55:13 +03:00
|
|
|
"go.uber.org/zap"
|
|
|
|
|
2023-07-14 15:05:07 +03:00
|
|
|
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(), "")
|
2023-07-14 15:05:07 +03:00
|
|
|
if intervalStr == "" {
|
2023-08-20 21:09:41 +03:00
|
|
|
log.Debug("no SystemSettingAutoBackupIntervalName setting, disable auto backup")
|
2023-07-14 15:05:07 +03:00
|
|
|
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")
|
2023-07-14 15:05:07 +03:00
|
|
|
log.Info(fmt.Sprintf("create backup to %s", filename))
|
2023-07-30 04:53:24 +03:00
|
|
|
err := r.Store.BackupTo(ctx, filename)
|
2023-07-14 15:05:07 +03:00
|
|
|
if err != nil {
|
|
|
|
log.Error("fail to create backup", zap.Error(err))
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|