Handle the case of io.EOF when reading the second meta page

Signed-off-by: Benjamin Wang <wachao@vmware.com>
pull/367/head
Benjamin Wang 2022-12-29 10:26:07 +08:00
parent dab07c58b4
commit c19ea9b613
2 changed files with 13 additions and 11 deletions

4
db.go
View File

@ -4,6 +4,7 @@ import (
"errors"
"fmt"
"hash/fnv"
"io"
"os"
"runtime"
"sort"
@ -377,7 +378,8 @@ func (db *DB) getPageSizeFromSecondMeta() (int, bool, error) {
if pos >= fileSize-1024 {
break
}
if bw, err := db.file.ReadAt(buf[:], pos); err == nil && bw == len(buf) {
bw, err := db.file.ReadAt(buf[:], pos)
if (err == nil && bw == len(buf)) || (err == io.EOF && int64(bw) == (fileSize-pos)) {
metaCanRead = true
if m := db.pageInBuffer(buf[:], 0).meta(); m.validate() == nil {
return int(m.pageSize), metaCanRead, nil

View File

@ -233,10 +233,9 @@ func TestOpen_ReadPageSize_FromMeta1_OS(t *testing.T) {
t.Fatal(err)
}
// Reopen data file.
// Reopen data file.
db = btesting.MustOpenDBWithOption(t, path, nil)
require.Equalf(t, os.Getpagesize(), db.Info().PageSize, "The page size is expected to be %d, but actually is %d", os.Getpagesize(), db.Info().PageSize)
require.Equalf(t, os.Getpagesize(), db.Info().PageSize, "check page size failed")
}
// Ensure that it can read the page size from the second meta page if the first one is invalid.
@ -257,17 +256,18 @@ func TestOpen_ReadPageSize_FromMeta1_Given(t *testing.T) {
require.NoError(t, err)
// Rewrite meta pages.
if i%3 == 0 {
t.Logf("#%d: Intentionally corrupt the first meta page for pageSize %d", i, givenPageSize)
meta0 := (*meta)(unsafe.Pointer(&buf[pageHeaderSize]))
meta0.pgid++
err = os.WriteFile(path, buf, 0666)
require.NoError(t, err)
}
// Reopen data file.
db = btesting.MustOpenDBWithOption(t, path, nil)
require.Equalf(t, givenPageSize, db.Info().PageSize, "The page size is expected to be %d, but actually is %d", givenPageSize, db.Info().PageSize)
// The db.DB is set to nil in MustClose(), so the testing Cleanup
// will do nothing when executing PostTestCleanup().
db.PostTestCleanup()
require.Equalf(t, givenPageSize, db.Info().PageSize, "check page size failed")
db.MustClose()
}
}