Some checks failed
go: build dev binaries / cleanup (push) Successful in 4s
Codespell / Check for spelling errors (push) Failing after 3s
docker: build dev containers / build-rust-binaries (amd64, x86_64-unknown-linux-musl) (push) Failing after 3s
docker: build dev containers / build-dev-containers (push) Has been skipped
docker: build dev containers / build-rust-binaries (arm64, true, aarch64-unknown-linux-musl) (push) Failing after 3s
End to End / FUSE Mount (push) Failing after 2s
EC Integration Tests / EC Integration Tests (push) Failing after 30s
FUSE DLM Integration Tests / FUSE DLM Integration Tests (push) Failing after 3s
FUSE Volume Server Failover Tests / FUSE Volume Server Failover (push) Failing after 3s
FUSE Integration Tests / FUSE Integration Testing (push) Failing after 2s
FUSE P2P Peer Chunk Sharing Integration Tests / FUSE P2P Peer Chunk Sharing (push) Failing after 3s
go: build binary / Go Vet (push) Failing after 2s
go: build binary / Go Vet 32-bit (push) Failing after 3s
go: build binary / Build (push) Failing after 4s
go: build binary / Build cross-platform (freebsd/amd64) (push) Failing after 3s
go: build binary / Build cross-platform (windows/amd64) (push) Failing after 3s
go: build binary / Build cross-platform (darwin/arm64) (push) Failing after 3s
go: build binary / Build cross-platform (windows/arm64) (push) Failing after 3s
go: build binary / Test (push) Failing after 2s
go: build binary / Test 32-bit (push) Failing after 3s
helm: lint and test charts / lint-test (push) Failing after 3s
Java Client Integration Tests / Java Integration Tests (11) (push) Failing after 3s
Java Client Integration Tests / Java Integration Tests (17) (push) Failing after 3s
go: build dev binaries / build_dev_linux_windows (amd64, linux) (push) Failing after 2s
go: build dev binaries / build_dev_linux_windows (amd64, windows) (push) Failing after 3s
go: build dev binaries / build_dev_darwin (amd64, darwin) (push) Has been skipped
go: build dev binaries / build_dev_darwin (arm64, darwin) (push) Has been skipped
Java Client Unit Tests / Java Unit Tests (11) (push) Failing after 3s
Java Client Unit Tests / Java Unit Tests (17) (push) Failing after 2s
Java Client Unit Tests / Java Unit Tests (21) (push) Failing after 3s
Java Client Unit Tests / Java Unit Tests (8) (push) Failing after 3s
Kafka Quick Test (Load Test with Schema Registry) / Kafka Client Load Test (Quick) (push) Failing after 3s
Kafka Gateway Tests / Kafka Unit Tests (unit-tests-1) (push) Failing after 11s
Kafka Gateway Tests / Kafka Integration Tests (Critical) (integration-1) (push) Failing after 3s
Kafka Gateway Tests / Kafka End-to-End Tests (with SMQ) (e2e-1) (push) Failing after 3s
Kafka Gateway Tests / Kafka Consumer Group Tests (Highly Isolated) (consumer-group-1) (push) Failing after 2s
Kafka Gateway Tests / Kafka Client Compatibility (with SMQ) (client-compat-1) (push) Failing after 3s
Kafka Gateway Tests / Kafka SMQ Integration Tests (Full Stack) (smq-integration-1) (push) Failing after 3s
Kafka Gateway Tests / Kafka Protocol Tests (Isolated) (protocol-1) (push) Failing after 3s
KMS Tests / KMS Provider Integration Tests (push) Failing after 2s
KMS Tests / S3 KMS End-to-End Tests (push) Failing after 3s
Master Cold Start Tests / Master Cold Start Tests (push) Failing after 4s
Metadata Subscribe Integration Tests / Metadata Subscribe Integration Tests (push) Failing after 3s
Multi-Master Tests / Multi-Master Failover Tests (push) Failing after 3s
Performance / CPU and Heap Profile (push) Failing after 2s
Performance / S3 Read/Write Benchmark (rust volume) (push) Failing after 3s
pjdfstest POSIX Compliance / pjdfstest (push) Failing after 2s
Plugin Worker Integration Tests / Plugin Worker: erasure_coding (push) Failing after 3s
Plugin Worker Integration Tests / Plugin Worker: vacuum (push) Failing after 3s
Rust Volume Server Tests / Rust Integration Tests (push) Failing after 3s
Rust Volume Server Tests / Go Tests with Rust Volume (grpc - Shard 1) (push) Failing after 2s
Rust Volume Server Tests / Go Tests with Rust Volume (http - Shard 1) (push) Failing after 3s
Rust Volume Server Tests / Go Tests with Rust Volume (grpc - Shard 2) (push) Failing after 3s
Rust Volume Server Tests / Go Tests with Rust Volume (http - Shard 2) (push) Failing after 3s
Rust Volume Server Tests / Go Tests with Rust Volume (grpc - Shard 3) (push) Failing after 3s
S3 IAM Integration Tests / S3 IAM Distributed Tests (push) Failing after 2s
S3 IAM Integration Tests / S3 IAM Performance Tests (push) Failing after 3s
Performance / Throughput Benchmark (go volume) (push) Failing after 3s
Performance / Throughput Benchmark (rust volume) (push) Failing after 2s
Performance / S3 Read/Write Benchmark (go volume) (push) Failing after 3s
Plugin Worker Integration Tests / Plugin Worker: volume_balance (push) Failing after 3s
PostgreSQL Gateway Tests / PostgreSQL Basic Tests (push) Failing after 3s
Rust Volume Server Tests / Rust Unit Tests (push) Failing after 2s
Rust Volume Server Tests / Go Tests with Rust Volume (http - Shard 3) (push) Failing after 3s
Rust Plugin Worker Tests / Rust Plugin Worker Build and Unit Tests (push) Failing after 3s
rust: build dev volume server binaries / cleanup (push) Successful in 3s
S3 ETag and ACL Tests / S3 ETag + ACL Integration Tests (push) Failing after 3s
S3 IAM Integration Tests / IAM Unit Tests (push) Failing after 3s
S3 IAM Integration Tests / S3 IAM Integration Tests (advanced) (push) Failing after 3s
S3 IAM Integration Tests / S3 IAM Integration Tests (basic) (push) Failing after 2s
S3 IAM Integration Tests / S3 IAM Integration Tests (group) (push) Failing after 3s
S3 IAM Integration Tests / S3 IAM Integration Tests (policy-enforcement) (push) Failing after 2s
S3 IAM Integration Tests / S3 IAM Integration Tests (sts) (push) Failing after 4s
S3 Keycloak Integration Tests / S3 Keycloak Integration Tests (push) Failing after 3s
S3 PyArrow Parquet Tests / PyArrow Parquet Tests (Python 3.11) (push) Failing after 3s
S3 PyArrow Parquet Tests / Go Unit Tests (Implicit Directory) (push) Has been cancelled
S3 PyArrow Parquet Tests / PyArrow Parquet Tests (Python 3.12) (push) Has been cancelled
rust: build dev volume server binaries / build-rust-volume-dev-darwin (darwin-amd64, x86_64-apple-darwin) (push) Has been cancelled
rust: build dev volume server binaries / build-rust-volume-dev-darwin (darwin-arm64, aarch64-apple-darwin) (push) Has been cancelled
rust: build dev volume server binaries / build-rust-volume-dev-linux (linux-amd64, x86_64-unknown-linux-gnu) (push) Has been cancelled
S3 PyArrow Parquet Tests / PyArrow Parquet Tests (Python 3.9) (push) Has been cancelled
S3 Proxy Signature Tests / S3 Proxy Signature Verification Tests (push) Has been cancelled
S3 SDK V2 Route Disambiguation Tests / S3 SDK V2 Routing Tests (push) Has been cancelled
S3 SSE Tests / S3 SSE Integration Tests (quick) (push) Has been cancelled
S3 SSE Tests / S3 SSE Compatibility Test (push) Has been cancelled
S3 SSE Tests / S3 SSE Metadata Persistence Test (push) Has been cancelled
S3 SSE Tests / S3 SSE Copy Operations Test (push) Has been cancelled
S3 SSE Tests / S3 SSE Multipart Upload Test (push) Has been cancelled
S3 SSE Tests / S3 SSE Performance Test (push) Has been cancelled
S3 SSE Tests / S3 Volume Encryption Test (push) Has been cancelled
S3 SSE Tests / S3 SSE Integration Tests (comprehensive) (push) Has been cancelled
Spark Integration Tests / Spark Integration Tests (push) Failing after 2s
Telemetry Integration Tests / telemetry-integration-test (push) Failing after 3s
Volume Server Integration Tests / Volume Server Integration Tests (grpc - Shard 1) (push) Failing after 3s
Volume Server Integration Tests / Volume Server Integration Tests (http - Shard 1) (push) Failing after 3s
Ceph S3 tests / Basic S3 tests (KV store) (push) Has been cancelled
Ceph S3 tests / S3 Versioning & Object Lock tests (push) Has been cancelled
S3 Policy Integration Tests / S3 Policy Unit Tests (push) Failing after 3s
Ceph S3 tests / S3 CORS tests (push) Has been cancelled
Ceph S3 tests / SeaweedFS Custom S3 Copy tests (push) Has been cancelled
Ceph S3 tests / Basic S3 tests (SQL store) (push) Has been cancelled
test s3 over https using aws-cli / awscli-tests (push) Has been cancelled
TLS Rotation Integration Tests / TLS Rotation Integration Tests (push) Has been cancelled
Vacuum Integration Tests / Vacuum Integration Tests (push) Has been cancelled
S3 Policy Integration Tests / S3 Policy Variables Integration Tests (push) Failing after 3s
S3 Policy Integration Tests / S3 Policy Enforcement Integration Tests (advanced-policy) (push) Failing after 3s
S3 Policy Integration Tests / S3 Policy Enforcement Integration Tests (basic-policy) (push) Failing after 2s
S3 Policy Integration Tests / S3 Policy Enforcement Integration Tests (contextual-policy) (push) Failing after 4s
S3 Policy Integration Tests / Trusted Proxy Detection Tests (push) Failing after 2s
S3 Policy Integration Tests / S3 Policy Shell Integration Tests (push) Failing after 3s
Samba on FUSE Integration / samba-integration (push) Failing after 2s
SFTP Integration Tests / SFTP Integration Testing (push) Failing after 3s
terraform: validate and test modules / fmt, validate, plan-level tests (push) Failing after 3s
terraform: validate and test modules / local cluster smoke test (real weed) (push) Failing after 2s
Volume Server Integration Tests / Volume Server Integration Tests (grpc - Shard 3) (push) Failing after 3s
Volume Server Integration Tests / Volume Server Integration Tests (grpc - Shard 2) (push) Failing after 3s
Volume Server Integration Tests / Volume Server Integration Tests (http - Shard 2) (push) Failing after 2s
Volume Server Integration Tests / Volume Server Integration Tests (http - Shard 3) (push) Failing after 5s
mount: windows conformance / WinFsp conformance (push) Has been cancelled
mount: windows / Mount on Windows (push) Has been cancelled
327 lines
12 KiB
Go
327 lines
12 KiB
Go
package mount
|
|
|
|
import (
|
|
"bytes"
|
|
"context"
|
|
"crypto/md5"
|
|
"encoding/hex"
|
|
"fmt"
|
|
"io"
|
|
"sort"
|
|
"time"
|
|
|
|
"github.com/seaweedfs/seaweedfs/weed/filer"
|
|
"github.com/seaweedfs/seaweedfs/weed/glog"
|
|
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
|
"github.com/seaweedfs/seaweedfs/weed/pb/mount_peer_pb"
|
|
"github.com/seaweedfs/seaweedfs/weed/util"
|
|
"google.golang.org/grpc/codes"
|
|
"google.golang.org/grpc/status"
|
|
)
|
|
|
|
// errPeerReadSkipped signals that the read didn't go through the peer
|
|
// path for a benign reason (local cache hit, no peer owner, etc.) rather
|
|
// than a genuine failure. Callers fall through to the volume path just
|
|
// as they would for a real error, but suppress the "peer read failed"
|
|
// log that would otherwise mislead operators into thinking peer sharing
|
|
// is broken.
|
|
var errPeerReadSkipped = fmt.Errorf("peer read skipped (not an error)")
|
|
|
|
// peerLookupTimeout bounds the ChunkLookup RPC. Short because the result
|
|
// is consumed on the read critical path.
|
|
const peerLookupTimeout = 500 * time.Millisecond
|
|
|
|
// peerFetchTimeout bounds a single FetchChunk stream; on expiry we fall
|
|
// through to the next holder or the volume server.
|
|
const peerFetchTimeout = 5 * time.Second
|
|
|
|
// maxPeerFetchChunkBytes caps how much we will accept from a single
|
|
// FetchChunk stream. gRPC per-message size is already capped by the
|
|
// server option; this is belt-and-suspenders against a runaway peer.
|
|
const maxPeerFetchChunkBytes = 64 * 1024 * 1024
|
|
|
|
// tryPeerRead attempts to satisfy a read from a peer mount's chunk cache.
|
|
// Returns (bytesRead, modifiedTsNs, nil) on success. On any failure it
|
|
// returns (0, 0, err) so the caller falls through to
|
|
// entryChunkGroup.ReadDataAt (the volume-server path).
|
|
//
|
|
// Flow:
|
|
// 1. Resolve the offset's leaf chunk (flattening manifests).
|
|
// 2. Ask the HRW owner mount for current holders via ChunkLookup.
|
|
// 3. For each holder (LRU order from PR #5), open a FetchChunk stream,
|
|
// assemble frames into a size-bounded buffer, and verify MD5
|
|
// end-to-end against FileChunk.ETag.
|
|
// 4. On success, populate chunk_cache and enqueue an announce so
|
|
// other mounts can discover us as a new holder.
|
|
//
|
|
// chunks is a snapshot captured under the LockedEntry lock by the caller.
|
|
func (fh *FileHandle) tryPeerRead(ctx context.Context, fileSize int64, buff []byte, offset int64, chunks []*filer_pb.FileChunk) (int64, int64, error) {
|
|
if fh.wfs.peerRegistrar == nil || fh.wfs.peerConnPool == nil {
|
|
return 0, 0, fmt.Errorf("peer sharing not configured")
|
|
}
|
|
|
|
// Resolve offset → leaf chunk, flattening any manifest indirection.
|
|
readStop := offset + int64(len(buff))
|
|
if readStop > fileSize {
|
|
readStop = fileSize
|
|
}
|
|
dataChunks, _, err := filer.ResolveChunkManifest(ctx, fh.wfs.LookupFn(), chunks, offset, readStop, fh.wfs.CacheInvalidator())
|
|
if err != nil {
|
|
return 0, 0, fmt.Errorf("resolve manifest: %w", err)
|
|
}
|
|
targetChunk, chunkOffset := findChunkContaining(dataChunks, offset)
|
|
if targetChunk == nil {
|
|
return 0, 0, fmt.Errorf("no leaf chunk for offset %d", offset)
|
|
}
|
|
// Reject reads that cross a chunk boundary. We only fetch one chunk
|
|
// here, and the caller (readFromChunks) maps a short non-error
|
|
// return to "success, zero-fill the rest" — which would silently
|
|
// corrupt reads that should actually span two chunks. Bail so the
|
|
// fallback ReadDataAt path can handle the multi-chunk case
|
|
// correctly. See weedfs_file_read.go short-read semantics.
|
|
chunkEnd := targetChunk.Offset + int64(targetChunk.Size)
|
|
if readStop > chunkEnd {
|
|
return 0, 0, errPeerReadSkipped
|
|
}
|
|
|
|
// Fail fast when the chunk is already cached locally: the fallback
|
|
// ReadDataAt path will satisfy the read from chunkCache with no RPCs,
|
|
// so dialing a peer (ChunkLookup + FetchChunk) would be pure overhead.
|
|
if fh.wfs.chunkCache != nil && fh.wfs.chunkCache.IsInCache(targetChunk.FileId, true) {
|
|
return 0, 0, errPeerReadSkipped
|
|
}
|
|
|
|
selfAddr := ""
|
|
if fh.wfs.peerGrpcServer != nil {
|
|
selfAddr = fh.wfs.peerGrpcServer.SelfAddr()
|
|
}
|
|
|
|
owner := fh.wfs.peerRegistrar.OwnerFor(targetChunk.FileId)
|
|
if owner == "" || owner == selfAddr {
|
|
return 0, 0, fmt.Errorf("no peer owner for fid %s", targetChunk.FileId)
|
|
}
|
|
|
|
holders, err := peerLookupHolders(ctx, fh.wfs.peerConnPool.Dialer(), owner, targetChunk.FileId)
|
|
if err != nil {
|
|
return 0, 0, fmt.Errorf("peer lookup: %w", err)
|
|
}
|
|
if len(holders) == 0 {
|
|
return 0, 0, fmt.Errorf("no peer holder for fid %s", targetChunk.FileId)
|
|
}
|
|
|
|
// Re-rank holders by locality (same rack > same DC > elsewhere), keeping
|
|
// the server's LRU order stable within each bucket. The server caps the
|
|
// list at maxLookupHolders, so this is always a small N.
|
|
sortHoldersByLocality(holders, fh.wfs.option.PeerDataCenter, fh.wfs.option.PeerRack)
|
|
|
|
dial := fh.wfs.peerConnPool.Dialer()
|
|
for _, h := range holders {
|
|
if h.addr == selfAddr {
|
|
continue
|
|
}
|
|
data, ferr := fetchChunkFromPeer(ctx, dial, h.addr, targetChunk.FileId, targetChunk.Size, targetChunk.ETag)
|
|
if ferr != nil {
|
|
glog.V(2).Infof("peer-fetch %s from %s: %v", targetChunk.FileId, h.addr, ferr)
|
|
continue
|
|
}
|
|
if fh.wfs.chunkCache != nil {
|
|
fh.wfs.chunkCache.SetChunk(targetChunk.FileId, data)
|
|
}
|
|
if fh.wfs.peerAnnouncer != nil {
|
|
fh.wfs.peerAnnouncer.EnqueueAnnounce(targetChunk.FileId)
|
|
}
|
|
if chunkOffset >= int64(len(data)) {
|
|
return 0, 0, fmt.Errorf("peer returned short chunk")
|
|
}
|
|
// Cap the copy to whichever is smaller: the caller's buffer, or
|
|
// the remaining bytes before logical EOF (readStop already
|
|
// clamped to fileSize). FileChunk.Size can legitimately exceed
|
|
// the logical file length when the last chunk is partially
|
|
// written and the filer stored the full padded buffer, so a
|
|
// naïve copy(buff, data[chunkOffset:]) would return bytes past
|
|
// EOF. The caller treats a short non-error return as success
|
|
// and zero-fills the tail, so returning too many bytes here is
|
|
// a correctness bug, not just wasted I/O.
|
|
remaining := readStop - offset
|
|
available := int64(len(data)) - chunkOffset
|
|
maxCopy := int64(len(buff))
|
|
if remaining < maxCopy {
|
|
maxCopy = remaining
|
|
}
|
|
if available < maxCopy {
|
|
maxCopy = available
|
|
}
|
|
copied := copy(buff[:maxCopy], data[chunkOffset:chunkOffset+maxCopy])
|
|
return int64(copied), targetChunk.ModifiedTsNs, nil
|
|
}
|
|
return 0, 0, fmt.Errorf("no peer served fid %s", targetChunk.FileId)
|
|
}
|
|
|
|
func findChunkContaining(chunks []*filer_pb.FileChunk, offset int64) (*filer_pb.FileChunk, int64) {
|
|
for _, c := range chunks {
|
|
start := c.Offset
|
|
stop := c.Offset + int64(c.Size)
|
|
if offset >= start && offset < stop {
|
|
return c, offset - start
|
|
}
|
|
}
|
|
return nil, 0
|
|
}
|
|
|
|
// peerHolder is a holder entry carried through the fetcher: addr for
|
|
// dialing plus the DC/Rack labels the owner recorded at announce time, so
|
|
// the fetcher can re-rank by its own locality before dialing.
|
|
type peerHolder struct {
|
|
addr string
|
|
dc string
|
|
rack string
|
|
}
|
|
|
|
// peerLookupHolders calls ChunkLookup on the given HRW owner and returns
|
|
// the holders in the server-reported (LRU) order along with their locality
|
|
// labels. The pooled dialer is passed in from the caller.
|
|
func peerLookupHolders(ctx context.Context, dial MountPeerDialer, ownerAddr, fid string) ([]peerHolder, error) {
|
|
client, closeFn, err := dial(ctx, ownerAddr)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
defer closeFn()
|
|
|
|
callCtx, cancel := context.WithTimeout(ctx, peerLookupTimeout)
|
|
defer cancel()
|
|
resp, err := client.ChunkLookup(callCtx, &mount_peer_pb.ChunkLookupRequest{FileIds: []string{fid}})
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
set, ok := resp.PeersByFid[fid]
|
|
if !ok || set == nil {
|
|
return nil, nil
|
|
}
|
|
out := make([]peerHolder, 0, len(set.Peers))
|
|
for _, p := range set.Peers {
|
|
out = append(out, peerHolder{addr: p.PeerAddr, dc: p.DataCenter, rack: p.Rack})
|
|
}
|
|
return out, nil
|
|
}
|
|
|
|
// localityBucket scores how "close" a peer is to self. Lower is better:
|
|
//
|
|
// 0 = same rack in same DC (shortest hop)
|
|
// 1 = same DC, different rack (cross-rack but still intra-DC)
|
|
// 2 = different DC, or unknown (anything else)
|
|
//
|
|
// Missing labels on either side fall to bucket 2 — we don't claim locality
|
|
// we can't prove.
|
|
func localityBucket(selfDC, selfRack, peerDC, peerRack string) int {
|
|
if selfDC == "" || peerDC == "" || selfDC != peerDC {
|
|
return 2
|
|
}
|
|
if selfRack != "" && peerRack != "" && selfRack == peerRack {
|
|
return 0
|
|
}
|
|
return 1
|
|
}
|
|
|
|
// sortHoldersByLocality stable-sorts holders so the most local peers are
|
|
// tried first. The server-returned order is LRU (freshest holder first),
|
|
// and sort.SliceStable preserves that ordering within each locality
|
|
// bucket, so among equally-local peers we still prefer the freshest.
|
|
func sortHoldersByLocality(holders []peerHolder, selfDC, selfRack string) {
|
|
if len(holders) < 2 {
|
|
return
|
|
}
|
|
sort.SliceStable(holders, func(i, j int) bool {
|
|
return localityBucket(selfDC, selfRack, holders[i].dc, holders[i].rack) <
|
|
localityBucket(selfDC, selfRack, holders[j].dc, holders[j].rack)
|
|
})
|
|
}
|
|
|
|
// fetchChunkFromPeer server-streams a chunk from the given peer and
|
|
// verifies the MD5 of the assembled bytes against expectedETag.
|
|
//
|
|
// expectedSize (when > 0) is the authoritative chunk length from the
|
|
// filer entry; we pre-allocate exactly that to avoid slice growth and
|
|
// reject streams that overshoot it. A zero expectedSize falls back to
|
|
// maxPeerFetchChunkBytes as a safety ceiling.
|
|
func fetchChunkFromPeer(ctx context.Context, dial MountPeerDialer, peerAddr, fid string, expectedSize uint64, expectedETag string) ([]byte, error) {
|
|
client, closeFn, err := dial(ctx, peerAddr)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
defer closeFn()
|
|
|
|
callCtx, cancel := context.WithTimeout(ctx, peerFetchTimeout)
|
|
defer cancel()
|
|
|
|
stream, err := client.FetchChunk(callCtx, &mount_peer_pb.FetchChunkRequest{
|
|
FileId: fid,
|
|
ExpectedEtag: expectedETag,
|
|
ExpectedSize: expectedSize,
|
|
})
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
// capHint pre-sizes the assembly buffer from the filer-reported chunk
|
|
// size. When the caller didn't know the size (expectedSize == 0), we
|
|
// let append grow the buffer rather than reserve the 64 MiB ceiling —
|
|
// typical chunks are a few MiB, and the maxPeerFetchChunkBytes check
|
|
// during Recv is the real safety ceiling.
|
|
capHint := expectedSize
|
|
if capHint > maxPeerFetchChunkBytes {
|
|
capHint = maxPeerFetchChunkBytes
|
|
}
|
|
buf := make([]byte, 0, capHint)
|
|
|
|
for {
|
|
resp, rerr := stream.Recv()
|
|
if rerr == io.EOF {
|
|
break
|
|
}
|
|
if rerr != nil {
|
|
if status.Code(rerr) == codes.NotFound {
|
|
return nil, fmt.Errorf("peer not cached")
|
|
}
|
|
return nil, rerr
|
|
}
|
|
if len(buf)+len(resp.Data) > int(maxPeerFetchChunkBytes) {
|
|
return nil, fmt.Errorf("peer response exceeds max chunk size %d", maxPeerFetchChunkBytes)
|
|
}
|
|
buf = append(buf, resp.Data...)
|
|
}
|
|
|
|
if expectedSize > 0 && uint64(len(buf)) != expectedSize {
|
|
return nil, fmt.Errorf("peer returned %d bytes, expected %d", len(buf), expectedSize)
|
|
}
|
|
|
|
// Per-chunk integrity check — the peer is treated as untrusted.
|
|
// FileChunk.ETag is UploadResult.ContentMd5, which is base64 of the
|
|
// raw 16-byte MD5 (see weed/operation/upload_content.go:64 and
|
|
// filer's ETagChunks which decodes via util.Base64Md5ToBytes).
|
|
// Compare raw digests so we don't reject every valid peer response
|
|
// because of an encoding mismatch.
|
|
if expectedETag != "" {
|
|
got := md5.Sum(buf)
|
|
if !etagMatchesMD5(expectedETag, got[:]) {
|
|
return nil, fmt.Errorf("etag mismatch: peer=%s got=%x want=%s", peerAddr, got, expectedETag)
|
|
}
|
|
}
|
|
return buf, nil
|
|
}
|
|
|
|
// etagMatchesMD5 compares a stored FileChunk.ETag string to a raw 16-byte
|
|
// MD5 digest. FileChunk.ETag is produced as base64(md5) on upload, but
|
|
// some older chunks (and tests) use hex(md5). Accept either.
|
|
func etagMatchesMD5(etag string, rawMD5 []byte) bool {
|
|
if len(rawMD5) != md5.Size {
|
|
return false
|
|
}
|
|
if dec := util.Base64Md5ToBytes(etag); len(dec) == md5.Size {
|
|
return bytes.Equal(dec, rawMD5)
|
|
}
|
|
if dec, err := hex.DecodeString(etag); err == nil && len(dec) == md5.Size {
|
|
return bytes.Equal(dec, rawMD5)
|
|
}
|
|
return false
|
|
}
|