From f2e32d8b4f15dcd1afed58e1569b2270bab7ca12 Mon Sep 17 00:00:00 2001 From: Kelvin Clement Mwinuka Date: Sun, 25 Feb 2024 12:07:41 +0800 Subject: [PATCH] Implemented truncate of preamble and aof files --- src/server/aof/aof_engine.go | 19 +++++++++---------- src/server/aof/aof_store.go | 10 ++++++++++ src/server/aof/preamble_store.go | 13 +++++++++++++ 3 files changed, 32 insertions(+), 10 deletions(-) diff --git a/src/server/aof/aof_engine.go b/src/server/aof/aof_engine.go index 4b5b2e5b..ae8035f3 100644 --- a/src/server/aof/aof_engine.go +++ b/src/server/aof/aof_engine.go @@ -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 { @@ -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 } diff --git a/src/server/aof/aof_store.go b/src/server/aof/aof_store.go index aaf3c290..45bbb4e8 100644 --- a/src/server/aof/aof_store.go +++ b/src/server/aof/aof_store.go @@ -5,6 +5,7 @@ import ( "bytes" "context" "errors" + "fmt" "io" "net" "os" @@ -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 } diff --git a/src/server/aof/preamble_store.go b/src/server/aof/preamble_store.go index e3901abc..c1a352e7 100644 --- a/src/server/aof/preamble_store.go +++ b/src/server/aof/preamble_store.go @@ -3,6 +3,7 @@ package aof import ( "context" "encoding/json" + "errors" "io" "log" "os" @@ -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 }