syncthing/vendor/github.com/syndtr/goleveldb/leveldb/table/reader.go

1136 lines
27 KiB
Go
Raw Normal View History

2014-07-06 12:46:48 +00:00
// Copyright (c) 2012, Suryandaru Triandana <syndtr@gmail.com>
// All rights reserved.
//
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package table
import (
"encoding/binary"
"fmt"
"io"
"sort"
"strings"
2014-10-06 20:07:33 +00:00
"sync"
2014-07-06 12:46:48 +00:00
2015-07-22 10:09:36 +00:00
"github.com/golang/snappy"
2014-07-06 12:46:48 +00:00
"github.com/syndtr/goleveldb/leveldb/cache"
"github.com/syndtr/goleveldb/leveldb/comparer"
2014-11-18 12:24:42 +00:00
"github.com/syndtr/goleveldb/leveldb/errors"
2014-07-06 12:46:48 +00:00
"github.com/syndtr/goleveldb/leveldb/filter"
"github.com/syndtr/goleveldb/leveldb/iterator"
"github.com/syndtr/goleveldb/leveldb/opt"
2014-11-18 12:24:42 +00:00
"github.com/syndtr/goleveldb/leveldb/storage"
2014-07-06 12:46:48 +00:00
"github.com/syndtr/goleveldb/leveldb/util"
)
// Reader errors.
2014-07-06 12:46:48 +00:00
var (
2014-11-18 12:24:42 +00:00
ErrNotFound = errors.ErrNotFound
2014-10-06 20:07:33 +00:00
ErrReaderReleased = errors.New("leveldb/table: reader released")
ErrIterReleased = errors.New("leveldb/table: iterator released")
2014-07-06 12:46:48 +00:00
)
// ErrCorrupted describes error due to corruption. This error will be wrapped
// with errors.ErrCorrupted.
2014-11-18 12:24:42 +00:00
type ErrCorrupted struct {
Pos int64
Size int64
Kind string
Reason string
}
func (e *ErrCorrupted) Error() string {
return fmt.Sprintf("leveldb/table: corruption on %s (pos=%d): %s", e.Kind, e.Pos, e.Reason)
}
2014-07-06 12:46:48 +00:00
func max(x, y int) int {
if x > y {
return x
}
return y
}
type block struct {
2014-11-04 04:00:11 +00:00
bpool *util.BufferPool
2014-11-18 12:24:42 +00:00
bh blockHandle
2014-07-06 12:46:48 +00:00
data []byte
restartsLen int
restartsOffset int
}
2014-11-04 04:00:11 +00:00
func (b *block) seek(cmp comparer.Comparer, rstart, rlimit int, key []byte) (index, offset int, err error) {
2014-07-06 12:46:48 +00:00
index = sort.Search(b.restartsLen-rstart-(b.restartsLen-rlimit), func(i int) bool {
2014-09-02 07:43:42 +00:00
offset := int(binary.LittleEndian.Uint32(b.data[b.restartsOffset+4*(rstart+i):]))
offset++ // shared always zero, since this is a restart point
2014-09-02 07:43:42 +00:00
v1, n1 := binary.Uvarint(b.data[offset:]) // key length
_, n2 := binary.Uvarint(b.data[offset+n1:]) // value length
2014-07-06 12:46:48 +00:00
m := offset + n1 + n2
2014-11-04 04:00:11 +00:00
return cmp.Compare(b.data[m:m+int(v1)], key) > 0
2014-07-06 12:46:48 +00:00
}) + rstart - 1
if index < rstart {
// The smallest key is greater-than key sought.
index = rstart
}
2014-09-02 07:43:42 +00:00
offset = int(binary.LittleEndian.Uint32(b.data[b.restartsOffset+4*index:]))
2014-07-06 12:46:48 +00:00
return
}
func (b *block) restartIndex(rstart, rlimit, offset int) int {
return sort.Search(b.restartsLen-rstart-(b.restartsLen-rlimit), func(i int) bool {
2014-09-02 07:43:42 +00:00
return int(binary.LittleEndian.Uint32(b.data[b.restartsOffset+4*(rstart+i):])) > offset
2014-07-06 12:46:48 +00:00
}) + rstart - 1
}
func (b *block) restartOffset(index int) int {
return int(binary.LittleEndian.Uint32(b.data[b.restartsOffset+4*index:]))
}
func (b *block) entry(offset int) (key, value []byte, nShared, n int, err error) {
if offset >= b.restartsOffset {
if offset != b.restartsOffset {
2014-11-18 12:24:42 +00:00
err = &ErrCorrupted{Reason: "entries offset not aligned"}
2014-07-06 12:46:48 +00:00
}
return
}
v0, n0 := binary.Uvarint(b.data[offset:]) // Shared prefix length
v1, n1 := binary.Uvarint(b.data[offset+n0:]) // Key length
v2, n2 := binary.Uvarint(b.data[offset+n0+n1:]) // Value length
m := n0 + n1 + n2
n = m + int(v1) + int(v2)
if n0 <= 0 || n1 <= 0 || n2 <= 0 || offset+n > b.restartsOffset {
2014-11-18 12:24:42 +00:00
err = &ErrCorrupted{Reason: "entries corrupted"}
2014-07-06 12:46:48 +00:00
return
}
key = b.data[offset+m : offset+m+int(v1)]
value = b.data[offset+m+int(v1) : offset+n]
nShared = int(v0)
return
}
2014-08-29 10:36:45 +00:00
func (b *block) Release() {
2014-11-04 04:00:11 +00:00
b.bpool.Put(b.data)
b.bpool = nil
2014-08-29 10:36:45 +00:00
b.data = nil
}
2014-07-06 12:46:48 +00:00
type dir int
const (
dirReleased dir = iota - 1
dirSOI
dirEOI
dirBackward
dirForward
)
type blockIter struct {
2014-11-04 04:00:11 +00:00
tr *Reader
block *block
blockReleaser util.Releaser
releaser util.Releaser
key, value []byte
offset int
2014-07-06 12:46:48 +00:00
// Previous offset, only filled by Next.
prevOffset int
prevNode []int
prevKeys []byte
restartIndex int
// Iterator direction.
dir dir
// Restart index slice range.
riStart int
riLimit int
// Offset slice range.
offsetStart int
offsetRealStart int
offsetLimit int
// Error.
err error
}
func (i *blockIter) sErr(err error) {
i.err = err
i.key = nil
i.value = nil
i.prevNode = nil
i.prevKeys = nil
}
func (i *blockIter) reset() {
if i.dir == dirBackward {
i.prevNode = i.prevNode[:0]
i.prevKeys = i.prevKeys[:0]
}
i.restartIndex = i.riStart
i.offset = i.offsetStart
i.dir = dirSOI
i.key = i.key[:0]
i.value = nil
}
func (i *blockIter) isFirst() bool {
switch i.dir {
case dirForward:
return i.prevOffset == i.offsetRealStart
case dirBackward:
return len(i.prevNode) == 1 && i.restartIndex == i.riStart
}
return false
}
func (i *blockIter) isLast() bool {
switch i.dir {
case dirForward, dirBackward:
return i.offset == i.offsetLimit
}
return false
}
func (i *blockIter) First() bool {
if i.err != nil {
return false
} else if i.dir == dirReleased {
i.err = ErrIterReleased
return false
}
if i.dir == dirBackward {
i.prevNode = i.prevNode[:0]
i.prevKeys = i.prevKeys[:0]
}
i.dir = dirSOI
return i.Next()
}
func (i *blockIter) Last() bool {
if i.err != nil {
return false
} else if i.dir == dirReleased {
i.err = ErrIterReleased
return false
}
if i.dir == dirBackward {
i.prevNode = i.prevNode[:0]
i.prevKeys = i.prevKeys[:0]
}
i.dir = dirEOI
return i.Prev()
}
func (i *blockIter) Seek(key []byte) bool {
if i.err != nil {
return false
} else if i.dir == dirReleased {
i.err = ErrIterReleased
return false
}
2014-11-04 04:00:11 +00:00
ri, offset, err := i.block.seek(i.tr.cmp, i.riStart, i.riLimit, key)
2014-07-06 12:46:48 +00:00
if err != nil {
i.sErr(err)
return false
}
i.restartIndex = ri
i.offset = max(i.offsetStart, offset)
if i.dir == dirSOI || i.dir == dirEOI {
i.dir = dirForward
}
for i.Next() {
2014-11-04 04:00:11 +00:00
if i.tr.cmp.Compare(i.key, key) >= 0 {
2014-07-06 12:46:48 +00:00
return true
}
}
return false
}
func (i *blockIter) Next() bool {
if i.dir == dirEOI || i.err != nil {
return false
} else if i.dir == dirReleased {
i.err = ErrIterReleased
return false
}
if i.dir == dirSOI {
i.restartIndex = i.riStart
i.offset = i.offsetStart
} else if i.dir == dirBackward {
i.prevNode = i.prevNode[:0]
i.prevKeys = i.prevKeys[:0]
}
for i.offset < i.offsetRealStart {
key, value, nShared, n, err := i.block.entry(i.offset)
if err != nil {
2014-11-18 12:24:42 +00:00
i.sErr(i.tr.fixErrCorruptedBH(i.block.bh, err))
2014-07-06 12:46:48 +00:00
return false
}
if n == 0 {
i.dir = dirEOI
return false
}
i.key = append(i.key[:nShared], key...)
i.value = value
i.offset += n
}
if i.offset >= i.offsetLimit {
i.dir = dirEOI
if i.offset != i.offsetLimit {
2014-11-18 12:24:42 +00:00
i.sErr(i.tr.newErrCorruptedBH(i.block.bh, "entries offset not aligned"))
2014-07-06 12:46:48 +00:00
}
return false
}
key, value, nShared, n, err := i.block.entry(i.offset)
if err != nil {
2014-11-18 12:24:42 +00:00
i.sErr(i.tr.fixErrCorruptedBH(i.block.bh, err))
2014-07-06 12:46:48 +00:00
return false
}
if n == 0 {
i.dir = dirEOI
return false
}
i.key = append(i.key[:nShared], key...)
i.value = value
i.prevOffset = i.offset
i.offset += n
i.dir = dirForward
return true
}
func (i *blockIter) Prev() bool {
if i.dir == dirSOI || i.err != nil {
return false
} else if i.dir == dirReleased {
i.err = ErrIterReleased
return false
}
var ri int
if i.dir == dirForward {
// Change direction.
i.offset = i.prevOffset
if i.offset == i.offsetRealStart {
i.dir = dirSOI
return false
}
ri = i.block.restartIndex(i.restartIndex, i.riLimit, i.offset)
i.dir = dirBackward
} else if i.dir == dirEOI {
// At the end of iterator.
i.restartIndex = i.riLimit
i.offset = i.offsetLimit
if i.offset == i.offsetRealStart {
i.dir = dirSOI
return false
}
ri = i.riLimit - 1
i.dir = dirBackward
} else if len(i.prevNode) == 1 {
// This is the end of a restart range.
i.offset = i.prevNode[0]
i.prevNode = i.prevNode[:0]
if i.restartIndex == i.riStart {
i.dir = dirSOI
return false
}
i.restartIndex--
ri = i.restartIndex
} else {
// In the middle of restart range, get from cache.
n := len(i.prevNode) - 3
node := i.prevNode[n:]
i.prevNode = i.prevNode[:n]
// Get the key.
ko := node[0]
i.key = append(i.key[:0], i.prevKeys[ko:]...)
i.prevKeys = i.prevKeys[:ko]
// Get the value.
vo := node[1]
vl := vo + node[2]
i.value = i.block.data[vo:vl]
i.offset = vl
return true
}
// Build entries cache.
i.key = i.key[:0]
i.value = nil
offset := i.block.restartOffset(ri)
if offset == i.offset {
ri--
2014-07-06 12:46:48 +00:00
if ri < 0 {
i.dir = dirSOI
return false
}
offset = i.block.restartOffset(ri)
}
i.prevNode = append(i.prevNode, offset)
for {
key, value, nShared, n, err := i.block.entry(offset)
if err != nil {
2014-11-18 12:24:42 +00:00
i.sErr(i.tr.fixErrCorruptedBH(i.block.bh, err))
2014-07-06 12:46:48 +00:00
return false
}
if offset >= i.offsetRealStart {
if i.value != nil {
// Appends 3 variables:
// 1. Previous keys offset
// 2. Value offset in the data block
// 3. Value length
i.prevNode = append(i.prevNode, len(i.prevKeys), offset-len(i.value), len(i.value))
i.prevKeys = append(i.prevKeys, i.key...)
}
i.value = value
}
i.key = append(i.key[:nShared], key...)
offset += n
// Stop if target offset reached.
if offset >= i.offset {
if offset != i.offset {
2014-11-18 12:24:42 +00:00
i.sErr(i.tr.newErrCorruptedBH(i.block.bh, "entries offset not aligned"))
2014-07-06 12:46:48 +00:00
return false
}
break
}
}
i.restartIndex = ri
i.offset = offset
return true
}
func (i *blockIter) Key() []byte {
if i.err != nil || i.dir <= dirEOI {
return nil
}
return i.key
}
func (i *blockIter) Value() []byte {
if i.err != nil || i.dir <= dirEOI {
return nil
}
return i.value
}
func (i *blockIter) Release() {
2014-10-06 20:07:33 +00:00
if i.dir != dirReleased {
2014-11-04 04:00:11 +00:00
i.tr = nil
2014-08-29 10:36:45 +00:00
i.block = nil
2014-08-14 10:14:48 +00:00
i.prevNode = nil
i.prevKeys = nil
i.key = nil
i.value = nil
i.dir = dirReleased
2014-11-04 04:00:11 +00:00
if i.blockReleaser != nil {
i.blockReleaser.Release()
i.blockReleaser = nil
2014-08-14 10:14:48 +00:00
}
if i.releaser != nil {
i.releaser.Release()
i.releaser = nil
}
2014-07-06 12:46:48 +00:00
}
}
func (i *blockIter) SetReleaser(releaser util.Releaser) {
2014-10-06 20:07:33 +00:00
if i.dir == dirReleased {
panic(util.ErrReleased)
}
if i.releaser != nil && releaser != nil {
panic(util.ErrHasReleaser)
2014-07-06 12:46:48 +00:00
}
2014-10-06 20:07:33 +00:00
i.releaser = releaser
2014-07-06 12:46:48 +00:00
}
func (i *blockIter) Valid() bool {
return i.err == nil && (i.dir == dirBackward || i.dir == dirForward)
}
func (i *blockIter) Error() error {
return i.err
}
type filterBlock struct {
2014-11-04 04:00:11 +00:00
bpool *util.BufferPool
2014-07-06 12:46:48 +00:00
data []byte
oOffset int
baseLg uint
filtersNum int
}
2014-11-04 04:00:11 +00:00
func (b *filterBlock) contains(filter filter.Filter, offset uint64, key []byte) bool {
2014-07-06 12:46:48 +00:00
i := int(offset >> b.baseLg)
if i < b.filtersNum {
o := b.data[b.oOffset+i*4:]
n := int(binary.LittleEndian.Uint32(o))
m := int(binary.LittleEndian.Uint32(o[4:]))
if n < m && m <= b.oOffset {
2014-11-04 04:00:11 +00:00
return filter.Contains(b.data[n:m], key)
2014-07-06 12:46:48 +00:00
} else if n == m {
return false
}
}
return true
}
2014-09-02 07:43:42 +00:00
func (b *filterBlock) Release() {
2014-11-04 04:00:11 +00:00
b.bpool.Put(b.data)
b.bpool = nil
2014-09-02 07:43:42 +00:00
b.data = nil
}
2014-07-06 12:46:48 +00:00
type indexIter struct {
2014-09-02 07:43:42 +00:00
*blockIter
2014-11-04 04:00:11 +00:00
tr *Reader
2014-09-02 07:43:42 +00:00
slice *util.Range
2014-07-06 12:46:48 +00:00
// Options
fillCache bool
}
func (i *indexIter) Get() iterator.Iterator {
value := i.Value()
if value == nil {
return nil
}
dataBH, n := decodeBlockHandle(value)
if n == 0 {
2014-11-18 12:24:42 +00:00
return iterator.NewEmptyIterator(i.tr.newErrCorruptedBH(i.tr.indexBH, "bad data block handle"))
2014-07-06 12:46:48 +00:00
}
2014-10-06 20:07:33 +00:00
2014-07-06 12:46:48 +00:00
var slice *util.Range
if i.slice != nil && (i.blockIter.isFirst() || i.blockIter.isLast()) {
slice = i.slice
}
2014-11-18 12:24:42 +00:00
return i.tr.getDataIterErr(dataBH, slice, i.tr.verifyChecksum, i.fillCache)
2014-07-06 12:46:48 +00:00
}
// Reader is a table reader.
type Reader struct {
2014-10-06 20:07:33 +00:00
mu sync.RWMutex
fd storage.FileDesc
2014-07-06 12:46:48 +00:00
reader io.ReaderAt
cache *cache.NamespaceGetter
2014-07-06 12:46:48 +00:00
err error
2014-08-14 10:14:48 +00:00
bpool *util.BufferPool
2014-07-06 12:46:48 +00:00
// Options
2014-11-18 12:24:42 +00:00
o *opt.Options
cmp comparer.Comparer
filter filter.Filter
verifyChecksum bool
2014-07-06 12:46:48 +00:00
2014-11-24 10:57:31 +00:00
dataEnd int64
metaBH, indexBH, filterBH blockHandle
indexBlock *block
filterBlock *filterBlock
2014-07-06 12:46:48 +00:00
}
2014-11-18 12:24:42 +00:00
func (r *Reader) blockKind(bh blockHandle) string {
switch bh.offset {
2014-11-24 10:57:31 +00:00
case r.metaBH.offset:
return "meta-block"
2014-11-18 12:24:42 +00:00
case r.indexBH.offset:
return "index-block"
case r.filterBH.offset:
2014-11-24 10:57:31 +00:00
if r.filterBH.length > 0 {
return "filter-block"
}
2014-11-18 12:24:42 +00:00
}
2014-11-24 10:57:31 +00:00
return "data-block"
2014-07-06 12:46:48 +00:00
}
2014-11-18 12:24:42 +00:00
func (r *Reader) newErrCorrupted(pos, size int64, kind, reason string) error {
return &errors.ErrCorrupted{Fd: r.fd, Err: &ErrCorrupted{Pos: pos, Size: size, Kind: kind, Reason: reason}}
2014-11-18 12:24:42 +00:00
}
func (r *Reader) newErrCorruptedBH(bh blockHandle, reason string) error {
return r.newErrCorrupted(int64(bh.offset), int64(bh.length), r.blockKind(bh), reason)
}
func (r *Reader) fixErrCorruptedBH(bh blockHandle, err error) error {
if cerr, ok := err.(*ErrCorrupted); ok {
cerr.Pos = int64(bh.offset)
cerr.Size = int64(bh.length)
cerr.Kind = r.blockKind(bh)
return &errors.ErrCorrupted{Fd: r.fd, Err: cerr}
2014-11-18 12:24:42 +00:00
}
return err
}
func (r *Reader) readRawBlock(bh blockHandle, verifyChecksum bool) ([]byte, error) {
2014-08-14 10:14:48 +00:00
data := r.bpool.Get(int(bh.length + blockTrailerLen))
2014-07-06 12:46:48 +00:00
if _, err := r.reader.ReadAt(data, int64(bh.offset)); err != nil && err != io.EOF {
return nil, err
}
2014-11-24 10:57:31 +00:00
if verifyChecksum {
n := bh.length + 1
checksum0 := binary.LittleEndian.Uint32(data[n:])
checksum1 := util.NewCRC(data[:n]).Value()
if checksum0 != checksum1 {
r.bpool.Put(data)
return nil, r.newErrCorruptedBH(bh, fmt.Sprintf("checksum mismatch, want=%#x got=%#x", checksum0, checksum1))
}
2014-07-06 12:46:48 +00:00
}
2014-11-24 10:57:31 +00:00
2014-07-06 12:46:48 +00:00
switch data[bh.length] {
case blockTypeNoCompression:
data = data[:bh.length]
case blockTypeSnappyCompression:
2014-08-14 10:14:48 +00:00
decLen, err := snappy.DecodedLen(data[:bh.length])
if err != nil {
r.bpool.Put(data)
2014-11-18 12:24:42 +00:00
return nil, r.newErrCorruptedBH(bh, err.Error())
2014-08-14 10:14:48 +00:00
}
2014-11-18 12:24:42 +00:00
decData := r.bpool.Get(decLen)
decData, err = snappy.Decode(decData, data[:bh.length])
r.bpool.Put(data)
2014-07-06 12:46:48 +00:00
if err != nil {
2014-11-18 12:24:42 +00:00
r.bpool.Put(decData)
return nil, r.newErrCorruptedBH(bh, err.Error())
2014-07-06 12:46:48 +00:00
}
2014-11-18 12:24:42 +00:00
data = decData
2014-07-06 12:46:48 +00:00
default:
2014-09-02 07:43:42 +00:00
r.bpool.Put(data)
2014-11-18 12:24:42 +00:00
return nil, r.newErrCorruptedBH(bh, fmt.Sprintf("unknown compression type %#x", data[bh.length]))
2014-07-06 12:46:48 +00:00
}
return data, nil
}
2014-11-18 12:24:42 +00:00
func (r *Reader) readBlock(bh blockHandle, verifyChecksum bool) (*block, error) {
data, err := r.readRawBlock(bh, verifyChecksum)
2014-07-06 12:46:48 +00:00
if err != nil {
return nil, err
}
restartsLen := int(binary.LittleEndian.Uint32(data[len(data)-4:]))
b := &block{
2014-11-04 04:00:11 +00:00
bpool: r.bpool,
2014-11-18 12:24:42 +00:00
bh: bh,
2014-07-06 12:46:48 +00:00
data: data,
restartsLen: restartsLen,
restartsOffset: len(data) - (restartsLen+1)*4,
}
return b, nil
}
2014-11-18 12:24:42 +00:00
func (r *Reader) readBlockCached(bh blockHandle, verifyChecksum, fillCache bool) (*block, util.Releaser, error) {
2014-09-02 07:43:42 +00:00
if r.cache != nil {
2014-12-29 11:22:58 +00:00
var (
err error
ch *cache.Handle
)
if fillCache {
ch = r.cache.Get(bh.offset, func() (size int, value cache.Value) {
var b *block
b, err = r.readBlock(bh, verifyChecksum)
if err != nil {
return 0, nil
}
return cap(b.data), b
})
} else {
ch = r.cache.Get(bh.offset, nil)
}
2014-09-02 07:43:42 +00:00
if ch != nil {
b, ok := ch.Value().(*block)
if !ok {
ch.Release()
2014-11-18 12:24:42 +00:00
return nil, nil, errors.New("leveldb/table: inconsistent block type")
2014-09-02 07:43:42 +00:00
}
return b, ch, err
} else if err != nil {
return nil, nil, err
}
}
2014-11-18 12:24:42 +00:00
b, err := r.readBlock(bh, verifyChecksum)
2014-09-02 07:43:42 +00:00
return b, b, err
}
func (r *Reader) readFilterBlock(bh blockHandle) (*filterBlock, error) {
2014-07-06 12:46:48 +00:00
data, err := r.readRawBlock(bh, true)
if err != nil {
return nil, err
}
n := len(data)
if n < 5 {
2014-11-18 12:24:42 +00:00
return nil, r.newErrCorruptedBH(bh, "too short")
2014-07-06 12:46:48 +00:00
}
m := n - 5
oOffset := int(binary.LittleEndian.Uint32(data[m:]))
if oOffset > m {
2014-11-18 12:24:42 +00:00
return nil, r.newErrCorruptedBH(bh, "invalid data-offsets offset")
2014-07-06 12:46:48 +00:00
}
b := &filterBlock{
2014-11-04 04:00:11 +00:00
bpool: r.bpool,
2014-07-06 12:46:48 +00:00
data: data,
oOffset: oOffset,
baseLg: uint(data[n-1]),
filtersNum: (m - oOffset) / 4,
}
return b, nil
}
2014-09-02 07:43:42 +00:00
func (r *Reader) readFilterBlockCached(bh blockHandle, fillCache bool) (*filterBlock, util.Releaser, error) {
2014-07-06 12:46:48 +00:00
if r.cache != nil {
2014-12-29 11:22:58 +00:00
var (
err error
ch *cache.Handle
)
if fillCache {
ch = r.cache.Get(bh.offset, func() (size int, value cache.Value) {
var b *filterBlock
b, err = r.readFilterBlock(bh)
if err != nil {
return 0, nil
}
return cap(b.data), b
})
} else {
ch = r.cache.Get(bh.offset, nil)
}
2014-09-02 07:43:42 +00:00
if ch != nil {
b, ok := ch.Value().(*filterBlock)
if !ok {
ch.Release()
2014-11-18 12:24:42 +00:00
return nil, nil, errors.New("leveldb/table: inconsistent block type")
2014-07-06 12:46:48 +00:00
}
2014-09-02 07:43:42 +00:00
return b, ch, err
} else if err != nil {
return nil, nil, err
2014-07-06 12:46:48 +00:00
}
}
2014-09-02 07:43:42 +00:00
b, err := r.readFilterBlock(bh)
return b, b, err
}
2014-10-06 20:07:33 +00:00
func (r *Reader) getIndexBlock(fillCache bool) (b *block, rel util.Releaser, err error) {
if r.indexBlock == nil {
return r.readBlockCached(r.indexBH, true, fillCache)
}
return r.indexBlock, util.NoopReleaser{}, nil
}
func (r *Reader) getFilterBlock(fillCache bool) (*filterBlock, util.Releaser, error) {
if r.filterBlock == nil {
return r.readFilterBlockCached(r.filterBH, fillCache)
}
return r.filterBlock, util.NoopReleaser{}, nil
}
2014-11-04 04:00:11 +00:00
func (r *Reader) newBlockIter(b *block, bReleaser util.Releaser, slice *util.Range, inclLimit bool) *blockIter {
bi := &blockIter{
tr: r,
block: b,
blockReleaser: bReleaser,
// Valid key should never be nil.
key: make([]byte, 0),
dir: dirSOI,
riStart: 0,
riLimit: b.restartsLen,
offsetStart: 0,
offsetRealStart: 0,
offsetLimit: b.restartsOffset,
}
if slice != nil {
if slice.Start != nil {
if bi.Seek(slice.Start) {
bi.riStart = b.restartIndex(bi.restartIndex, b.restartsLen, bi.prevOffset)
bi.offsetStart = b.restartOffset(bi.riStart)
bi.offsetRealStart = bi.prevOffset
} else {
bi.riStart = b.restartsLen
bi.offsetStart = b.restartsOffset
bi.offsetRealStart = b.restartsOffset
}
}
if slice.Limit != nil {
if bi.Seek(slice.Limit) && (!inclLimit || bi.Next()) {
bi.offsetLimit = bi.prevOffset
bi.riLimit = bi.restartIndex + 1
}
}
bi.reset()
if bi.offsetStart > bi.offsetLimit {
2014-11-18 12:24:42 +00:00
bi.sErr(errors.New("leveldb/table: invalid slice range"))
2014-11-04 04:00:11 +00:00
}
}
return bi
}
2014-11-18 12:24:42 +00:00
func (r *Reader) getDataIter(dataBH blockHandle, slice *util.Range, verifyChecksum, fillCache bool) iterator.Iterator {
b, rel, err := r.readBlockCached(dataBH, verifyChecksum, fillCache)
if err != nil {
return iterator.NewEmptyIterator(err)
}
return r.newBlockIter(b, rel, slice, false)
}
func (r *Reader) getDataIterErr(dataBH blockHandle, slice *util.Range, verifyChecksum, fillCache bool) iterator.Iterator {
r.mu.RLock()
defer r.mu.RUnlock()
if r.err != nil {
return iterator.NewEmptyIterator(r.err)
}
return r.getDataIter(dataBH, slice, verifyChecksum, fillCache)
}
2014-07-06 12:46:48 +00:00
// NewIterator creates an iterator from the table.
//
// Slice allows slicing the iterator to only contains keys in the given
// range. A nil Range.Start is treated as a key before all keys in the
// table. And a nil Range.Limit is treated as a key after all keys in
// the table.
//
// The returned iterator is not safe for concurrent use and should be released
// after use.
2014-07-06 12:46:48 +00:00
//
// Also read Iterator documentation of the leveldb/iterator package.
func (r *Reader) NewIterator(slice *util.Range, ro *opt.ReadOptions) iterator.Iterator {
2014-10-06 20:07:33 +00:00
r.mu.RLock()
defer r.mu.RUnlock()
2014-07-06 12:46:48 +00:00
if r.err != nil {
return iterator.NewEmptyIterator(r.err)
}
2014-09-02 07:43:42 +00:00
fillCache := !ro.GetDontFillCache()
2014-10-06 20:07:33 +00:00
indexBlock, rel, err := r.getIndexBlock(fillCache)
2014-09-02 07:43:42 +00:00
if err != nil {
return iterator.NewEmptyIterator(err)
}
2014-07-06 12:46:48 +00:00
index := &indexIter{
2014-11-04 04:00:11 +00:00
blockIter: r.newBlockIter(indexBlock, rel, slice, true),
tr: r,
2014-09-02 07:43:42 +00:00
slice: slice,
fillCache: !ro.GetDontFillCache(),
2014-07-06 12:46:48 +00:00
}
2014-11-18 12:24:42 +00:00
return iterator.NewIndexedIterator(index, opt.GetStrict(r.o, ro, opt.StrictReader))
2014-07-06 12:46:48 +00:00
}
2014-11-24 10:57:31 +00:00
func (r *Reader) find(key []byte, filtered bool, ro *opt.ReadOptions, noValue bool) (rkey, value []byte, err error) {
2014-10-06 20:07:33 +00:00
r.mu.RLock()
defer r.mu.RUnlock()
2014-07-06 12:46:48 +00:00
if r.err != nil {
err = r.err
return
}
2014-10-06 20:07:33 +00:00
indexBlock, rel, err := r.getIndexBlock(true)
2014-09-02 07:43:42 +00:00
if err != nil {
return
}
defer rel.Release()
2014-11-04 04:00:11 +00:00
index := r.newBlockIter(indexBlock, nil, nil, true)
2014-07-06 12:46:48 +00:00
defer index.Release()
2014-07-06 12:46:48 +00:00
if !index.Seek(key) {
if err = index.Error(); err == nil {
2014-07-06 12:46:48 +00:00
err = ErrNotFound
}
return
}
2014-07-06 12:46:48 +00:00
dataBH, n := decodeBlockHandle(index.Value())
if n == 0 {
2014-11-18 12:24:42 +00:00
r.err = r.newErrCorruptedBH(r.indexBH, "bad data block handle")
return nil, nil, r.err
2014-07-06 12:46:48 +00:00
}
// The filter should only used for exact match.
2014-11-24 10:57:31 +00:00
if filtered && r.filter != nil {
filterBlock, frel, ferr := r.getFilterBlock(true)
2014-09-02 07:43:42 +00:00
if ferr == nil {
2014-11-04 04:00:11 +00:00
if !filterBlock.contains(r.filter, dataBH.offset, key) {
2014-11-24 10:57:31 +00:00
frel.Release()
2014-09-02 07:43:42 +00:00
return nil, nil, ErrNotFound
}
2014-11-24 10:57:31 +00:00
frel.Release()
} else if !errors.IsCorrupted(ferr) {
return nil, nil, ferr
2014-09-02 07:43:42 +00:00
}
2014-07-06 12:46:48 +00:00
}
2014-11-18 12:24:42 +00:00
data := r.getDataIter(dataBH, nil, r.verifyChecksum, !ro.GetDontFillCache())
2014-07-06 12:46:48 +00:00
if !data.Seek(key) {
data.Release()
if err = data.Error(); err != nil {
return
}
// The nearest greater-than key is the first key of the next block.
if !index.Next() {
if err = index.Error(); err == nil {
err = ErrNotFound
}
return
}
dataBH, n = decodeBlockHandle(index.Value())
if n == 0 {
r.err = r.newErrCorruptedBH(r.indexBH, "bad data block handle")
return nil, nil, r.err
}
data = r.getDataIter(dataBH, nil, r.verifyChecksum, !ro.GetDontFillCache())
if !data.Next() {
data.Release()
if err = data.Error(); err == nil {
err = ErrNotFound
}
return
2014-07-06 12:46:48 +00:00
}
}
// Key doesn't use block buffer, no need to copy the buffer.
2014-07-06 12:46:48 +00:00
rkey = data.Key()
2014-11-24 10:57:31 +00:00
if !noValue {
if r.bpool == nil {
value = data.Value()
} else {
// Value does use block buffer, and since the buffer will be
// recycled, it need to be copied.
2014-11-24 10:57:31 +00:00
value = append([]byte{}, data.Value()...)
}
2014-10-06 20:07:33 +00:00
}
data.Release()
2014-07-06 12:46:48 +00:00
return
}
2014-11-24 10:57:31 +00:00
// Find finds key/value pair whose key is greater than or equal to the
// given key. It returns ErrNotFound if the table doesn't contain
// such pair.
// If filtered is true then the nearest 'block' will be checked against
// 'filter data' (if present) and will immediately return ErrNotFound if
// 'filter data' indicates that such pair doesn't exist.
//
// The caller may modify the contents of the returned slice as it is its
// own copy.
// It is safe to modify the contents of the argument after Find returns.
func (r *Reader) Find(key []byte, filtered bool, ro *opt.ReadOptions) (rkey, value []byte, err error) {
return r.find(key, filtered, ro, false)
}
// FindKey finds key that is greater than or equal to the given key.
2014-11-24 10:57:31 +00:00
// It returns ErrNotFound if the table doesn't contain such key.
// If filtered is true then the nearest 'block' will be checked against
// 'filter data' (if present) and will immediately return ErrNotFound if
// 'filter data' indicates that such key doesn't exist.
//
// The caller may modify the contents of the returned slice as it is its
// own copy.
// It is safe to modify the contents of the argument after Find returns.
func (r *Reader) FindKey(key []byte, filtered bool, ro *opt.ReadOptions) (rkey []byte, err error) {
rkey, _, err = r.find(key, filtered, ro, true)
return
}
2014-07-06 12:46:48 +00:00
// Get gets the value for the given key. It returns errors.ErrNotFound
// if the table does not contain the key.
//
2014-11-24 10:57:31 +00:00
// The caller may modify the contents of the returned slice as it is its
// own copy.
// It is safe to modify the contents of the argument after Find returns.
2014-07-06 12:46:48 +00:00
func (r *Reader) Get(key []byte, ro *opt.ReadOptions) (value []byte, err error) {
2014-10-06 20:07:33 +00:00
r.mu.RLock()
defer r.mu.RUnlock()
2014-07-06 12:46:48 +00:00
if r.err != nil {
err = r.err
return
}
2014-11-24 10:57:31 +00:00
rkey, value, err := r.find(key, false, ro, false)
2014-07-06 12:46:48 +00:00
if err == nil && r.cmp.Compare(rkey, key) != 0 {
value = nil
err = ErrNotFound
}
return
}
2014-07-06 21:13:10 +00:00
// OffsetOf returns approximate offset for the given key.
2014-07-06 12:46:48 +00:00
//
// It is safe to modify the contents of the argument after Get returns.
2014-07-06 21:13:10 +00:00
func (r *Reader) OffsetOf(key []byte) (offset int64, err error) {
2014-10-06 20:07:33 +00:00
r.mu.RLock()
defer r.mu.RUnlock()
2014-07-06 12:46:48 +00:00
if r.err != nil {
err = r.err
return
}
2014-09-02 07:43:42 +00:00
indexBlock, rel, err := r.readBlockCached(r.indexBH, true, true)
if err != nil {
return
}
defer rel.Release()
2014-11-04 04:00:11 +00:00
index := r.newBlockIter(indexBlock, nil, nil, true)
2014-07-06 12:46:48 +00:00
defer index.Release()
if index.Seek(key) {
dataBH, n := decodeBlockHandle(index.Value())
if n == 0 {
2014-11-18 12:24:42 +00:00
r.err = r.newErrCorruptedBH(r.indexBH, "bad data block handle")
2014-07-06 12:46:48 +00:00
return
}
offset = int64(dataBH.offset)
return
}
err = index.Error()
if err == nil {
offset = r.dataEnd
}
return
}
2014-09-02 07:43:42 +00:00
// Release implements util.Releaser.
// It also close the file if it is an io.Closer.
func (r *Reader) Release() {
2014-10-06 20:07:33 +00:00
r.mu.Lock()
defer r.mu.Unlock()
2014-09-02 07:43:42 +00:00
if closer, ok := r.reader.(io.Closer); ok {
closer.Close()
}
2014-10-06 20:07:33 +00:00
if r.indexBlock != nil {
r.indexBlock.Release()
r.indexBlock = nil
}
if r.filterBlock != nil {
r.filterBlock.Release()
r.filterBlock = nil
}
2014-09-02 07:43:42 +00:00
r.reader = nil
r.cache = nil
r.bpool = nil
2014-10-06 20:07:33 +00:00
r.err = ErrReaderReleased
2014-09-02 07:43:42 +00:00
}
2014-07-06 12:46:48 +00:00
// NewReader creates a new initialized table reader for the file.
2014-11-18 12:24:42 +00:00
// The fi, cache and bpool is optional and can be nil.
2014-07-23 06:31:36 +00:00
//
// The returned table reader instance is safe for concurrent use.
func NewReader(f io.ReaderAt, size int64, fd storage.FileDesc, cache *cache.NamespaceGetter, bpool *util.BufferPool, o *opt.Options) (*Reader, error) {
2014-11-24 10:57:31 +00:00
if f == nil {
return nil, errors.New("leveldb/table: nil file")
}
2014-07-06 12:46:48 +00:00
r := &Reader{
fd: fd,
2014-11-18 12:24:42 +00:00
reader: f,
cache: cache,
bpool: bpool,
o: o,
cmp: o.GetComparer(),
verifyChecksum: o.GetStrict(opt.StrictBlockChecksum),
2014-07-06 12:46:48 +00:00
}
2014-11-24 10:57:31 +00:00
2014-07-06 12:46:48 +00:00
if size < footerLen {
2014-11-18 12:24:42 +00:00
r.err = r.newErrCorrupted(0, size, "table", "too small")
return r, nil
2014-07-06 12:46:48 +00:00
}
2014-11-24 10:57:31 +00:00
2014-11-18 12:24:42 +00:00
footerPos := size - footerLen
2014-07-06 12:46:48 +00:00
var footer [footerLen]byte
2014-11-18 12:24:42 +00:00
if _, err := r.reader.ReadAt(footer[:], footerPos); err != nil && err != io.EOF {
return nil, err
2014-07-06 12:46:48 +00:00
}
if string(footer[footerLen-len(magic):footerLen]) != magic {
2014-11-18 12:24:42 +00:00
r.err = r.newErrCorrupted(footerPos, footerLen, "table-footer", "bad magic number")
return r, nil
2014-07-06 12:46:48 +00:00
}
2014-11-24 10:57:31 +00:00
var n int
2014-07-06 12:46:48 +00:00
// Decode the metaindex block handle.
2014-11-24 10:57:31 +00:00
r.metaBH, n = decodeBlockHandle(footer[:])
2014-07-06 12:46:48 +00:00
if n == 0 {
2014-11-18 12:24:42 +00:00
r.err = r.newErrCorrupted(footerPos, footerLen, "table-footer", "bad metaindex block handle")
return r, nil
2014-07-06 12:46:48 +00:00
}
2014-11-24 10:57:31 +00:00
2014-07-06 12:46:48 +00:00
// Decode the index block handle.
2014-09-02 07:43:42 +00:00
r.indexBH, n = decodeBlockHandle(footer[n:])
2014-07-06 12:46:48 +00:00
if n == 0 {
2014-11-18 12:24:42 +00:00
r.err = r.newErrCorrupted(footerPos, footerLen, "table-footer", "bad index block handle")
return r, nil
2014-07-06 12:46:48 +00:00
}
2014-11-24 10:57:31 +00:00
2014-07-06 12:46:48 +00:00
// Read metaindex block.
2014-11-24 10:57:31 +00:00
metaBlock, err := r.readBlock(r.metaBH, true)
2014-07-06 12:46:48 +00:00
if err != nil {
2014-11-18 12:24:42 +00:00
if errors.IsCorrupted(err) {
r.err = err
return r, nil
}
return nil, err
2014-07-06 12:46:48 +00:00
}
2014-11-24 10:57:31 +00:00
2014-07-06 12:46:48 +00:00
// Set data end.
2014-11-24 10:57:31 +00:00
r.dataEnd = int64(r.metaBH.offset)
// Read metaindex.
metaIter := r.newBlockIter(metaBlock, nil, nil, true)
2014-07-06 12:46:48 +00:00
for metaIter.Next() {
key := string(metaIter.Key())
if !strings.HasPrefix(key, "filter.") {
continue
}
fn := key[7:]
if f0 := o.GetFilter(); f0 != nil && f0.Name() == fn {
2014-09-02 07:43:42 +00:00
r.filter = f0
2014-07-06 12:46:48 +00:00
} else {
for _, f0 := range o.GetAltFilters() {
if f0.Name() == fn {
2014-09-02 07:43:42 +00:00
r.filter = f0
2014-07-06 12:46:48 +00:00
break
}
}
}
2014-09-02 07:43:42 +00:00
if r.filter != nil {
2014-07-06 12:46:48 +00:00
filterBH, n := decodeBlockHandle(metaIter.Value())
if n == 0 {
continue
}
2014-09-02 07:43:42 +00:00
r.filterBH = filterBH
2014-07-06 12:46:48 +00:00
// Update data end.
r.dataEnd = int64(filterBH.offset)
break
}
}
metaIter.Release()
2014-09-02 07:43:42 +00:00
metaBlock.Release()
2014-10-06 20:07:33 +00:00
// Cache index and filter block locally, since we don't have global cache.
if cache == nil {
2014-11-18 12:24:42 +00:00
r.indexBlock, err = r.readBlock(r.indexBH, true)
if err != nil {
if errors.IsCorrupted(err) {
r.err = err
return r, nil
}
return nil, err
2014-10-06 20:07:33 +00:00
}
if r.filter != nil {
r.filterBlock, err = r.readFilterBlock(r.filterBH)
if err != nil {
2014-11-24 10:57:31 +00:00
if !errors.IsCorrupted(err) {
2014-11-18 12:24:42 +00:00
return nil, err
}
2014-10-06 20:07:33 +00:00
// Don't use filter then.
r.filter = nil
}
}
}
2014-11-18 12:24:42 +00:00
return r, nil
2014-07-06 12:46:48 +00:00
}