mirror of
https://github.com/seaweedfs/seaweedfs.git
synced 2026-10-24 06:50:40 +02:00
* volume: drop index entries that resolve to a different needle An index row whose offset lands on a needle with a different id and a different size cannot have been produced by any write path: every appender indexes a key at the offset and size of the record it wrote, and WriteNeedleBlob keeps its indexed size consistent with the blob header. Such rows are corruption (for example an offset replayed with stale high bytes) and until now made the volume reject every write for the key with "mismatching cookie" while reads resolved to the wrong needle. When the duplicate check finds the indexed record belongs to a different key and size, drop the stale entry and let the append re-index the key. Same-key conflicts still fail the cookie check, and entries staying consistent with a re-keyed blob keep their existing semantics. * volume: verify the indexed needle header before streaming reads The buffered read path re-parses the record and rejects a needle whose stored size disagrees with the index, but the streamed path serves data bytes without ever looking at the header, so a stale index row would stream another needle's payload. Probe the header once up front and report a miss when the record is neither the requested key nor the indexed size, the same staleness test the write path applies. * rust volume: drop index entries that resolve to a different needle Mirror of the Go volume change: when the duplicate check finds the indexed record belongs to a different key and size, delete the stale entry and let the append re-index the key. * volume: overwrite a stale index entry on commit, not up front Deleting the stale row during the duplicate check published a tombstone before the replacement append and, for durable writes, before its fsync. A failed append or sync then rolled back the data but left the key deleted. The publish step already overwrites any older offset, so leave the entry in place and let it be replaced once the record commits. * volume: report streaming header-probe failures to the io error tracker A failed header read returned before the tracked body-read loop, so repeated EIO on the probe never reached checkReadWriteError. Skip io.EOF the way the loop does: it is a truncated record, not a disk fault. * rust volume: overwrite a stale index entry on commit, not up front Mirror of the Go volume change: the staged delete published a tombstone before the replacement append and its .dat flush, so a failed append or sync left the key deleted. publish_write already overwrites any older offset once the record commits. * rust volume: report needle meta read failures to the io error tracker read_meta is the header probe ahead of a streamed body: an EIO there escaped check_read_write_error entirely, so a failing disk could not trip the tolerance. Report the outcome the way read_full already does. * volume: retry the wrapped offset before judging an index entry stale A 4-byte index value can index past the 32 GiB wrap: the low offset may hold another needle while the real record sits at +MaxPossibleVolumeSize, which is where reads already retry on a size mismatch. Skipping the cookie check on the low-offset record alone would accept a foreign-cookie write over a live key. Retry the wrapped header read first, the same condition the read path uses; a wrapped read that fails for reasons other than EOF stops the write like the low-offset read does. * volume: probe the streamed needle header under the access lock With HasSlowRead the access lock is dropped after the index lookup, so a compaction commit could swap the backend between the lookup and the header probe and fail a valid download on the old offset. Take the read lock for the probe and resolve the compaction revision first, the way the streaming loop re-resolves it on every page. * rust volume: retry the wrapped offset before judging an index entry stale Mirror of the Go volume change: probe offset + MAX_POSSIBLE_VOLUME_SIZE under the 4-byte-offset build before treating a mismatched record as stale, so a live wrapped entry still gets its cookie checked. * rust volume: do not clear the io error streak on a successful meta read read_meta runs before the payload read in read_needle_for_get, so recording success there reset the streak before every failing download and the volume could never reach quarantine. Report failures only; read_full still records success after a complete read. * volume: record a meta-only read's success against the io error streak A meta read no longer clears the streak because a payload read still follows on GETs, but requests the meta read ends outright — HEAD answers and cookie mismatches — never reached the body path, so their success left earlier failures counted. Note the success on those terminal paths; mirrored in the Rust volume server. Generated with [Devin](https://devin.ai) Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com> * rust volume: report streamed reads to the io error streak Streamed GETs never touched the tracker: a failing chunk read went uncounted and a completed download never cleared the streak, unlike readNeedleDataInto which does both. Generated with [Devin](https://devin.ai) Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com> * volume: reset the io error streak only at terminal meta reads A streamed GET's metadata read runs before its payload read, so clearing the streak there erased the count before every failing download and the volume could never reach quarantine. Record the meta-read success only where the request actually ends: must-meta-only reads, HEAD responses, and cookie mismatches — matching the Rust volume server's placement. * rust volume: record the streamed read's success at the final frame Hyper can complete a Content-Length response without polling the body again, so a success recorded only when the stream is next polled could be skipped, leaving an earlier io error streak in place after a successful download. * volume: record a meta-only read's success on conditional 304 replies * rust volume: record a meta-only read's success on conditional 304 replies * volume: reset the io error streak only after the checksum passes A streamed read that ends in a CRC mismatch still cleared the EIO streak, so corruption could mask progress toward quarantine. The Rust side records success only after the final frame's checksum verifies; move the reset below the CRC check to match. * volume: satisfy codespell in the meta-read comment * rust volume: report range reads to the io error streak * rust volume: cover the range read's io error reporting --------- Co-authored-by: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
436 lines
13 KiB
Go
436 lines
13 KiB
Go
package storage
|
|
|
|
import (
|
|
"fmt"
|
|
"io"
|
|
"time"
|
|
|
|
"github.com/seaweedfs/seaweedfs/weed/util/mem"
|
|
|
|
"github.com/seaweedfs/seaweedfs/weed/glog"
|
|
"github.com/seaweedfs/seaweedfs/weed/stats"
|
|
"github.com/seaweedfs/seaweedfs/weed/storage/backend"
|
|
"github.com/seaweedfs/seaweedfs/weed/storage/needle"
|
|
"github.com/seaweedfs/seaweedfs/weed/storage/super_block"
|
|
. "github.com/seaweedfs/seaweedfs/weed/storage/types"
|
|
)
|
|
|
|
const PagedReadLimit = 1024 * 1024
|
|
|
|
// read fills in Needle content by looking up n.Id from NeedleMapper
|
|
func (v *Volume) readNeedle(n *needle.Needle, readOption *ReadOption, onReadSizeFn func(size Size)) (count int, err error) {
|
|
v.dataFileAccessLock.RLock()
|
|
defer v.dataFileAccessLock.RUnlock()
|
|
|
|
if err := v.UnavailableError(); err != nil {
|
|
return 0, err
|
|
}
|
|
|
|
if v.nm == nil {
|
|
glog.V(0).Infof("volume %d: needle map not loaded; read returns not-found", v.Id)
|
|
return -1, ErrorNotFound
|
|
}
|
|
|
|
nv, ok := v.nm.Get(n.Id)
|
|
if !ok || nv.Offset.IsZero() {
|
|
return -1, ErrorNotFound
|
|
}
|
|
readSize := nv.Size
|
|
if readSize.IsDeleted() {
|
|
if readOption != nil && readOption.ReadDeleted && readSize != TombstoneFileSize {
|
|
glog.V(3).Infof("reading deleted %s", n.String())
|
|
stats.VolumeServerHandlerCounter.WithLabelValues(stats.ReadDeletedNeedle).Inc()
|
|
readSize = -readSize
|
|
} else {
|
|
return -1, ErrorDeleted
|
|
}
|
|
}
|
|
if readSize == 0 {
|
|
return 0, nil
|
|
}
|
|
if onReadSizeFn != nil {
|
|
onReadSizeFn(readSize)
|
|
}
|
|
// A version 1 needle has no data size field and no metadata after its
|
|
// data, which ReadNeedleMeta relies on, so it is always read in full.
|
|
if readOption != nil && readOption.AttemptMetaOnly && v.Version() != needle.Version1 && (readOption.MustMetaOnly || readSize > PagedReadLimit) {
|
|
readOption.VolumeRevision = v.SuperBlock.CompactionRevision
|
|
err = n.ReadNeedleMeta(v.DataBackend, nv.Offset.ToActualOffset(), readSize, v.Version())
|
|
if err == needle.ErrorSizeMismatch && OffsetSize == 4 {
|
|
readOption.IsOutOfRange = true
|
|
err = n.ReadNeedleMeta(v.DataBackend, nv.Offset.ToActualOffset()+int64(MaxPossibleVolumeSize), readSize, v.Version())
|
|
}
|
|
if err != nil {
|
|
v.checkReadWriteError(err)
|
|
return 0, err
|
|
}
|
|
if !n.IsCompressed() && !n.IsChunkedManifest() {
|
|
readOption.IsMetaOnly = true
|
|
// A must-meta-only read ends here, so its success may reset the
|
|
// streak. For a streamed GET the meta read precedes the payload read,
|
|
// which reports the outcome itself.
|
|
if readOption.MustMetaOnly {
|
|
v.checkReadWriteError(nil)
|
|
}
|
|
}
|
|
}
|
|
if readOption == nil || !readOption.IsMetaOnly {
|
|
err = n.ReadData(v.DataBackend, nv.Offset.ToActualOffset(), readSize, v.Version())
|
|
v.checkReadWriteError(err)
|
|
if err != nil {
|
|
return 0, err
|
|
}
|
|
}
|
|
count = int(n.DataSize)
|
|
if !n.HasTtl() {
|
|
return
|
|
}
|
|
ttlMinutes := n.Ttl.Minutes()
|
|
if ttlMinutes == 0 {
|
|
return
|
|
}
|
|
if !n.HasLastModifiedDate() {
|
|
return
|
|
}
|
|
if time.Now().Before(time.Unix(0, int64(n.AppendAtNs)).Add(time.Duration(ttlMinutes) * time.Minute)) {
|
|
return
|
|
}
|
|
return -1, ErrorNotFound
|
|
}
|
|
|
|
// NoteMetaOnlySuccess records a request that ended at the metadata read
|
|
// (e.g. a HEAD or a cookie mismatch), so its success may reset the streak —
|
|
// unlike a meta read that precedes a payload read.
|
|
func (v *Volume) NoteMetaOnlySuccess() {
|
|
v.checkReadWriteError(nil)
|
|
}
|
|
|
|
// read needle at a specific offset
|
|
func (v *Volume) readNeedleMetaAt(n *needle.Needle, offset int64, size int32) (err error) {
|
|
v.dataFileAccessLock.RLock()
|
|
defer v.dataFileAccessLock.RUnlock()
|
|
|
|
if err := v.UnavailableError(); err != nil {
|
|
return err
|
|
}
|
|
|
|
// read deleted needle meta data
|
|
if size < 0 {
|
|
size = 0
|
|
}
|
|
err = n.ReadNeedleMeta(v.DataBackend, offset, Size(size), v.Version())
|
|
if err == needle.ErrorSizeMismatch && OffsetSize == 4 {
|
|
err = n.ReadNeedleMeta(v.DataBackend, offset+int64(MaxPossibleVolumeSize), Size(size), v.Version())
|
|
}
|
|
if err != nil {
|
|
return err
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// read fills in Needle content by looking up n.Id from NeedleMapper
|
|
func (v *Volume) readNeedleDataInto(n *needle.Needle, readOption *ReadOption, writer io.Writer, offset int64, size int64) (err error) {
|
|
|
|
if !readOption.HasSlowRead {
|
|
v.dataFileAccessLock.RLock()
|
|
defer v.dataFileAccessLock.RUnlock()
|
|
}
|
|
|
|
if readOption.HasSlowRead {
|
|
v.dataFileAccessLock.RLock()
|
|
}
|
|
if err := v.UnavailableError(); err != nil {
|
|
if readOption.HasSlowRead {
|
|
v.dataFileAccessLock.RUnlock()
|
|
}
|
|
return err
|
|
}
|
|
if v.nm == nil {
|
|
if readOption.HasSlowRead {
|
|
v.dataFileAccessLock.RUnlock()
|
|
}
|
|
glog.V(0).Infof("volume %d: needle map not loaded; read returns not-found", v.Id)
|
|
return ErrorNotFound
|
|
}
|
|
nv, ok := v.nm.Get(n.Id)
|
|
if readOption.HasSlowRead {
|
|
v.dataFileAccessLock.RUnlock()
|
|
}
|
|
|
|
if !ok || nv.Offset.IsZero() {
|
|
return ErrorNotFound
|
|
}
|
|
readSize := nv.Size
|
|
if readSize.IsDeleted() {
|
|
if readOption != nil && readOption.ReadDeleted && readSize != TombstoneFileSize {
|
|
glog.V(3).Infof("reading deleted %s", n.String())
|
|
readSize = -readSize
|
|
} else {
|
|
return ErrorDeleted
|
|
}
|
|
}
|
|
if readSize == 0 {
|
|
return nil
|
|
}
|
|
|
|
actualOffset := nv.Offset.ToActualOffset()
|
|
if readOption.IsOutOfRange {
|
|
actualOffset += int64(MaxPossibleVolumeSize)
|
|
}
|
|
|
|
buf := mem.Allocate(min(readOption.ReadBufferSize, int(size)))
|
|
// A full-needle read holds the last page back in `pending` until the CRC
|
|
// matches; `spare` is a second buffer swapped in so the held page is not
|
|
// overwritten while streaming.
|
|
var spare []byte
|
|
defer func() {
|
|
mem.Free(buf)
|
|
if spare != nil {
|
|
mem.Free(spare)
|
|
}
|
|
}()
|
|
|
|
// The header is not part of the streamed body, so verify the indexed
|
|
// offset really holds this needle before sending another needle's data.
|
|
// A slow read dropped the access lock after the index lookup; take it
|
|
// back for the probe so a compaction commit cannot swap the backend
|
|
// under it, and resolve the offset the way the streaming loop does.
|
|
probeHeader := func() error {
|
|
if readOption.VolumeRevision != v.SuperBlock.CompactionRevision {
|
|
if v.nm == nil {
|
|
return ErrorNotFound
|
|
}
|
|
refreshed, found := v.nm.Get(n.Id)
|
|
if !found || refreshed.Offset.IsZero() {
|
|
return ErrorNotFound
|
|
}
|
|
nv = refreshed
|
|
actualOffset = nv.Offset.ToActualOffset()
|
|
readOption.VolumeRevision = v.SuperBlock.CompactionRevision
|
|
}
|
|
header := make([]byte, NeedleHeaderSize)
|
|
headerCount, headerErr := v.DataBackend.ReadAt(header, actualOffset)
|
|
if headerErr == io.EOF && headerCount == NeedleHeaderSize {
|
|
headerErr = nil
|
|
}
|
|
if headerErr != nil {
|
|
if headerErr != io.EOF {
|
|
v.checkReadWriteError(headerErr)
|
|
}
|
|
return fmt.Errorf("ReadNeedleData header: %w", headerErr)
|
|
}
|
|
probe := new(needle.Needle)
|
|
probe.ParseNeedleHeader(header)
|
|
if probe.Id != n.Id && probe.Size != nv.Size {
|
|
glog.V(0).Infof("volume %d index entry for needle %x resolves to needle %x; reporting not-found",
|
|
v.Id, uint64(n.Id), uint64(probe.Id))
|
|
return ErrorNotFound
|
|
}
|
|
return nil
|
|
}
|
|
if readOption.HasSlowRead {
|
|
v.dataFileAccessLock.RLock()
|
|
}
|
|
probeErr := probeHeader()
|
|
if readOption.HasSlowRead {
|
|
v.dataFileAccessLock.RUnlock()
|
|
}
|
|
if probeErr != nil {
|
|
return probeErr
|
|
}
|
|
|
|
// read needle data
|
|
crc := needle.CRC(0)
|
|
var pending []byte
|
|
checkCRC := offset == 0 && size == int64(n.DataSize)
|
|
for x := offset; x < offset+size; x += int64(len(buf)) {
|
|
|
|
if readOption.HasSlowRead {
|
|
v.dataFileAccessLock.RLock()
|
|
if err := v.UnavailableError(); err != nil {
|
|
v.dataFileAccessLock.RUnlock()
|
|
return err
|
|
}
|
|
}
|
|
// possibly re-read needle offset if volume is compacted
|
|
if readOption.VolumeRevision != v.SuperBlock.CompactionRevision {
|
|
if v.nm == nil {
|
|
if readOption.HasSlowRead {
|
|
v.dataFileAccessLock.RUnlock()
|
|
}
|
|
glog.V(0).Infof("volume %d: needle map not loaded mid-read", v.Id)
|
|
return ErrorNotFound
|
|
}
|
|
// the volume is compacted
|
|
nv, ok = v.nm.Get(n.Id)
|
|
if !ok || nv.Offset.IsZero() {
|
|
if readOption.HasSlowRead {
|
|
v.dataFileAccessLock.RUnlock()
|
|
}
|
|
return ErrorNotFound
|
|
}
|
|
actualOffset = nv.Offset.ToActualOffset()
|
|
readOption.VolumeRevision = v.SuperBlock.CompactionRevision
|
|
}
|
|
count, err := n.ReadNeedleData(v.DataBackend, actualOffset, buf, x)
|
|
if readOption.HasSlowRead {
|
|
v.dataFileAccessLock.RUnlock()
|
|
}
|
|
// Thread the underlying read error through the EIO tracker.
|
|
// Without this, large/range GETs through readNeedleDataInto
|
|
// would never trip IoErrorTolerance even on a failing disk.
|
|
// io.EOF is treated as a clean end-of-stream below, not an
|
|
// error.
|
|
if err != nil && err != io.EOF {
|
|
v.checkReadWriteError(err)
|
|
}
|
|
|
|
toWrite := min(count, int(offset+size-x))
|
|
if toWrite > 0 {
|
|
crc = crc.Update(buf[0:toWrite])
|
|
// The CRC is known only after the last byte; hold each page until
|
|
// the next one is read so a bad needle is never fully written.
|
|
if checkCRC {
|
|
if pending != nil {
|
|
if _, err = writer.Write(pending); err != nil {
|
|
return fmt.Errorf("ReadNeedleData write: %w", err)
|
|
}
|
|
}
|
|
pending = buf[:toWrite]
|
|
if x+int64(len(buf)) < offset+size {
|
|
if spare == nil {
|
|
spare = mem.Allocate(len(buf))
|
|
}
|
|
buf, spare = spare, buf
|
|
}
|
|
} else if _, err = writer.Write(buf[0:toWrite]); err != nil {
|
|
return fmt.Errorf("ReadNeedleData write: %w", err)
|
|
}
|
|
}
|
|
if err != nil {
|
|
if err == io.EOF {
|
|
err = nil
|
|
break
|
|
}
|
|
return fmt.Errorf("ReadNeedleData: %w", err)
|
|
}
|
|
if count <= 0 {
|
|
break
|
|
}
|
|
}
|
|
if checkCRC && (n.Checksum != crc && uint32(n.Checksum) != crc.Value()) {
|
|
// the crc.Value() function is to be deprecated. this double checking is for backward compatibility
|
|
// with seaweed version using crc.Value() instead of uint32(crc), which appears in commit 056c480eb
|
|
// and switch appeared in version 3.09.
|
|
// pending is the last page and is intentionally not written.
|
|
stats.VolumeServerHandlerCounter.WithLabelValues(stats.ErrorCRC).Inc()
|
|
return fmt.Errorf("ReadNeedleData checksum %v expected %v for Needle: %v,%v", crc, n.Checksum, v.Id, n)
|
|
}
|
|
// The read succeeded only once the checksum passes; a failed needle
|
|
// leaves the io error streak untouched, matching the streamed path.
|
|
v.checkReadWriteError(nil)
|
|
if pending != nil {
|
|
if _, err = writer.Write(pending); err != nil {
|
|
return fmt.Errorf("ReadNeedleData write: %w", err)
|
|
}
|
|
}
|
|
return nil
|
|
|
|
}
|
|
|
|
func min(x, y int) int {
|
|
if x < y {
|
|
return x
|
|
}
|
|
return y
|
|
}
|
|
|
|
// read fills in Needle content by looking up n.Id from NeedleMapper
|
|
func (v *Volume) ReadNeedleBlob(offset int64, size Size) ([]byte, error) {
|
|
// A deletion marker is not a record length; reject it before taking the lock.
|
|
if size.IsDeleted() {
|
|
return nil, fmt.Errorf("invalid needle size %d", size)
|
|
}
|
|
|
|
v.dataFileAccessLock.RLock()
|
|
defer v.dataFileAccessLock.RUnlock()
|
|
|
|
if err := v.UnavailableError(); err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
blob, err := needle.ReadNeedleBlob(v.DataBackend, offset, size, v.Version())
|
|
v.checkReadWriteError(err)
|
|
return blob, err
|
|
}
|
|
|
|
type VolumeFileScanner interface {
|
|
VisitSuperBlock(super_block.SuperBlock) error
|
|
ReadNeedleBody() bool
|
|
VisitNeedle(n *needle.Needle, offset int64, needleHeader, needleBody []byte) error
|
|
}
|
|
|
|
func ScanVolumeFile(dirname string, collection string, id needle.VolumeId,
|
|
needleMapKind NeedleMapKind,
|
|
volumeFileScanner VolumeFileScanner) (err error) {
|
|
var v *Volume
|
|
if v, err = loadVolumeWithoutIndex(dirname, collection, id, needleMapKind, needle.GetCurrentVersion()); err != nil {
|
|
return fmt.Errorf("failed to load volume %d: %w", id, err)
|
|
}
|
|
if err = volumeFileScanner.VisitSuperBlock(v.SuperBlock); err != nil {
|
|
return fmt.Errorf("failed to process volume %d super block: %w", id, err)
|
|
}
|
|
defer v.Close()
|
|
|
|
version := v.Version()
|
|
|
|
offset := int64(v.SuperBlock.BlockSize())
|
|
|
|
return ScanVolumeFileFrom(version, v.DataBackend, offset, volumeFileScanner)
|
|
}
|
|
|
|
func ScanVolumeFileFrom(version needle.Version, datBackend backend.BackendStorageFile, offset int64, volumeFileScanner VolumeFileScanner) (err error) {
|
|
n, nh, rest, e := needle.ReadNeedleHeader(datBackend, version, offset)
|
|
if e != nil {
|
|
if e == io.EOF {
|
|
return nil
|
|
}
|
|
return fmt.Errorf("cannot read %s at offset %d: %w", datBackend.Name(), offset, e)
|
|
}
|
|
for n != nil {
|
|
var needleBody []byte
|
|
if volumeFileScanner.ReadNeedleBody() {
|
|
// println("needle", n.Id.String(), "offset", offset, "size", n.Size, "rest", rest)
|
|
if needleBody, err = n.ReadNeedleBody(datBackend, version, offset+NeedleHeaderSize, rest); err != nil {
|
|
glog.V(0).Infof("cannot read needle head [%d, %d) body [%d, %d) body length %d: %v", offset, offset+NeedleHeaderSize, offset+NeedleHeaderSize, offset+NeedleHeaderSize+rest, rest, err)
|
|
// err = fmt.Errorf("cannot read needle body: %v", err)
|
|
// return
|
|
}
|
|
}
|
|
err := volumeFileScanner.VisitNeedle(n, offset, nh, needleBody)
|
|
if err == io.EOF {
|
|
return nil
|
|
}
|
|
if err != nil {
|
|
glog.V(0).Infof("visit needle error: %v", err)
|
|
return fmt.Errorf("visit needle error: %w", err)
|
|
}
|
|
// A corrupt header can carry a size so negative that the record length
|
|
// is zero or less; the scan cannot advance past it.
|
|
recordSize := NeedleHeaderSize + rest
|
|
if recordSize <= 0 {
|
|
return fmt.Errorf("%s: needle header at offset %d has size %d, record length %d: %w", datBackend.Name(), offset, n.Size, recordSize, needle.ErrorCorrupted)
|
|
}
|
|
offset += recordSize
|
|
glog.V(4).Infof("==> new entry offset %d", offset)
|
|
if n, nh, rest, err = needle.ReadNeedleHeader(datBackend, version, offset); err != nil {
|
|
if err == io.EOF {
|
|
return nil
|
|
}
|
|
return fmt.Errorf("cannot read needle header at offset %d: %w", offset, err)
|
|
}
|
|
glog.V(4).Infof("new entry needle size:%d rest:%d", n.Size, rest)
|
|
}
|
|
return nil
|
|
}
|