Compare commits
2 Commits
v0.4.0-alp
...
v0.3.7
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
393317b6f8 | ||
|
|
1e6878998c |
@@ -102,7 +102,7 @@ func (c *ReplicaClient) Generations(ctx context.Context) ([]string, error) {
|
||||
internal.OperationTotalCounterVec.WithLabelValues(ReplicaClientType, "LIST").Inc()
|
||||
|
||||
resp, err := c.containerURL.ListBlobsHierarchySegment(ctx, marker, "/", azblob.ListBlobsSegmentOptions{
|
||||
Prefix: path.Join(c.Path, "generations") + "/",
|
||||
Prefix: litestream.GenerationsPath(c.Path) + "/",
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@@ -125,17 +125,18 @@ func (c *ReplicaClient) Generations(ctx context.Context) ([]string, error) {
|
||||
func (c *ReplicaClient) DeleteGeneration(ctx context.Context, generation string) error {
|
||||
if err := c.Init(ctx); err != nil {
|
||||
return err
|
||||
} else if generation == "" {
|
||||
return fmt.Errorf("generation required")
|
||||
}
|
||||
|
||||
prefix := path.Join(c.Path, "generations", generation) + "/"
|
||||
dir, err := litestream.GenerationPath(c.Path, generation)
|
||||
if err != nil {
|
||||
return fmt.Errorf("cannot determine generation path: %w", err)
|
||||
}
|
||||
|
||||
var marker azblob.Marker
|
||||
for marker.NotDone() {
|
||||
internal.OperationTotalCounterVec.WithLabelValues(ReplicaClientType, "LIST").Inc()
|
||||
|
||||
resp, err := c.containerURL.ListBlobsFlatSegment(ctx, marker, azblob.ListBlobsSegmentOptions{Prefix: prefix})
|
||||
resp, err := c.containerURL.ListBlobsFlatSegment(ctx, marker, azblob.ListBlobsSegmentOptions{Prefix: dir + "/"})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -170,11 +171,12 @@ func (c *ReplicaClient) Snapshots(ctx context.Context, generation string) (lites
|
||||
func (c *ReplicaClient) WriteSnapshot(ctx context.Context, generation string, index int, rd io.Reader) (info litestream.SnapshotInfo, err error) {
|
||||
if err := c.Init(ctx); err != nil {
|
||||
return info, err
|
||||
} else if generation == "" {
|
||||
return info, fmt.Errorf("generation required")
|
||||
}
|
||||
|
||||
key := path.Join(c.Path, "generations", generation, "snapshots", litestream.FormatIndex(index)+".snapshot.lz4")
|
||||
key, err := litestream.SnapshotPath(c.Path, generation, index)
|
||||
if err != nil {
|
||||
return info, fmt.Errorf("cannot determine snapshot path: %w", err)
|
||||
}
|
||||
startTime := time.Now()
|
||||
|
||||
rc := internal.NewReadCounter(rd)
|
||||
@@ -204,11 +206,12 @@ func (c *ReplicaClient) WriteSnapshot(ctx context.Context, generation string, in
|
||||
func (c *ReplicaClient) SnapshotReader(ctx context.Context, generation string, index int) (io.ReadCloser, error) {
|
||||
if err := c.Init(ctx); err != nil {
|
||||
return nil, err
|
||||
} else if generation == "" {
|
||||
return nil, fmt.Errorf("generation required")
|
||||
}
|
||||
|
||||
key := path.Join(c.Path, "generations", generation, "snapshots", litestream.FormatIndex(index)+".snapshot.lz4")
|
||||
key, err := litestream.SnapshotPath(c.Path, generation, index)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("cannot determine snapshot path: %w", err)
|
||||
}
|
||||
|
||||
blobURL := c.containerURL.NewBlobURL(key)
|
||||
resp, err := blobURL.Download(ctx, 0, 0, azblob.BlobAccessConditions{}, false, azblob.ClientProvidedKeyOptions{})
|
||||
@@ -228,11 +231,12 @@ func (c *ReplicaClient) SnapshotReader(ctx context.Context, generation string, i
|
||||
func (c *ReplicaClient) DeleteSnapshot(ctx context.Context, generation string, index int) error {
|
||||
if err := c.Init(ctx); err != nil {
|
||||
return err
|
||||
} else if generation == "" {
|
||||
return fmt.Errorf("generation required")
|
||||
}
|
||||
|
||||
key := path.Join(c.Path, "generations", generation, "snapshots", litestream.FormatIndex(index)+".snapshot.lz4")
|
||||
key, err := litestream.SnapshotPath(c.Path, generation, index)
|
||||
if err != nil {
|
||||
return fmt.Errorf("cannot determine snapshot path: %w", err)
|
||||
}
|
||||
|
||||
internal.OperationTotalCounterVec.WithLabelValues(ReplicaClientType, "DELETE").Inc()
|
||||
|
||||
@@ -257,11 +261,12 @@ func (c *ReplicaClient) WALSegments(ctx context.Context, generation string) (lit
|
||||
func (c *ReplicaClient) WriteWALSegment(ctx context.Context, pos litestream.Pos, rd io.Reader) (info litestream.WALSegmentInfo, err error) {
|
||||
if err := c.Init(ctx); err != nil {
|
||||
return info, err
|
||||
} else if pos.Generation == "" {
|
||||
return info, fmt.Errorf("generation required")
|
||||
}
|
||||
|
||||
key := path.Join(c.Path, "generations", pos.Generation, "wal", litestream.FormatIndex(pos.Index), litestream.FormatOffset(pos.Offset)+".wal.lz4")
|
||||
key, err := litestream.WALSegmentPath(c.Path, pos.Generation, pos.Index, pos.Offset)
|
||||
if err != nil {
|
||||
return info, fmt.Errorf("cannot determine wal segment path: %w", err)
|
||||
}
|
||||
startTime := time.Now()
|
||||
|
||||
rc := internal.NewReadCounter(rd)
|
||||
@@ -291,11 +296,12 @@ func (c *ReplicaClient) WriteWALSegment(ctx context.Context, pos litestream.Pos,
|
||||
func (c *ReplicaClient) WALSegmentReader(ctx context.Context, pos litestream.Pos) (io.ReadCloser, error) {
|
||||
if err := c.Init(ctx); err != nil {
|
||||
return nil, err
|
||||
} else if pos.Generation == "" {
|
||||
return nil, fmt.Errorf("generation required")
|
||||
}
|
||||
|
||||
key := path.Join(c.Path, "generations", pos.Generation, "wal", litestream.FormatIndex(pos.Index), litestream.FormatOffset(pos.Offset)+".wal.lz4")
|
||||
key, err := litestream.WALSegmentPath(c.Path, pos.Generation, pos.Index, pos.Offset)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("cannot determine wal segment path: %w", err)
|
||||
}
|
||||
|
||||
blobURL := c.containerURL.NewBlobURL(key)
|
||||
resp, err := blobURL.Download(ctx, 0, 0, azblob.BlobAccessConditions{}, false, azblob.ClientProvidedKeyOptions{})
|
||||
@@ -318,12 +324,11 @@ func (c *ReplicaClient) DeleteWALSegments(ctx context.Context, a []litestream.Po
|
||||
}
|
||||
|
||||
for _, pos := range a {
|
||||
if pos.Generation == "" {
|
||||
return fmt.Errorf("generation required")
|
||||
key, err := litestream.WALSegmentPath(c.Path, pos.Generation, pos.Index, pos.Offset)
|
||||
if err != nil {
|
||||
return fmt.Errorf("cannot determine wal segment path: %w", err)
|
||||
}
|
||||
|
||||
key := path.Join(c.Path, "generations", pos.Generation, "wal", litestream.FormatIndex(pos.Index), litestream.FormatOffset(pos.Offset)+".wal.lz4")
|
||||
|
||||
internal.OperationTotalCounterVec.WithLabelValues(ReplicaClientType, "DELETE").Inc()
|
||||
|
||||
blobURL := c.containerURL.NewBlobURL(key)
|
||||
@@ -367,24 +372,24 @@ func newSnapshotIterator(ctx context.Context, generation string, client *Replica
|
||||
func (itr *snapshotIterator) fetch() error {
|
||||
defer close(itr.ch)
|
||||
|
||||
if itr.generation == "" {
|
||||
return fmt.Errorf("generation required")
|
||||
dir, err := litestream.SnapshotsPath(itr.client.Path, itr.generation)
|
||||
if err != nil {
|
||||
return fmt.Errorf("cannot determine snapshots path: %w", err)
|
||||
}
|
||||
|
||||
prefix := path.Join(itr.client.Path, "generations", itr.generation) + "/"
|
||||
|
||||
var marker azblob.Marker
|
||||
for marker.NotDone() {
|
||||
internal.OperationTotalCounterVec.WithLabelValues(ReplicaClientType, "LIST").Inc()
|
||||
|
||||
resp, err := itr.client.containerURL.ListBlobsFlatSegment(itr.ctx, marker, azblob.ListBlobsSegmentOptions{Prefix: prefix})
|
||||
resp, err := itr.client.containerURL.ListBlobsFlatSegment(itr.ctx, marker, azblob.ListBlobsSegmentOptions{Prefix: dir + "/"})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
marker = resp.NextMarker
|
||||
|
||||
for _, item := range resp.Segment.BlobItems {
|
||||
index, err := internal.ParseSnapshotPath(path.Base(item.Name))
|
||||
key := path.Base(item.Name)
|
||||
index, err := litestream.ParseSnapshotPath(key)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
@@ -473,24 +478,24 @@ func newWALSegmentIterator(ctx context.Context, generation string, client *Repli
|
||||
func (itr *walSegmentIterator) fetch() error {
|
||||
defer close(itr.ch)
|
||||
|
||||
if itr.generation == "" {
|
||||
return fmt.Errorf("generation required")
|
||||
dir, err := litestream.WALPath(itr.client.Path, itr.generation)
|
||||
if err != nil {
|
||||
return fmt.Errorf("cannot determine wal path: %w", err)
|
||||
}
|
||||
prefix := path.Join(itr.client.Path, "generations", itr.generation, "wal")
|
||||
|
||||
var marker azblob.Marker
|
||||
for marker.NotDone() {
|
||||
internal.OperationTotalCounterVec.WithLabelValues(ReplicaClientType, "LIST").Inc()
|
||||
|
||||
resp, err := itr.client.containerURL.ListBlobsFlatSegment(itr.ctx, marker, azblob.ListBlobsSegmentOptions{Prefix: prefix})
|
||||
resp, err := itr.client.containerURL.ListBlobsFlatSegment(itr.ctx, marker, azblob.ListBlobsSegmentOptions{Prefix: dir + "/"})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
marker = resp.NextMarker
|
||||
|
||||
for _, item := range resp.Segment.BlobItems {
|
||||
key := strings.TrimPrefix(item.Name, prefix+"/")
|
||||
index, offset, err := internal.ParseWALSegmentPath(key)
|
||||
key := path.Base(item.Name)
|
||||
index, offset, err := litestream.ParseWALSegmentPath(key)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
|
||||
@@ -9,7 +9,6 @@ import (
|
||||
"log"
|
||||
"net/url"
|
||||
"os"
|
||||
"os/signal"
|
||||
"os/user"
|
||||
"path"
|
||||
"path/filepath"
|
||||
@@ -87,8 +86,7 @@ func (m *Main) Run(ctx context.Context, args []string) (err error) {
|
||||
|
||||
// Setup signal handler.
|
||||
ctx, cancel := context.WithCancel(ctx)
|
||||
signalCh := make(chan os.Signal, 1)
|
||||
signal.Notify(signalCh, notifySignals...)
|
||||
signalCh := signalChan()
|
||||
|
||||
if err := c.Run(ctx); err != nil {
|
||||
return err
|
||||
@@ -96,8 +94,6 @@ func (m *Main) Run(ctx context.Context, args []string) (err error) {
|
||||
|
||||
// Wait for signal to stop program.
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
fmt.Println("context done, litestream shutting down")
|
||||
case err = <-c.execCh:
|
||||
cancel()
|
||||
fmt.Println("subprocess exited, litestream shutting down")
|
||||
|
||||
@@ -5,6 +5,7 @@ package main
|
||||
import (
|
||||
"context"
|
||||
"os"
|
||||
"os/signal"
|
||||
"syscall"
|
||||
)
|
||||
|
||||
@@ -18,4 +19,8 @@ func runWindowsService(ctx context.Context) error {
|
||||
panic("cannot run windows service as unix process")
|
||||
}
|
||||
|
||||
var notifySignals = []os.Signal{syscall.SIGINT, syscall.SIGTERM}
|
||||
func signalChan() <-chan os.Signal {
|
||||
ch := make(chan os.Signal, 2)
|
||||
signal.Notify(ch, syscall.SIGINT, syscall.SIGTERM)
|
||||
return ch
|
||||
}
|
||||
|
||||
@@ -2,22 +2,16 @@ package main_test
|
||||
|
||||
import (
|
||||
"io/ioutil"
|
||||
"log"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"github.com/benbjohnson/litestream"
|
||||
main "github.com/benbjohnson/litestream/cmd/litestream"
|
||||
"github.com/benbjohnson/litestream/file"
|
||||
"github.com/benbjohnson/litestream/gcs"
|
||||
"github.com/benbjohnson/litestream/s3"
|
||||
)
|
||||
|
||||
func init() {
|
||||
litestream.LogFlags = log.Lmsgprefix | log.Ldate | log.Ltime | log.Lmicroseconds | log.LUTC | log.Lshortfile
|
||||
}
|
||||
|
||||
func TestReadConfigFile(t *testing.T) {
|
||||
// Ensure global AWS settings are propagated down to replica configurations.
|
||||
t.Run("PropagateGlobalSettings", func(t *testing.T) {
|
||||
|
||||
@@ -7,6 +7,7 @@ import (
|
||||
"io"
|
||||
"log"
|
||||
"os"
|
||||
"os/signal"
|
||||
|
||||
"golang.org/x/sys/windows"
|
||||
"golang.org/x/sys/windows/svc"
|
||||
@@ -104,4 +105,8 @@ func (w *eventlogWriter) Write(p []byte) (n int, err error) {
|
||||
return 0, elog.Info(1, string(p))
|
||||
}
|
||||
|
||||
var notifySignals = []os.Signal{os.Interrupt}
|
||||
func signalChan() <-chan os.Signal {
|
||||
ch := make(chan os.Signal, 1)
|
||||
signal.Notify(ch, os.Interrupt)
|
||||
return ch
|
||||
}
|
||||
|
||||
@@ -42,6 +42,7 @@ func NewReplicateCommand() *ReplicateCommand {
|
||||
func (c *ReplicateCommand) ParseFlags(ctx context.Context, args []string) (err error) {
|
||||
fs := flag.NewFlagSet("litestream-replicate", flag.ContinueOnError)
|
||||
execFlag := fs.String("exec", "", "execute subcommand")
|
||||
tracePath := fs.String("trace", "", "trace path")
|
||||
configPath, noExpandEnv := registerConfigFlag(fs)
|
||||
fs.Usage = c.Usage
|
||||
if err := fs.Parse(args); err != nil {
|
||||
@@ -79,6 +80,16 @@ func (c *ReplicateCommand) ParseFlags(ctx context.Context, args []string) (err e
|
||||
c.Config.Exec = *execFlag
|
||||
}
|
||||
|
||||
// Enable trace logging.
|
||||
if *tracePath != "" {
|
||||
f, err := os.Create(*tracePath)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer f.Close()
|
||||
litestream.Tracef = log.New(f, "", log.LstdFlags|log.Lmicroseconds|log.LUTC|log.Lshortfile).Printf
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -204,5 +215,8 @@ Arguments:
|
||||
-no-expand-env
|
||||
Disables environment variable expansion in configuration file.
|
||||
|
||||
-trace PATH
|
||||
Write verbose trace logging to PATH.
|
||||
|
||||
`[1:], DefaultConfigPath())
|
||||
}
|
||||
|
||||
@@ -1,135 +0,0 @@
|
||||
package main_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"errors"
|
||||
"fmt"
|
||||
"hash/crc64"
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
main "github.com/benbjohnson/litestream/cmd/litestream"
|
||||
"golang.org/x/sync/errgroup"
|
||||
)
|
||||
|
||||
func TestReplicateCommand(t *testing.T) {
|
||||
if testing.Short() {
|
||||
t.Skip("long running test, skipping")
|
||||
} else if runtime.GOOS != "linux" {
|
||||
t.Skip("must run system tests on Linux, skipping")
|
||||
}
|
||||
|
||||
const writeTime = 10 * time.Second
|
||||
|
||||
dir := t.TempDir()
|
||||
configPath := filepath.Join(dir, "litestream.yml")
|
||||
dbPath := filepath.Join(dir, "db")
|
||||
restorePath := filepath.Join(dir, "restored")
|
||||
replicaPath := filepath.Join(dir, "replica")
|
||||
|
||||
if err := os.WriteFile(configPath, []byte(`
|
||||
dbs:
|
||||
- path: `+dbPath+`
|
||||
replicas:
|
||||
- path: `+replicaPath+`
|
||||
`), 0666); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
// Generate data into SQLite database from separate goroutine.
|
||||
g, ctx := errgroup.WithContext(context.Background())
|
||||
mainctx, cancel := context.WithCancel(ctx)
|
||||
g.Go(func() error {
|
||||
defer cancel()
|
||||
|
||||
db, err := sql.Open("sqlite3", dbPath)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer db.Close()
|
||||
|
||||
if _, err := db.ExecContext(ctx, `PRAGMA journal_mode = WAL`); err != nil {
|
||||
return fmt.Errorf("cannot enable wal: %w", err)
|
||||
} else if _, err := db.ExecContext(ctx, `PRAGMA synchronous = NORMAL`); err != nil {
|
||||
return fmt.Errorf("cannot enable wal: %w", err)
|
||||
} else if _, err := db.ExecContext(ctx, `CREATE TABLE t (id INTEGER PRIMARY KEY)`); err != nil {
|
||||
return fmt.Errorf("cannot create table: %w", err)
|
||||
}
|
||||
|
||||
ticker := time.NewTicker(1 * time.Millisecond)
|
||||
defer ticker.Stop()
|
||||
timer := time.NewTimer(writeTime)
|
||||
defer timer.Stop()
|
||||
|
||||
for i := 0; ; i++ {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
case <-timer.C:
|
||||
return nil
|
||||
case <-ticker.C:
|
||||
if _, err := db.ExecContext(ctx, `INSERT INTO t (id) VALUES (?);`, i); err != nil {
|
||||
return fmt.Errorf("cannot insert: i=%d err=%w", i, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
// Replicate database unless the context is canceled.
|
||||
g.Go(func() error {
|
||||
return main.NewMain().Run(mainctx, []string{"replicate", "-config", configPath})
|
||||
})
|
||||
|
||||
if err := g.Wait(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
// Checkpoint database.
|
||||
mustCheckpoint(t, dbPath)
|
||||
chksum0 := mustChecksum(t, dbPath)
|
||||
|
||||
// Restore to another path.
|
||||
if err := main.NewMain().Run(context.Background(), []string{"restore", "-config", configPath, "-o", restorePath, dbPath}); err != nil && !errors.Is(err, context.Canceled) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
// Verify contents match.
|
||||
if chksum1 := mustChecksum(t, restorePath); chksum0 != chksum1 {
|
||||
t.Fatal("restore mismatch")
|
||||
}
|
||||
}
|
||||
|
||||
func mustCheckpoint(tb testing.TB, path string) {
|
||||
tb.Helper()
|
||||
|
||||
db, err := sql.Open("sqlite3", path)
|
||||
if err != nil {
|
||||
tb.Fatal(err)
|
||||
}
|
||||
defer db.Close()
|
||||
|
||||
if _, err := db.Exec(`PRAGMA wal_checkpoint(TRUNCATE)`); err != nil {
|
||||
tb.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
func mustChecksum(tb testing.TB, path string) uint64 {
|
||||
tb.Helper()
|
||||
|
||||
f, err := os.Open(path)
|
||||
if err != nil {
|
||||
tb.Fatal(err)
|
||||
}
|
||||
defer f.Close()
|
||||
|
||||
h := crc64.New(crc64.MakeTable(crc64.ISO))
|
||||
if _, err := io.Copy(h, f); err != nil {
|
||||
tb.Fatal(err)
|
||||
}
|
||||
return h.Sum64()
|
||||
}
|
||||
169
db_test.go
169
db_test.go
@@ -3,6 +3,7 @@ package litestream_test
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"io/ioutil"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
@@ -29,13 +30,13 @@ func TestDB_WALPath(t *testing.T) {
|
||||
func TestDB_MetaPath(t *testing.T) {
|
||||
t.Run("Absolute", func(t *testing.T) {
|
||||
db := litestream.NewDB("/tmp/db")
|
||||
if got, want := db.MetaPath(), `/tmp/db-litestream`; got != want {
|
||||
if got, want := db.MetaPath(), `/tmp/.db-litestream`; got != want {
|
||||
t.Fatalf("MetaPath()=%v, want %v", got, want)
|
||||
}
|
||||
})
|
||||
t.Run("Relative", func(t *testing.T) {
|
||||
db := litestream.NewDB("db")
|
||||
if got, want := db.MetaPath(), `db-litestream`; got != want {
|
||||
if got, want := db.MetaPath(), `.db-litestream`; got != want {
|
||||
t.Fatalf("MetaPath()=%v, want %v", got, want)
|
||||
}
|
||||
})
|
||||
@@ -43,25 +44,32 @@ func TestDB_MetaPath(t *testing.T) {
|
||||
|
||||
func TestDB_GenerationNamePath(t *testing.T) {
|
||||
db := litestream.NewDB("/tmp/db")
|
||||
if got, want := db.GenerationNamePath(), `/tmp/db-litestream/generation`; got != want {
|
||||
if got, want := db.GenerationNamePath(), `/tmp/.db-litestream/generation`; got != want {
|
||||
t.Fatalf("GenerationNamePath()=%v, want %v", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDB_GenerationPath(t *testing.T) {
|
||||
db := litestream.NewDB("/tmp/db")
|
||||
if got, want := db.GenerationPath("xxxx"), `/tmp/db-litestream/generations/xxxx`; got != want {
|
||||
if got, want := db.GenerationPath("xxxx"), `/tmp/.db-litestream/generations/xxxx`; got != want {
|
||||
t.Fatalf("GenerationPath()=%v, want %v", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDB_ShadowWALDir(t *testing.T) {
|
||||
db := litestream.NewDB("/tmp/db")
|
||||
if got, want := db.ShadowWALDir("xxxx"), `/tmp/db-litestream/generations/xxxx/wal`; got != want {
|
||||
if got, want := db.ShadowWALDir("xxxx"), `/tmp/.db-litestream/generations/xxxx/wal`; got != want {
|
||||
t.Fatalf("ShadowWALDir()=%v, want %v", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDB_ShadowWALPath(t *testing.T) {
|
||||
db := litestream.NewDB("/tmp/db")
|
||||
if got, want := db.ShadowWALPath("xxxx", 1000), `/tmp/.db-litestream/generations/xxxx/wal/000003e8.wal`; got != want {
|
||||
t.Fatalf("ShadowWALPath()=%v, want %v", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
// Ensure we can check the last modified time of the real database and its WAL.
|
||||
func TestDB_UpdatedAt(t *testing.T) {
|
||||
t.Run("ErrNotExist", func(t *testing.T) {
|
||||
@@ -187,7 +195,9 @@ func TestDB_Sync(t *testing.T) {
|
||||
}
|
||||
|
||||
// Ensure position now available.
|
||||
if pos := db.Pos(); pos.Generation == "" {
|
||||
if pos, err := db.Pos(); err != nil {
|
||||
t.Fatal(err)
|
||||
} else if pos.Generation == "" {
|
||||
t.Fatal("expected generation")
|
||||
} else if got, want := pos.Index, 0; got != want {
|
||||
t.Fatalf("pos.Index=%v, want %v", got, want)
|
||||
@@ -211,7 +221,10 @@ func TestDB_Sync(t *testing.T) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
pos0 := db.Pos()
|
||||
pos0, err := db.Pos()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
// Insert into table.
|
||||
if _, err := sqldb.Exec(`INSERT INTO foo (bar) VALUES ('baz');`); err != nil {
|
||||
@@ -221,7 +234,9 @@ func TestDB_Sync(t *testing.T) {
|
||||
// Sync to ensure position moves forward one page.
|
||||
if err := db.Sync(context.Background()); err != nil {
|
||||
t.Fatal(err)
|
||||
} else if pos1 := db.Pos(); pos0.Generation != pos1.Generation {
|
||||
} else if pos1, err := db.Pos(); err != nil {
|
||||
t.Fatal(err)
|
||||
} else if pos0.Generation != pos1.Generation {
|
||||
t.Fatal("expected the same generation")
|
||||
} else if got, want := pos1.Index, pos0.Index; got != want {
|
||||
t.Fatalf("Index=%v, want %v", got, want)
|
||||
@@ -241,7 +256,10 @@ func TestDB_Sync(t *testing.T) {
|
||||
}
|
||||
|
||||
// Obtain initial position.
|
||||
pos0 := db.Pos()
|
||||
pos0, err := db.Pos()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
// Checkpoint & fully close which should close WAL file.
|
||||
if err := db.Checkpoint(context.Background(), litestream.CheckpointModeTruncate); err != nil {
|
||||
@@ -267,7 +285,9 @@ func TestDB_Sync(t *testing.T) {
|
||||
}
|
||||
|
||||
// Obtain initial position.
|
||||
if pos1 := db.Pos(); pos0.Generation == pos1.Generation {
|
||||
if pos1, err := db.Pos(); err != nil {
|
||||
t.Fatal(err)
|
||||
} else if pos0.Generation == pos1.Generation {
|
||||
t.Fatal("expected new generation after truncation")
|
||||
}
|
||||
})
|
||||
@@ -288,7 +308,10 @@ func TestDB_Sync(t *testing.T) {
|
||||
}
|
||||
|
||||
// Obtain initial position.
|
||||
pos0 := db.Pos()
|
||||
pos0, err := db.Pos()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
// Fully close which should close WAL file.
|
||||
if err := db.Close(); err != nil {
|
||||
@@ -321,13 +344,13 @@ func TestDB_Sync(t *testing.T) {
|
||||
}
|
||||
|
||||
// Obtain initial position.
|
||||
if pos1 := db.Pos(); pos0.Generation == pos1.Generation {
|
||||
if pos1, err := db.Pos(); err != nil {
|
||||
t.Fatal(err)
|
||||
} else if pos0.Generation == pos1.Generation {
|
||||
t.Fatal("expected new generation after truncation")
|
||||
}
|
||||
})
|
||||
|
||||
// TODO: Fix test to check for header mismatch
|
||||
/*
|
||||
// Ensure DB can handle a mismatched header-only and start new generation.
|
||||
t.Run("WALHeaderMismatch", func(t *testing.T) {
|
||||
db, sqldb := MustOpenDBs(t)
|
||||
@@ -341,17 +364,19 @@ func TestDB_Sync(t *testing.T) {
|
||||
}
|
||||
|
||||
// Grab initial position & close.
|
||||
pos0 := db.Pos()
|
||||
if err := db.Close(); err != nil {
|
||||
pos0, err := db.Pos()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
} else if err := db.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
// Read existing file, update header checksum, and write back only header
|
||||
// to simulate a header with a mismatched checksum.
|
||||
shadowWALPath := db.ShadowWALPath(pos0.Generation, pos0.Index)
|
||||
if buf, err := os.ReadFile(shadowWALPath); err != nil {
|
||||
if buf, err := ioutil.ReadFile(shadowWALPath); err != nil {
|
||||
t.Fatal(err)
|
||||
} else if err := os.WriteFile(shadowWALPath, append(buf[:litestream.WALHeaderSize-8], 0, 0, 0, 0, 0, 0, 0, 0), 0600); err != nil {
|
||||
} else if err := ioutil.WriteFile(shadowWALPath, append(buf[:litestream.WALHeaderSize-8], 0, 0, 0, 0, 0, 0, 0, 0), 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
@@ -369,10 +394,98 @@ func TestDB_Sync(t *testing.T) {
|
||||
t.Fatal("expected new generation")
|
||||
}
|
||||
})
|
||||
*/
|
||||
|
||||
// TODO: Fix test for segmented shadow WAL.
|
||||
/*
|
||||
// Ensure DB can handle partial shadow WAL header write.
|
||||
t.Run("PartialShadowWALHeader", func(t *testing.T) {
|
||||
db, sqldb := MustOpenDBs(t)
|
||||
defer MustCloseDBs(t, db, sqldb)
|
||||
|
||||
// Execute a query to force a write to the WAL and then sync.
|
||||
if _, err := sqldb.Exec(`CREATE TABLE foo (bar TEXT);`); err != nil {
|
||||
t.Fatal(err)
|
||||
} else if err := db.Sync(context.Background()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
pos0, err := db.Pos()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
// Close & truncate shadow WAL to simulate a partial header write.
|
||||
if err := db.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
} else if err := os.Truncate(db.ShadowWALPath(pos0.Generation, pos0.Index), litestream.WALHeaderSize-1); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
// Reopen managed database & ensure sync will still work.
|
||||
db = MustOpenDBAt(t, db.Path())
|
||||
defer MustCloseDB(t, db)
|
||||
if err := db.Sync(context.Background()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
// Verify a new generation was started.
|
||||
if pos1, err := db.Pos(); err != nil {
|
||||
t.Fatal(err)
|
||||
} else if pos0.Generation == pos1.Generation {
|
||||
t.Fatal("expected new generation")
|
||||
}
|
||||
})
|
||||
|
||||
// Ensure DB can handle partial shadow WAL writes.
|
||||
t.Run("PartialShadowWALFrame", func(t *testing.T) {
|
||||
db, sqldb := MustOpenDBs(t)
|
||||
defer MustCloseDBs(t, db, sqldb)
|
||||
|
||||
// Execute a query to force a write to the WAL and then sync.
|
||||
if _, err := sqldb.Exec(`CREATE TABLE foo (bar TEXT);`); err != nil {
|
||||
t.Fatal(err)
|
||||
} else if err := db.Sync(context.Background()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
pos0, err := db.Pos()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
// Obtain current shadow WAL size.
|
||||
fi, err := os.Stat(db.ShadowWALPath(pos0.Generation, pos0.Index))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
// Close & truncate shadow WAL to simulate a partial frame write.
|
||||
if err := db.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
} else if err := os.Truncate(db.ShadowWALPath(pos0.Generation, pos0.Index), fi.Size()-1); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
// Reopen managed database & ensure sync will still work.
|
||||
db = MustOpenDBAt(t, db.Path())
|
||||
defer MustCloseDB(t, db)
|
||||
if err := db.Sync(context.Background()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
// Verify same generation is kept.
|
||||
if pos1, err := db.Pos(); err != nil {
|
||||
t.Fatal(err)
|
||||
} else if got, want := pos1, pos0; got != want {
|
||||
t.Fatalf("Pos()=%s want %s", got, want)
|
||||
}
|
||||
|
||||
// Ensure shadow WAL has recovered.
|
||||
if fi0, err := os.Stat(db.ShadowWALPath(pos0.Generation, pos0.Index)); err != nil {
|
||||
t.Fatal(err)
|
||||
} else if got, want := fi0.Size(), fi.Size(); got != want {
|
||||
t.Fatalf("Size()=%v, want %v", got, want)
|
||||
}
|
||||
})
|
||||
|
||||
// Ensure DB can handle a generation directory with a missing shadow WAL.
|
||||
t.Run("NoShadowWAL", func(t *testing.T) {
|
||||
db, sqldb := MustOpenDBs(t)
|
||||
@@ -385,7 +498,10 @@ func TestDB_Sync(t *testing.T) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
pos0 := db.Pos()
|
||||
pos0, err := db.Pos()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
// Close & delete shadow WAL to simulate dir created but not WAL.
|
||||
if err := db.Close(); err != nil {
|
||||
@@ -412,7 +528,6 @@ func TestDB_Sync(t *testing.T) {
|
||||
t.Fatalf("Offset=%v want %v", got, want)
|
||||
}
|
||||
})
|
||||
*/
|
||||
|
||||
// Ensure DB checkpoints after minimum number of pages.
|
||||
t.Run("MinCheckpointPageN", func(t *testing.T) {
|
||||
@@ -439,7 +554,9 @@ func TestDB_Sync(t *testing.T) {
|
||||
}
|
||||
|
||||
// Ensure position is now on the second index.
|
||||
if got, want := db.Pos().Index, 1; got != want {
|
||||
if pos, err := db.Pos(); err != nil {
|
||||
t.Fatal(err)
|
||||
} else if got, want := pos.Index, 1; got != want {
|
||||
t.Fatalf("Index=%v, want %v", got, want)
|
||||
}
|
||||
})
|
||||
@@ -467,7 +584,9 @@ func TestDB_Sync(t *testing.T) {
|
||||
}
|
||||
|
||||
// Ensure position is now on the second index.
|
||||
if got, want := db.Pos().Index, 1; got != want {
|
||||
if pos, err := db.Pos(); err != nil {
|
||||
t.Fatal(err)
|
||||
} else if got, want := pos.Index, 1; got != want {
|
||||
t.Fatalf("Index=%v, want %v", got, want)
|
||||
}
|
||||
})
|
||||
|
||||
@@ -8,7 +8,6 @@ import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sort"
|
||||
"strings"
|
||||
|
||||
"github.com/benbjohnson/litestream"
|
||||
"github.com/benbjohnson/litestream/internal"
|
||||
@@ -85,7 +84,7 @@ func (c *ReplicaClient) SnapshotPath(generation string, index int) (string, erro
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return filepath.Join(dir, litestream.FormatIndex(index)+".snapshot.lz4"), nil
|
||||
return filepath.Join(dir, litestream.FormatSnapshotPath(index)), nil
|
||||
}
|
||||
|
||||
// WALDir returns the path to a generation's WAL directory
|
||||
@@ -103,7 +102,7 @@ func (c *ReplicaClient) WALSegmentPath(generation string, index int, offset int6
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return filepath.Join(dir, litestream.FormatIndex(index), fmt.Sprintf("%08x.wal.lz4", offset)), nil
|
||||
return filepath.Join(dir, litestream.FormatWALSegmentPath(index, offset)), nil
|
||||
}
|
||||
|
||||
// Generations returns a list of available generation names.
|
||||
@@ -149,7 +148,7 @@ func (c *ReplicaClient) DeleteGeneration(ctx context.Context, generation string)
|
||||
func (c *ReplicaClient) Snapshots(ctx context.Context, generation string) (litestream.SnapshotIterator, error) {
|
||||
dir, err := c.SnapshotsDir(generation)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
return nil, fmt.Errorf("cannot determine snapshots path: %w", err)
|
||||
}
|
||||
|
||||
f, err := os.Open(dir)
|
||||
@@ -169,7 +168,7 @@ func (c *ReplicaClient) Snapshots(ctx context.Context, generation string) (lites
|
||||
infos := make([]litestream.SnapshotInfo, 0, len(fis))
|
||||
for _, fi := range fis {
|
||||
// Parse index from filename.
|
||||
index, err := internal.ParseSnapshotPath(filepath.Base(fi.Name()))
|
||||
index, err := litestream.ParseSnapshotPath(fi.Name())
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
@@ -191,7 +190,7 @@ func (c *ReplicaClient) Snapshots(ctx context.Context, generation string) (lites
|
||||
func (c *ReplicaClient) WriteSnapshot(ctx context.Context, generation string, index int, rd io.Reader) (info litestream.SnapshotInfo, err error) {
|
||||
filename, err := c.SnapshotPath(generation, index)
|
||||
if err != nil {
|
||||
return info, err
|
||||
return info, fmt.Errorf("cannot determine snapshot path: %w", err)
|
||||
}
|
||||
|
||||
var fileInfo, dirInfo os.FileInfo
|
||||
@@ -244,7 +243,7 @@ func (c *ReplicaClient) WriteSnapshot(ctx context.Context, generation string, in
|
||||
func (c *ReplicaClient) SnapshotReader(ctx context.Context, generation string, index int) (io.ReadCloser, error) {
|
||||
filename, err := c.SnapshotPath(generation, index)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
return nil, fmt.Errorf("cannot determine snapshot path: %w", err)
|
||||
}
|
||||
return os.Open(filename)
|
||||
}
|
||||
@@ -265,7 +264,7 @@ func (c *ReplicaClient) DeleteSnapshot(ctx context.Context, generation string, i
|
||||
func (c *ReplicaClient) WALSegments(ctx context.Context, generation string) (litestream.WALSegmentIterator, error) {
|
||||
dir, err := c.WALDir(generation)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
return nil, fmt.Errorf("cannot determine wal path: %w", err)
|
||||
}
|
||||
|
||||
f, err := os.Open(dir)
|
||||
@@ -282,25 +281,33 @@ func (c *ReplicaClient) WALSegments(ctx context.Context, generation string) (lit
|
||||
}
|
||||
|
||||
// Iterate over every file and convert to metadata.
|
||||
indexes := make([]int, 0, len(fis))
|
||||
infos := make([]litestream.WALSegmentInfo, 0, len(fis))
|
||||
for _, fi := range fis {
|
||||
index, err := litestream.ParseIndex(fi.Name())
|
||||
if err != nil || !fi.IsDir() {
|
||||
// Parse index from filename.
|
||||
index, offset, err := litestream.ParseWALSegmentPath(fi.Name())
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
indexes = append(indexes, index)
|
||||
|
||||
infos = append(infos, litestream.WALSegmentInfo{
|
||||
Generation: generation,
|
||||
Index: index,
|
||||
Offset: offset,
|
||||
Size: fi.Size(),
|
||||
CreatedAt: fi.ModTime().UTC(),
|
||||
})
|
||||
}
|
||||
|
||||
sort.Ints(indexes)
|
||||
sort.Sort(litestream.WALSegmentInfoSlice(infos))
|
||||
|
||||
return newWALSegmentIterator(dir, generation, indexes), nil
|
||||
return litestream.NewWALSegmentInfoSliceIterator(infos), nil
|
||||
}
|
||||
|
||||
// WriteWALSegment writes LZ4 compressed data from rd into a file on disk.
|
||||
func (c *ReplicaClient) WriteWALSegment(ctx context.Context, pos litestream.Pos, rd io.Reader) (info litestream.WALSegmentInfo, err error) {
|
||||
filename, err := c.WALSegmentPath(pos.Generation, pos.Index, pos.Offset)
|
||||
if err != nil {
|
||||
return info, err
|
||||
return info, fmt.Errorf("cannot determine wal segment path: %w", err)
|
||||
}
|
||||
|
||||
var fileInfo, dirInfo os.FileInfo
|
||||
@@ -354,7 +361,7 @@ func (c *ReplicaClient) WriteWALSegment(ctx context.Context, pos litestream.Pos,
|
||||
func (c *ReplicaClient) WALSegmentReader(ctx context.Context, pos litestream.Pos) (io.ReadCloser, error) {
|
||||
filename, err := c.WALSegmentPath(pos.Generation, pos.Index, pos.Offset)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
return nil, fmt.Errorf("cannot determine wal segment path: %w", err)
|
||||
}
|
||||
return os.Open(filename)
|
||||
}
|
||||
@@ -364,7 +371,7 @@ func (c *ReplicaClient) DeleteWALSegments(ctx context.Context, a []litestream.Po
|
||||
for _, pos := range a {
|
||||
filename, err := c.WALSegmentPath(pos.Generation, pos.Index, pos.Offset)
|
||||
if err != nil {
|
||||
return err
|
||||
return fmt.Errorf("cannot determine wal segment path: %w", err)
|
||||
}
|
||||
if err := os.Remove(filename); err != nil && !os.IsNotExist(err) {
|
||||
return err
|
||||
@@ -372,100 +379,3 @@ func (c *ReplicaClient) DeleteWALSegments(ctx context.Context, a []litestream.Po
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
type walSegmentIterator struct {
|
||||
dir string
|
||||
generation string
|
||||
indexes []int
|
||||
|
||||
infos []litestream.WALSegmentInfo
|
||||
err error
|
||||
}
|
||||
|
||||
func newWALSegmentIterator(dir, generation string, indexes []int) *walSegmentIterator {
|
||||
return &walSegmentIterator{
|
||||
dir: dir,
|
||||
generation: generation,
|
||||
indexes: indexes,
|
||||
}
|
||||
}
|
||||
|
||||
func (itr *walSegmentIterator) Close() (err error) {
|
||||
return itr.err
|
||||
}
|
||||
|
||||
func (itr *walSegmentIterator) Next() bool {
|
||||
// Exit if an error has already occurred.
|
||||
if itr.err != nil {
|
||||
return false
|
||||
}
|
||||
|
||||
for {
|
||||
// Move to the next segment in cache, if available.
|
||||
if len(itr.infos) > 1 {
|
||||
itr.infos = itr.infos[1:]
|
||||
return true
|
||||
}
|
||||
itr.infos = itr.infos[:0] // otherwise clear infos
|
||||
|
||||
// If no indexes remain, stop iteration.
|
||||
if len(itr.indexes) == 0 {
|
||||
return false
|
||||
}
|
||||
|
||||
// Read segments into a cache for the current index.
|
||||
index := itr.indexes[0]
|
||||
itr.indexes = itr.indexes[1:]
|
||||
f, err := os.Open(filepath.Join(itr.dir, litestream.FormatIndex(index)))
|
||||
if err != nil {
|
||||
itr.err = err
|
||||
return false
|
||||
}
|
||||
defer f.Close()
|
||||
|
||||
fis, err := f.Readdir(-1)
|
||||
if err != nil {
|
||||
itr.err = err
|
||||
return false
|
||||
} else if err := f.Close(); err != nil {
|
||||
itr.err = err
|
||||
return false
|
||||
}
|
||||
|
||||
for _, fi := range fis {
|
||||
filename := filepath.Base(fi.Name())
|
||||
if fi.IsDir() {
|
||||
continue
|
||||
}
|
||||
|
||||
offset, err := litestream.ParseOffset(strings.TrimSuffix(filename, ".wal.lz4"))
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
|
||||
itr.infos = append(itr.infos, litestream.WALSegmentInfo{
|
||||
Generation: itr.generation,
|
||||
Index: index,
|
||||
Offset: offset,
|
||||
Size: fi.Size(),
|
||||
CreatedAt: fi.ModTime().UTC(),
|
||||
})
|
||||
}
|
||||
|
||||
// Ensure segments are sorted within index.
|
||||
sort.Sort(litestream.WALSegmentInfoSlice(itr.infos))
|
||||
|
||||
if len(itr.infos) > 0 {
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (itr *walSegmentIterator) Err() error { return itr.err }
|
||||
|
||||
func (itr *walSegmentIterator) WALSegment() litestream.WALSegmentInfo {
|
||||
if len(itr.infos) == 0 {
|
||||
return litestream.WALSegmentInfo{}
|
||||
}
|
||||
return itr.infos[0]
|
||||
}
|
||||
|
||||
@@ -118,7 +118,7 @@ func TestReplicaClient_WALSegmentPath(t *testing.T) {
|
||||
t.Run("OK", func(t *testing.T) {
|
||||
if got, err := file.NewReplicaClient("/foo").WALSegmentPath("0123456701234567", 1000, 1001); err != nil {
|
||||
t.Fatal(err)
|
||||
} else if want := "/foo/generations/0123456701234567/wal/000003e8/000003e9.wal.lz4"; got != want {
|
||||
} else if want := "/foo/generations/0123456701234567/wal/000003e8_000003e9.wal.lz4"; got != want {
|
||||
t.Fatalf("WALPath()=%v, want %v", got, want)
|
||||
}
|
||||
})
|
||||
@@ -133,3 +133,91 @@ func TestReplicaClient_WALSegmentPath(t *testing.T) {
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/*
|
||||
func TestReplica_Sync(t *testing.T) {
|
||||
// Ensure replica can successfully sync after DB has sync'd.
|
||||
t.Run("InitialSync", func(t *testing.T) {
|
||||
db, sqldb := MustOpenDBs(t)
|
||||
defer MustCloseDBs(t, db, sqldb)
|
||||
|
||||
r := litestream.NewReplica(db, "", file.NewReplicaClient(t.TempDir()))
|
||||
r.MonitorEnabled = false
|
||||
db.Replicas = []*litestream.Replica{r}
|
||||
|
||||
// Sync database & then sync replica.
|
||||
if err := db.Sync(context.Background()); err != nil {
|
||||
t.Fatal(err)
|
||||
} else if err := r.Sync(context.Background()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
// Ensure posistions match.
|
||||
if want, err := db.Pos(); err != nil {
|
||||
t.Fatal(err)
|
||||
} else if got, err := r.Pos(context.Background()); err != nil {
|
||||
t.Fatal(err)
|
||||
} else if got != want {
|
||||
t.Fatalf("Pos()=%v, want %v", got, want)
|
||||
}
|
||||
})
|
||||
|
||||
// Ensure replica can successfully sync multiple times.
|
||||
t.Run("MultiSync", func(t *testing.T) {
|
||||
db, sqldb := MustOpenDBs(t)
|
||||
defer MustCloseDBs(t, db, sqldb)
|
||||
|
||||
r := litestream.NewReplica(db, "", file.NewReplicaClient(t.TempDir()))
|
||||
r.MonitorEnabled = false
|
||||
db.Replicas = []*litestream.Replica{r}
|
||||
|
||||
if _, err := sqldb.Exec(`CREATE TABLE foo (bar TEXT);`); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
// Write to the database multiple times and sync after each write.
|
||||
for i, n := 0, db.MinCheckpointPageN*2; i < n; i++ {
|
||||
if _, err := sqldb.Exec(`INSERT INTO foo (bar) VALUES ('baz')`); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
// Sync periodically.
|
||||
if i%100 == 0 || i == n-1 {
|
||||
if err := db.Sync(context.Background()); err != nil {
|
||||
t.Fatal(err)
|
||||
} else if err := r.Sync(context.Background()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Ensure posistions match.
|
||||
pos, err := db.Pos()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
} else if got, want := pos.Index, 2; got != want {
|
||||
t.Fatalf("Index=%v, want %v", got, want)
|
||||
}
|
||||
|
||||
if want, err := r.Pos(context.Background()); err != nil {
|
||||
t.Fatal(err)
|
||||
} else if got := pos; got != want {
|
||||
t.Fatalf("Pos()=%v, want %v", got, want)
|
||||
}
|
||||
})
|
||||
|
||||
// Ensure replica returns an error if there is no generation available from the DB.
|
||||
t.Run("ErrNoGeneration", func(t *testing.T) {
|
||||
db, sqldb := MustOpenDBs(t)
|
||||
defer MustCloseDBs(t, db, sqldb)
|
||||
|
||||
r := litestream.NewReplica(db, "", file.NewReplicaClient(t.TempDir()))
|
||||
r.MonitorEnabled = false
|
||||
db.Replicas = []*litestream.Replica{r}
|
||||
|
||||
if err := r.Sync(context.Background()); err == nil || err.Error() != `no generation, waiting for data` {
|
||||
t.Fatal(err)
|
||||
}
|
||||
})
|
||||
}
|
||||
*/
|
||||
|
||||
@@ -68,7 +68,7 @@ func (c *ReplicaClient) Generations(ctx context.Context) ([]string, error) {
|
||||
// Construct query to only pull generation directory names.
|
||||
query := &storage.Query{
|
||||
Delimiter: "/",
|
||||
Prefix: path.Join(c.Path, "generations") + "/",
|
||||
Prefix: litestream.GenerationsPath(c.Path) + "/",
|
||||
}
|
||||
|
||||
// Loop over results and only build list of generation-formatted names.
|
||||
@@ -96,15 +96,16 @@ func (c *ReplicaClient) Generations(ctx context.Context) ([]string, error) {
|
||||
func (c *ReplicaClient) DeleteGeneration(ctx context.Context, generation string) error {
|
||||
if err := c.Init(ctx); err != nil {
|
||||
return err
|
||||
} else if generation == "" {
|
||||
return fmt.Errorf("generation required")
|
||||
}
|
||||
|
||||
prefix := path.Join(c.Path, "generations", generation) + "/"
|
||||
dir, err := litestream.GenerationPath(c.Path, generation)
|
||||
if err != nil {
|
||||
return fmt.Errorf("cannot determine generation path: %w", err)
|
||||
}
|
||||
|
||||
// Iterate over every object in generation and delete it.
|
||||
internal.OperationTotalCounterVec.WithLabelValues(ReplicaClientType, "LIST").Inc()
|
||||
for it := c.bkt.Objects(ctx, &storage.Query{Prefix: prefix}); ; {
|
||||
for it := c.bkt.Objects(ctx, &storage.Query{Prefix: dir + "/"}); ; {
|
||||
attrs, err := it.Next()
|
||||
if err == iterator.Done {
|
||||
break
|
||||
@@ -129,22 +130,24 @@ func (c *ReplicaClient) DeleteGeneration(ctx context.Context, generation string)
|
||||
func (c *ReplicaClient) Snapshots(ctx context.Context, generation string) (litestream.SnapshotIterator, error) {
|
||||
if err := c.Init(ctx); err != nil {
|
||||
return nil, err
|
||||
} else if generation == "" {
|
||||
return nil, fmt.Errorf("generation required")
|
||||
}
|
||||
prefix := path.Join(c.Path, "generations", generation) + "/"
|
||||
return newSnapshotIterator(generation, c.bkt.Objects(ctx, &storage.Query{Prefix: prefix})), nil
|
||||
dir, err := litestream.SnapshotsPath(c.Path, generation)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("cannot determine snapshots path: %w", err)
|
||||
}
|
||||
return newSnapshotIterator(generation, c.bkt.Objects(ctx, &storage.Query{Prefix: dir + "/"})), nil
|
||||
}
|
||||
|
||||
// WriteSnapshot writes LZ4 compressed data from rd to the object storage.
|
||||
func (c *ReplicaClient) WriteSnapshot(ctx context.Context, generation string, index int, rd io.Reader) (info litestream.SnapshotInfo, err error) {
|
||||
if err := c.Init(ctx); err != nil {
|
||||
return info, err
|
||||
} else if generation == "" {
|
||||
return info, fmt.Errorf("generation required")
|
||||
}
|
||||
|
||||
key := path.Join(c.Path, "generations", generation, "snapshots", litestream.FormatIndex(index)+".snapshot.lz4")
|
||||
key, err := litestream.SnapshotPath(c.Path, generation, index)
|
||||
if err != nil {
|
||||
return info, fmt.Errorf("cannot determine snapshot path: %w", err)
|
||||
}
|
||||
startTime := time.Now()
|
||||
|
||||
w := c.bkt.Object(key).NewWriter(ctx)
|
||||
@@ -174,11 +177,12 @@ func (c *ReplicaClient) WriteSnapshot(ctx context.Context, generation string, in
|
||||
func (c *ReplicaClient) SnapshotReader(ctx context.Context, generation string, index int) (io.ReadCloser, error) {
|
||||
if err := c.Init(ctx); err != nil {
|
||||
return nil, err
|
||||
} else if generation == "" {
|
||||
return nil, fmt.Errorf("generation required")
|
||||
}
|
||||
|
||||
key := path.Join(c.Path, "generations", generation, "snapshots", litestream.FormatIndex(index)+".snapshot.lz4")
|
||||
key, err := litestream.SnapshotPath(c.Path, generation, index)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("cannot determine snapshot path: %w", err)
|
||||
}
|
||||
|
||||
r, err := c.bkt.Object(key).NewReader(ctx)
|
||||
if isNotExists(err) {
|
||||
@@ -197,11 +201,12 @@ func (c *ReplicaClient) SnapshotReader(ctx context.Context, generation string, i
|
||||
func (c *ReplicaClient) DeleteSnapshot(ctx context.Context, generation string, index int) error {
|
||||
if err := c.Init(ctx); err != nil {
|
||||
return err
|
||||
} else if generation == "" {
|
||||
return fmt.Errorf("generation required")
|
||||
}
|
||||
|
||||
key := path.Join(c.Path, "generations", generation, "snapshots", litestream.FormatIndex(index), ".snapshot.lz4")
|
||||
key, err := litestream.SnapshotPath(c.Path, generation, index)
|
||||
if err != nil {
|
||||
return fmt.Errorf("cannot determine snapshot path: %w", err)
|
||||
}
|
||||
|
||||
if err := c.bkt.Object(key).Delete(ctx); err != nil && !isNotExists(err) {
|
||||
return fmt.Errorf("cannot delete snapshot %q: %w", key, err)
|
||||
@@ -215,22 +220,24 @@ func (c *ReplicaClient) DeleteSnapshot(ctx context.Context, generation string, i
|
||||
func (c *ReplicaClient) WALSegments(ctx context.Context, generation string) (litestream.WALSegmentIterator, error) {
|
||||
if err := c.Init(ctx); err != nil {
|
||||
return nil, err
|
||||
} else if generation == "" {
|
||||
return nil, fmt.Errorf("generation required")
|
||||
}
|
||||
prefix := path.Join(c.Path, "generations", generation, "wal") + "/"
|
||||
return newWALSegmentIterator(generation, prefix, c.bkt.Objects(ctx, &storage.Query{Prefix: prefix})), nil
|
||||
dir, err := litestream.WALPath(c.Path, generation)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("cannot determine wal path: %w", err)
|
||||
}
|
||||
return newWALSegmentIterator(generation, c.bkt.Objects(ctx, &storage.Query{Prefix: dir + "/"})), nil
|
||||
}
|
||||
|
||||
// WriteWALSegment writes LZ4 compressed data from rd into a file on disk.
|
||||
func (c *ReplicaClient) WriteWALSegment(ctx context.Context, pos litestream.Pos, rd io.Reader) (info litestream.WALSegmentInfo, err error) {
|
||||
if err := c.Init(ctx); err != nil {
|
||||
return info, err
|
||||
} else if pos.Generation == "" {
|
||||
return info, fmt.Errorf("generation required")
|
||||
}
|
||||
|
||||
key := path.Join(c.Path, "generations", pos.Generation, "wal", litestream.FormatIndex(pos.Index), litestream.FormatOffset(pos.Offset)+".wal.lz4")
|
||||
key, err := litestream.WALSegmentPath(c.Path, pos.Generation, pos.Index, pos.Offset)
|
||||
if err != nil {
|
||||
return info, fmt.Errorf("cannot determine wal segment path: %w", err)
|
||||
}
|
||||
startTime := time.Now()
|
||||
|
||||
w := c.bkt.Object(key).NewWriter(ctx)
|
||||
@@ -260,11 +267,12 @@ func (c *ReplicaClient) WriteWALSegment(ctx context.Context, pos litestream.Pos,
|
||||
func (c *ReplicaClient) WALSegmentReader(ctx context.Context, pos litestream.Pos) (io.ReadCloser, error) {
|
||||
if err := c.Init(ctx); err != nil {
|
||||
return nil, err
|
||||
} else if pos.Generation == "" {
|
||||
return nil, fmt.Errorf("generation required")
|
||||
}
|
||||
|
||||
key := path.Join(c.Path, "generations", pos.Generation, "wal", litestream.FormatIndex(pos.Index), litestream.FormatOffset(pos.Offset)+".wal.lz4")
|
||||
key, err := litestream.WALSegmentPath(c.Path, pos.Generation, pos.Index, pos.Offset)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("cannot determine wal segment path: %w", err)
|
||||
}
|
||||
|
||||
r, err := c.bkt.Object(key).NewReader(ctx)
|
||||
if isNotExists(err) {
|
||||
@@ -286,11 +294,11 @@ func (c *ReplicaClient) DeleteWALSegments(ctx context.Context, a []litestream.Po
|
||||
}
|
||||
|
||||
for _, pos := range a {
|
||||
if pos.Generation == "" {
|
||||
return fmt.Errorf("generation required")
|
||||
key, err := litestream.WALSegmentPath(c.Path, pos.Generation, pos.Index, pos.Offset)
|
||||
if err != nil {
|
||||
return fmt.Errorf("cannot determine wal segment path: %w", err)
|
||||
}
|
||||
|
||||
key := path.Join(c.Path, "generations", pos.Generation, "wal", litestream.FormatIndex(pos.Index), litestream.FormatOffset(pos.Offset)+".wal.lz4")
|
||||
if err := c.bkt.Object(key).Delete(ctx); err != nil && !isNotExists(err) {
|
||||
return fmt.Errorf("cannot delete wal segment %q: %w", key, err)
|
||||
}
|
||||
@@ -336,7 +344,7 @@ func (itr *snapshotIterator) Next() bool {
|
||||
}
|
||||
|
||||
// Parse index, otherwise skip to the next object.
|
||||
index, err := internal.ParseSnapshotPath(path.Base(attrs.Name))
|
||||
index, err := litestream.ParseSnapshotPath(path.Base(attrs.Name))
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
@@ -358,17 +366,15 @@ func (itr *snapshotIterator) Snapshot() litestream.SnapshotInfo { return itr.inf
|
||||
|
||||
type walSegmentIterator struct {
|
||||
generation string
|
||||
prefix string
|
||||
|
||||
it *storage.ObjectIterator
|
||||
info litestream.WALSegmentInfo
|
||||
err error
|
||||
}
|
||||
|
||||
func newWALSegmentIterator(generation, prefix string, it *storage.ObjectIterator) *walSegmentIterator {
|
||||
func newWALSegmentIterator(generation string, it *storage.ObjectIterator) *walSegmentIterator {
|
||||
return &walSegmentIterator{
|
||||
generation: generation,
|
||||
prefix: prefix,
|
||||
it: it,
|
||||
}
|
||||
}
|
||||
@@ -394,7 +400,7 @@ func (itr *walSegmentIterator) Next() bool {
|
||||
}
|
||||
|
||||
// Parse index & offset, otherwise skip to the next object.
|
||||
index, offset, err := internal.ParseWALSegmentPath(strings.TrimPrefix(attrs.Name, itr.prefix))
|
||||
index, offset, err := litestream.ParseWALSegmentPath(path.Base(attrs.Name))
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
|
||||
@@ -1,11 +1,8 @@
|
||||
package internal
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"regexp"
|
||||
"strconv"
|
||||
"syscall"
|
||||
|
||||
"github.com/prometheus/client_golang/prometheus"
|
||||
@@ -39,39 +36,6 @@ func (r *ReadCloser) Close() error {
|
||||
return r.c.Close()
|
||||
}
|
||||
|
||||
// MultiReadCloser is a logical concatenation of io.ReadCloser.
|
||||
// It works like io.MultiReader except all objects are closed when Close() is called.
|
||||
type MultiReadCloser struct {
|
||||
mr io.Reader
|
||||
closers []io.Closer
|
||||
}
|
||||
|
||||
// NewMultiReadCloser returns a new instance of MultiReadCloser.
|
||||
func NewMultiReadCloser(a []io.ReadCloser) *MultiReadCloser {
|
||||
readers := make([]io.Reader, len(a))
|
||||
closers := make([]io.Closer, len(a))
|
||||
for i, rc := range a {
|
||||
readers[i] = rc
|
||||
closers[i] = rc
|
||||
}
|
||||
return &MultiReadCloser{mr: io.MultiReader(readers...), closers: closers}
|
||||
}
|
||||
|
||||
// Read reads from the next available reader.
|
||||
func (mrc *MultiReadCloser) Read(p []byte) (n int, err error) {
|
||||
return mrc.mr.Read(p)
|
||||
}
|
||||
|
||||
// Close closes all underlying ReadClosers and returns first error encountered.
|
||||
func (mrc *MultiReadCloser) Close() (err error) {
|
||||
for _, c := range mrc.closers {
|
||||
if e := c.Close(); e != nil && err == nil {
|
||||
err = e
|
||||
}
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
// ReadCounter wraps an io.Reader and counts the total number of bytes read.
|
||||
type ReadCounter struct {
|
||||
r io.Reader
|
||||
@@ -163,33 +127,6 @@ func MkdirAll(path string, fi os.FileInfo) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// ParseSnapshotPath parses the index from a snapshot filename. Used by path-based replicas.
|
||||
func ParseSnapshotPath(s string) (index int, err error) {
|
||||
a := snapshotPathRegex.FindStringSubmatch(s)
|
||||
if a == nil {
|
||||
return 0, fmt.Errorf("invalid snapshot path")
|
||||
}
|
||||
|
||||
i64, _ := strconv.ParseUint(a[1], 16, 64)
|
||||
return int(i64), nil
|
||||
}
|
||||
|
||||
var snapshotPathRegex = regexp.MustCompile(`^([0-9a-f]{8})\.snapshot\.lz4$`)
|
||||
|
||||
// ParseWALSegmentPath parses the index/offset from a segment filename. Used by path-based replicas.
|
||||
func ParseWALSegmentPath(s string) (index int, offset int64, err error) {
|
||||
a := walSegmentPathRegex.FindStringSubmatch(s)
|
||||
if a == nil {
|
||||
return 0, 0, fmt.Errorf("invalid wal segment path")
|
||||
}
|
||||
|
||||
i64, _ := strconv.ParseUint(a[1], 16, 64)
|
||||
off64, _ := strconv.ParseUint(a[2], 16, 64)
|
||||
return int(i64), int64(off64), nil
|
||||
}
|
||||
|
||||
var walSegmentPathRegex = regexp.MustCompile(`^([0-9a-f]{8})\/([0-9a-f]{8})\.wal\.lz4$`)
|
||||
|
||||
// Shared replica metrics.
|
||||
var (
|
||||
OperationTotalCounterVec = promauto.NewCounterVec(prometheus.CounterOpts{
|
||||
|
||||
@@ -1,61 +0,0 @@
|
||||
package internal_test
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"reflect"
|
||||
"testing"
|
||||
|
||||
"github.com/benbjohnson/litestream/internal"
|
||||
)
|
||||
|
||||
func TestParseSnapshotPath(t *testing.T) {
|
||||
for _, tt := range []struct {
|
||||
s string
|
||||
index int
|
||||
err error
|
||||
}{
|
||||
{"00bc614e.snapshot.lz4", 12345678, nil},
|
||||
{"xxxxxxxx.snapshot.lz4", 0, fmt.Errorf("invalid snapshot path")},
|
||||
{"00bc614.snapshot.lz4", 0, fmt.Errorf("invalid snapshot path")},
|
||||
{"00bc614e.snapshot.lz", 0, fmt.Errorf("invalid snapshot path")},
|
||||
{"00bc614e.snapshot", 0, fmt.Errorf("invalid snapshot path")},
|
||||
{"00bc614e", 0, fmt.Errorf("invalid snapshot path")},
|
||||
{"", 0, fmt.Errorf("invalid snapshot path")},
|
||||
} {
|
||||
t.Run("", func(t *testing.T) {
|
||||
index, err := internal.ParseSnapshotPath(tt.s)
|
||||
if got, want := index, tt.index; got != want {
|
||||
t.Errorf("index=%#v, want %#v", got, want)
|
||||
} else if got, want := err, tt.err; !reflect.DeepEqual(got, want) {
|
||||
t.Errorf("err=%#v, want %#v", got, want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseWALSegmentPath(t *testing.T) {
|
||||
for _, tt := range []struct {
|
||||
s string
|
||||
index int
|
||||
offset int64
|
||||
err error
|
||||
}{
|
||||
{"00bc614e/000003e8.wal.lz4", 12345678, 1000, nil},
|
||||
{"00000000/00000000.wal", 0, 0, fmt.Errorf("invalid wal segment path")},
|
||||
{"00000000/00000000", 0, 0, fmt.Errorf("invalid wal segment path")},
|
||||
{"00000000/", 0, 0, fmt.Errorf("invalid wal segment path")},
|
||||
{"00000000", 0, 0, fmt.Errorf("invalid wal segment path")},
|
||||
{"", 0, 0, fmt.Errorf("invalid wal segment path")},
|
||||
} {
|
||||
t.Run("", func(t *testing.T) {
|
||||
index, offset, err := internal.ParseWALSegmentPath(tt.s)
|
||||
if got, want := index, tt.index; got != want {
|
||||
t.Errorf("index=%#v, want %#v", got, want)
|
||||
} else if got, want := offset, tt.offset; got != want {
|
||||
t.Errorf("offset=%#v, want %#v", got, want)
|
||||
} else if got, want := err, tt.err; !reflect.DeepEqual(got, want) {
|
||||
t.Errorf("err=%#v, want %#v", got, want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
172
litestream.go
172
litestream.go
@@ -7,7 +7,9 @@ import (
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"path"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
@@ -40,14 +42,6 @@ var (
|
||||
ErrChecksumMismatch = errors.New("invalid replica, checksum mismatch")
|
||||
)
|
||||
|
||||
var (
|
||||
// LogWriter is the destination writer for all logging.
|
||||
LogWriter = os.Stderr
|
||||
|
||||
// LogFlags are the flags passed to log.New().
|
||||
LogFlags = 0
|
||||
)
|
||||
|
||||
// SnapshotIterator represents an iterator over a collection of snapshot metadata.
|
||||
type SnapshotIterator interface {
|
||||
io.Closer
|
||||
@@ -213,11 +207,13 @@ func FilterSnapshotsAfter(a []SnapshotInfo, t time.Time) []SnapshotInfo {
|
||||
// FindMinSnapshotByGeneration finds the snapshot with the lowest index in a generation.
|
||||
func FindMinSnapshotByGeneration(a []SnapshotInfo, generation string) *SnapshotInfo {
|
||||
var min *SnapshotInfo
|
||||
for _, snapshot := range a {
|
||||
for i := range a {
|
||||
snapshot := &a[i]
|
||||
|
||||
if snapshot.Generation != generation {
|
||||
continue
|
||||
} else if min == nil || snapshot.Index < min.Index {
|
||||
min = &snapshot
|
||||
min = snapshot
|
||||
}
|
||||
}
|
||||
return min
|
||||
@@ -299,26 +295,6 @@ func (p Pos) Truncate() Pos {
|
||||
return Pos{Generation: p.Generation, Index: p.Index}
|
||||
}
|
||||
|
||||
// ComparePos returns -1 if a is less than b, 1 if a is greater than b, and
|
||||
// returns 0 if a and b are equal. Only index & offset are compared.
|
||||
// Returns an error if generations are not equal.
|
||||
func ComparePos(a, b Pos) (int, error) {
|
||||
if a.Generation != b.Generation {
|
||||
return 0, fmt.Errorf("generation mismatch")
|
||||
}
|
||||
|
||||
if a.Index < b.Index {
|
||||
return -1, nil
|
||||
} else if a.Index > b.Index {
|
||||
return 1, nil
|
||||
} else if a.Offset < b.Offset {
|
||||
return -1, nil
|
||||
} else if a.Offset > b.Offset {
|
||||
return 1, nil
|
||||
}
|
||||
return 0, nil
|
||||
}
|
||||
|
||||
// Checksum computes a running SQLite checksum over a byte slice.
|
||||
func Checksum(bo binary.ByteOrder, s0, s1 uint32, b []byte) (uint32, uint32) {
|
||||
assert(len(b)%8 == 0, "misaligned checksum byte slice")
|
||||
@@ -410,34 +386,134 @@ func IsGenerationName(s string) bool {
|
||||
return true
|
||||
}
|
||||
|
||||
// FormatIndex formats an index as an 8-character hex value.
|
||||
func FormatIndex(index int) string {
|
||||
return fmt.Sprintf("%08x", index)
|
||||
// GenerationsPath returns the path to a generation root directory.
|
||||
func GenerationsPath(root string) string {
|
||||
return path.Join(root, "generations")
|
||||
}
|
||||
|
||||
// ParseIndex parses a hex-formatted index into an integer.
|
||||
func ParseIndex(s string) (int, error) {
|
||||
v, err := strconv.ParseUint(s, 16, 32)
|
||||
// GenerationPath returns the path to a generation's root directory.
|
||||
func GenerationPath(root, generation string) (string, error) {
|
||||
dir := GenerationsPath(root)
|
||||
if generation == "" {
|
||||
return "", fmt.Errorf("generation required")
|
||||
}
|
||||
return path.Join(dir, generation), nil
|
||||
}
|
||||
|
||||
// SnapshotsPath returns the path to a generation's snapshot directory.
|
||||
func SnapshotsPath(root, generation string) (string, error) {
|
||||
dir, err := GenerationPath(root, generation)
|
||||
if err != nil {
|
||||
return -1, fmt.Errorf("cannot parse index: %q", s)
|
||||
return "", err
|
||||
}
|
||||
return int(v), nil
|
||||
return path.Join(dir, "snapshots"), nil
|
||||
}
|
||||
|
||||
// FormatOffset formats an offset as an 8-character hex value.
|
||||
func FormatOffset(offset int64) string {
|
||||
return fmt.Sprintf("%08x", offset)
|
||||
}
|
||||
|
||||
// ParseOffset parses a hex-formatted offset into an integer.
|
||||
func ParseOffset(s string) (int64, error) {
|
||||
v, err := strconv.ParseInt(s, 16, 32)
|
||||
// SnapshotPath returns the path to an uncompressed snapshot file.
|
||||
func SnapshotPath(root, generation string, index int) (string, error) {
|
||||
dir, err := SnapshotsPath(root, generation)
|
||||
if err != nil {
|
||||
return -1, fmt.Errorf("cannot parse index: %q", s)
|
||||
return "", err
|
||||
}
|
||||
return v, nil
|
||||
return path.Join(dir, FormatSnapshotPath(index)), nil
|
||||
}
|
||||
|
||||
// WALPath returns the path to a generation's WAL directory
|
||||
func WALPath(root, generation string) (string, error) {
|
||||
dir, err := GenerationPath(root, generation)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return path.Join(dir, "wal"), nil
|
||||
}
|
||||
|
||||
// WALSegmentPath returns the path to a WAL segment file.
|
||||
func WALSegmentPath(root, generation string, index int, offset int64) (string, error) {
|
||||
dir, err := WALPath(root, generation)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return path.Join(dir, FormatWALSegmentPath(index, offset)), nil
|
||||
}
|
||||
|
||||
// IsSnapshotPath returns true if s is a path to a snapshot file.
|
||||
func IsSnapshotPath(s string) bool {
|
||||
return snapshotPathRegex.MatchString(s)
|
||||
}
|
||||
|
||||
// ParseSnapshotPath returns the index for the snapshot.
|
||||
// Returns an error if the path is not a valid snapshot path.
|
||||
func ParseSnapshotPath(s string) (index int, err error) {
|
||||
s = filepath.Base(s)
|
||||
|
||||
a := snapshotPathRegex.FindStringSubmatch(s)
|
||||
if a == nil {
|
||||
return 0, fmt.Errorf("invalid snapshot path: %s", s)
|
||||
}
|
||||
|
||||
i64, _ := strconv.ParseUint(a[1], 16, 64)
|
||||
return int(i64), nil
|
||||
}
|
||||
|
||||
// FormatSnapshotPath formats a snapshot filename with a given index.
|
||||
func FormatSnapshotPath(index int) string {
|
||||
assert(index >= 0, "snapshot index must be non-negative")
|
||||
return fmt.Sprintf("%08x%s", index, SnapshotExt)
|
||||
}
|
||||
|
||||
var snapshotPathRegex = regexp.MustCompile(`^([0-9a-f]{8})\.snapshot\.lz4$`)
|
||||
|
||||
// IsWALPath returns true if s is a path to a WAL file.
|
||||
func IsWALPath(s string) bool {
|
||||
return walPathRegex.MatchString(s)
|
||||
}
|
||||
|
||||
// ParseWALPath returns the index for the WAL file.
|
||||
// Returns an error if the path is not a valid WAL path.
|
||||
func ParseWALPath(s string) (index int, err error) {
|
||||
s = filepath.Base(s)
|
||||
|
||||
a := walPathRegex.FindStringSubmatch(s)
|
||||
if a == nil {
|
||||
return 0, fmt.Errorf("invalid wal path: %s", s)
|
||||
}
|
||||
|
||||
i64, _ := strconv.ParseUint(a[1], 16, 64)
|
||||
return int(i64), nil
|
||||
}
|
||||
|
||||
// FormatWALPath formats a WAL filename with a given index.
|
||||
func FormatWALPath(index int) string {
|
||||
assert(index >= 0, "wal index must be non-negative")
|
||||
return fmt.Sprintf("%08x%s", index, WALExt)
|
||||
}
|
||||
|
||||
var walPathRegex = regexp.MustCompile(`^([0-9a-f]{8})\.wal$`)
|
||||
|
||||
// ParseWALSegmentPath returns the index & offset for the WAL segment file.
|
||||
// Returns an error if the path is not a valid wal segment path.
|
||||
func ParseWALSegmentPath(s string) (index int, offset int64, err error) {
|
||||
s = filepath.Base(s)
|
||||
|
||||
a := walSegmentPathRegex.FindStringSubmatch(s)
|
||||
if a == nil {
|
||||
return 0, 0, fmt.Errorf("invalid wal segment path: %s", s)
|
||||
}
|
||||
|
||||
i64, _ := strconv.ParseUint(a[1], 16, 64)
|
||||
off64, _ := strconv.ParseUint(a[2], 16, 64)
|
||||
return int(i64), int64(off64), nil
|
||||
}
|
||||
|
||||
// FormatWALSegmentPath formats a WAL segment filename with a given index & offset.
|
||||
func FormatWALSegmentPath(index int, offset int64) string {
|
||||
assert(index >= 0, "wal index must be non-negative")
|
||||
assert(offset >= 0, "wal offset must be non-negative")
|
||||
return fmt.Sprintf("%08x_%08x%s", index, offset, WALSegmentExt)
|
||||
}
|
||||
|
||||
var walSegmentPathRegex = regexp.MustCompile(`^([0-9a-f]{8})(?:_([0-9a-f]{8}))\.wal\.lz4$`)
|
||||
|
||||
// isHexChar returns true if ch is a lowercase hex character.
|
||||
func isHexChar(ch rune) bool {
|
||||
return (ch >= '0' && ch <= '9') || (ch >= 'a' && ch <= 'f')
|
||||
|
||||
@@ -40,6 +40,104 @@ func TestChecksum(t *testing.T) {
|
||||
})
|
||||
}
|
||||
|
||||
func TestGenerationsPath(t *testing.T) {
|
||||
t.Run("OK", func(t *testing.T) {
|
||||
if got, want := litestream.GenerationsPath("foo"), "foo/generations"; got != want {
|
||||
t.Fatalf("GenerationsPath()=%v, want %v", got, want)
|
||||
}
|
||||
})
|
||||
t.Run("NoPath", func(t *testing.T) {
|
||||
if got, want := litestream.GenerationsPath(""), "generations"; got != want {
|
||||
t.Fatalf("GenerationsPath()=%v, want %v", got, want)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestGenerationPath(t *testing.T) {
|
||||
t.Run("OK", func(t *testing.T) {
|
||||
if got, err := litestream.GenerationPath("foo", "0123456701234567"); err != nil {
|
||||
t.Fatal(err)
|
||||
} else if want := "foo/generations/0123456701234567"; got != want {
|
||||
t.Fatalf("GenerationPath()=%v, want %v", got, want)
|
||||
}
|
||||
})
|
||||
t.Run("ErrNoGeneration", func(t *testing.T) {
|
||||
if _, err := litestream.GenerationPath("foo", ""); err == nil || err.Error() != `generation required` {
|
||||
t.Fatalf("expected error: %v", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestSnapshotsPath(t *testing.T) {
|
||||
t.Run("OK", func(t *testing.T) {
|
||||
if got, err := litestream.SnapshotsPath("foo", "0123456701234567"); err != nil {
|
||||
t.Fatal(err)
|
||||
} else if want := "foo/generations/0123456701234567/snapshots"; got != want {
|
||||
t.Fatalf("SnapshotsPath()=%v, want %v", got, want)
|
||||
}
|
||||
})
|
||||
t.Run("ErrNoGeneration", func(t *testing.T) {
|
||||
if _, err := litestream.SnapshotsPath("foo", ""); err == nil || err.Error() != `generation required` {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestSnapshotPath(t *testing.T) {
|
||||
t.Run("OK", func(t *testing.T) {
|
||||
if got, err := litestream.SnapshotPath("foo", "0123456701234567", 1000); err != nil {
|
||||
t.Fatal(err)
|
||||
} else if want := "foo/generations/0123456701234567/snapshots/000003e8.snapshot.lz4"; got != want {
|
||||
t.Fatalf("SnapshotPath()=%v, want %v", got, want)
|
||||
}
|
||||
})
|
||||
t.Run("ErrNoGeneration", func(t *testing.T) {
|
||||
if _, err := litestream.SnapshotPath("foo", "", 1000); err == nil || err.Error() != `generation required` {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestWALPath(t *testing.T) {
|
||||
t.Run("OK", func(t *testing.T) {
|
||||
if got, err := litestream.WALPath("foo", "0123456701234567"); err != nil {
|
||||
t.Fatal(err)
|
||||
} else if want := "foo/generations/0123456701234567/wal"; got != want {
|
||||
t.Fatalf("WALPath()=%v, want %v", got, want)
|
||||
}
|
||||
})
|
||||
t.Run("ErrNoGeneration", func(t *testing.T) {
|
||||
if _, err := litestream.WALPath("foo", ""); err == nil || err.Error() != `generation required` {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestWALSegmentPath(t *testing.T) {
|
||||
t.Run("OK", func(t *testing.T) {
|
||||
if got, err := litestream.WALSegmentPath("foo", "0123456701234567", 1000, 1001); err != nil {
|
||||
t.Fatal(err)
|
||||
} else if want := "foo/generations/0123456701234567/wal/000003e8_000003e9.wal.lz4"; got != want {
|
||||
t.Fatalf("WALPath()=%v, want %v", got, want)
|
||||
}
|
||||
})
|
||||
t.Run("ErrNoGeneration", func(t *testing.T) {
|
||||
if _, err := litestream.WALSegmentPath("foo", "", 1000, 0); err == nil || err.Error() != `generation required` {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestFindMinSnapshotByGeneration(t *testing.T) {
|
||||
infos := []litestream.SnapshotInfo{
|
||||
{Generation: "29cf4bced74e92ab", Index: 0},
|
||||
{Generation: "5dfeb4aa03232553", Index: 24},
|
||||
}
|
||||
if got, want := litestream.FindMinSnapshotByGeneration(infos, "29cf4bced74e92ab"), &infos[0]; got != want {
|
||||
t.Fatalf("info=%#v, want %#v", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
func MustDecodeHexString(s string) []byte {
|
||||
b, err := hex.DecodeString(s)
|
||||
if err != nil {
|
||||
|
||||
207
replica.go
207
replica.go
@@ -2,6 +2,7 @@ package litestream
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/binary"
|
||||
"fmt"
|
||||
"hash/crc64"
|
||||
"io"
|
||||
@@ -66,8 +67,6 @@ type Replica struct {
|
||||
// If true, replica monitors database for changes automatically.
|
||||
// Set to false if replica is being used synchronously (such as in tests).
|
||||
MonitorEnabled bool
|
||||
|
||||
Logger *log.Logger
|
||||
}
|
||||
|
||||
func NewReplica(db *DB, name string) *Replica {
|
||||
@@ -82,12 +81,6 @@ func NewReplica(db *DB, name string) *Replica {
|
||||
MonitorEnabled: true,
|
||||
}
|
||||
|
||||
prefix := fmt.Sprintf("%s: ", r.Name())
|
||||
if db != nil {
|
||||
prefix = fmt.Sprintf("%s(%s): ", db.Path(), r.Name())
|
||||
}
|
||||
r.Logger = log.New(LogWriter, prefix, LogFlags)
|
||||
|
||||
return r
|
||||
}
|
||||
|
||||
@@ -156,12 +149,19 @@ func (r *Replica) Sync(ctx context.Context) (err error) {
|
||||
}()
|
||||
|
||||
// Find current position of database.
|
||||
dpos := r.db.Pos()
|
||||
if dpos.IsZero() {
|
||||
dpos, err := r.db.Pos()
|
||||
if err != nil {
|
||||
return fmt.Errorf("cannot determine current generation: %w", err)
|
||||
} else if dpos.IsZero() {
|
||||
return fmt.Errorf("no generation, waiting for data")
|
||||
}
|
||||
generation := dpos.Generation
|
||||
|
||||
Tracef("%s(%s): replica sync: db.pos=%s", r.db.Path(), r.Name(), dpos)
|
||||
|
||||
// Create a new snapshot and update the current replica position if
|
||||
// the generation on the database has changed.
|
||||
if r.Pos().Generation != generation {
|
||||
// Create snapshot if no snapshots exist for generation.
|
||||
snapshotN, err := r.snapshotN(generation)
|
||||
if err != nil {
|
||||
@@ -172,151 +172,124 @@ func (r *Replica) Sync(ctx context.Context) (err error) {
|
||||
} else if info.Generation != generation {
|
||||
return fmt.Errorf("generation changed during snapshot, exiting sync")
|
||||
}
|
||||
snapshotN = 1
|
||||
}
|
||||
replicaSnapshotTotalGaugeVec.WithLabelValues(r.db.Path(), r.Name()).Set(float64(snapshotN))
|
||||
|
||||
// Determine position, if necessary.
|
||||
if r.Pos().Generation != generation {
|
||||
pos, err := r.calcPos(ctx, generation)
|
||||
if err != nil {
|
||||
return fmt.Errorf("cannot determine replica position: %s", err)
|
||||
}
|
||||
|
||||
Tracef("%s(%s): replica sync: calc new pos: %s", r.db.Path(), r.Name(), pos)
|
||||
r.mu.Lock()
|
||||
r.pos = pos
|
||||
r.mu.Unlock()
|
||||
}
|
||||
|
||||
// Read all WAL files since the last position.
|
||||
if err = r.syncWAL(ctx); err != nil {
|
||||
for {
|
||||
if err = r.syncWAL(ctx); err == io.EOF {
|
||||
break
|
||||
} else if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *Replica) syncWAL(ctx context.Context) (err error) {
|
||||
pos := r.Pos()
|
||||
|
||||
itr, err := r.db.WALSegments(ctx, pos.Generation)
|
||||
if err != nil {
|
||||
rd, err := r.db.ShadowWALReader(r.Pos())
|
||||
if err == io.EOF {
|
||||
return err
|
||||
} else if err != nil {
|
||||
return fmt.Errorf("replica wal reader: %w", err)
|
||||
}
|
||||
defer itr.Close()
|
||||
|
||||
// Group segments by index.
|
||||
var segments [][]WALSegmentInfo
|
||||
for itr.Next() {
|
||||
info := itr.WALSegment()
|
||||
if cmp, err := ComparePos(pos, info.Pos()); err != nil {
|
||||
return fmt.Errorf("compare pos: %w", err)
|
||||
} else if cmp == 1 {
|
||||
continue // already processed, skip
|
||||
}
|
||||
|
||||
// Start a new chunk if index has changed.
|
||||
if len(segments) == 0 || segments[len(segments)-1][0].Index != info.Index {
|
||||
segments = append(segments, []WALSegmentInfo{info})
|
||||
continue
|
||||
}
|
||||
|
||||
// Add segment to the end of the current index, if matching.
|
||||
segments[len(segments)-1] = append(segments[len(segments)-1], info)
|
||||
}
|
||||
|
||||
// Write out segments to replica by index so they can be combined.
|
||||
for i := range segments {
|
||||
if err := r.writeIndexSegments(ctx, segments[i]); err != nil {
|
||||
return fmt.Errorf("write index segments: index=%d err=%w", segments[i][0].Index, err)
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *Replica) writeIndexSegments(ctx context.Context, segments []WALSegmentInfo) (err error) {
|
||||
assert(len(segments) > 0, "segments required for replication")
|
||||
|
||||
// First segment position must be equal to last replica position or
|
||||
// the start of the next index.
|
||||
if pos := r.Pos(); pos != segments[0].Pos() {
|
||||
nextIndexPos := pos.Truncate()
|
||||
nextIndexPos.Index++
|
||||
if nextIndexPos != segments[0].Pos() {
|
||||
return fmt.Errorf("replica skipped position: replica=%s initial=%s", pos, segments[0].Pos())
|
||||
}
|
||||
}
|
||||
|
||||
pos := segments[0].Pos()
|
||||
initialPos := pos
|
||||
defer rd.Close()
|
||||
|
||||
// Copy shadow WAL to client write via io.Pipe().
|
||||
pr, pw := io.Pipe()
|
||||
defer func() { _ = pw.CloseWithError(err) }()
|
||||
|
||||
// Obtain initial position from shadow reader.
|
||||
// It may have moved to the next index if previous position was at the end.
|
||||
pos := rd.Pos()
|
||||
|
||||
// Copy through pipe into client from the starting position.
|
||||
var g errgroup.Group
|
||||
g.Go(func() error {
|
||||
_, err := r.Client.WriteWALSegment(ctx, initialPos, pr)
|
||||
_, err := r.Client.WriteWALSegment(ctx, pos, pr)
|
||||
return err
|
||||
})
|
||||
|
||||
// Wrap writer to LZ4 compress.
|
||||
zw := lz4.NewWriter(pw)
|
||||
|
||||
// Write each segment out to the replica.
|
||||
for _, info := range segments {
|
||||
if err := func() error {
|
||||
// Ensure segments are in order and no bytes are skipped.
|
||||
if pos != info.Pos() {
|
||||
return fmt.Errorf("non-contiguous segment: expected=%s current=%s", pos, info.Pos())
|
||||
// Track total WAL bytes written to replica client.
|
||||
walBytesCounter := replicaWALBytesCounterVec.WithLabelValues(r.db.Path(), r.Name())
|
||||
|
||||
// Copy header if at offset zero.
|
||||
var psalt uint64 // previous salt value
|
||||
if pos := rd.Pos(); pos.Offset == 0 {
|
||||
buf := make([]byte, WALHeaderSize)
|
||||
if _, err := io.ReadFull(rd, buf); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
rc, err := r.db.WALSegmentReader(ctx, info.Pos())
|
||||
psalt = binary.BigEndian.Uint64(buf[16:24])
|
||||
|
||||
n, err := zw.Write(buf)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer rc.Close()
|
||||
walBytesCounter.Add(float64(n))
|
||||
}
|
||||
|
||||
n, err := io.Copy(zw, lz4.NewReader(rc))
|
||||
// Copy frames.
|
||||
for {
|
||||
pos := rd.Pos()
|
||||
assert(pos.Offset == frameAlign(pos.Offset, r.db.pageSize), "shadow wal reader not frame aligned")
|
||||
|
||||
buf := make([]byte, WALFrameHeaderSize+r.db.pageSize)
|
||||
if _, err := io.ReadFull(rd, buf); err == io.EOF {
|
||||
break
|
||||
} else if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Verify salt matches the previous frame/header read.
|
||||
salt := binary.BigEndian.Uint64(buf[8:16])
|
||||
if psalt != 0 && psalt != salt {
|
||||
return fmt.Errorf("replica salt mismatch: %s", pos.String())
|
||||
}
|
||||
psalt = salt
|
||||
|
||||
n, err := zw.Write(buf)
|
||||
if err != nil {
|
||||
return err
|
||||
} else if err := rc.Close(); err != nil {
|
||||
return err
|
||||
}
|
||||
walBytesCounter.Add(float64(n))
|
||||
}
|
||||
|
||||
// Track last position written.
|
||||
pos = info.Pos()
|
||||
pos.Offset += n
|
||||
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return fmt.Errorf("wal segment: pos=%s err=%w", info.Pos(), err)
|
||||
}
|
||||
}
|
||||
|
||||
// Flush LZ4 writer, close pipe, and wait for write to finish.
|
||||
// Flush LZ4 writer and close pipe.
|
||||
if err := zw.Close(); err != nil {
|
||||
return err
|
||||
} else if err := pw.Close(); err != nil {
|
||||
return err
|
||||
} else if err := g.Wait(); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Wait for client to finish write.
|
||||
if err := g.Wait(); err != nil {
|
||||
return fmt.Errorf("client write: %w", err)
|
||||
}
|
||||
|
||||
// Save last replicated position.
|
||||
r.mu.Lock()
|
||||
r.pos = pos
|
||||
r.pos = rd.Pos()
|
||||
r.mu.Unlock()
|
||||
|
||||
replicaWALBytesCounterVec.WithLabelValues(r.db.Path(), r.Name()).Add(float64(pos.Offset - initialPos.Offset))
|
||||
|
||||
// Track total WAL bytes written to replica client.
|
||||
replicaWALIndexGaugeVec.WithLabelValues(r.db.Path(), r.Name()).Set(float64(pos.Index))
|
||||
replicaWALOffsetGaugeVec.WithLabelValues(r.db.Path(), r.Name()).Set(float64(pos.Offset))
|
||||
|
||||
r.Logger.Printf("wal segment written: %s sz=%d", initialPos, pos.Offset-initialPos.Offset)
|
||||
// Track current position
|
||||
replicaWALIndexGaugeVec.WithLabelValues(r.db.Path(), r.Name()).Set(float64(rd.Pos().Index))
|
||||
replicaWALOffsetGaugeVec.WithLabelValues(r.db.Path(), r.Name()).Set(float64(rd.Pos().Offset))
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -474,8 +447,10 @@ func (r *Replica) Snapshot(ctx context.Context) (info SnapshotInfo, err error) {
|
||||
defer func() { _ = tx.Rollback() }()
|
||||
|
||||
// Obtain current position.
|
||||
pos := r.db.Pos()
|
||||
if pos.IsZero() {
|
||||
pos, err := r.db.Pos()
|
||||
if err != nil {
|
||||
return info, fmt.Errorf("cannot determine db position: %w", err)
|
||||
} else if pos.IsZero() {
|
||||
return info, ErrNoGeneration
|
||||
}
|
||||
|
||||
@@ -515,7 +490,7 @@ func (r *Replica) Snapshot(ctx context.Context) (info SnapshotInfo, err error) {
|
||||
return info, err
|
||||
}
|
||||
|
||||
log.Printf("snapshot written %s/%08x", pos.Generation, pos.Index)
|
||||
log.Printf("%s(%s): snapshot written %s/%08x", r.db.Path(), r.Name(), pos.Generation, pos.Index)
|
||||
|
||||
return info, nil
|
||||
}
|
||||
@@ -583,7 +558,7 @@ func (r *Replica) deleteSnapshotsBeforeIndex(ctx context.Context, generation str
|
||||
if err := r.Client.DeleteSnapshot(ctx, info.Generation, info.Index); err != nil {
|
||||
return fmt.Errorf("delete snapshot %s/%08x: %w", info.Generation, info.Index, err)
|
||||
}
|
||||
r.Logger.Printf("snapshot deleted %s/%08x", generation, index)
|
||||
log.Printf("%s(%s): snapshot deleted %s/%08x", r.db.Path(), r.Name(), generation, index)
|
||||
}
|
||||
|
||||
return itr.Close()
|
||||
@@ -615,10 +590,7 @@ func (r *Replica) deleteWALSegmentsBeforeIndex(ctx context.Context, generation s
|
||||
if err := r.Client.DeleteWALSegments(ctx, a); err != nil {
|
||||
return fmt.Errorf("delete wal segments: %w", err)
|
||||
}
|
||||
|
||||
for _, pos := range a {
|
||||
r.Logger.Printf("wal segmented deleted: %s", pos)
|
||||
}
|
||||
log.Printf("%s(%s): wal segmented deleted before %s/%08x: n=%d", r.db.Path(), r.Name(), generation, index, len(a))
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -655,7 +627,7 @@ func (r *Replica) monitor(ctx context.Context) {
|
||||
|
||||
// Synchronize the shadow wal into the replication directory.
|
||||
if err := r.Sync(ctx); err != nil {
|
||||
r.Logger.Printf("monitor error: %s", err)
|
||||
log.Printf("%s(%s): monitor error: %s", r.db.Path(), r.Name(), err)
|
||||
continue
|
||||
}
|
||||
}
|
||||
@@ -683,7 +655,7 @@ func (r *Replica) retainer(ctx context.Context) {
|
||||
return
|
||||
case <-ticker.C:
|
||||
if err := r.EnforceRetention(ctx); err != nil {
|
||||
r.Logger.Printf("retainer error: %s", err)
|
||||
log.Printf("%s(%s): retainer error: %s", r.db.Path(), r.Name(), err)
|
||||
continue
|
||||
}
|
||||
}
|
||||
@@ -705,7 +677,7 @@ func (r *Replica) snapshotter(ctx context.Context) {
|
||||
return
|
||||
case <-ticker.C:
|
||||
if _, err := r.Snapshot(ctx); err != nil && err != ErrNoGeneration {
|
||||
r.Logger.Printf("snapshotter error: %s", err)
|
||||
log.Printf("%s(%s): snapshotter error: %s", r.db.Path(), r.Name(), err)
|
||||
continue
|
||||
}
|
||||
}
|
||||
@@ -733,7 +705,7 @@ func (r *Replica) validator(ctx context.Context) {
|
||||
return
|
||||
case <-ticker.C:
|
||||
if err := r.Validate(ctx); err != nil {
|
||||
r.Logger.Printf("validation error: %s", err)
|
||||
log.Printf("%s(%s): validation error: %s", r.db.Path(), r.Name(), err)
|
||||
continue
|
||||
}
|
||||
}
|
||||
@@ -795,7 +767,7 @@ func (r *Replica) Validate(ctx context.Context) error {
|
||||
if mismatch {
|
||||
status = "mismatch"
|
||||
}
|
||||
r.Logger.Printf("validator: status=%s db=%016x replica=%016x pos=%s", status, chksum0, chksum1, pos)
|
||||
log.Printf("%s(%s): validator: status=%s db=%016x replica=%016x pos=%s", db.Path(), r.Name(), status, chksum0, chksum1, pos)
|
||||
|
||||
// Validate checksums match.
|
||||
if mismatch {
|
||||
@@ -813,6 +785,8 @@ func (r *Replica) Validate(ctx context.Context) error {
|
||||
|
||||
// waitForReplica blocks until replica reaches at least the given position.
|
||||
func (r *Replica) waitForReplica(ctx context.Context, pos Pos) error {
|
||||
db := r.DB()
|
||||
|
||||
ticker := time.NewTicker(500 * time.Millisecond)
|
||||
defer ticker.Stop()
|
||||
|
||||
@@ -835,7 +809,7 @@ func (r *Replica) waitForReplica(ctx context.Context, pos Pos) error {
|
||||
// Obtain current position of replica, check if past target position.
|
||||
curr := r.Pos()
|
||||
if curr.IsZero() {
|
||||
r.Logger.Printf("validator: no replica position available")
|
||||
log.Printf("%s(%s): validator: no replica position available", db.Path(), r.Name())
|
||||
continue
|
||||
}
|
||||
|
||||
@@ -1332,13 +1306,6 @@ func (r *Replica) downloadWAL(ctx context.Context, generation string, index int,
|
||||
|
||||
// Replica metrics.
|
||||
var (
|
||||
replicaSnapshotTotalGaugeVec = promauto.NewGaugeVec(prometheus.GaugeOpts{
|
||||
Namespace: "litestream",
|
||||
Subsystem: "replica",
|
||||
Name: "snapshot_total",
|
||||
Help: "The current number of snapshots",
|
||||
}, []string{"db", "name"})
|
||||
|
||||
replicaWALBytesCounterVec = promauto.NewCounterVec(prometheus.CounterOpts{
|
||||
Namespace: "litestream",
|
||||
Subsystem: "replica",
|
||||
|
||||
@@ -177,7 +177,7 @@ func TestReplicaClient_Snapshots(t *testing.T) {
|
||||
if err == nil {
|
||||
err = itr.Close()
|
||||
}
|
||||
if err == nil || err.Error() != `generation required` {
|
||||
if err == nil || err.Error() != `cannot determine snapshots path: generation required` {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
})
|
||||
@@ -204,7 +204,7 @@ func TestReplicaClient_WriteSnapshot(t *testing.T) {
|
||||
|
||||
RunWithReplicaClient(t, "ErrNoGeneration", func(t *testing.T, c litestream.ReplicaClient) {
|
||||
t.Parallel()
|
||||
if _, err := c.WriteSnapshot(context.Background(), "", 0, nil); err == nil || err.Error() != `generation required` {
|
||||
if _, err := c.WriteSnapshot(context.Background(), "", 0, nil); err == nil || err.Error() != `cannot determine snapshot path: generation required` {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
})
|
||||
@@ -242,13 +242,13 @@ func TestReplicaClient_SnapshotReader(t *testing.T) {
|
||||
RunWithReplicaClient(t, "ErrNoGeneration", func(t *testing.T, c litestream.ReplicaClient) {
|
||||
t.Parallel()
|
||||
|
||||
if _, err := c.SnapshotReader(context.Background(), "", 1); err == nil || err.Error() != `generation required` {
|
||||
if _, err := c.SnapshotReader(context.Background(), "", 1); err == nil || err.Error() != `cannot determine snapshot path: generation required` {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestReplicaClient_WALSegments(t *testing.T) {
|
||||
func TestReplicaClient_WALs(t *testing.T) {
|
||||
RunWithReplicaClient(t, "OK", func(t *testing.T, c litestream.ReplicaClient) {
|
||||
t.Parallel()
|
||||
|
||||
@@ -362,7 +362,7 @@ func TestReplicaClient_WALSegments(t *testing.T) {
|
||||
if err == nil {
|
||||
err = itr.Close()
|
||||
}
|
||||
if err == nil || err.Error() != `generation required` {
|
||||
if err == nil || err.Error() != `cannot determine wal path: generation required` {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
})
|
||||
@@ -389,13 +389,13 @@ func TestReplicaClient_WriteWALSegment(t *testing.T) {
|
||||
|
||||
RunWithReplicaClient(t, "ErrNoGeneration", func(t *testing.T, c litestream.ReplicaClient) {
|
||||
t.Parallel()
|
||||
if _, err := c.WriteWALSegment(context.Background(), litestream.Pos{Generation: "", Index: 0, Offset: 0}, nil); err == nil || err.Error() != `generation required` {
|
||||
if _, err := c.WriteWALSegment(context.Background(), litestream.Pos{Generation: "", Index: 0, Offset: 0}, nil); err == nil || err.Error() != `cannot determine wal segment path: generation required` {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestReplicaClient_WALSegmentReader(t *testing.T) {
|
||||
func TestReplicaClient_WALReader(t *testing.T) {
|
||||
|
||||
RunWithReplicaClient(t, "OK", func(t *testing.T, c litestream.ReplicaClient) {
|
||||
t.Parallel()
|
||||
@@ -451,7 +451,7 @@ func TestReplicaClient_DeleteWALSegments(t *testing.T) {
|
||||
|
||||
RunWithReplicaClient(t, "ErrNoGeneration", func(t *testing.T, c litestream.ReplicaClient) {
|
||||
t.Parallel()
|
||||
if err := c.DeleteWALSegments(context.Background(), []litestream.Pos{{}}); err == nil || err.Error() != `generation required` {
|
||||
if err := c.DeleteWALSegments(context.Background(), []litestream.Pos{{}}); err == nil || err.Error() != `cannot determine wal segment path: generation required` {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
})
|
||||
|
||||
@@ -43,7 +43,10 @@ func TestReplica_Sync(t *testing.T) {
|
||||
}
|
||||
|
||||
// Fetch current database position.
|
||||
dpos := db.Pos()
|
||||
dpos, err := db.Pos()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
c := file.NewReplicaClient(t.TempDir())
|
||||
r := litestream.NewReplica(db, "")
|
||||
@@ -66,11 +69,11 @@ func TestReplica_Sync(t *testing.T) {
|
||||
// Verify WAL matches replica WAL.
|
||||
if b0, err := os.ReadFile(db.Path() + "-wal"); err != nil {
|
||||
t.Fatal(err)
|
||||
} else if r0, err := c.WALSegmentReader(context.Background(), litestream.Pos{Generation: generations[0], Index: 0, Offset: 0}); err != nil {
|
||||
} else if r, err := c.WALSegmentReader(context.Background(), litestream.Pos{Generation: generations[0], Index: 0, Offset: 0}); err != nil {
|
||||
t.Fatal(err)
|
||||
} else if b1, err := io.ReadAll(lz4.NewReader(r0)); err != nil {
|
||||
} else if b1, err := io.ReadAll(lz4.NewReader(r)); err != nil {
|
||||
t.Fatal(err)
|
||||
} else if err := r0.Close(); err != nil {
|
||||
} else if err := r.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
} else if !bytes.Equal(b0, b1) {
|
||||
t.Fatalf("wal mismatch: len(%d), len(%d)", len(b0), len(b1))
|
||||
@@ -95,8 +98,10 @@ func TestReplica_Snapshot(t *testing.T) {
|
||||
}
|
||||
|
||||
// Fetch current database position & snapshot.
|
||||
pos0 := db.Pos()
|
||||
if info, err := r.Snapshot(context.Background()); err != nil {
|
||||
pos0, err := db.Pos()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
} else if info, err := r.Snapshot(context.Background()); err != nil {
|
||||
t.Fatal(err)
|
||||
} else if got, want := info.Pos(), pos0.Truncate(); got != want {
|
||||
t.Fatalf("pos=%s, want %s", got, want)
|
||||
@@ -117,8 +122,10 @@ func TestReplica_Snapshot(t *testing.T) {
|
||||
}
|
||||
|
||||
// Fetch current database position & snapshot.
|
||||
pos1 := db.Pos()
|
||||
if info, err := r.Snapshot(context.Background()); err != nil {
|
||||
pos1, err := db.Pos()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
} else if info, err := r.Snapshot(context.Background()); err != nil {
|
||||
t.Fatal(err)
|
||||
} else if got, want := info.Pos(), pos1.Truncate(); got != want {
|
||||
t.Fatalf("pos=%v, want %v", got, want)
|
||||
|
||||
@@ -10,7 +10,6 @@ import (
|
||||
"os"
|
||||
"path"
|
||||
"regexp"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
@@ -155,7 +154,7 @@ func (c *ReplicaClient) Generations(ctx context.Context) ([]string, error) {
|
||||
var generations []string
|
||||
if err := c.s3.ListObjectsPagesWithContext(ctx, &s3.ListObjectsInput{
|
||||
Bucket: aws.String(c.Bucket),
|
||||
Prefix: aws.String(path.Join(c.Path, "generations") + "/"),
|
||||
Prefix: aws.String(litestream.GenerationsPath(c.Path) + "/"),
|
||||
Delimiter: aws.String("/"),
|
||||
}, func(page *s3.ListObjectsOutput, lastPage bool) bool {
|
||||
internal.OperationTotalCounterVec.WithLabelValues(ReplicaClientType, "LIST").Inc()
|
||||
@@ -179,15 +178,18 @@ func (c *ReplicaClient) Generations(ctx context.Context) ([]string, error) {
|
||||
func (c *ReplicaClient) DeleteGeneration(ctx context.Context, generation string) error {
|
||||
if err := c.Init(ctx); err != nil {
|
||||
return err
|
||||
} else if generation == "" {
|
||||
return fmt.Errorf("generation required")
|
||||
}
|
||||
|
||||
dir, err := litestream.GenerationPath(c.Path, generation)
|
||||
if err != nil {
|
||||
return fmt.Errorf("cannot determine generation path: %w", err)
|
||||
}
|
||||
|
||||
// Collect all files for the generation.
|
||||
var objIDs []*s3.ObjectIdentifier
|
||||
if err := c.s3.ListObjectsPagesWithContext(ctx, &s3.ListObjectsInput{
|
||||
Bucket: aws.String(c.Bucket),
|
||||
Prefix: aws.String(path.Join(c.Path, "generations", generation)),
|
||||
Prefix: aws.String(dir),
|
||||
}, func(page *s3.ListObjectsOutput, lastPage bool) bool {
|
||||
internal.OperationTotalCounterVec.WithLabelValues(ReplicaClientType, "LIST").Inc()
|
||||
|
||||
@@ -234,11 +236,12 @@ func (c *ReplicaClient) Snapshots(ctx context.Context, generation string) (lites
|
||||
func (c *ReplicaClient) WriteSnapshot(ctx context.Context, generation string, index int, rd io.Reader) (info litestream.SnapshotInfo, err error) {
|
||||
if err := c.Init(ctx); err != nil {
|
||||
return info, err
|
||||
} else if generation == "" {
|
||||
return info, fmt.Errorf("generation required")
|
||||
}
|
||||
|
||||
key := path.Join(c.Path, "generations", generation, "snapshots", litestream.FormatIndex(index)+".snapshot.lz4")
|
||||
key, err := litestream.SnapshotPath(c.Path, generation, index)
|
||||
if err != nil {
|
||||
return info, fmt.Errorf("cannot determine snapshot path: %w", err)
|
||||
}
|
||||
startTime := time.Now()
|
||||
|
||||
rc := internal.NewReadCounter(rd)
|
||||
@@ -267,11 +270,12 @@ func (c *ReplicaClient) WriteSnapshot(ctx context.Context, generation string, in
|
||||
func (c *ReplicaClient) SnapshotReader(ctx context.Context, generation string, index int) (io.ReadCloser, error) {
|
||||
if err := c.Init(ctx); err != nil {
|
||||
return nil, err
|
||||
} else if generation == "" {
|
||||
return nil, fmt.Errorf("generation required")
|
||||
}
|
||||
|
||||
key := path.Join(c.Path, "generations", generation, "snapshots", litestream.FormatIndex(index)+".snapshot.lz4")
|
||||
key, err := litestream.SnapshotPath(c.Path, generation, index)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("cannot determine snapshot path: %w", err)
|
||||
}
|
||||
|
||||
out, err := c.s3.GetObjectWithContext(ctx, &s3.GetObjectInput{
|
||||
Bucket: aws.String(c.Bucket),
|
||||
@@ -292,11 +296,12 @@ func (c *ReplicaClient) SnapshotReader(ctx context.Context, generation string, i
|
||||
func (c *ReplicaClient) DeleteSnapshot(ctx context.Context, generation string, index int) error {
|
||||
if err := c.Init(ctx); err != nil {
|
||||
return err
|
||||
} else if generation == "" {
|
||||
return fmt.Errorf("generation required")
|
||||
}
|
||||
|
||||
key := path.Join(c.Path, "generations", generation, "snapshots", litestream.FormatIndex(index)+".snapshot.lz4")
|
||||
key, err := litestream.SnapshotPath(c.Path, generation, index)
|
||||
if err != nil {
|
||||
return fmt.Errorf("cannot determine snapshot path: %w", err)
|
||||
}
|
||||
|
||||
if _, err := c.s3.DeleteObjectsWithContext(ctx, &s3.DeleteObjectsInput{
|
||||
Bucket: aws.String(c.Bucket),
|
||||
@@ -321,11 +326,12 @@ func (c *ReplicaClient) WALSegments(ctx context.Context, generation string) (lit
|
||||
func (c *ReplicaClient) WriteWALSegment(ctx context.Context, pos litestream.Pos, rd io.Reader) (info litestream.WALSegmentInfo, err error) {
|
||||
if err := c.Init(ctx); err != nil {
|
||||
return info, err
|
||||
} else if pos.Generation == "" {
|
||||
return info, fmt.Errorf("generation required")
|
||||
}
|
||||
|
||||
key := path.Join(c.Path, "generations", pos.Generation, "wal", litestream.FormatIndex(pos.Index), litestream.FormatOffset(pos.Offset)+".wal.lz4")
|
||||
key, err := litestream.WALSegmentPath(c.Path, pos.Generation, pos.Index, pos.Offset)
|
||||
if err != nil {
|
||||
return info, fmt.Errorf("cannot determine wal segment path: %w", err)
|
||||
}
|
||||
startTime := time.Now()
|
||||
|
||||
rc := internal.NewReadCounter(rd)
|
||||
@@ -354,11 +360,12 @@ func (c *ReplicaClient) WriteWALSegment(ctx context.Context, pos litestream.Pos,
|
||||
func (c *ReplicaClient) WALSegmentReader(ctx context.Context, pos litestream.Pos) (io.ReadCloser, error) {
|
||||
if err := c.Init(ctx); err != nil {
|
||||
return nil, err
|
||||
} else if pos.Generation == "" {
|
||||
return nil, fmt.Errorf("generation required")
|
||||
}
|
||||
|
||||
key := path.Join(c.Path, "generations", pos.Generation, "wal", litestream.FormatIndex(pos.Index), litestream.FormatOffset(pos.Offset)+".wal.lz4")
|
||||
key, err := litestream.WALSegmentPath(c.Path, pos.Generation, pos.Index, pos.Offset)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("cannot determine wal segment path: %w", err)
|
||||
}
|
||||
|
||||
out, err := c.s3.GetObjectWithContext(ctx, &s3.GetObjectInput{
|
||||
Bucket: aws.String(c.Bucket),
|
||||
@@ -390,10 +397,10 @@ func (c *ReplicaClient) DeleteWALSegments(ctx context.Context, a []litestream.Po
|
||||
|
||||
// Generate a batch of object IDs for deleting the WAL segments.
|
||||
for i, pos := range a[:n] {
|
||||
if pos.Generation == "" {
|
||||
return fmt.Errorf("generation required")
|
||||
key, err := litestream.WALSegmentPath(c.Path, pos.Generation, pos.Index, pos.Offset)
|
||||
if err != nil {
|
||||
return fmt.Errorf("cannot determine wal segment path: %w", err)
|
||||
}
|
||||
key := path.Join(c.Path, "generations", pos.Generation, "wal", litestream.FormatIndex(pos.Index), litestream.FormatOffset(pos.Offset)+".wal.lz4")
|
||||
objIDs[i] = &s3.ObjectIdentifier{Key: &key}
|
||||
}
|
||||
|
||||
@@ -491,12 +498,11 @@ func newSnapshotIterator(ctx context.Context, client *ReplicaClient, generation
|
||||
func (itr *snapshotIterator) fetch() error {
|
||||
defer close(itr.ch)
|
||||
|
||||
if itr.generation == "" {
|
||||
return fmt.Errorf("generation required")
|
||||
dir, err := litestream.SnapshotsPath(itr.client.Path, itr.generation)
|
||||
if err != nil {
|
||||
return fmt.Errorf("cannot determine snapshots path: %w", err)
|
||||
}
|
||||
|
||||
dir := path.Join(itr.client.Path, "generations", itr.generation, "snapshots")
|
||||
|
||||
return itr.client.s3.ListObjectsPagesWithContext(itr.ctx, &s3.ListObjectsInput{
|
||||
Bucket: aws.String(itr.client.Bucket),
|
||||
Prefix: aws.String(dir + "/"),
|
||||
@@ -505,7 +511,8 @@ func (itr *snapshotIterator) fetch() error {
|
||||
internal.OperationTotalCounterVec.WithLabelValues(ReplicaClientType, "LIST").Inc()
|
||||
|
||||
for _, obj := range page.Contents {
|
||||
index, err := internal.ParseSnapshotPath(path.Base(*obj.Key))
|
||||
key := path.Base(*obj.Key)
|
||||
index, err := litestream.ParseSnapshotPath(key)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
@@ -594,20 +601,21 @@ func newWALSegmentIterator(ctx context.Context, client *ReplicaClient, generatio
|
||||
func (itr *walSegmentIterator) fetch() error {
|
||||
defer close(itr.ch)
|
||||
|
||||
if itr.generation == "" {
|
||||
return fmt.Errorf("generation required")
|
||||
dir, err := litestream.WALPath(itr.client.Path, itr.generation)
|
||||
if err != nil {
|
||||
return fmt.Errorf("cannot determine wal path: %w", err)
|
||||
}
|
||||
|
||||
prefix := path.Join(itr.client.Path, "generations", itr.generation, "wal") + "/"
|
||||
|
||||
return itr.client.s3.ListObjectsPagesWithContext(itr.ctx, &s3.ListObjectsInput{
|
||||
Bucket: aws.String(itr.client.Bucket),
|
||||
Prefix: aws.String(prefix),
|
||||
Prefix: aws.String(dir + "/"),
|
||||
Delimiter: aws.String("/"),
|
||||
}, func(page *s3.ListObjectsOutput, lastPage bool) bool {
|
||||
internal.OperationTotalCounterVec.WithLabelValues(ReplicaClientType, "LIST").Inc()
|
||||
|
||||
for _, obj := range page.Contents {
|
||||
index, offset, err := internal.ParseWALSegmentPath(strings.TrimPrefix(*obj.Key, prefix))
|
||||
key := path.Base(*obj.Key)
|
||||
index, offset, err := litestream.ParseWALSegmentPath(key)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
|
||||
@@ -9,7 +9,6 @@ import (
|
||||
"os"
|
||||
"path"
|
||||
"sort"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
@@ -122,7 +121,7 @@ func (c *ReplicaClient) Generations(ctx context.Context) (_ []string, err error)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
fis, err := sftpClient.ReadDir(path.Join(c.Path, "generations"))
|
||||
fis, err := sftpClient.ReadDir(litestream.GenerationsPath(c.Path))
|
||||
if os.IsNotExist(err) {
|
||||
return nil, nil
|
||||
} else if err != nil {
|
||||
@@ -154,11 +153,12 @@ func (c *ReplicaClient) DeleteGeneration(ctx context.Context, generation string)
|
||||
sftpClient, err := c.Init(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
} else if generation == "" {
|
||||
return fmt.Errorf("generation required")
|
||||
}
|
||||
|
||||
dir := path.Join(c.Path, "generations", generation)
|
||||
dir, err := litestream.GenerationPath(c.Path, generation)
|
||||
if err != nil {
|
||||
return fmt.Errorf("cannot determine generation path: %w", err)
|
||||
}
|
||||
|
||||
var dirs []string
|
||||
walker := sftpClient.Walk(dir)
|
||||
@@ -198,11 +198,12 @@ func (c *ReplicaClient) Snapshots(ctx context.Context, generation string) (_ lit
|
||||
sftpClient, err := c.Init(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
} else if generation == "" {
|
||||
return nil, fmt.Errorf("generation required")
|
||||
}
|
||||
|
||||
dir := path.Join(c.Path, "generations", generation, "snapshots")
|
||||
dir, err := litestream.SnapshotsPath(c.Path, generation)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("cannot determine snapshots path: %w", err)
|
||||
}
|
||||
|
||||
fis, err := sftpClient.ReadDir(dir)
|
||||
if os.IsNotExist(err) {
|
||||
@@ -215,7 +216,7 @@ func (c *ReplicaClient) Snapshots(ctx context.Context, generation string) (_ lit
|
||||
infos := make([]litestream.SnapshotInfo, 0, len(fis))
|
||||
for _, fi := range fis {
|
||||
// Parse index from filename.
|
||||
index, err := internal.ParseSnapshotPath(path.Base(fi.Name()))
|
||||
index, err := litestream.ParseSnapshotPath(path.Base(fi.Name()))
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
@@ -240,11 +241,12 @@ func (c *ReplicaClient) WriteSnapshot(ctx context.Context, generation string, in
|
||||
sftpClient, err := c.Init(ctx)
|
||||
if err != nil {
|
||||
return info, err
|
||||
} else if generation == "" {
|
||||
return info, fmt.Errorf("generation required")
|
||||
}
|
||||
|
||||
filename := path.Join(c.Path, "generations", generation, "snapshots", litestream.FormatIndex(index)+".snapshot.lz4")
|
||||
filename, err := litestream.SnapshotPath(c.Path, generation, index)
|
||||
if err != nil {
|
||||
return info, fmt.Errorf("cannot determine snapshot path: %w", err)
|
||||
}
|
||||
startTime := time.Now()
|
||||
|
||||
if err := sftpClient.MkdirAll(path.Dir(filename)); err != nil {
|
||||
@@ -284,11 +286,12 @@ func (c *ReplicaClient) SnapshotReader(ctx context.Context, generation string, i
|
||||
sftpClient, err := c.Init(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
} else if generation == "" {
|
||||
return nil, fmt.Errorf("generation required")
|
||||
}
|
||||
|
||||
filename := path.Join(c.Path, "generations", generation, "snapshots", litestream.FormatIndex(index)+".snapshot.lz4")
|
||||
filename, err := litestream.SnapshotPath(c.Path, generation, index)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("cannot determine snapshot path: %w", err)
|
||||
}
|
||||
|
||||
f, err := sftpClient.Open(filename)
|
||||
if err != nil {
|
||||
@@ -307,11 +310,12 @@ func (c *ReplicaClient) DeleteSnapshot(ctx context.Context, generation string, i
|
||||
sftpClient, err := c.Init(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
} else if generation == "" {
|
||||
return fmt.Errorf("generation required")
|
||||
}
|
||||
|
||||
filename := path.Join(c.Path, "generations", generation, "snapshots", litestream.FormatIndex(index)+".snapshot.lz4")
|
||||
filename, err := litestream.SnapshotPath(c.Path, generation, index)
|
||||
if err != nil {
|
||||
return fmt.Errorf("cannot determine snapshot path: %w", err)
|
||||
}
|
||||
|
||||
if err := sftpClient.Remove(filename); err != nil && !os.IsNotExist(err) {
|
||||
return fmt.Errorf("cannot delete snapshot %q: %w", filename, err)
|
||||
@@ -328,11 +332,12 @@ func (c *ReplicaClient) WALSegments(ctx context.Context, generation string) (_ l
|
||||
sftpClient, err := c.Init(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
} else if generation == "" {
|
||||
return nil, fmt.Errorf("generation required")
|
||||
}
|
||||
|
||||
dir := path.Join(c.Path, "generations", generation, "wal")
|
||||
dir, err := litestream.WALPath(c.Path, generation)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("cannot determine wal path: %w", err)
|
||||
}
|
||||
|
||||
fis, err := sftpClient.ReadDir(dir)
|
||||
if os.IsNotExist(err) {
|
||||
@@ -342,18 +347,25 @@ func (c *ReplicaClient) WALSegments(ctx context.Context, generation string) (_ l
|
||||
}
|
||||
|
||||
// Iterate over every file and convert to metadata.
|
||||
indexes := make([]int, 0, len(fis))
|
||||
infos := make([]litestream.WALSegmentInfo, 0, len(fis))
|
||||
for _, fi := range fis {
|
||||
index, err := litestream.ParseIndex(fi.Name())
|
||||
if err != nil || !fi.IsDir() {
|
||||
index, offset, err := litestream.ParseWALSegmentPath(path.Base(fi.Name()))
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
indexes = append(indexes, index)
|
||||
|
||||
infos = append(infos, litestream.WALSegmentInfo{
|
||||
Generation: generation,
|
||||
Index: index,
|
||||
Offset: offset,
|
||||
Size: fi.Size(),
|
||||
CreatedAt: fi.ModTime().UTC(),
|
||||
})
|
||||
}
|
||||
|
||||
sort.Ints(indexes)
|
||||
sort.Sort(litestream.WALSegmentInfoSlice(infos))
|
||||
|
||||
return newWALSegmentIterator(ctx, c, dir, generation, indexes), nil
|
||||
return litestream.NewWALSegmentInfoSliceIterator(infos), nil
|
||||
}
|
||||
|
||||
// WriteWALSegment writes LZ4 compressed data from rd into a file on disk.
|
||||
@@ -363,11 +375,12 @@ func (c *ReplicaClient) WriteWALSegment(ctx context.Context, pos litestream.Pos,
|
||||
sftpClient, err := c.Init(ctx)
|
||||
if err != nil {
|
||||
return info, err
|
||||
} else if pos.Generation == "" {
|
||||
return info, fmt.Errorf("generation required")
|
||||
}
|
||||
|
||||
filename := path.Join(c.Path, "generations", pos.Generation, "wal", litestream.FormatIndex(pos.Index), litestream.FormatOffset(pos.Offset)+".wal.lz4")
|
||||
filename, err := litestream.WALSegmentPath(c.Path, pos.Generation, pos.Index, pos.Offset)
|
||||
if err != nil {
|
||||
return info, fmt.Errorf("cannot determine wal segment path: %w", err)
|
||||
}
|
||||
startTime := time.Now()
|
||||
|
||||
if err := sftpClient.MkdirAll(path.Dir(filename)); err != nil {
|
||||
@@ -407,11 +420,12 @@ func (c *ReplicaClient) WALSegmentReader(ctx context.Context, pos litestream.Pos
|
||||
sftpClient, err := c.Init(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
} else if pos.Generation == "" {
|
||||
return nil, fmt.Errorf("generation required")
|
||||
}
|
||||
|
||||
filename := path.Join(c.Path, "generations", pos.Generation, "wal", litestream.FormatIndex(pos.Index), litestream.FormatOffset(pos.Offset)+".wal.lz4")
|
||||
filename, err := litestream.WALSegmentPath(c.Path, pos.Generation, pos.Index, pos.Offset)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("cannot determine wal segment path: %w", err)
|
||||
}
|
||||
|
||||
f, err := sftpClient.Open(filename)
|
||||
if err != nil {
|
||||
@@ -433,12 +447,11 @@ func (c *ReplicaClient) DeleteWALSegments(ctx context.Context, a []litestream.Po
|
||||
}
|
||||
|
||||
for _, pos := range a {
|
||||
if pos.Generation == "" {
|
||||
return fmt.Errorf("generation required")
|
||||
filename, err := litestream.WALSegmentPath(c.Path, pos.Generation, pos.Index, pos.Offset)
|
||||
if err != nil {
|
||||
return fmt.Errorf("cannot determine wal segment path: %w", err)
|
||||
}
|
||||
|
||||
filename := path.Join(c.Path, "generations", pos.Generation, "wal", litestream.FormatIndex(pos.Index), litestream.FormatOffset(pos.Offset)+".wal.lz4")
|
||||
|
||||
if err := sftpClient.Remove(filename); err != nil && !os.IsNotExist(err) {
|
||||
return fmt.Errorf("cannot delete wal segment %q: %w", filename, err)
|
||||
}
|
||||
@@ -457,7 +470,7 @@ func (c *ReplicaClient) Cleanup(ctx context.Context) (err error) {
|
||||
return err
|
||||
}
|
||||
|
||||
if err := sftpClient.RemoveDirectory(path.Join(c.Path, "generations")); err != nil && !os.IsNotExist(err) {
|
||||
if err := sftpClient.RemoveDirectory(litestream.GenerationsPath(c.Path)); err != nil && !os.IsNotExist(err) {
|
||||
return fmt.Errorf("cannot delete generations path: %w", err)
|
||||
} else if err := sftpClient.RemoveDirectory(c.Path); err != nil && !os.IsNotExist(err) {
|
||||
return fmt.Errorf("cannot delete path: %w", err)
|
||||
@@ -480,101 +493,3 @@ func (c *ReplicaClient) resetOnConnError(err error) {
|
||||
c.sshClient = nil
|
||||
}
|
||||
}
|
||||
|
||||
type walSegmentIterator struct {
|
||||
ctx context.Context
|
||||
client *ReplicaClient
|
||||
dir string
|
||||
generation string
|
||||
indexes []int
|
||||
|
||||
infos []litestream.WALSegmentInfo
|
||||
err error
|
||||
}
|
||||
|
||||
func newWALSegmentIterator(ctx context.Context, client *ReplicaClient, dir, generation string, indexes []int) *walSegmentIterator {
|
||||
return &walSegmentIterator{
|
||||
ctx: ctx,
|
||||
client: client,
|
||||
dir: dir,
|
||||
generation: generation,
|
||||
indexes: indexes,
|
||||
}
|
||||
}
|
||||
|
||||
func (itr *walSegmentIterator) Close() (err error) {
|
||||
return itr.err
|
||||
}
|
||||
|
||||
func (itr *walSegmentIterator) Next() bool {
|
||||
sftpClient, err := itr.client.Init(itr.ctx)
|
||||
if err != nil {
|
||||
itr.err = err
|
||||
return false
|
||||
}
|
||||
|
||||
// Exit if an error has already occurred.
|
||||
if itr.err != nil {
|
||||
return false
|
||||
}
|
||||
|
||||
for {
|
||||
// Move to the next segment in cache, if available.
|
||||
if len(itr.infos) > 1 {
|
||||
itr.infos = itr.infos[1:]
|
||||
return true
|
||||
}
|
||||
itr.infos = itr.infos[:0] // otherwise clear infos
|
||||
|
||||
// Move to the next index unless this is the first time initializing.
|
||||
if itr.infos != nil && len(itr.indexes) > 0 {
|
||||
itr.indexes = itr.indexes[1:]
|
||||
}
|
||||
|
||||
// If no indexes remain, stop iteration.
|
||||
if len(itr.indexes) == 0 {
|
||||
return false
|
||||
}
|
||||
|
||||
// Read segments into a cache for the current index.
|
||||
index := itr.indexes[0]
|
||||
fis, err := sftpClient.ReadDir(path.Join(itr.dir, litestream.FormatIndex(index)))
|
||||
if err != nil {
|
||||
itr.err = err
|
||||
return false
|
||||
}
|
||||
|
||||
for _, fi := range fis {
|
||||
filename := path.Base(fi.Name())
|
||||
if fi.IsDir() {
|
||||
continue
|
||||
}
|
||||
|
||||
offset, err := litestream.ParseOffset(strings.TrimSuffix(filename, ".wal.lz4"))
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
|
||||
itr.infos = append(itr.infos, litestream.WALSegmentInfo{
|
||||
Generation: itr.generation,
|
||||
Index: index,
|
||||
Offset: offset,
|
||||
Size: fi.Size(),
|
||||
CreatedAt: fi.ModTime().UTC(),
|
||||
})
|
||||
}
|
||||
|
||||
if len(itr.infos) > 0 {
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (itr *walSegmentIterator) Err() error { return itr.err }
|
||||
|
||||
func (itr *walSegmentIterator) WALSegment() litestream.WALSegmentInfo {
|
||||
if len(itr.infos) == 0 {
|
||||
return litestream.WALSegmentInfo{}
|
||||
}
|
||||
return itr.infos[0]
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user