push backup

This commit is contained in:
2025-07-30 15:14:01 +02:00
parent c6edb91f29
commit 30b76e1887
11 changed files with 290 additions and 148 deletions

View File

@@ -37,11 +37,7 @@ func (p *RunCmd) Execute(_ context.Context, f *flag.FlagSet, _ ...interface{}) s
return subcommands.ExitFailure
}
pg := progressbar.New(len(datastore))
defer pg.Close()
for _, metadata := range datastore {
pg.Describe("Scanning " + metadata.Name + "...")
metadataPath := filepath.Join(repository.DatastorePath(), metadata.ID)
//todo transaction
err := archiveIfChanged(metadata.ID, metadata.Path, filepath.Join(metadataPath, "data.tar.gz"), filepath.Join(metadataPath, ".last_run"))
@@ -57,11 +53,8 @@ func (p *RunCmd) Execute(_ context.Context, f *flag.FlagSet, _ ...interface{}) s
fmt.Fprintf(os.Stderr, "error: cannot process the data of %s: %s\n", metadata.ID, err)
return subcommands.ExitFailure
}
pg.Add(1)
}
pg.Finish()
return subcommands.ExitSuccess
}
@@ -69,6 +62,11 @@ func (p *RunCmd) Execute(_ context.Context, f *flag.FlagSet, _ ...interface{}) s
// in srcDir has a modification time > the last run time stored in stateFile.
// After archiving, it updates stateFile to the current time.
func archiveIfChanged(gameID, srcDir, destTarGz, stateFile string) error {
pg := progressbar.New(-1)
defer pg.Close()
pg.Describe("Scanning " + gameID + "...")
// load last run time
var lastRun time.Time
data, err := os.ReadFile(stateFile)
@@ -99,15 +97,18 @@ func archiveIfChanged(gameID, srcDir, destTarGz, stateFile string) error {
}
if !changed {
pg.Finish()
return nil
}
// make a backup
pg.Describe("Backup current data...")
if err := repository.Archive(gameID); err != nil {
return fmt.Errorf("failed to archive data: %w", err)
}
// create archive
pg.Describe("Archiving new data...")
f, err := os.Create(destTarGz)
if err != nil {
return fmt.Errorf("failed to creating archive file: %w", err)

View File

@@ -65,10 +65,13 @@ func (p *SyncCmd) Execute(_ context.Context, f *flag.FlagSet, _ ...interface{})
}
if !exists {
if err := push(r.GameID, g, cli); err != nil {
if err := push(g, cli); err != nil {
fmt.Fprintln(os.Stderr, "failed to push:", err)
return subcommands.ExitFailure
}
if err := pushBackup(g, cli); err != nil {
slog.Warn("failed to push backup files", "err", err)
}
continue
}
@@ -96,6 +99,10 @@ func (p *SyncCmd) Execute(_ context.Context, f *flag.FlagSet, _ ...interface{})
continue
}
if err := pushBackup(g, cli); err != nil {
slog.Warn("failed to push backup files", "err", err)
}
if hlocal == hremote {
if vlocal != remoteMetadata.Version {
slog.Debug("version is not the same, but the hash is equal. Updating local database")
@@ -109,7 +116,7 @@ func (p *SyncCmd) Execute(_ context.Context, f *flag.FlagSet, _ ...interface{})
}
if vlocal > remoteMetadata.Version {
if err := push(r.GameID, g, cli); err != nil {
if err := push(g, cli); err != nil {
fmt.Fprintln(os.Stderr, "failed to push:", err)
return subcommands.ExitFailure
}
@@ -164,7 +171,7 @@ func conflict(gameID string, m, remoteMetadata repository.Metadata, cli *client.
switch res {
case prompt.My:
{
if err := push(gameID, m, cli); err != nil {
if err := push(m, cli); err != nil {
return fmt.Errorf("failed to push: %w", err)
}
}
@@ -185,10 +192,34 @@ func conflict(gameID string, m, remoteMetadata repository.Metadata, cli *client.
return nil
}
func push(gameID string, m repository.Metadata, cli *client.Client) error {
archivePath := filepath.Join(repository.DatastorePath(), gameID, "data.tar.gz")
func push(m repository.Metadata, cli *client.Client) error {
archivePath := filepath.Join(repository.DatastorePath(), m.ID, "data.tar.gz")
return cli.Push(gameID, archivePath, m)
return cli.PushSave(archivePath, m)
}
func pushBackup(m repository.Metadata, cli *client.Client) error {
bs, err := repository.Archives(m.ID)
if err != nil {
return err
}
for _, b := range bs {
binfo, err := cli.ArchiveInfo(m.ID, b.UUID)
if err != nil {
if !errors.Is(err, client.ErrNotFound) {
return fmt.Errorf("failed to get remote information about the backup file: %w", err)
}
}
if binfo.MD5 != b.MD5 {
if err := cli.PushBackup(b, m); err != nil {
return fmt.Errorf("failed to push backup: %w", err)
}
}
}
return nil
}
func pull(gameID string, cli *client.Client) error {

View File

@@ -61,7 +61,8 @@ func NewServer(documentRoot string, creds map[string]string, port int) *HTTPServ
// Data routes
gamesRouter.Group(func(saveRouter chi.Router) {
saveRouter.Post("/{id}/data", s.upload)
saveRouter.Post("/{id}/hist/data", s.histUpload)
saveRouter.Post("/{id}/hist/{uuid}/data", s.histUpload)
saveRouter.Get("/{id}/hist/{uuid}/info", s.histExists)
saveRouter.Get("/{id}/data", s.download)
saveRouter.Get("/{id}/hash", s.hash)
saveRouter.Get("/{id}/metadata", s.metadata)
@@ -215,19 +216,14 @@ func (s HTTPServer) histUpload(w http.ResponseWriter, r *http.Request) {
sizeLimit int64 = 500 << 20 // 500 MB
)
id := chi.URLParam(r, "id")
dt, err := formParseDate("date", r.MultipartForm.Value)
if err != nil {
fmt.Fprintln(os.Stderr, "error: failed to load payload:", err)
badRequest("bad payload", w, r)
return
}
gameID := chi.URLParam(r, "id")
uuid := chi.URLParam(r, "uuid")
// Limit max upload size
r.Body = http.MaxBytesReader(w, r.Body, sizeLimit)
// Parse multipart form
err = r.ParseMultipartForm(sizeLimit)
err := r.ParseMultipartForm(sizeLimit)
if err != nil {
fmt.Fprintln(os.Stderr, "error: failed to load payload:", err)
badRequest("bad payload", w, r)
@@ -243,7 +239,7 @@ func (s HTTPServer) histUpload(w http.ResponseWriter, r *http.Request) {
}
defer file.Close()
if err := data.WriteHist(id, s.documentRoot, dt, file); err != nil {
if err := data.WriteHist(gameID, s.documentRoot, uuid, file); err != nil {
fmt.Fprintln(os.Stderr, "error: failed to write file to disk:", err)
internalServerError(w, r)
return
@@ -253,6 +249,24 @@ func (s HTTPServer) histUpload(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusCreated)
}
func (s HTTPServer) histExists(w http.ResponseWriter, r *http.Request) {
gameID := chi.URLParam(r, "id")
uuid := chi.URLParam(r, "uuid")
finfo, err := data.ArchiveInfo(gameID, s.documentRoot, uuid)
if err != nil {
if errors.Is(err, data.ErrBackupNotExists) {
notFound("backup not found", w, r)
return
}
fmt.Fprintln(os.Stderr, "error: failed to read data:", err)
internalServerError(w, r)
return
}
ok(finfo, w, r)
}
func (s HTTPServer) hash(w http.ResponseWriter, r *http.Request) {
id := chi.URLParam(r, "id")
path := filepath.Clean(filepath.Join(s.documentRoot, "data", id))
@@ -374,21 +388,3 @@ func parseFormMetadata(gameID string, values map[string][]string) (repository.Me
Date: date,
}, nil
}
func formParseDate(key string, values map[string][]string) (time.Time, error) {
var date time.Time
if v, ok := values[key]; ok {
if len(v) == 0 {
return time.Time{}, fmt.Errorf("error: corrupted metadata")
}
if v, err := time.Parse(time.RFC3339, v[0]); err == nil {
date = v
} else {
return time.Time{}, err
}
} else {
return time.Time{}, fmt.Errorf("error: cannot find metadata in the form")
}
return date, nil
}

View File

@@ -2,12 +2,17 @@ package data
import (
"cloudsave/pkg/repository"
"cloudsave/pkg/tools/hash"
"encoding/json"
"errors"
"fmt"
"io"
"os"
"path/filepath"
"time"
)
var (
ErrBackupNotExists error = errors.New("backup not found")
)
func Write(gameID, documentRoot string, r io.Reader) error {
@@ -40,15 +45,19 @@ func Write(gameID, documentRoot string, r io.Reader) error {
return nil
}
func WriteHist(gameID, documentRoot string, dt time.Time, r io.Reader) error {
dataFolderPath := filepath.Join(documentRoot, "data", gameID, "hist")
partPath := filepath.Join(dataFolderPath, dt.Format("2006-01-02T15-04-05Z07-00")+".data.tar.gz.part")
finalFilePath := filepath.Join(dataFolderPath, dt.Format("2006-01-02T15-04-05Z07-00")+".data.tar.gz")
func WriteHist(gameID, documentRoot, uuid string, r io.Reader) error {
dataFolderPath := filepath.Join(documentRoot, "data", gameID, "hist", uuid)
partPath := filepath.Join(dataFolderPath, "data.tar.gz.part")
finalFilePath := filepath.Join(dataFolderPath, "data.tar.gz")
if err := makeDataFolder(gameID, documentRoot); err != nil {
return err
}
if err := os.MkdirAll(dataFolderPath, 0740); err != nil {
return err
}
f, err := os.OpenFile(partPath, os.O_CREATE|os.O_WRONLY, 0740)
if err != nil {
return err
@@ -86,6 +95,29 @@ func UpdateMetadata(gameID, documentRoot string, m repository.Metadata) error {
return e.Encode(m)
}
func ArchiveInfo(gameID, documentRoot, uuid string) (repository.Backup, error) {
dataFolderPath := filepath.Join(documentRoot, "data", gameID, "hist", uuid, "data.tar.gz")
finfo, err := os.Stat(dataFolderPath)
if err != nil {
if errors.Is(err, os.ErrNotExist) {
return repository.Backup{}, ErrBackupNotExists
}
return repository.Backup{}, err
}
h, err := hash.FileMD5(dataFolderPath)
if err != nil {
return repository.Backup{}, fmt.Errorf("failed to calculate file md5: %w", err)
}
return repository.Backup{
CreatedAt: finfo.ModTime(),
UUID: uuid,
MD5: h,
}, nil
}
func makeDataFolder(gameID, documentRoot string) error {
if err := os.MkdirAll(filepath.Join(documentRoot, "data", gameID), 0740); err != nil {
return err