Skip to content

Commit

Permalink
Add state snapshot export functionality (cosmos#1)
Browse files Browse the repository at this point in the history
  • Loading branch information
brendan-kelly authored and patrycjazawadka committed Mar 4, 2023
1 parent 47f4664 commit 998c021
Showing 1 changed file with 53 additions and 0 deletions.
53 changes: 53 additions & 0 deletions baseapp/abci.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,9 @@ import (
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"sort"
"strings"
"syscall"
Expand Down Expand Up @@ -401,6 +403,57 @@ func (app *BaseApp) snapshot(height int64) {

app.logger.Debug("pruned state snapshots", "pruned", pruned)
}

if os.Getenv("SNAPSHOT_EXPORT_ENABLED") == "1" {
app.logger.Info("exporting state snapshot", "height", height)
if err := app.ExportSnapshot(snapshot); err != nil {
app.logger.Error("failed to export snapshot", "height", height, "err", err)
}
}
}

func (app *BaseApp) ExportSnapshot(snapshot *snapshottypes.Snapshot) error {
snapshotsDir := os.Getenv("SNAPSHOT_EXPORT_DIR")
if snapshotsDir == "" {
return errors.New("SNAPSHOT_EXPORT_DIR env var is not set, not exporting the snapshot")
}

baseDir := fmt.Sprintf("%s/%d", snapshotsDir, snapshot.Height)
snapshotPath := fmt.Sprintf("%s/snapshot", baseDir)
chunkPath := filepath.Join(baseDir, "%d.chunk")

if err := os.MkdirAll(baseDir, 0755); err != nil {
return err
}

abciSnap, err := snapshot.ToABCI()
if err != nil {
return err
}

data, err := abciSnap.Marshal()
if err != nil {
return err
}

if err := ioutil.WriteFile(snapshotPath, data, 0666); err != nil {
return err
}

for i := uint32(0); i < snapshot.Chunks; i++ {
app.logger.Info("exporting snapshot chunk", "height", snapshot.Height, "chunk", i)

chunkData, err := app.snapshotManager.LoadChunk(snapshot.Height, snapshot.Format, i)
if err != nil {
return err
}

if err := ioutil.WriteFile(fmt.Sprintf(chunkPath, i), chunkData, 0666); err != nil {
return err
}
}

return nil
}

// Query implements the ABCI interface. It delegates to CommitMultiStore if it
Expand Down

0 comments on commit 998c021

Please sign in to comment.