feat(server): provide native backup/restore mechanism (#3194)

* [enhancement]: Provide native backup/restore mechanism

- db.go: add Backup/Restore functions that utilize Sqlite's built-in online backup mechanism
- support automatic backup with schedule, limit number of files
- provide commands to manually backup/restore Navidrome

Notes:
`Step(-1)` results in a read-only lock being held for the entire duration of the backup.
This will block out any other write operation (and may hold additional locks.
An alternate implementation that doesn't block but instead retries is available at https://www.sqlite.org/backup.html#:~:text=of%20a%20Running-,database,-%2F*%0A**%20Perform%20an%20online (easily adaptable to go), but has the potential problem of continually getting restarted by background writes.

Additionally, the restore should still only be called when Navidrome is offline, as the restore process does not run migrations that are missing.

* remove empty line

* add more granular backup schedule

* do not remove files when bypass is set

* move prune

* refactor: small nitpicks

* change commands and flags

* tests, return path from backup

* refactor: small nitpicks

---------

Co-authored-by: Deluan <deluan@navidrome.org>
This commit is contained in:
Kendall Garner
2024-10-01 23:58:54 +00:00
committed by GitHub
parent 768160b05e
commit 55730514ea
6 changed files with 602 additions and 5 deletions
+24
View File
@@ -1,10 +1,12 @@
package db
import (
"context"
"database/sql"
"embed"
"fmt"
"runtime"
"time"
"github.com/mattn/go-sqlite3"
"github.com/navidrome/navidrome/conf"
@@ -29,6 +31,10 @@ type DB interface {
ReadDB() *sql.DB
WriteDB() *sql.DB
Close()
Backup(ctx context.Context) (string, error)
Prune(ctx context.Context) (int, error)
Restore(ctx context.Context, path string) error
}
type db struct {
@@ -53,6 +59,24 @@ func (d *db) Close() {
}
}
func (d *db) Backup(ctx context.Context) (string, error) {
destPath := backupPath(time.Now())
err := d.backupOrRestore(ctx, true, destPath)
if err != nil {
return "", err
}
return destPath, nil
}
func (d *db) Prune(ctx context.Context) (int, error) {
return prune(ctx)
}
func (d *db) Restore(ctx context.Context, path string) error {
return d.backupOrRestore(ctx, false, path)
}
func Db() DB {
return singleton.GetInstance(func() *db {
sql.Register(Driver+"_custom", &sqlite3.SQLiteDriver{