Skip to content

Commit

Permalink
Implemented truncate of preamble and aof files
Browse files Browse the repository at this point in the history
  • Loading branch information
kelvinmwinuka committed Feb 25, 2024
1 parent ab366c4 commit f2e32d8
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 10 deletions.
19 changes: 9 additions & 10 deletions src/server/aof/aof_engine.go
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ func NewAOFEngine(opts Opts, appendRW io.ReadWriter, preambleRW io.ReadWriter) (
// Obtain preamble file handler
if preambleRW == nil {
f, err := os.OpenFile(
path.Join(engine.options.Config.DataDir, "aof", "peamble.bin"),
path.Join(engine.options.Config.DataDir, "aof", "preamble.bin"),
os.O_WRONLY|os.O_CREATE|os.O_APPEND,
os.ModePerm)
if err != nil {
Expand Down Expand Up @@ -135,16 +135,15 @@ func (engine *Engine) RewriteLog() error {
engine.options.StartRewriteAOF()
defer engine.options.FinishRewriteAOF()

// Replace aof file with empty file.
aof, err := os.Create(path.Join(engine.options.Config.DataDir, "aof", "log.aof"))
if err != nil {
return err
// Create AOF preamble
if err := engine.preambleStore.CreatePreamble(); err != nil {
log.Println(err)
}

// Truncate the AOF file.
if err := engine.appendStore.Truncate(); err != nil {
log.Println(err)
}
defer func() {
if err = aof.Close(); err != nil {
log.Println(err)
}
}()

return nil
}
Expand Down
10 changes: 10 additions & 0 deletions src/server/aof/aof_store.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"bytes"
"context"
"errors"
"fmt"
"io"
"net"
"os"
Expand Down Expand Up @@ -77,6 +78,15 @@ func (store *AppendStore) Restore(ctx context.Context) error {
}

func (store *AppendStore) Truncate() error {
rw, ok := store.rw.(interface {
Truncate(size int64) error
})
if !ok {
fmt.Println("could not truncate AOF file")
}
if err := rw.Truncate(0); err != nil {
return err
}
return nil
}

Expand Down
13 changes: 13 additions & 0 deletions src/server/aof/preamble_store.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package aof
import (
"context"
"encoding/json"
"errors"
"io"
"log"
"os"
Expand Down Expand Up @@ -65,6 +66,18 @@ func (store *PreambleStore) CreatePreamble() error {
return err
}

// Truncate the preamble first
rw, ok := store.rw.(interface {
Truncate(size int64) error
})
if !ok {
return errors.New("could not truncate preamble file")
}

if err = rw.Truncate(0); err != nil {
return err
}

if _, err = store.rw.Write(o); err != nil {
return err
}
Expand Down

0 comments on commit f2e32d8

Please sign in to comment.