Compare commits
2 Commits
v0.3.8-bet
...
v0.4.0-alp
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
8ff784b34d | ||
|
|
fc897b481f |
@@ -102,7 +102,7 @@ func (c *ReplicaClient) Generations(ctx context.Context) ([]string, error) {
|
|||||||
internal.OperationTotalCounterVec.WithLabelValues(ReplicaClientType, "LIST").Inc()
|
internal.OperationTotalCounterVec.WithLabelValues(ReplicaClientType, "LIST").Inc()
|
||||||
|
|
||||||
resp, err := c.containerURL.ListBlobsHierarchySegment(ctx, marker, "/", azblob.ListBlobsSegmentOptions{
|
resp, err := c.containerURL.ListBlobsHierarchySegment(ctx, marker, "/", azblob.ListBlobsSegmentOptions{
|
||||||
Prefix: litestream.GenerationsPath(c.Path) + "/",
|
Prefix: path.Join(c.Path, "generations") + "/",
|
||||||
})
|
})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
@@ -125,18 +125,17 @@ func (c *ReplicaClient) Generations(ctx context.Context) ([]string, error) {
|
|||||||
func (c *ReplicaClient) DeleteGeneration(ctx context.Context, generation string) error {
|
func (c *ReplicaClient) DeleteGeneration(ctx context.Context, generation string) error {
|
||||||
if err := c.Init(ctx); err != nil {
|
if err := c.Init(ctx); err != nil {
|
||||||
return err
|
return err
|
||||||
|
} else if generation == "" {
|
||||||
|
return fmt.Errorf("generation required")
|
||||||
}
|
}
|
||||||
|
|
||||||
dir, err := litestream.GenerationPath(c.Path, generation)
|
prefix := path.Join(c.Path, "generations", generation) + "/"
|
||||||
if err != nil {
|
|
||||||
return fmt.Errorf("cannot determine generation path: %w", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
var marker azblob.Marker
|
var marker azblob.Marker
|
||||||
for marker.NotDone() {
|
for marker.NotDone() {
|
||||||
internal.OperationTotalCounterVec.WithLabelValues(ReplicaClientType, "LIST").Inc()
|
internal.OperationTotalCounterVec.WithLabelValues(ReplicaClientType, "LIST").Inc()
|
||||||
|
|
||||||
resp, err := c.containerURL.ListBlobsFlatSegment(ctx, marker, azblob.ListBlobsSegmentOptions{Prefix: dir + "/"})
|
resp, err := c.containerURL.ListBlobsFlatSegment(ctx, marker, azblob.ListBlobsSegmentOptions{Prefix: prefix})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
@@ -171,12 +170,11 @@ 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) {
|
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 {
|
if err := c.Init(ctx); err != nil {
|
||||||
return info, err
|
return info, err
|
||||||
|
} else if generation == "" {
|
||||||
|
return info, fmt.Errorf("generation required")
|
||||||
}
|
}
|
||||||
|
|
||||||
key, err := litestream.SnapshotPath(c.Path, generation, index)
|
key := path.Join(c.Path, "generations", generation, "snapshots", litestream.FormatIndex(index)+".snapshot.lz4")
|
||||||
if err != nil {
|
|
||||||
return info, fmt.Errorf("cannot determine snapshot path: %w", err)
|
|
||||||
}
|
|
||||||
startTime := time.Now()
|
startTime := time.Now()
|
||||||
|
|
||||||
rc := internal.NewReadCounter(rd)
|
rc := internal.NewReadCounter(rd)
|
||||||
@@ -206,12 +204,11 @@ func (c *ReplicaClient) WriteSnapshot(ctx context.Context, generation string, in
|
|||||||
func (c *ReplicaClient) SnapshotReader(ctx context.Context, generation string, index int) (io.ReadCloser, error) {
|
func (c *ReplicaClient) SnapshotReader(ctx context.Context, generation string, index int) (io.ReadCloser, error) {
|
||||||
if err := c.Init(ctx); err != nil {
|
if err := c.Init(ctx); err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
|
} else if generation == "" {
|
||||||
|
return nil, fmt.Errorf("generation required")
|
||||||
}
|
}
|
||||||
|
|
||||||
key, err := litestream.SnapshotPath(c.Path, generation, index)
|
key := path.Join(c.Path, "generations", generation, "snapshots", litestream.FormatIndex(index)+".snapshot.lz4")
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("cannot determine snapshot path: %w", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
blobURL := c.containerURL.NewBlobURL(key)
|
blobURL := c.containerURL.NewBlobURL(key)
|
||||||
resp, err := blobURL.Download(ctx, 0, 0, azblob.BlobAccessConditions{}, false, azblob.ClientProvidedKeyOptions{})
|
resp, err := blobURL.Download(ctx, 0, 0, azblob.BlobAccessConditions{}, false, azblob.ClientProvidedKeyOptions{})
|
||||||
@@ -231,12 +228,11 @@ func (c *ReplicaClient) SnapshotReader(ctx context.Context, generation string, i
|
|||||||
func (c *ReplicaClient) DeleteSnapshot(ctx context.Context, generation string, index int) error {
|
func (c *ReplicaClient) DeleteSnapshot(ctx context.Context, generation string, index int) error {
|
||||||
if err := c.Init(ctx); err != nil {
|
if err := c.Init(ctx); err != nil {
|
||||||
return err
|
return err
|
||||||
|
} else if generation == "" {
|
||||||
|
return fmt.Errorf("generation required")
|
||||||
}
|
}
|
||||||
|
|
||||||
key, err := litestream.SnapshotPath(c.Path, generation, index)
|
key := path.Join(c.Path, "generations", generation, "snapshots", litestream.FormatIndex(index)+".snapshot.lz4")
|
||||||
if err != nil {
|
|
||||||
return fmt.Errorf("cannot determine snapshot path: %w", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
internal.OperationTotalCounterVec.WithLabelValues(ReplicaClientType, "DELETE").Inc()
|
internal.OperationTotalCounterVec.WithLabelValues(ReplicaClientType, "DELETE").Inc()
|
||||||
|
|
||||||
@@ -261,12 +257,11 @@ 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) {
|
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 {
|
if err := c.Init(ctx); err != nil {
|
||||||
return info, err
|
return info, err
|
||||||
|
} else if pos.Generation == "" {
|
||||||
|
return info, fmt.Errorf("generation required")
|
||||||
}
|
}
|
||||||
|
|
||||||
key, err := litestream.WALSegmentPath(c.Path, pos.Generation, pos.Index, pos.Offset)
|
key := path.Join(c.Path, "generations", pos.Generation, "wal", litestream.FormatIndex(pos.Index), litestream.FormatOffset(pos.Offset)+".wal.lz4")
|
||||||
if err != nil {
|
|
||||||
return info, fmt.Errorf("cannot determine wal segment path: %w", err)
|
|
||||||
}
|
|
||||||
startTime := time.Now()
|
startTime := time.Now()
|
||||||
|
|
||||||
rc := internal.NewReadCounter(rd)
|
rc := internal.NewReadCounter(rd)
|
||||||
@@ -296,12 +291,11 @@ func (c *ReplicaClient) WriteWALSegment(ctx context.Context, pos litestream.Pos,
|
|||||||
func (c *ReplicaClient) WALSegmentReader(ctx context.Context, pos litestream.Pos) (io.ReadCloser, error) {
|
func (c *ReplicaClient) WALSegmentReader(ctx context.Context, pos litestream.Pos) (io.ReadCloser, error) {
|
||||||
if err := c.Init(ctx); err != nil {
|
if err := c.Init(ctx); err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
|
} else if pos.Generation == "" {
|
||||||
|
return nil, fmt.Errorf("generation required")
|
||||||
}
|
}
|
||||||
|
|
||||||
key, err := litestream.WALSegmentPath(c.Path, pos.Generation, pos.Index, pos.Offset)
|
key := path.Join(c.Path, "generations", pos.Generation, "wal", litestream.FormatIndex(pos.Index), litestream.FormatOffset(pos.Offset)+".wal.lz4")
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("cannot determine wal segment path: %w", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
blobURL := c.containerURL.NewBlobURL(key)
|
blobURL := c.containerURL.NewBlobURL(key)
|
||||||
resp, err := blobURL.Download(ctx, 0, 0, azblob.BlobAccessConditions{}, false, azblob.ClientProvidedKeyOptions{})
|
resp, err := blobURL.Download(ctx, 0, 0, azblob.BlobAccessConditions{}, false, azblob.ClientProvidedKeyOptions{})
|
||||||
@@ -324,11 +318,12 @@ func (c *ReplicaClient) DeleteWALSegments(ctx context.Context, a []litestream.Po
|
|||||||
}
|
}
|
||||||
|
|
||||||
for _, pos := range a {
|
for _, pos := range a {
|
||||||
key, err := litestream.WALSegmentPath(c.Path, pos.Generation, pos.Index, pos.Offset)
|
if pos.Generation == "" {
|
||||||
if err != nil {
|
return fmt.Errorf("generation required")
|
||||||
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()
|
internal.OperationTotalCounterVec.WithLabelValues(ReplicaClientType, "DELETE").Inc()
|
||||||
|
|
||||||
blobURL := c.containerURL.NewBlobURL(key)
|
blobURL := c.containerURL.NewBlobURL(key)
|
||||||
@@ -372,24 +367,24 @@ func newSnapshotIterator(ctx context.Context, generation string, client *Replica
|
|||||||
func (itr *snapshotIterator) fetch() error {
|
func (itr *snapshotIterator) fetch() error {
|
||||||
defer close(itr.ch)
|
defer close(itr.ch)
|
||||||
|
|
||||||
dir, err := litestream.SnapshotsPath(itr.client.Path, itr.generation)
|
if itr.generation == "" {
|
||||||
if err != nil {
|
return fmt.Errorf("generation required")
|
||||||
return fmt.Errorf("cannot determine snapshots path: %w", err)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
prefix := path.Join(itr.client.Path, "generations", itr.generation) + "/"
|
||||||
|
|
||||||
var marker azblob.Marker
|
var marker azblob.Marker
|
||||||
for marker.NotDone() {
|
for marker.NotDone() {
|
||||||
internal.OperationTotalCounterVec.WithLabelValues(ReplicaClientType, "LIST").Inc()
|
internal.OperationTotalCounterVec.WithLabelValues(ReplicaClientType, "LIST").Inc()
|
||||||
|
|
||||||
resp, err := itr.client.containerURL.ListBlobsFlatSegment(itr.ctx, marker, azblob.ListBlobsSegmentOptions{Prefix: dir + "/"})
|
resp, err := itr.client.containerURL.ListBlobsFlatSegment(itr.ctx, marker, azblob.ListBlobsSegmentOptions{Prefix: prefix})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
marker = resp.NextMarker
|
marker = resp.NextMarker
|
||||||
|
|
||||||
for _, item := range resp.Segment.BlobItems {
|
for _, item := range resp.Segment.BlobItems {
|
||||||
key := path.Base(item.Name)
|
index, err := internal.ParseSnapshotPath(path.Base(item.Name))
|
||||||
index, err := litestream.ParseSnapshotPath(key)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
@@ -478,24 +473,24 @@ func newWALSegmentIterator(ctx context.Context, generation string, client *Repli
|
|||||||
func (itr *walSegmentIterator) fetch() error {
|
func (itr *walSegmentIterator) fetch() error {
|
||||||
defer close(itr.ch)
|
defer close(itr.ch)
|
||||||
|
|
||||||
dir, err := litestream.WALPath(itr.client.Path, itr.generation)
|
if itr.generation == "" {
|
||||||
if err != nil {
|
return fmt.Errorf("generation required")
|
||||||
return fmt.Errorf("cannot determine wal path: %w", err)
|
|
||||||
}
|
}
|
||||||
|
prefix := path.Join(itr.client.Path, "generations", itr.generation, "wal")
|
||||||
|
|
||||||
var marker azblob.Marker
|
var marker azblob.Marker
|
||||||
for marker.NotDone() {
|
for marker.NotDone() {
|
||||||
internal.OperationTotalCounterVec.WithLabelValues(ReplicaClientType, "LIST").Inc()
|
internal.OperationTotalCounterVec.WithLabelValues(ReplicaClientType, "LIST").Inc()
|
||||||
|
|
||||||
resp, err := itr.client.containerURL.ListBlobsFlatSegment(itr.ctx, marker, azblob.ListBlobsSegmentOptions{Prefix: dir + "/"})
|
resp, err := itr.client.containerURL.ListBlobsFlatSegment(itr.ctx, marker, azblob.ListBlobsSegmentOptions{Prefix: prefix})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
marker = resp.NextMarker
|
marker = resp.NextMarker
|
||||||
|
|
||||||
for _, item := range resp.Segment.BlobItems {
|
for _, item := range resp.Segment.BlobItems {
|
||||||
key := path.Base(item.Name)
|
key := strings.TrimPrefix(item.Name, prefix+"/")
|
||||||
index, offset, err := litestream.ParseWALSegmentPath(key)
|
index, offset, err := internal.ParseWALSegmentPath(key)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -9,6 +9,7 @@ import (
|
|||||||
"log"
|
"log"
|
||||||
"net/url"
|
"net/url"
|
||||||
"os"
|
"os"
|
||||||
|
"os/signal"
|
||||||
"os/user"
|
"os/user"
|
||||||
"path"
|
"path"
|
||||||
"path/filepath"
|
"path/filepath"
|
||||||
@@ -86,7 +87,8 @@ func (m *Main) Run(ctx context.Context, args []string) (err error) {
|
|||||||
|
|
||||||
// Setup signal handler.
|
// Setup signal handler.
|
||||||
ctx, cancel := context.WithCancel(ctx)
|
ctx, cancel := context.WithCancel(ctx)
|
||||||
signalCh := signalChan()
|
signalCh := make(chan os.Signal, 1)
|
||||||
|
signal.Notify(signalCh, notifySignals...)
|
||||||
|
|
||||||
if err := c.Run(ctx); err != nil {
|
if err := c.Run(ctx); err != nil {
|
||||||
return err
|
return err
|
||||||
@@ -94,6 +96,8 @@ func (m *Main) Run(ctx context.Context, args []string) (err error) {
|
|||||||
|
|
||||||
// Wait for signal to stop program.
|
// Wait for signal to stop program.
|
||||||
select {
|
select {
|
||||||
|
case <-ctx.Done():
|
||||||
|
fmt.Println("context done, litestream shutting down")
|
||||||
case err = <-c.execCh:
|
case err = <-c.execCh:
|
||||||
cancel()
|
cancel()
|
||||||
fmt.Println("subprocess exited, litestream shutting down")
|
fmt.Println("subprocess exited, litestream shutting down")
|
||||||
|
|||||||
@@ -5,7 +5,6 @@ package main
|
|||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"os"
|
"os"
|
||||||
"os/signal"
|
|
||||||
"syscall"
|
"syscall"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -19,8 +18,4 @@ func runWindowsService(ctx context.Context) error {
|
|||||||
panic("cannot run windows service as unix process")
|
panic("cannot run windows service as unix process")
|
||||||
}
|
}
|
||||||
|
|
||||||
func signalChan() <-chan os.Signal {
|
var notifySignals = []os.Signal{syscall.SIGINT, syscall.SIGTERM}
|
||||||
ch := make(chan os.Signal, 2)
|
|
||||||
signal.Notify(ch, syscall.SIGINT, syscall.SIGTERM)
|
|
||||||
return ch
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -2,16 +2,22 @@ package main_test
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"io/ioutil"
|
"io/ioutil"
|
||||||
|
"log"
|
||||||
"os"
|
"os"
|
||||||
"path/filepath"
|
"path/filepath"
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
|
"github.com/benbjohnson/litestream"
|
||||||
main "github.com/benbjohnson/litestream/cmd/litestream"
|
main "github.com/benbjohnson/litestream/cmd/litestream"
|
||||||
"github.com/benbjohnson/litestream/file"
|
"github.com/benbjohnson/litestream/file"
|
||||||
"github.com/benbjohnson/litestream/gcs"
|
"github.com/benbjohnson/litestream/gcs"
|
||||||
"github.com/benbjohnson/litestream/s3"
|
"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) {
|
func TestReadConfigFile(t *testing.T) {
|
||||||
// Ensure global AWS settings are propagated down to replica configurations.
|
// Ensure global AWS settings are propagated down to replica configurations.
|
||||||
t.Run("PropagateGlobalSettings", func(t *testing.T) {
|
t.Run("PropagateGlobalSettings", func(t *testing.T) {
|
||||||
|
|||||||
@@ -7,7 +7,6 @@ import (
|
|||||||
"io"
|
"io"
|
||||||
"log"
|
"log"
|
||||||
"os"
|
"os"
|
||||||
"os/signal"
|
|
||||||
|
|
||||||
"golang.org/x/sys/windows"
|
"golang.org/x/sys/windows"
|
||||||
"golang.org/x/sys/windows/svc"
|
"golang.org/x/sys/windows/svc"
|
||||||
@@ -105,8 +104,4 @@ func (w *eventlogWriter) Write(p []byte) (n int, err error) {
|
|||||||
return 0, elog.Info(1, string(p))
|
return 0, elog.Info(1, string(p))
|
||||||
}
|
}
|
||||||
|
|
||||||
func signalChan() <-chan os.Signal {
|
var notifySignals = []os.Signal{os.Interrupt}
|
||||||
ch := make(chan os.Signal, 1)
|
|
||||||
signal.Notify(ch, os.Interrupt)
|
|
||||||
return ch
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -42,7 +42,6 @@ func NewReplicateCommand() *ReplicateCommand {
|
|||||||
func (c *ReplicateCommand) ParseFlags(ctx context.Context, args []string) (err error) {
|
func (c *ReplicateCommand) ParseFlags(ctx context.Context, args []string) (err error) {
|
||||||
fs := flag.NewFlagSet("litestream-replicate", flag.ContinueOnError)
|
fs := flag.NewFlagSet("litestream-replicate", flag.ContinueOnError)
|
||||||
execFlag := fs.String("exec", "", "execute subcommand")
|
execFlag := fs.String("exec", "", "execute subcommand")
|
||||||
tracePath := fs.String("trace", "", "trace path")
|
|
||||||
configPath, noExpandEnv := registerConfigFlag(fs)
|
configPath, noExpandEnv := registerConfigFlag(fs)
|
||||||
fs.Usage = c.Usage
|
fs.Usage = c.Usage
|
||||||
if err := fs.Parse(args); err != nil {
|
if err := fs.Parse(args); err != nil {
|
||||||
@@ -80,16 +79,6 @@ func (c *ReplicateCommand) ParseFlags(ctx context.Context, args []string) (err e
|
|||||||
c.Config.Exec = *execFlag
|
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
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -215,8 +204,5 @@ Arguments:
|
|||||||
-no-expand-env
|
-no-expand-env
|
||||||
Disables environment variable expansion in configuration file.
|
Disables environment variable expansion in configuration file.
|
||||||
|
|
||||||
-trace PATH
|
|
||||||
Write verbose trace logging to PATH.
|
|
||||||
|
|
||||||
`[1:], DefaultConfigPath())
|
`[1:], DefaultConfigPath())
|
||||||
}
|
}
|
||||||
|
|||||||
135
cmd/litestream/replicate_test.go
Normal file
135
cmd/litestream/replicate_test.go
Normal file
@@ -0,0 +1,135 @@
|
|||||||
|
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()
|
||||||
|
}
|
||||||
299
db_test.go
299
db_test.go
@@ -3,7 +3,6 @@ package litestream_test
|
|||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"database/sql"
|
"database/sql"
|
||||||
"io/ioutil"
|
|
||||||
"os"
|
"os"
|
||||||
"path/filepath"
|
"path/filepath"
|
||||||
"strings"
|
"strings"
|
||||||
@@ -30,13 +29,13 @@ func TestDB_WALPath(t *testing.T) {
|
|||||||
func TestDB_MetaPath(t *testing.T) {
|
func TestDB_MetaPath(t *testing.T) {
|
||||||
t.Run("Absolute", func(t *testing.T) {
|
t.Run("Absolute", func(t *testing.T) {
|
||||||
db := litestream.NewDB("/tmp/db")
|
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.Fatalf("MetaPath()=%v, want %v", got, want)
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
t.Run("Relative", func(t *testing.T) {
|
t.Run("Relative", func(t *testing.T) {
|
||||||
db := litestream.NewDB("db")
|
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)
|
t.Fatalf("MetaPath()=%v, want %v", got, want)
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
@@ -44,32 +43,25 @@ func TestDB_MetaPath(t *testing.T) {
|
|||||||
|
|
||||||
func TestDB_GenerationNamePath(t *testing.T) {
|
func TestDB_GenerationNamePath(t *testing.T) {
|
||||||
db := litestream.NewDB("/tmp/db")
|
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)
|
t.Fatalf("GenerationNamePath()=%v, want %v", got, want)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestDB_GenerationPath(t *testing.T) {
|
func TestDB_GenerationPath(t *testing.T) {
|
||||||
db := litestream.NewDB("/tmp/db")
|
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)
|
t.Fatalf("GenerationPath()=%v, want %v", got, want)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestDB_ShadowWALDir(t *testing.T) {
|
func TestDB_ShadowWALDir(t *testing.T) {
|
||||||
db := litestream.NewDB("/tmp/db")
|
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)
|
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.
|
// Ensure we can check the last modified time of the real database and its WAL.
|
||||||
func TestDB_UpdatedAt(t *testing.T) {
|
func TestDB_UpdatedAt(t *testing.T) {
|
||||||
t.Run("ErrNotExist", func(t *testing.T) {
|
t.Run("ErrNotExist", func(t *testing.T) {
|
||||||
@@ -195,9 +187,7 @@ func TestDB_Sync(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Ensure position now available.
|
// Ensure position now available.
|
||||||
if pos, err := db.Pos(); err != nil {
|
if pos := db.Pos(); pos.Generation == "" {
|
||||||
t.Fatal(err)
|
|
||||||
} else if pos.Generation == "" {
|
|
||||||
t.Fatal("expected generation")
|
t.Fatal("expected generation")
|
||||||
} else if got, want := pos.Index, 0; got != want {
|
} else if got, want := pos.Index, 0; got != want {
|
||||||
t.Fatalf("pos.Index=%v, want %v", got, want)
|
t.Fatalf("pos.Index=%v, want %v", got, want)
|
||||||
@@ -221,10 +211,7 @@ func TestDB_Sync(t *testing.T) {
|
|||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
|
|
||||||
pos0, err := db.Pos()
|
pos0 := db.Pos()
|
||||||
if err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Insert into table.
|
// Insert into table.
|
||||||
if _, err := sqldb.Exec(`INSERT INTO foo (bar) VALUES ('baz');`); err != nil {
|
if _, err := sqldb.Exec(`INSERT INTO foo (bar) VALUES ('baz');`); err != nil {
|
||||||
@@ -234,9 +221,7 @@ func TestDB_Sync(t *testing.T) {
|
|||||||
// Sync to ensure position moves forward one page.
|
// Sync to ensure position moves forward one page.
|
||||||
if err := db.Sync(context.Background()); err != nil {
|
if err := db.Sync(context.Background()); err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
} else if pos1, err := db.Pos(); err != nil {
|
} else if pos1 := db.Pos(); pos0.Generation != pos1.Generation {
|
||||||
t.Fatal(err)
|
|
||||||
} else if pos0.Generation != pos1.Generation {
|
|
||||||
t.Fatal("expected the same generation")
|
t.Fatal("expected the same generation")
|
||||||
} else if got, want := pos1.Index, pos0.Index; got != want {
|
} else if got, want := pos1.Index, pos0.Index; got != want {
|
||||||
t.Fatalf("Index=%v, want %v", got, want)
|
t.Fatalf("Index=%v, want %v", got, want)
|
||||||
@@ -256,10 +241,7 @@ func TestDB_Sync(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Obtain initial position.
|
// Obtain initial position.
|
||||||
pos0, err := db.Pos()
|
pos0 := db.Pos()
|
||||||
if err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Checkpoint & fully close which should close WAL file.
|
// Checkpoint & fully close which should close WAL file.
|
||||||
if err := db.Checkpoint(context.Background(), litestream.CheckpointModeTruncate); err != nil {
|
if err := db.Checkpoint(context.Background(), litestream.CheckpointModeTruncate); err != nil {
|
||||||
@@ -285,9 +267,7 @@ func TestDB_Sync(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Obtain initial position.
|
// Obtain initial position.
|
||||||
if pos1, err := db.Pos(); err != nil {
|
if pos1 := db.Pos(); pos0.Generation == pos1.Generation {
|
||||||
t.Fatal(err)
|
|
||||||
} else if pos0.Generation == pos1.Generation {
|
|
||||||
t.Fatal("expected new generation after truncation")
|
t.Fatal("expected new generation after truncation")
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
@@ -308,10 +288,7 @@ func TestDB_Sync(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Obtain initial position.
|
// Obtain initial position.
|
||||||
pos0, err := db.Pos()
|
pos0 := db.Pos()
|
||||||
if err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Fully close which should close WAL file.
|
// Fully close which should close WAL file.
|
||||||
if err := db.Close(); err != nil {
|
if err := db.Close(); err != nil {
|
||||||
@@ -344,190 +321,98 @@ func TestDB_Sync(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Obtain initial position.
|
// Obtain initial position.
|
||||||
if pos1, err := db.Pos(); err != nil {
|
if pos1 := db.Pos(); pos0.Generation == pos1.Generation {
|
||||||
t.Fatal(err)
|
|
||||||
} else if pos0.Generation == pos1.Generation {
|
|
||||||
t.Fatal("expected new generation after truncation")
|
t.Fatal("expected new generation after truncation")
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
// Ensure DB can handle a mismatched header-only and start new generation.
|
// TODO: Fix test to check for header mismatch
|
||||||
t.Run("WALHeaderMismatch", func(t *testing.T) {
|
/*
|
||||||
db, sqldb := MustOpenDBs(t)
|
// Ensure DB can handle a mismatched header-only and start new generation.
|
||||||
defer MustCloseDBs(t, db, sqldb)
|
t.Run("WALHeaderMismatch", 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.
|
// Execute a query to force a write to the WAL and then sync.
|
||||||
if _, err := sqldb.Exec(`CREATE TABLE foo (bar TEXT);`); err != nil {
|
if _, err := sqldb.Exec(`CREATE TABLE foo (bar TEXT);`); err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
} else if err := db.Sync(context.Background()); err != nil {
|
} else if err := db.Sync(context.Background()); err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Grab initial position & close.
|
// Grab initial position & close.
|
||||||
pos0, err := db.Pos()
|
pos0 := db.Pos()
|
||||||
if err != nil {
|
if err := db.Close(); err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
} else if err := db.Close(); err != nil {
|
}
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Read existing file, update header checksum, and write back only header
|
// Read existing file, update header checksum, and write back only header
|
||||||
// to simulate a header with a mismatched checksum.
|
// to simulate a header with a mismatched checksum.
|
||||||
shadowWALPath := db.ShadowWALPath(pos0.Generation, pos0.Index)
|
shadowWALPath := db.ShadowWALPath(pos0.Generation, pos0.Index)
|
||||||
if buf, err := ioutil.ReadFile(shadowWALPath); err != nil {
|
if buf, err := os.ReadFile(shadowWALPath); err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
} else if err := ioutil.WriteFile(shadowWALPath, append(buf[:litestream.WALHeaderSize-8], 0, 0, 0, 0, 0, 0, 0, 0), 0600); err != nil {
|
} else if err := os.WriteFile(shadowWALPath, append(buf[:litestream.WALHeaderSize-8], 0, 0, 0, 0, 0, 0, 0, 0), 0600); err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Reopen managed database & ensure sync will still work.
|
// Reopen managed database & ensure sync will still work.
|
||||||
db = MustOpenDBAt(t, db.Path())
|
db = MustOpenDBAt(t, db.Path())
|
||||||
defer MustCloseDB(t, db)
|
defer MustCloseDB(t, db)
|
||||||
if err := db.Sync(context.Background()); err != nil {
|
if err := db.Sync(context.Background()); err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Verify a new generation was started.
|
// Verify a new generation was started.
|
||||||
if pos1, err := db.Pos(); err != nil {
|
if pos1, err := db.Pos(); err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
} else if pos0.Generation == pos1.Generation {
|
} else if pos0.Generation == pos1.Generation {
|
||||||
t.Fatal("expected new generation")
|
t.Fatal("expected new generation")
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
*/
|
||||||
|
|
||||||
// Ensure DB can handle partial shadow WAL header write.
|
// TODO: Fix test for segmented shadow WAL.
|
||||||
t.Run("PartialShadowWALHeader", func(t *testing.T) {
|
/*
|
||||||
db, sqldb := MustOpenDBs(t)
|
// Ensure DB can handle a generation directory with a missing shadow WAL.
|
||||||
defer MustCloseDBs(t, db, sqldb)
|
t.Run("NoShadowWAL", 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.
|
// Execute a query to force a write to the WAL and then sync.
|
||||||
if _, err := sqldb.Exec(`CREATE TABLE foo (bar TEXT);`); err != nil {
|
if _, err := sqldb.Exec(`CREATE TABLE foo (bar TEXT);`); err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
} else if err := db.Sync(context.Background()); err != nil {
|
} else if err := db.Sync(context.Background()); err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
|
|
||||||
pos0, err := db.Pos()
|
pos0 := db.Pos()
|
||||||
if err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Close & truncate shadow WAL to simulate a partial header write.
|
// Close & delete shadow WAL to simulate dir created but not WAL.
|
||||||
if err := db.Close(); err != nil {
|
if err := db.Close(); err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
} else if err := os.Truncate(db.ShadowWALPath(pos0.Generation, pos0.Index), litestream.WALHeaderSize-1); err != nil {
|
} else if err := os.Remove(db.ShadowWALPath(pos0.Generation, pos0.Index)); err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Reopen managed database & ensure sync will still work.
|
// Reopen managed database & ensure sync will still work.
|
||||||
db = MustOpenDBAt(t, db.Path())
|
db = MustOpenDBAt(t, db.Path())
|
||||||
defer MustCloseDB(t, db)
|
defer MustCloseDB(t, db)
|
||||||
if err := db.Sync(context.Background()); err != nil {
|
if err := db.Sync(context.Background()); err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Verify a new generation was started.
|
// Verify new generation created but index/offset the same.
|
||||||
if pos1, err := db.Pos(); err != nil {
|
if pos1, err := db.Pos(); err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
} else if pos0.Generation == pos1.Generation {
|
} else if pos0.Generation == pos1.Generation {
|
||||||
t.Fatal("expected new generation")
|
t.Fatal("expected new generation")
|
||||||
}
|
} else if got, want := pos1.Index, pos0.Index; got != want {
|
||||||
})
|
t.Fatalf("Index=%v want %v", got, want)
|
||||||
|
} else if got, want := pos1.Offset, pos0.Offset; got != want {
|
||||||
// Ensure DB can handle partial shadow WAL writes.
|
t.Fatalf("Offset=%v want %v", got, want)
|
||||||
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)
|
|
||||||
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 & delete shadow WAL to simulate dir created but not WAL.
|
|
||||||
if err := db.Close(); err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
} else if err := os.Remove(db.ShadowWALPath(pos0.Generation, pos0.Index)); 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 new generation created but index/offset the same.
|
|
||||||
if pos1, err := db.Pos(); err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
} else if pos0.Generation == pos1.Generation {
|
|
||||||
t.Fatal("expected new generation")
|
|
||||||
} else if got, want := pos1.Index, pos0.Index; got != want {
|
|
||||||
t.Fatalf("Index=%v want %v", got, want)
|
|
||||||
} else if got, want := pos1.Offset, pos0.Offset; got != want {
|
|
||||||
t.Fatalf("Offset=%v want %v", got, want)
|
|
||||||
}
|
|
||||||
})
|
|
||||||
|
|
||||||
// Ensure DB checkpoints after minimum number of pages.
|
// Ensure DB checkpoints after minimum number of pages.
|
||||||
t.Run("MinCheckpointPageN", func(t *testing.T) {
|
t.Run("MinCheckpointPageN", func(t *testing.T) {
|
||||||
@@ -554,9 +439,7 @@ func TestDB_Sync(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Ensure position is now on the second index.
|
// Ensure position is now on the second index.
|
||||||
if pos, err := db.Pos(); err != nil {
|
if got, want := db.Pos().Index, 1; got != want {
|
||||||
t.Fatal(err)
|
|
||||||
} else if got, want := pos.Index, 1; got != want {
|
|
||||||
t.Fatalf("Index=%v, want %v", got, want)
|
t.Fatalf("Index=%v, want %v", got, want)
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
@@ -584,9 +467,7 @@ func TestDB_Sync(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Ensure position is now on the second index.
|
// Ensure position is now on the second index.
|
||||||
if pos, err := db.Pos(); err != nil {
|
if got, want := db.Pos().Index, 1; got != want {
|
||||||
t.Fatal(err)
|
|
||||||
} else if got, want := pos.Index, 1; got != want {
|
|
||||||
t.Fatalf("Index=%v, want %v", got, want)
|
t.Fatalf("Index=%v, want %v", got, want)
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -8,6 +8,7 @@ import (
|
|||||||
"os"
|
"os"
|
||||||
"path/filepath"
|
"path/filepath"
|
||||||
"sort"
|
"sort"
|
||||||
|
"strings"
|
||||||
|
|
||||||
"github.com/benbjohnson/litestream"
|
"github.com/benbjohnson/litestream"
|
||||||
"github.com/benbjohnson/litestream/internal"
|
"github.com/benbjohnson/litestream/internal"
|
||||||
@@ -84,7 +85,7 @@ func (c *ReplicaClient) SnapshotPath(generation string, index int) (string, erro
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return "", err
|
return "", err
|
||||||
}
|
}
|
||||||
return filepath.Join(dir, litestream.FormatSnapshotPath(index)), nil
|
return filepath.Join(dir, litestream.FormatIndex(index)+".snapshot.lz4"), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// WALDir returns the path to a generation's WAL directory
|
// WALDir returns the path to a generation's WAL directory
|
||||||
@@ -102,7 +103,7 @@ func (c *ReplicaClient) WALSegmentPath(generation string, index int, offset int6
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return "", err
|
return "", err
|
||||||
}
|
}
|
||||||
return filepath.Join(dir, litestream.FormatWALSegmentPath(index, offset)), nil
|
return filepath.Join(dir, litestream.FormatIndex(index), fmt.Sprintf("%08x.wal.lz4", offset)), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// Generations returns a list of available generation names.
|
// Generations returns a list of available generation names.
|
||||||
@@ -148,7 +149,7 @@ func (c *ReplicaClient) DeleteGeneration(ctx context.Context, generation string)
|
|||||||
func (c *ReplicaClient) Snapshots(ctx context.Context, generation string) (litestream.SnapshotIterator, error) {
|
func (c *ReplicaClient) Snapshots(ctx context.Context, generation string) (litestream.SnapshotIterator, error) {
|
||||||
dir, err := c.SnapshotsDir(generation)
|
dir, err := c.SnapshotsDir(generation)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("cannot determine snapshots path: %w", err)
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
f, err := os.Open(dir)
|
f, err := os.Open(dir)
|
||||||
@@ -168,7 +169,7 @@ func (c *ReplicaClient) Snapshots(ctx context.Context, generation string) (lites
|
|||||||
infos := make([]litestream.SnapshotInfo, 0, len(fis))
|
infos := make([]litestream.SnapshotInfo, 0, len(fis))
|
||||||
for _, fi := range fis {
|
for _, fi := range fis {
|
||||||
// Parse index from filename.
|
// Parse index from filename.
|
||||||
index, err := litestream.ParseSnapshotPath(fi.Name())
|
index, err := internal.ParseSnapshotPath(filepath.Base(fi.Name()))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
@@ -190,7 +191,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) {
|
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)
|
filename, err := c.SnapshotPath(generation, index)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return info, fmt.Errorf("cannot determine snapshot path: %w", err)
|
return info, err
|
||||||
}
|
}
|
||||||
|
|
||||||
var fileInfo, dirInfo os.FileInfo
|
var fileInfo, dirInfo os.FileInfo
|
||||||
@@ -243,7 +244,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) {
|
func (c *ReplicaClient) SnapshotReader(ctx context.Context, generation string, index int) (io.ReadCloser, error) {
|
||||||
filename, err := c.SnapshotPath(generation, index)
|
filename, err := c.SnapshotPath(generation, index)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("cannot determine snapshot path: %w", err)
|
return nil, err
|
||||||
}
|
}
|
||||||
return os.Open(filename)
|
return os.Open(filename)
|
||||||
}
|
}
|
||||||
@@ -264,7 +265,7 @@ func (c *ReplicaClient) DeleteSnapshot(ctx context.Context, generation string, i
|
|||||||
func (c *ReplicaClient) WALSegments(ctx context.Context, generation string) (litestream.WALSegmentIterator, error) {
|
func (c *ReplicaClient) WALSegments(ctx context.Context, generation string) (litestream.WALSegmentIterator, error) {
|
||||||
dir, err := c.WALDir(generation)
|
dir, err := c.WALDir(generation)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("cannot determine wal path: %w", err)
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
f, err := os.Open(dir)
|
f, err := os.Open(dir)
|
||||||
@@ -281,33 +282,25 @@ func (c *ReplicaClient) WALSegments(ctx context.Context, generation string) (lit
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Iterate over every file and convert to metadata.
|
// Iterate over every file and convert to metadata.
|
||||||
infos := make([]litestream.WALSegmentInfo, 0, len(fis))
|
indexes := make([]int, 0, len(fis))
|
||||||
for _, fi := range fis {
|
for _, fi := range fis {
|
||||||
// Parse index from filename.
|
index, err := litestream.ParseIndex(fi.Name())
|
||||||
index, offset, err := litestream.ParseWALSegmentPath(fi.Name())
|
if err != nil || !fi.IsDir() {
|
||||||
if err != nil {
|
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
|
indexes = append(indexes, index)
|
||||||
infos = append(infos, litestream.WALSegmentInfo{
|
|
||||||
Generation: generation,
|
|
||||||
Index: index,
|
|
||||||
Offset: offset,
|
|
||||||
Size: fi.Size(),
|
|
||||||
CreatedAt: fi.ModTime().UTC(),
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
|
|
||||||
sort.Sort(litestream.WALSegmentInfoSlice(infos))
|
sort.Ints(indexes)
|
||||||
|
|
||||||
return litestream.NewWALSegmentInfoSliceIterator(infos), nil
|
return newWALSegmentIterator(dir, generation, indexes), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// WriteWALSegment writes LZ4 compressed data from rd into a file on disk.
|
// 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) {
|
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)
|
filename, err := c.WALSegmentPath(pos.Generation, pos.Index, pos.Offset)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return info, fmt.Errorf("cannot determine wal segment path: %w", err)
|
return info, err
|
||||||
}
|
}
|
||||||
|
|
||||||
var fileInfo, dirInfo os.FileInfo
|
var fileInfo, dirInfo os.FileInfo
|
||||||
@@ -361,7 +354,7 @@ func (c *ReplicaClient) WriteWALSegment(ctx context.Context, pos litestream.Pos,
|
|||||||
func (c *ReplicaClient) WALSegmentReader(ctx context.Context, pos litestream.Pos) (io.ReadCloser, error) {
|
func (c *ReplicaClient) WALSegmentReader(ctx context.Context, pos litestream.Pos) (io.ReadCloser, error) {
|
||||||
filename, err := c.WALSegmentPath(pos.Generation, pos.Index, pos.Offset)
|
filename, err := c.WALSegmentPath(pos.Generation, pos.Index, pos.Offset)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("cannot determine wal segment path: %w", err)
|
return nil, err
|
||||||
}
|
}
|
||||||
return os.Open(filename)
|
return os.Open(filename)
|
||||||
}
|
}
|
||||||
@@ -371,7 +364,7 @@ func (c *ReplicaClient) DeleteWALSegments(ctx context.Context, a []litestream.Po
|
|||||||
for _, pos := range a {
|
for _, pos := range a {
|
||||||
filename, err := c.WALSegmentPath(pos.Generation, pos.Index, pos.Offset)
|
filename, err := c.WALSegmentPath(pos.Generation, pos.Index, pos.Offset)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return fmt.Errorf("cannot determine wal segment path: %w", err)
|
return err
|
||||||
}
|
}
|
||||||
if err := os.Remove(filename); err != nil && !os.IsNotExist(err) {
|
if err := os.Remove(filename); err != nil && !os.IsNotExist(err) {
|
||||||
return err
|
return err
|
||||||
@@ -379,3 +372,100 @@ func (c *ReplicaClient) DeleteWALSegments(ctx context.Context, a []litestream.Po
|
|||||||
}
|
}
|
||||||
return nil
|
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) {
|
t.Run("OK", func(t *testing.T) {
|
||||||
if got, err := file.NewReplicaClient("/foo").WALSegmentPath("0123456701234567", 1000, 1001); err != nil {
|
if got, err := file.NewReplicaClient("/foo").WALSegmentPath("0123456701234567", 1000, 1001); err != nil {
|
||||||
t.Fatal(err)
|
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)
|
t.Fatalf("WALPath()=%v, want %v", got, want)
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
@@ -133,91 +133,3 @@ 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.
|
// Construct query to only pull generation directory names.
|
||||||
query := &storage.Query{
|
query := &storage.Query{
|
||||||
Delimiter: "/",
|
Delimiter: "/",
|
||||||
Prefix: litestream.GenerationsPath(c.Path) + "/",
|
Prefix: path.Join(c.Path, "generations") + "/",
|
||||||
}
|
}
|
||||||
|
|
||||||
// Loop over results and only build list of generation-formatted names.
|
// Loop over results and only build list of generation-formatted names.
|
||||||
@@ -96,16 +96,15 @@ func (c *ReplicaClient) Generations(ctx context.Context) ([]string, error) {
|
|||||||
func (c *ReplicaClient) DeleteGeneration(ctx context.Context, generation string) error {
|
func (c *ReplicaClient) DeleteGeneration(ctx context.Context, generation string) error {
|
||||||
if err := c.Init(ctx); err != nil {
|
if err := c.Init(ctx); err != nil {
|
||||||
return err
|
return err
|
||||||
|
} else if generation == "" {
|
||||||
|
return fmt.Errorf("generation required")
|
||||||
}
|
}
|
||||||
|
|
||||||
dir, err := litestream.GenerationPath(c.Path, generation)
|
prefix := path.Join(c.Path, "generations", generation) + "/"
|
||||||
if err != nil {
|
|
||||||
return fmt.Errorf("cannot determine generation path: %w", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Iterate over every object in generation and delete it.
|
// Iterate over every object in generation and delete it.
|
||||||
internal.OperationTotalCounterVec.WithLabelValues(ReplicaClientType, "LIST").Inc()
|
internal.OperationTotalCounterVec.WithLabelValues(ReplicaClientType, "LIST").Inc()
|
||||||
for it := c.bkt.Objects(ctx, &storage.Query{Prefix: dir + "/"}); ; {
|
for it := c.bkt.Objects(ctx, &storage.Query{Prefix: prefix}); ; {
|
||||||
attrs, err := it.Next()
|
attrs, err := it.Next()
|
||||||
if err == iterator.Done {
|
if err == iterator.Done {
|
||||||
break
|
break
|
||||||
@@ -130,24 +129,22 @@ func (c *ReplicaClient) DeleteGeneration(ctx context.Context, generation string)
|
|||||||
func (c *ReplicaClient) Snapshots(ctx context.Context, generation string) (litestream.SnapshotIterator, error) {
|
func (c *ReplicaClient) Snapshots(ctx context.Context, generation string) (litestream.SnapshotIterator, error) {
|
||||||
if err := c.Init(ctx); err != nil {
|
if err := c.Init(ctx); err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
|
} else if generation == "" {
|
||||||
|
return nil, fmt.Errorf("generation required")
|
||||||
}
|
}
|
||||||
dir, err := litestream.SnapshotsPath(c.Path, generation)
|
prefix := path.Join(c.Path, "generations", generation) + "/"
|
||||||
if err != nil {
|
return newSnapshotIterator(generation, c.bkt.Objects(ctx, &storage.Query{Prefix: prefix})), 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.
|
// 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) {
|
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 {
|
if err := c.Init(ctx); err != nil {
|
||||||
return info, err
|
return info, err
|
||||||
|
} else if generation == "" {
|
||||||
|
return info, fmt.Errorf("generation required")
|
||||||
}
|
}
|
||||||
|
|
||||||
key, err := litestream.SnapshotPath(c.Path, generation, index)
|
key := path.Join(c.Path, "generations", generation, "snapshots", litestream.FormatIndex(index)+".snapshot.lz4")
|
||||||
if err != nil {
|
|
||||||
return info, fmt.Errorf("cannot determine snapshot path: %w", err)
|
|
||||||
}
|
|
||||||
startTime := time.Now()
|
startTime := time.Now()
|
||||||
|
|
||||||
w := c.bkt.Object(key).NewWriter(ctx)
|
w := c.bkt.Object(key).NewWriter(ctx)
|
||||||
@@ -177,12 +174,11 @@ func (c *ReplicaClient) WriteSnapshot(ctx context.Context, generation string, in
|
|||||||
func (c *ReplicaClient) SnapshotReader(ctx context.Context, generation string, index int) (io.ReadCloser, error) {
|
func (c *ReplicaClient) SnapshotReader(ctx context.Context, generation string, index int) (io.ReadCloser, error) {
|
||||||
if err := c.Init(ctx); err != nil {
|
if err := c.Init(ctx); err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
|
} else if generation == "" {
|
||||||
|
return nil, fmt.Errorf("generation required")
|
||||||
}
|
}
|
||||||
|
|
||||||
key, err := litestream.SnapshotPath(c.Path, generation, index)
|
key := path.Join(c.Path, "generations", generation, "snapshots", litestream.FormatIndex(index)+".snapshot.lz4")
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("cannot determine snapshot path: %w", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
r, err := c.bkt.Object(key).NewReader(ctx)
|
r, err := c.bkt.Object(key).NewReader(ctx)
|
||||||
if isNotExists(err) {
|
if isNotExists(err) {
|
||||||
@@ -201,12 +197,11 @@ func (c *ReplicaClient) SnapshotReader(ctx context.Context, generation string, i
|
|||||||
func (c *ReplicaClient) DeleteSnapshot(ctx context.Context, generation string, index int) error {
|
func (c *ReplicaClient) DeleteSnapshot(ctx context.Context, generation string, index int) error {
|
||||||
if err := c.Init(ctx); err != nil {
|
if err := c.Init(ctx); err != nil {
|
||||||
return err
|
return err
|
||||||
|
} else if generation == "" {
|
||||||
|
return fmt.Errorf("generation required")
|
||||||
}
|
}
|
||||||
|
|
||||||
key, err := litestream.SnapshotPath(c.Path, generation, index)
|
key := path.Join(c.Path, "generations", generation, "snapshots", litestream.FormatIndex(index), ".snapshot.lz4")
|
||||||
if err != nil {
|
|
||||||
return fmt.Errorf("cannot determine snapshot path: %w", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
if err := c.bkt.Object(key).Delete(ctx); err != nil && !isNotExists(err) {
|
if err := c.bkt.Object(key).Delete(ctx); err != nil && !isNotExists(err) {
|
||||||
return fmt.Errorf("cannot delete snapshot %q: %w", key, err)
|
return fmt.Errorf("cannot delete snapshot %q: %w", key, err)
|
||||||
@@ -220,24 +215,22 @@ func (c *ReplicaClient) DeleteSnapshot(ctx context.Context, generation string, i
|
|||||||
func (c *ReplicaClient) WALSegments(ctx context.Context, generation string) (litestream.WALSegmentIterator, error) {
|
func (c *ReplicaClient) WALSegments(ctx context.Context, generation string) (litestream.WALSegmentIterator, error) {
|
||||||
if err := c.Init(ctx); err != nil {
|
if err := c.Init(ctx); err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
|
} else if generation == "" {
|
||||||
|
return nil, fmt.Errorf("generation required")
|
||||||
}
|
}
|
||||||
dir, err := litestream.WALPath(c.Path, generation)
|
prefix := path.Join(c.Path, "generations", generation, "wal") + "/"
|
||||||
if err != nil {
|
return newWALSegmentIterator(generation, prefix, c.bkt.Objects(ctx, &storage.Query{Prefix: prefix})), 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.
|
// 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) {
|
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 {
|
if err := c.Init(ctx); err != nil {
|
||||||
return info, err
|
return info, err
|
||||||
|
} else if pos.Generation == "" {
|
||||||
|
return info, fmt.Errorf("generation required")
|
||||||
}
|
}
|
||||||
|
|
||||||
key, err := litestream.WALSegmentPath(c.Path, pos.Generation, pos.Index, pos.Offset)
|
key := path.Join(c.Path, "generations", pos.Generation, "wal", litestream.FormatIndex(pos.Index), litestream.FormatOffset(pos.Offset)+".wal.lz4")
|
||||||
if err != nil {
|
|
||||||
return info, fmt.Errorf("cannot determine wal segment path: %w", err)
|
|
||||||
}
|
|
||||||
startTime := time.Now()
|
startTime := time.Now()
|
||||||
|
|
||||||
w := c.bkt.Object(key).NewWriter(ctx)
|
w := c.bkt.Object(key).NewWriter(ctx)
|
||||||
@@ -267,12 +260,11 @@ func (c *ReplicaClient) WriteWALSegment(ctx context.Context, pos litestream.Pos,
|
|||||||
func (c *ReplicaClient) WALSegmentReader(ctx context.Context, pos litestream.Pos) (io.ReadCloser, error) {
|
func (c *ReplicaClient) WALSegmentReader(ctx context.Context, pos litestream.Pos) (io.ReadCloser, error) {
|
||||||
if err := c.Init(ctx); err != nil {
|
if err := c.Init(ctx); err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
|
} else if pos.Generation == "" {
|
||||||
|
return nil, fmt.Errorf("generation required")
|
||||||
}
|
}
|
||||||
|
|
||||||
key, err := litestream.WALSegmentPath(c.Path, pos.Generation, pos.Index, pos.Offset)
|
key := path.Join(c.Path, "generations", pos.Generation, "wal", litestream.FormatIndex(pos.Index), litestream.FormatOffset(pos.Offset)+".wal.lz4")
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("cannot determine wal segment path: %w", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
r, err := c.bkt.Object(key).NewReader(ctx)
|
r, err := c.bkt.Object(key).NewReader(ctx)
|
||||||
if isNotExists(err) {
|
if isNotExists(err) {
|
||||||
@@ -294,11 +286,11 @@ func (c *ReplicaClient) DeleteWALSegments(ctx context.Context, a []litestream.Po
|
|||||||
}
|
}
|
||||||
|
|
||||||
for _, pos := range a {
|
for _, pos := range a {
|
||||||
key, err := litestream.WALSegmentPath(c.Path, pos.Generation, pos.Index, pos.Offset)
|
if pos.Generation == "" {
|
||||||
if err != nil {
|
return fmt.Errorf("generation required")
|
||||||
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) {
|
if err := c.bkt.Object(key).Delete(ctx); err != nil && !isNotExists(err) {
|
||||||
return fmt.Errorf("cannot delete wal segment %q: %w", key, err)
|
return fmt.Errorf("cannot delete wal segment %q: %w", key, err)
|
||||||
}
|
}
|
||||||
@@ -344,7 +336,7 @@ func (itr *snapshotIterator) Next() bool {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Parse index, otherwise skip to the next object.
|
// Parse index, otherwise skip to the next object.
|
||||||
index, err := litestream.ParseSnapshotPath(path.Base(attrs.Name))
|
index, err := internal.ParseSnapshotPath(path.Base(attrs.Name))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
@@ -366,15 +358,17 @@ func (itr *snapshotIterator) Snapshot() litestream.SnapshotInfo { return itr.inf
|
|||||||
|
|
||||||
type walSegmentIterator struct {
|
type walSegmentIterator struct {
|
||||||
generation string
|
generation string
|
||||||
|
prefix string
|
||||||
|
|
||||||
it *storage.ObjectIterator
|
it *storage.ObjectIterator
|
||||||
info litestream.WALSegmentInfo
|
info litestream.WALSegmentInfo
|
||||||
err error
|
err error
|
||||||
}
|
}
|
||||||
|
|
||||||
func newWALSegmentIterator(generation string, it *storage.ObjectIterator) *walSegmentIterator {
|
func newWALSegmentIterator(generation, prefix string, it *storage.ObjectIterator) *walSegmentIterator {
|
||||||
return &walSegmentIterator{
|
return &walSegmentIterator{
|
||||||
generation: generation,
|
generation: generation,
|
||||||
|
prefix: prefix,
|
||||||
it: it,
|
it: it,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -400,7 +394,7 @@ func (itr *walSegmentIterator) Next() bool {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Parse index & offset, otherwise skip to the next object.
|
// Parse index & offset, otherwise skip to the next object.
|
||||||
index, offset, err := litestream.ParseWALSegmentPath(path.Base(attrs.Name))
|
index, offset, err := internal.ParseWALSegmentPath(strings.TrimPrefix(attrs.Name, itr.prefix))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,8 +1,11 @@
|
|||||||
package internal
|
package internal
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"fmt"
|
||||||
"io"
|
"io"
|
||||||
"os"
|
"os"
|
||||||
|
"regexp"
|
||||||
|
"strconv"
|
||||||
"syscall"
|
"syscall"
|
||||||
|
|
||||||
"github.com/prometheus/client_golang/prometheus"
|
"github.com/prometheus/client_golang/prometheus"
|
||||||
@@ -36,6 +39,39 @@ func (r *ReadCloser) Close() error {
|
|||||||
return r.c.Close()
|
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.
|
// ReadCounter wraps an io.Reader and counts the total number of bytes read.
|
||||||
type ReadCounter struct {
|
type ReadCounter struct {
|
||||||
r io.Reader
|
r io.Reader
|
||||||
@@ -127,6 +163,33 @@ func MkdirAll(path string, fi os.FileInfo) error {
|
|||||||
return nil
|
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.
|
// Shared replica metrics.
|
||||||
var (
|
var (
|
||||||
OperationTotalCounterVec = promauto.NewCounterVec(prometheus.CounterOpts{
|
OperationTotalCounterVec = promauto.NewCounterVec(prometheus.CounterOpts{
|
||||||
|
|||||||
61
internal/internal_test.go
Normal file
61
internal/internal_test.go
Normal file
@@ -0,0 +1,61 @@
|
|||||||
|
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)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
166
litestream.go
166
litestream.go
@@ -7,9 +7,7 @@ import (
|
|||||||
"fmt"
|
"fmt"
|
||||||
"io"
|
"io"
|
||||||
"os"
|
"os"
|
||||||
"path"
|
|
||||||
"path/filepath"
|
"path/filepath"
|
||||||
"regexp"
|
|
||||||
"strconv"
|
"strconv"
|
||||||
"strings"
|
"strings"
|
||||||
"time"
|
"time"
|
||||||
@@ -42,6 +40,14 @@ var (
|
|||||||
ErrChecksumMismatch = errors.New("invalid replica, checksum mismatch")
|
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.
|
// SnapshotIterator represents an iterator over a collection of snapshot metadata.
|
||||||
type SnapshotIterator interface {
|
type SnapshotIterator interface {
|
||||||
io.Closer
|
io.Closer
|
||||||
@@ -293,6 +299,26 @@ func (p Pos) Truncate() Pos {
|
|||||||
return Pos{Generation: p.Generation, Index: p.Index}
|
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.
|
// Checksum computes a running SQLite checksum over a byte slice.
|
||||||
func Checksum(bo binary.ByteOrder, s0, s1 uint32, b []byte) (uint32, uint32) {
|
func Checksum(bo binary.ByteOrder, s0, s1 uint32, b []byte) (uint32, uint32) {
|
||||||
assert(len(b)%8 == 0, "misaligned checksum byte slice")
|
assert(len(b)%8 == 0, "misaligned checksum byte slice")
|
||||||
@@ -384,134 +410,34 @@ func IsGenerationName(s string) bool {
|
|||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
|
|
||||||
// GenerationsPath returns the path to a generation root directory.
|
// FormatIndex formats an index as an 8-character hex value.
|
||||||
func GenerationsPath(root string) string {
|
func FormatIndex(index int) string {
|
||||||
return path.Join(root, "generations")
|
return fmt.Sprintf("%08x", index)
|
||||||
}
|
}
|
||||||
|
|
||||||
// GenerationPath returns the path to a generation's root directory.
|
// ParseIndex parses a hex-formatted index into an integer.
|
||||||
func GenerationPath(root, generation string) (string, error) {
|
func ParseIndex(s string) (int, error) {
|
||||||
dir := GenerationsPath(root)
|
v, err := strconv.ParseUint(s, 16, 32)
|
||||||
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 {
|
if err != nil {
|
||||||
return "", err
|
return -1, fmt.Errorf("cannot parse index: %q", s)
|
||||||
}
|
}
|
||||||
return path.Join(dir, "snapshots"), nil
|
return int(v), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// SnapshotPath returns the path to an uncompressed snapshot file.
|
// FormatOffset formats an offset as an 8-character hex value.
|
||||||
func SnapshotPath(root, generation string, index int) (string, error) {
|
func FormatOffset(offset int64) string {
|
||||||
dir, err := SnapshotsPath(root, generation)
|
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)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return "", err
|
return -1, fmt.Errorf("cannot parse index: %q", s)
|
||||||
}
|
}
|
||||||
return path.Join(dir, FormatSnapshotPath(index)), nil
|
return v, 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.
|
// isHexChar returns true if ch is a lowercase hex character.
|
||||||
func isHexChar(ch rune) bool {
|
func isHexChar(ch rune) bool {
|
||||||
return (ch >= '0' && ch <= '9') || (ch >= 'a' && ch <= 'f')
|
return (ch >= '0' && ch <= '9') || (ch >= 'a' && ch <= 'f')
|
||||||
|
|||||||
@@ -40,94 +40,6 @@ 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 MustDecodeHexString(s string) []byte {
|
func MustDecodeHexString(s string) []byte {
|
||||||
b, err := hex.DecodeString(s)
|
b, err := hex.DecodeString(s)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
|||||||
207
replica.go
207
replica.go
@@ -2,7 +2,6 @@ package litestream
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"encoding/binary"
|
|
||||||
"fmt"
|
"fmt"
|
||||||
"hash/crc64"
|
"hash/crc64"
|
||||||
"io"
|
"io"
|
||||||
@@ -67,6 +66,8 @@ type Replica struct {
|
|||||||
// If true, replica monitors database for changes automatically.
|
// If true, replica monitors database for changes automatically.
|
||||||
// Set to false if replica is being used synchronously (such as in tests).
|
// Set to false if replica is being used synchronously (such as in tests).
|
||||||
MonitorEnabled bool
|
MonitorEnabled bool
|
||||||
|
|
||||||
|
Logger *log.Logger
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewReplica(db *DB, name string) *Replica {
|
func NewReplica(db *DB, name string) *Replica {
|
||||||
@@ -81,6 +82,12 @@ func NewReplica(db *DB, name string) *Replica {
|
|||||||
MonitorEnabled: true,
|
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
|
return r
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -149,16 +156,12 @@ func (r *Replica) Sync(ctx context.Context) (err error) {
|
|||||||
}()
|
}()
|
||||||
|
|
||||||
// Find current position of database.
|
// Find current position of database.
|
||||||
dpos, err := r.db.Pos()
|
dpos := r.db.Pos()
|
||||||
if err != nil {
|
if dpos.IsZero() {
|
||||||
return fmt.Errorf("cannot determine current generation: %w", err)
|
|
||||||
} else if dpos.IsZero() {
|
|
||||||
return fmt.Errorf("no generation, waiting for data")
|
return fmt.Errorf("no generation, waiting for data")
|
||||||
}
|
}
|
||||||
generation := dpos.Generation
|
generation := dpos.Generation
|
||||||
|
|
||||||
Tracef("%s(%s): replica sync: db.pos=%s", r.db.Path(), r.Name(), dpos)
|
|
||||||
|
|
||||||
// Create snapshot if no snapshots exist for generation.
|
// Create snapshot if no snapshots exist for generation.
|
||||||
snapshotN, err := r.snapshotN(generation)
|
snapshotN, err := r.snapshotN(generation)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -180,117 +183,140 @@ func (r *Replica) Sync(ctx context.Context) (err error) {
|
|||||||
return fmt.Errorf("cannot determine replica position: %s", err)
|
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.mu.Lock()
|
||||||
r.pos = pos
|
r.pos = pos
|
||||||
r.mu.Unlock()
|
r.mu.Unlock()
|
||||||
}
|
}
|
||||||
|
|
||||||
// Read all WAL files since the last position.
|
// Read all WAL files since the last position.
|
||||||
for {
|
if err = r.syncWAL(ctx); err != nil {
|
||||||
if err = r.syncWAL(ctx); err == io.EOF {
|
return err
|
||||||
break
|
|
||||||
} else if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (r *Replica) syncWAL(ctx context.Context) (err error) {
|
func (r *Replica) syncWAL(ctx context.Context) (err error) {
|
||||||
rd, err := r.db.ShadowWALReader(r.Pos())
|
pos := r.Pos()
|
||||||
if err == io.EOF {
|
|
||||||
|
itr, err := r.db.WALSegments(ctx, pos.Generation)
|
||||||
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
} else if err != nil {
|
|
||||||
return fmt.Errorf("replica wal reader: %w", err)
|
|
||||||
}
|
}
|
||||||
defer rd.Close()
|
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
|
||||||
|
|
||||||
// Copy shadow WAL to client write via io.Pipe().
|
// Copy shadow WAL to client write via io.Pipe().
|
||||||
pr, pw := io.Pipe()
|
pr, pw := io.Pipe()
|
||||||
defer func() { _ = pw.CloseWithError(err) }()
|
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.
|
// Copy through pipe into client from the starting position.
|
||||||
var g errgroup.Group
|
var g errgroup.Group
|
||||||
g.Go(func() error {
|
g.Go(func() error {
|
||||||
_, err := r.Client.WriteWALSegment(ctx, pos, pr)
|
_, err := r.Client.WriteWALSegment(ctx, initialPos, pr)
|
||||||
return err
|
return err
|
||||||
})
|
})
|
||||||
|
|
||||||
// Wrap writer to LZ4 compress.
|
// Wrap writer to LZ4 compress.
|
||||||
zw := lz4.NewWriter(pw)
|
zw := lz4.NewWriter(pw)
|
||||||
|
|
||||||
// Track total WAL bytes written to replica client.
|
// Write each segment out to the replica.
|
||||||
walBytesCounter := replicaWALBytesCounterVec.WithLabelValues(r.db.Path(), r.Name())
|
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())
|
||||||
|
}
|
||||||
|
|
||||||
// Copy header if at offset zero.
|
rc, err := r.db.WALSegmentReader(ctx, info.Pos())
|
||||||
var psalt uint64 // previous salt value
|
if err != nil {
|
||||||
if pos := rd.Pos(); pos.Offset == 0 {
|
return err
|
||||||
buf := make([]byte, WALHeaderSize)
|
}
|
||||||
if _, err := io.ReadFull(rd, buf); err != nil {
|
defer rc.Close()
|
||||||
return err
|
|
||||||
|
n, err := io.Copy(zw, lz4.NewReader(rc))
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
} else if err := rc.Close(); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
// 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)
|
||||||
}
|
}
|
||||||
|
|
||||||
psalt = binary.BigEndian.Uint64(buf[16:24])
|
|
||||||
|
|
||||||
n, err := zw.Write(buf)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
walBytesCounter.Add(float64(n))
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Copy frames.
|
// Flush LZ4 writer, close pipe, and wait for write to finish.
|
||||||
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
|
|
||||||
}
|
|
||||||
walBytesCounter.Add(float64(n))
|
|
||||||
}
|
|
||||||
|
|
||||||
// Flush LZ4 writer and close pipe.
|
|
||||||
if err := zw.Close(); err != nil {
|
if err := zw.Close(); err != nil {
|
||||||
return err
|
return err
|
||||||
} else if err := pw.Close(); err != nil {
|
} else if err := pw.Close(); err != nil {
|
||||||
return err
|
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.
|
// Save last replicated position.
|
||||||
r.mu.Lock()
|
r.mu.Lock()
|
||||||
r.pos = rd.Pos()
|
r.pos = pos
|
||||||
r.mu.Unlock()
|
r.mu.Unlock()
|
||||||
|
|
||||||
// Track current position
|
replicaWALBytesCounterVec.WithLabelValues(r.db.Path(), r.Name()).Add(float64(pos.Offset - initialPos.Offset))
|
||||||
replicaWALIndexGaugeVec.WithLabelValues(r.db.Path(), r.Name()).Set(float64(rd.Pos().Index))
|
|
||||||
replicaWALOffsetGaugeVec.WithLabelValues(r.db.Path(), r.Name()).Set(float64(rd.Pos().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)
|
||||||
|
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
@@ -448,10 +474,8 @@ func (r *Replica) Snapshot(ctx context.Context) (info SnapshotInfo, err error) {
|
|||||||
defer func() { _ = tx.Rollback() }()
|
defer func() { _ = tx.Rollback() }()
|
||||||
|
|
||||||
// Obtain current position.
|
// Obtain current position.
|
||||||
pos, err := r.db.Pos()
|
pos := r.db.Pos()
|
||||||
if err != nil {
|
if pos.IsZero() {
|
||||||
return info, fmt.Errorf("cannot determine db position: %w", err)
|
|
||||||
} else if pos.IsZero() {
|
|
||||||
return info, ErrNoGeneration
|
return info, ErrNoGeneration
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -491,7 +515,7 @@ func (r *Replica) Snapshot(ctx context.Context) (info SnapshotInfo, err error) {
|
|||||||
return info, err
|
return info, err
|
||||||
}
|
}
|
||||||
|
|
||||||
log.Printf("%s(%s): snapshot written %s/%08x", r.db.Path(), r.Name(), pos.Generation, pos.Index)
|
log.Printf("snapshot written %s/%08x", pos.Generation, pos.Index)
|
||||||
|
|
||||||
return info, nil
|
return info, nil
|
||||||
}
|
}
|
||||||
@@ -559,7 +583,7 @@ func (r *Replica) deleteSnapshotsBeforeIndex(ctx context.Context, generation str
|
|||||||
if err := r.Client.DeleteSnapshot(ctx, info.Generation, info.Index); err != nil {
|
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)
|
return fmt.Errorf("delete snapshot %s/%08x: %w", info.Generation, info.Index, err)
|
||||||
}
|
}
|
||||||
log.Printf("%s(%s): snapshot deleted %s/%08x", r.db.Path(), r.Name(), generation, index)
|
r.Logger.Printf("snapshot deleted %s/%08x", generation, index)
|
||||||
}
|
}
|
||||||
|
|
||||||
return itr.Close()
|
return itr.Close()
|
||||||
@@ -591,7 +615,10 @@ func (r *Replica) deleteWALSegmentsBeforeIndex(ctx context.Context, generation s
|
|||||||
if err := r.Client.DeleteWALSegments(ctx, a); err != nil {
|
if err := r.Client.DeleteWALSegments(ctx, a); err != nil {
|
||||||
return fmt.Errorf("delete wal segments: %w", err)
|
return fmt.Errorf("delete wal segments: %w", err)
|
||||||
}
|
}
|
||||||
log.Printf("%s(%s): wal segmented deleted before %s/%08x: n=%d", r.db.Path(), r.Name(), generation, index, len(a))
|
|
||||||
|
for _, pos := range a {
|
||||||
|
r.Logger.Printf("wal segmented deleted: %s", pos)
|
||||||
|
}
|
||||||
|
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
@@ -628,7 +655,7 @@ func (r *Replica) monitor(ctx context.Context) {
|
|||||||
|
|
||||||
// Synchronize the shadow wal into the replication directory.
|
// Synchronize the shadow wal into the replication directory.
|
||||||
if err := r.Sync(ctx); err != nil {
|
if err := r.Sync(ctx); err != nil {
|
||||||
log.Printf("%s(%s): monitor error: %s", r.db.Path(), r.Name(), err)
|
r.Logger.Printf("monitor error: %s", err)
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -656,7 +683,7 @@ func (r *Replica) retainer(ctx context.Context) {
|
|||||||
return
|
return
|
||||||
case <-ticker.C:
|
case <-ticker.C:
|
||||||
if err := r.EnforceRetention(ctx); err != nil {
|
if err := r.EnforceRetention(ctx); err != nil {
|
||||||
log.Printf("%s(%s): retainer error: %s", r.db.Path(), r.Name(), err)
|
r.Logger.Printf("retainer error: %s", err)
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -678,7 +705,7 @@ func (r *Replica) snapshotter(ctx context.Context) {
|
|||||||
return
|
return
|
||||||
case <-ticker.C:
|
case <-ticker.C:
|
||||||
if _, err := r.Snapshot(ctx); err != nil && err != ErrNoGeneration {
|
if _, err := r.Snapshot(ctx); err != nil && err != ErrNoGeneration {
|
||||||
log.Printf("%s(%s): snapshotter error: %s", r.db.Path(), r.Name(), err)
|
r.Logger.Printf("snapshotter error: %s", err)
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -706,7 +733,7 @@ func (r *Replica) validator(ctx context.Context) {
|
|||||||
return
|
return
|
||||||
case <-ticker.C:
|
case <-ticker.C:
|
||||||
if err := r.Validate(ctx); err != nil {
|
if err := r.Validate(ctx); err != nil {
|
||||||
log.Printf("%s(%s): validation error: %s", r.db.Path(), r.Name(), err)
|
r.Logger.Printf("validation error: %s", err)
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -768,7 +795,7 @@ func (r *Replica) Validate(ctx context.Context) error {
|
|||||||
if mismatch {
|
if mismatch {
|
||||||
status = "mismatch"
|
status = "mismatch"
|
||||||
}
|
}
|
||||||
log.Printf("%s(%s): validator: status=%s db=%016x replica=%016x pos=%s", db.Path(), r.Name(), status, chksum0, chksum1, pos)
|
r.Logger.Printf("validator: status=%s db=%016x replica=%016x pos=%s", status, chksum0, chksum1, pos)
|
||||||
|
|
||||||
// Validate checksums match.
|
// Validate checksums match.
|
||||||
if mismatch {
|
if mismatch {
|
||||||
@@ -786,8 +813,6 @@ func (r *Replica) Validate(ctx context.Context) error {
|
|||||||
|
|
||||||
// waitForReplica blocks until replica reaches at least the given position.
|
// waitForReplica blocks until replica reaches at least the given position.
|
||||||
func (r *Replica) waitForReplica(ctx context.Context, pos Pos) error {
|
func (r *Replica) waitForReplica(ctx context.Context, pos Pos) error {
|
||||||
db := r.DB()
|
|
||||||
|
|
||||||
ticker := time.NewTicker(500 * time.Millisecond)
|
ticker := time.NewTicker(500 * time.Millisecond)
|
||||||
defer ticker.Stop()
|
defer ticker.Stop()
|
||||||
|
|
||||||
@@ -810,7 +835,7 @@ func (r *Replica) waitForReplica(ctx context.Context, pos Pos) error {
|
|||||||
// Obtain current position of replica, check if past target position.
|
// Obtain current position of replica, check if past target position.
|
||||||
curr := r.Pos()
|
curr := r.Pos()
|
||||||
if curr.IsZero() {
|
if curr.IsZero() {
|
||||||
log.Printf("%s(%s): validator: no replica position available", db.Path(), r.Name())
|
r.Logger.Printf("validator: no replica position available")
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -177,7 +177,7 @@ func TestReplicaClient_Snapshots(t *testing.T) {
|
|||||||
if err == nil {
|
if err == nil {
|
||||||
err = itr.Close()
|
err = itr.Close()
|
||||||
}
|
}
|
||||||
if err == nil || err.Error() != `cannot determine snapshots path: generation required` {
|
if err == nil || err.Error() != `generation required` {
|
||||||
t.Fatalf("unexpected error: %v", err)
|
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) {
|
RunWithReplicaClient(t, "ErrNoGeneration", func(t *testing.T, c litestream.ReplicaClient) {
|
||||||
t.Parallel()
|
t.Parallel()
|
||||||
if _, err := c.WriteSnapshot(context.Background(), "", 0, nil); err == nil || err.Error() != `cannot determine snapshot path: generation required` {
|
if _, err := c.WriteSnapshot(context.Background(), "", 0, nil); err == nil || err.Error() != `generation required` {
|
||||||
t.Fatalf("unexpected error: %v", err)
|
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) {
|
RunWithReplicaClient(t, "ErrNoGeneration", func(t *testing.T, c litestream.ReplicaClient) {
|
||||||
t.Parallel()
|
t.Parallel()
|
||||||
|
|
||||||
if _, err := c.SnapshotReader(context.Background(), "", 1); err == nil || err.Error() != `cannot determine snapshot path: generation required` {
|
if _, err := c.SnapshotReader(context.Background(), "", 1); err == nil || err.Error() != `generation required` {
|
||||||
t.Fatalf("unexpected error: %v", err)
|
t.Fatalf("unexpected error: %v", err)
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestReplicaClient_WALs(t *testing.T) {
|
func TestReplicaClient_WALSegments(t *testing.T) {
|
||||||
RunWithReplicaClient(t, "OK", func(t *testing.T, c litestream.ReplicaClient) {
|
RunWithReplicaClient(t, "OK", func(t *testing.T, c litestream.ReplicaClient) {
|
||||||
t.Parallel()
|
t.Parallel()
|
||||||
|
|
||||||
@@ -362,7 +362,7 @@ func TestReplicaClient_WALs(t *testing.T) {
|
|||||||
if err == nil {
|
if err == nil {
|
||||||
err = itr.Close()
|
err = itr.Close()
|
||||||
}
|
}
|
||||||
if err == nil || err.Error() != `cannot determine wal path: generation required` {
|
if err == nil || err.Error() != `generation required` {
|
||||||
t.Fatalf("unexpected error: %v", err)
|
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) {
|
RunWithReplicaClient(t, "ErrNoGeneration", func(t *testing.T, c litestream.ReplicaClient) {
|
||||||
t.Parallel()
|
t.Parallel()
|
||||||
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` {
|
if _, err := c.WriteWALSegment(context.Background(), litestream.Pos{Generation: "", Index: 0, Offset: 0}, nil); err == nil || err.Error() != `generation required` {
|
||||||
t.Fatalf("unexpected error: %v", err)
|
t.Fatalf("unexpected error: %v", err)
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestReplicaClient_WALReader(t *testing.T) {
|
func TestReplicaClient_WALSegmentReader(t *testing.T) {
|
||||||
|
|
||||||
RunWithReplicaClient(t, "OK", func(t *testing.T, c litestream.ReplicaClient) {
|
RunWithReplicaClient(t, "OK", func(t *testing.T, c litestream.ReplicaClient) {
|
||||||
t.Parallel()
|
t.Parallel()
|
||||||
@@ -451,7 +451,7 @@ func TestReplicaClient_DeleteWALSegments(t *testing.T) {
|
|||||||
|
|
||||||
RunWithReplicaClient(t, "ErrNoGeneration", func(t *testing.T, c litestream.ReplicaClient) {
|
RunWithReplicaClient(t, "ErrNoGeneration", func(t *testing.T, c litestream.ReplicaClient) {
|
||||||
t.Parallel()
|
t.Parallel()
|
||||||
if err := c.DeleteWALSegments(context.Background(), []litestream.Pos{{}}); err == nil || err.Error() != `cannot determine wal segment path: generation required` {
|
if err := c.DeleteWALSegments(context.Background(), []litestream.Pos{{}}); err == nil || err.Error() != `generation required` {
|
||||||
t.Fatalf("unexpected error: %v", err)
|
t.Fatalf("unexpected error: %v", err)
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -43,10 +43,7 @@ func TestReplica_Sync(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Fetch current database position.
|
// Fetch current database position.
|
||||||
dpos, err := db.Pos()
|
dpos := db.Pos()
|
||||||
if err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
|
|
||||||
c := file.NewReplicaClient(t.TempDir())
|
c := file.NewReplicaClient(t.TempDir())
|
||||||
r := litestream.NewReplica(db, "")
|
r := litestream.NewReplica(db, "")
|
||||||
@@ -69,11 +66,11 @@ func TestReplica_Sync(t *testing.T) {
|
|||||||
// Verify WAL matches replica WAL.
|
// Verify WAL matches replica WAL.
|
||||||
if b0, err := os.ReadFile(db.Path() + "-wal"); err != nil {
|
if b0, err := os.ReadFile(db.Path() + "-wal"); err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
} else if r, err := c.WALSegmentReader(context.Background(), litestream.Pos{Generation: generations[0], Index: 0, Offset: 0}); err != nil {
|
} else if r0, err := c.WALSegmentReader(context.Background(), litestream.Pos{Generation: generations[0], Index: 0, Offset: 0}); err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
} else if b1, err := io.ReadAll(lz4.NewReader(r)); err != nil {
|
} else if b1, err := io.ReadAll(lz4.NewReader(r0)); err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
} else if err := r.Close(); err != nil {
|
} else if err := r0.Close(); err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
} else if !bytes.Equal(b0, b1) {
|
} else if !bytes.Equal(b0, b1) {
|
||||||
t.Fatalf("wal mismatch: len(%d), len(%d)", len(b0), len(b1))
|
t.Fatalf("wal mismatch: len(%d), len(%d)", len(b0), len(b1))
|
||||||
@@ -98,10 +95,8 @@ func TestReplica_Snapshot(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Fetch current database position & snapshot.
|
// Fetch current database position & snapshot.
|
||||||
pos0, err := db.Pos()
|
pos0 := db.Pos()
|
||||||
if err != nil {
|
if info, err := r.Snapshot(context.Background()); err != nil {
|
||||||
t.Fatal(err)
|
|
||||||
} else if info, err := r.Snapshot(context.Background()); err != nil {
|
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
} else if got, want := info.Pos(), pos0.Truncate(); got != want {
|
} else if got, want := info.Pos(), pos0.Truncate(); got != want {
|
||||||
t.Fatalf("pos=%s, want %s", got, want)
|
t.Fatalf("pos=%s, want %s", got, want)
|
||||||
@@ -122,10 +117,8 @@ func TestReplica_Snapshot(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Fetch current database position & snapshot.
|
// Fetch current database position & snapshot.
|
||||||
pos1, err := db.Pos()
|
pos1 := db.Pos()
|
||||||
if err != nil {
|
if info, err := r.Snapshot(context.Background()); err != nil {
|
||||||
t.Fatal(err)
|
|
||||||
} else if info, err := r.Snapshot(context.Background()); err != nil {
|
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
} else if got, want := info.Pos(), pos1.Truncate(); got != want {
|
} else if got, want := info.Pos(), pos1.Truncate(); got != want {
|
||||||
t.Fatalf("pos=%v, want %v", got, want)
|
t.Fatalf("pos=%v, want %v", got, want)
|
||||||
|
|||||||
@@ -10,6 +10,7 @@ import (
|
|||||||
"os"
|
"os"
|
||||||
"path"
|
"path"
|
||||||
"regexp"
|
"regexp"
|
||||||
|
"strings"
|
||||||
"sync"
|
"sync"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
@@ -154,7 +155,7 @@ func (c *ReplicaClient) Generations(ctx context.Context) ([]string, error) {
|
|||||||
var generations []string
|
var generations []string
|
||||||
if err := c.s3.ListObjectsPagesWithContext(ctx, &s3.ListObjectsInput{
|
if err := c.s3.ListObjectsPagesWithContext(ctx, &s3.ListObjectsInput{
|
||||||
Bucket: aws.String(c.Bucket),
|
Bucket: aws.String(c.Bucket),
|
||||||
Prefix: aws.String(litestream.GenerationsPath(c.Path) + "/"),
|
Prefix: aws.String(path.Join(c.Path, "generations") + "/"),
|
||||||
Delimiter: aws.String("/"),
|
Delimiter: aws.String("/"),
|
||||||
}, func(page *s3.ListObjectsOutput, lastPage bool) bool {
|
}, func(page *s3.ListObjectsOutput, lastPage bool) bool {
|
||||||
internal.OperationTotalCounterVec.WithLabelValues(ReplicaClientType, "LIST").Inc()
|
internal.OperationTotalCounterVec.WithLabelValues(ReplicaClientType, "LIST").Inc()
|
||||||
@@ -178,18 +179,15 @@ func (c *ReplicaClient) Generations(ctx context.Context) ([]string, error) {
|
|||||||
func (c *ReplicaClient) DeleteGeneration(ctx context.Context, generation string) error {
|
func (c *ReplicaClient) DeleteGeneration(ctx context.Context, generation string) error {
|
||||||
if err := c.Init(ctx); err != nil {
|
if err := c.Init(ctx); err != nil {
|
||||||
return err
|
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.
|
// Collect all files for the generation.
|
||||||
var objIDs []*s3.ObjectIdentifier
|
var objIDs []*s3.ObjectIdentifier
|
||||||
if err := c.s3.ListObjectsPagesWithContext(ctx, &s3.ListObjectsInput{
|
if err := c.s3.ListObjectsPagesWithContext(ctx, &s3.ListObjectsInput{
|
||||||
Bucket: aws.String(c.Bucket),
|
Bucket: aws.String(c.Bucket),
|
||||||
Prefix: aws.String(dir),
|
Prefix: aws.String(path.Join(c.Path, "generations", generation)),
|
||||||
}, func(page *s3.ListObjectsOutput, lastPage bool) bool {
|
}, func(page *s3.ListObjectsOutput, lastPage bool) bool {
|
||||||
internal.OperationTotalCounterVec.WithLabelValues(ReplicaClientType, "LIST").Inc()
|
internal.OperationTotalCounterVec.WithLabelValues(ReplicaClientType, "LIST").Inc()
|
||||||
|
|
||||||
@@ -236,12 +234,11 @@ 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) {
|
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 {
|
if err := c.Init(ctx); err != nil {
|
||||||
return info, err
|
return info, err
|
||||||
|
} else if generation == "" {
|
||||||
|
return info, fmt.Errorf("generation required")
|
||||||
}
|
}
|
||||||
|
|
||||||
key, err := litestream.SnapshotPath(c.Path, generation, index)
|
key := path.Join(c.Path, "generations", generation, "snapshots", litestream.FormatIndex(index)+".snapshot.lz4")
|
||||||
if err != nil {
|
|
||||||
return info, fmt.Errorf("cannot determine snapshot path: %w", err)
|
|
||||||
}
|
|
||||||
startTime := time.Now()
|
startTime := time.Now()
|
||||||
|
|
||||||
rc := internal.NewReadCounter(rd)
|
rc := internal.NewReadCounter(rd)
|
||||||
@@ -270,12 +267,11 @@ func (c *ReplicaClient) WriteSnapshot(ctx context.Context, generation string, in
|
|||||||
func (c *ReplicaClient) SnapshotReader(ctx context.Context, generation string, index int) (io.ReadCloser, error) {
|
func (c *ReplicaClient) SnapshotReader(ctx context.Context, generation string, index int) (io.ReadCloser, error) {
|
||||||
if err := c.Init(ctx); err != nil {
|
if err := c.Init(ctx); err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
|
} else if generation == "" {
|
||||||
|
return nil, fmt.Errorf("generation required")
|
||||||
}
|
}
|
||||||
|
|
||||||
key, err := litestream.SnapshotPath(c.Path, generation, index)
|
key := path.Join(c.Path, "generations", generation, "snapshots", litestream.FormatIndex(index)+".snapshot.lz4")
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("cannot determine snapshot path: %w", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
out, err := c.s3.GetObjectWithContext(ctx, &s3.GetObjectInput{
|
out, err := c.s3.GetObjectWithContext(ctx, &s3.GetObjectInput{
|
||||||
Bucket: aws.String(c.Bucket),
|
Bucket: aws.String(c.Bucket),
|
||||||
@@ -296,12 +292,11 @@ func (c *ReplicaClient) SnapshotReader(ctx context.Context, generation string, i
|
|||||||
func (c *ReplicaClient) DeleteSnapshot(ctx context.Context, generation string, index int) error {
|
func (c *ReplicaClient) DeleteSnapshot(ctx context.Context, generation string, index int) error {
|
||||||
if err := c.Init(ctx); err != nil {
|
if err := c.Init(ctx); err != nil {
|
||||||
return err
|
return err
|
||||||
|
} else if generation == "" {
|
||||||
|
return fmt.Errorf("generation required")
|
||||||
}
|
}
|
||||||
|
|
||||||
key, err := litestream.SnapshotPath(c.Path, generation, index)
|
key := path.Join(c.Path, "generations", generation, "snapshots", litestream.FormatIndex(index)+".snapshot.lz4")
|
||||||
if err != nil {
|
|
||||||
return fmt.Errorf("cannot determine snapshot path: %w", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
if _, err := c.s3.DeleteObjectsWithContext(ctx, &s3.DeleteObjectsInput{
|
if _, err := c.s3.DeleteObjectsWithContext(ctx, &s3.DeleteObjectsInput{
|
||||||
Bucket: aws.String(c.Bucket),
|
Bucket: aws.String(c.Bucket),
|
||||||
@@ -326,12 +321,11 @@ 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) {
|
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 {
|
if err := c.Init(ctx); err != nil {
|
||||||
return info, err
|
return info, err
|
||||||
|
} else if pos.Generation == "" {
|
||||||
|
return info, fmt.Errorf("generation required")
|
||||||
}
|
}
|
||||||
|
|
||||||
key, err := litestream.WALSegmentPath(c.Path, pos.Generation, pos.Index, pos.Offset)
|
key := path.Join(c.Path, "generations", pos.Generation, "wal", litestream.FormatIndex(pos.Index), litestream.FormatOffset(pos.Offset)+".wal.lz4")
|
||||||
if err != nil {
|
|
||||||
return info, fmt.Errorf("cannot determine wal segment path: %w", err)
|
|
||||||
}
|
|
||||||
startTime := time.Now()
|
startTime := time.Now()
|
||||||
|
|
||||||
rc := internal.NewReadCounter(rd)
|
rc := internal.NewReadCounter(rd)
|
||||||
@@ -360,12 +354,11 @@ func (c *ReplicaClient) WriteWALSegment(ctx context.Context, pos litestream.Pos,
|
|||||||
func (c *ReplicaClient) WALSegmentReader(ctx context.Context, pos litestream.Pos) (io.ReadCloser, error) {
|
func (c *ReplicaClient) WALSegmentReader(ctx context.Context, pos litestream.Pos) (io.ReadCloser, error) {
|
||||||
if err := c.Init(ctx); err != nil {
|
if err := c.Init(ctx); err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
|
} else if pos.Generation == "" {
|
||||||
|
return nil, fmt.Errorf("generation required")
|
||||||
}
|
}
|
||||||
|
|
||||||
key, err := litestream.WALSegmentPath(c.Path, pos.Generation, pos.Index, pos.Offset)
|
key := path.Join(c.Path, "generations", pos.Generation, "wal", litestream.FormatIndex(pos.Index), litestream.FormatOffset(pos.Offset)+".wal.lz4")
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("cannot determine wal segment path: %w", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
out, err := c.s3.GetObjectWithContext(ctx, &s3.GetObjectInput{
|
out, err := c.s3.GetObjectWithContext(ctx, &s3.GetObjectInput{
|
||||||
Bucket: aws.String(c.Bucket),
|
Bucket: aws.String(c.Bucket),
|
||||||
@@ -397,10 +390,10 @@ func (c *ReplicaClient) DeleteWALSegments(ctx context.Context, a []litestream.Po
|
|||||||
|
|
||||||
// Generate a batch of object IDs for deleting the WAL segments.
|
// Generate a batch of object IDs for deleting the WAL segments.
|
||||||
for i, pos := range a[:n] {
|
for i, pos := range a[:n] {
|
||||||
key, err := litestream.WALSegmentPath(c.Path, pos.Generation, pos.Index, pos.Offset)
|
if pos.Generation == "" {
|
||||||
if err != nil {
|
return fmt.Errorf("generation required")
|
||||||
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}
|
objIDs[i] = &s3.ObjectIdentifier{Key: &key}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -498,11 +491,12 @@ func newSnapshotIterator(ctx context.Context, client *ReplicaClient, generation
|
|||||||
func (itr *snapshotIterator) fetch() error {
|
func (itr *snapshotIterator) fetch() error {
|
||||||
defer close(itr.ch)
|
defer close(itr.ch)
|
||||||
|
|
||||||
dir, err := litestream.SnapshotsPath(itr.client.Path, itr.generation)
|
if itr.generation == "" {
|
||||||
if err != nil {
|
return fmt.Errorf("generation required")
|
||||||
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{
|
return itr.client.s3.ListObjectsPagesWithContext(itr.ctx, &s3.ListObjectsInput{
|
||||||
Bucket: aws.String(itr.client.Bucket),
|
Bucket: aws.String(itr.client.Bucket),
|
||||||
Prefix: aws.String(dir + "/"),
|
Prefix: aws.String(dir + "/"),
|
||||||
@@ -511,8 +505,7 @@ func (itr *snapshotIterator) fetch() error {
|
|||||||
internal.OperationTotalCounterVec.WithLabelValues(ReplicaClientType, "LIST").Inc()
|
internal.OperationTotalCounterVec.WithLabelValues(ReplicaClientType, "LIST").Inc()
|
||||||
|
|
||||||
for _, obj := range page.Contents {
|
for _, obj := range page.Contents {
|
||||||
key := path.Base(*obj.Key)
|
index, err := internal.ParseSnapshotPath(path.Base(*obj.Key))
|
||||||
index, err := litestream.ParseSnapshotPath(key)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
@@ -601,21 +594,20 @@ func newWALSegmentIterator(ctx context.Context, client *ReplicaClient, generatio
|
|||||||
func (itr *walSegmentIterator) fetch() error {
|
func (itr *walSegmentIterator) fetch() error {
|
||||||
defer close(itr.ch)
|
defer close(itr.ch)
|
||||||
|
|
||||||
dir, err := litestream.WALPath(itr.client.Path, itr.generation)
|
if itr.generation == "" {
|
||||||
if err != nil {
|
return fmt.Errorf("generation required")
|
||||||
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{
|
return itr.client.s3.ListObjectsPagesWithContext(itr.ctx, &s3.ListObjectsInput{
|
||||||
Bucket: aws.String(itr.client.Bucket),
|
Bucket: aws.String(itr.client.Bucket),
|
||||||
Prefix: aws.String(dir + "/"),
|
Prefix: aws.String(prefix),
|
||||||
Delimiter: aws.String("/"),
|
|
||||||
}, func(page *s3.ListObjectsOutput, lastPage bool) bool {
|
}, func(page *s3.ListObjectsOutput, lastPage bool) bool {
|
||||||
internal.OperationTotalCounterVec.WithLabelValues(ReplicaClientType, "LIST").Inc()
|
internal.OperationTotalCounterVec.WithLabelValues(ReplicaClientType, "LIST").Inc()
|
||||||
|
|
||||||
for _, obj := range page.Contents {
|
for _, obj := range page.Contents {
|
||||||
key := path.Base(*obj.Key)
|
index, offset, err := internal.ParseWALSegmentPath(strings.TrimPrefix(*obj.Key, prefix))
|
||||||
index, offset, err := litestream.ParseWALSegmentPath(key)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -9,6 +9,7 @@ import (
|
|||||||
"os"
|
"os"
|
||||||
"path"
|
"path"
|
||||||
"sort"
|
"sort"
|
||||||
|
"strings"
|
||||||
"sync"
|
"sync"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
@@ -121,7 +122,7 @@ func (c *ReplicaClient) Generations(ctx context.Context) (_ []string, err error)
|
|||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
fis, err := sftpClient.ReadDir(litestream.GenerationsPath(c.Path))
|
fis, err := sftpClient.ReadDir(path.Join(c.Path, "generations"))
|
||||||
if os.IsNotExist(err) {
|
if os.IsNotExist(err) {
|
||||||
return nil, nil
|
return nil, nil
|
||||||
} else if err != nil {
|
} else if err != nil {
|
||||||
@@ -153,12 +154,11 @@ func (c *ReplicaClient) DeleteGeneration(ctx context.Context, generation string)
|
|||||||
sftpClient, err := c.Init(ctx)
|
sftpClient, err := c.Init(ctx)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
|
} else if generation == "" {
|
||||||
|
return fmt.Errorf("generation required")
|
||||||
}
|
}
|
||||||
|
|
||||||
dir, err := litestream.GenerationPath(c.Path, generation)
|
dir := path.Join(c.Path, "generations", generation)
|
||||||
if err != nil {
|
|
||||||
return fmt.Errorf("cannot determine generation path: %w", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
var dirs []string
|
var dirs []string
|
||||||
walker := sftpClient.Walk(dir)
|
walker := sftpClient.Walk(dir)
|
||||||
@@ -198,12 +198,11 @@ func (c *ReplicaClient) Snapshots(ctx context.Context, generation string) (_ lit
|
|||||||
sftpClient, err := c.Init(ctx)
|
sftpClient, err := c.Init(ctx)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
|
} else if generation == "" {
|
||||||
|
return nil, fmt.Errorf("generation required")
|
||||||
}
|
}
|
||||||
|
|
||||||
dir, err := litestream.SnapshotsPath(c.Path, generation)
|
dir := path.Join(c.Path, "generations", generation, "snapshots")
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("cannot determine snapshots path: %w", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
fis, err := sftpClient.ReadDir(dir)
|
fis, err := sftpClient.ReadDir(dir)
|
||||||
if os.IsNotExist(err) {
|
if os.IsNotExist(err) {
|
||||||
@@ -216,7 +215,7 @@ func (c *ReplicaClient) Snapshots(ctx context.Context, generation string) (_ lit
|
|||||||
infos := make([]litestream.SnapshotInfo, 0, len(fis))
|
infos := make([]litestream.SnapshotInfo, 0, len(fis))
|
||||||
for _, fi := range fis {
|
for _, fi := range fis {
|
||||||
// Parse index from filename.
|
// Parse index from filename.
|
||||||
index, err := litestream.ParseSnapshotPath(path.Base(fi.Name()))
|
index, err := internal.ParseSnapshotPath(path.Base(fi.Name()))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
@@ -241,12 +240,11 @@ func (c *ReplicaClient) WriteSnapshot(ctx context.Context, generation string, in
|
|||||||
sftpClient, err := c.Init(ctx)
|
sftpClient, err := c.Init(ctx)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return info, err
|
return info, err
|
||||||
|
} else if generation == "" {
|
||||||
|
return info, fmt.Errorf("generation required")
|
||||||
}
|
}
|
||||||
|
|
||||||
filename, err := litestream.SnapshotPath(c.Path, generation, index)
|
filename := path.Join(c.Path, "generations", generation, "snapshots", litestream.FormatIndex(index)+".snapshot.lz4")
|
||||||
if err != nil {
|
|
||||||
return info, fmt.Errorf("cannot determine snapshot path: %w", err)
|
|
||||||
}
|
|
||||||
startTime := time.Now()
|
startTime := time.Now()
|
||||||
|
|
||||||
if err := sftpClient.MkdirAll(path.Dir(filename)); err != nil {
|
if err := sftpClient.MkdirAll(path.Dir(filename)); err != nil {
|
||||||
@@ -286,12 +284,11 @@ func (c *ReplicaClient) SnapshotReader(ctx context.Context, generation string, i
|
|||||||
sftpClient, err := c.Init(ctx)
|
sftpClient, err := c.Init(ctx)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
|
} else if generation == "" {
|
||||||
|
return nil, fmt.Errorf("generation required")
|
||||||
}
|
}
|
||||||
|
|
||||||
filename, err := litestream.SnapshotPath(c.Path, generation, index)
|
filename := path.Join(c.Path, "generations", generation, "snapshots", litestream.FormatIndex(index)+".snapshot.lz4")
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("cannot determine snapshot path: %w", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
f, err := sftpClient.Open(filename)
|
f, err := sftpClient.Open(filename)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -310,12 +307,11 @@ func (c *ReplicaClient) DeleteSnapshot(ctx context.Context, generation string, i
|
|||||||
sftpClient, err := c.Init(ctx)
|
sftpClient, err := c.Init(ctx)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
|
} else if generation == "" {
|
||||||
|
return fmt.Errorf("generation required")
|
||||||
}
|
}
|
||||||
|
|
||||||
filename, err := litestream.SnapshotPath(c.Path, generation, index)
|
filename := path.Join(c.Path, "generations", generation, "snapshots", litestream.FormatIndex(index)+".snapshot.lz4")
|
||||||
if err != nil {
|
|
||||||
return fmt.Errorf("cannot determine snapshot path: %w", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
if err := sftpClient.Remove(filename); err != nil && !os.IsNotExist(err) {
|
if err := sftpClient.Remove(filename); err != nil && !os.IsNotExist(err) {
|
||||||
return fmt.Errorf("cannot delete snapshot %q: %w", filename, err)
|
return fmt.Errorf("cannot delete snapshot %q: %w", filename, err)
|
||||||
@@ -332,12 +328,11 @@ func (c *ReplicaClient) WALSegments(ctx context.Context, generation string) (_ l
|
|||||||
sftpClient, err := c.Init(ctx)
|
sftpClient, err := c.Init(ctx)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
|
} else if generation == "" {
|
||||||
|
return nil, fmt.Errorf("generation required")
|
||||||
}
|
}
|
||||||
|
|
||||||
dir, err := litestream.WALPath(c.Path, generation)
|
dir := path.Join(c.Path, "generations", generation, "wal")
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("cannot determine wal path: %w", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
fis, err := sftpClient.ReadDir(dir)
|
fis, err := sftpClient.ReadDir(dir)
|
||||||
if os.IsNotExist(err) {
|
if os.IsNotExist(err) {
|
||||||
@@ -347,25 +342,18 @@ func (c *ReplicaClient) WALSegments(ctx context.Context, generation string) (_ l
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Iterate over every file and convert to metadata.
|
// Iterate over every file and convert to metadata.
|
||||||
infos := make([]litestream.WALSegmentInfo, 0, len(fis))
|
indexes := make([]int, 0, len(fis))
|
||||||
for _, fi := range fis {
|
for _, fi := range fis {
|
||||||
index, offset, err := litestream.ParseWALSegmentPath(path.Base(fi.Name()))
|
index, err := litestream.ParseIndex(fi.Name())
|
||||||
if err != nil {
|
if err != nil || !fi.IsDir() {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
|
indexes = append(indexes, index)
|
||||||
infos = append(infos, litestream.WALSegmentInfo{
|
|
||||||
Generation: generation,
|
|
||||||
Index: index,
|
|
||||||
Offset: offset,
|
|
||||||
Size: fi.Size(),
|
|
||||||
CreatedAt: fi.ModTime().UTC(),
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
|
|
||||||
sort.Sort(litestream.WALSegmentInfoSlice(infos))
|
sort.Ints(indexes)
|
||||||
|
|
||||||
return litestream.NewWALSegmentInfoSliceIterator(infos), nil
|
return newWALSegmentIterator(ctx, c, dir, generation, indexes), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// WriteWALSegment writes LZ4 compressed data from rd into a file on disk.
|
// WriteWALSegment writes LZ4 compressed data from rd into a file on disk.
|
||||||
@@ -375,12 +363,11 @@ func (c *ReplicaClient) WriteWALSegment(ctx context.Context, pos litestream.Pos,
|
|||||||
sftpClient, err := c.Init(ctx)
|
sftpClient, err := c.Init(ctx)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return info, err
|
return info, err
|
||||||
|
} else if pos.Generation == "" {
|
||||||
|
return info, fmt.Errorf("generation required")
|
||||||
}
|
}
|
||||||
|
|
||||||
filename, err := litestream.WALSegmentPath(c.Path, pos.Generation, pos.Index, pos.Offset)
|
filename := path.Join(c.Path, "generations", pos.Generation, "wal", litestream.FormatIndex(pos.Index), litestream.FormatOffset(pos.Offset)+".wal.lz4")
|
||||||
if err != nil {
|
|
||||||
return info, fmt.Errorf("cannot determine wal segment path: %w", err)
|
|
||||||
}
|
|
||||||
startTime := time.Now()
|
startTime := time.Now()
|
||||||
|
|
||||||
if err := sftpClient.MkdirAll(path.Dir(filename)); err != nil {
|
if err := sftpClient.MkdirAll(path.Dir(filename)); err != nil {
|
||||||
@@ -420,12 +407,11 @@ func (c *ReplicaClient) WALSegmentReader(ctx context.Context, pos litestream.Pos
|
|||||||
sftpClient, err := c.Init(ctx)
|
sftpClient, err := c.Init(ctx)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
|
} else if pos.Generation == "" {
|
||||||
|
return nil, fmt.Errorf("generation required")
|
||||||
}
|
}
|
||||||
|
|
||||||
filename, err := litestream.WALSegmentPath(c.Path, pos.Generation, pos.Index, pos.Offset)
|
filename := path.Join(c.Path, "generations", pos.Generation, "wal", litestream.FormatIndex(pos.Index), litestream.FormatOffset(pos.Offset)+".wal.lz4")
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("cannot determine wal segment path: %w", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
f, err := sftpClient.Open(filename)
|
f, err := sftpClient.Open(filename)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -447,11 +433,12 @@ func (c *ReplicaClient) DeleteWALSegments(ctx context.Context, a []litestream.Po
|
|||||||
}
|
}
|
||||||
|
|
||||||
for _, pos := range a {
|
for _, pos := range a {
|
||||||
filename, err := litestream.WALSegmentPath(c.Path, pos.Generation, pos.Index, pos.Offset)
|
if pos.Generation == "" {
|
||||||
if err != nil {
|
return fmt.Errorf("generation required")
|
||||||
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) {
|
if err := sftpClient.Remove(filename); err != nil && !os.IsNotExist(err) {
|
||||||
return fmt.Errorf("cannot delete wal segment %q: %w", filename, err)
|
return fmt.Errorf("cannot delete wal segment %q: %w", filename, err)
|
||||||
}
|
}
|
||||||
@@ -470,7 +457,7 @@ func (c *ReplicaClient) Cleanup(ctx context.Context) (err error) {
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
if err := sftpClient.RemoveDirectory(litestream.GenerationsPath(c.Path)); err != nil && !os.IsNotExist(err) {
|
if err := sftpClient.RemoveDirectory(path.Join(c.Path, "generations")); err != nil && !os.IsNotExist(err) {
|
||||||
return fmt.Errorf("cannot delete generations path: %w", err)
|
return fmt.Errorf("cannot delete generations path: %w", err)
|
||||||
} else if err := sftpClient.RemoveDirectory(c.Path); err != nil && !os.IsNotExist(err) {
|
} else if err := sftpClient.RemoveDirectory(c.Path); err != nil && !os.IsNotExist(err) {
|
||||||
return fmt.Errorf("cannot delete path: %w", err)
|
return fmt.Errorf("cannot delete path: %w", err)
|
||||||
@@ -493,3 +480,101 @@ func (c *ReplicaClient) resetOnConnError(err error) {
|
|||||||
c.sshClient = nil
|
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