From 9efaeec1e9320d157913ceb7551e11618e162004 Mon Sep 17 00:00:00 2001 From: Neil Macneale IV Date: Thu, 20 Feb 2025 16:01:38 -0800 Subject: [PATCH] WIP - checkpoint --- go/store/nbs/aws_chunk_source.go | 5 +- go/store/nbs/chunk_source_adapter.go | 2 + go/store/nbs/s3_object_reader.go | 160 +++++++++++++++++++++++++++ go/store/nbs/s3_table_reader.go | 139 ++--------------------- 4 files changed, 173 insertions(+), 133 deletions(-) create mode 100644 go/store/nbs/s3_object_reader.go diff --git a/go/store/nbs/aws_chunk_source.go b/go/store/nbs/aws_chunk_source.go index 1733aa7a887..b3f4665598c 100644 --- a/go/store/nbs/aws_chunk_source.go +++ b/go/store/nbs/aws_chunk_source.go @@ -32,7 +32,7 @@ import ( func tableExistsInChunkSource(ctx context.Context, s3 *s3ObjectReader, al awsLimits, name hash.Hash, chunkCount uint32, q MemoryQuotaProvider, stats *Stats) (bool, error) { magic := make([]byte, magicNumberSize) - n, _, err := s3.ReadFromEnd(ctx, name, magic, stats) + n, err := readS3TableFileFromEnd(ctx, s3, name.String(), magic, stats) if err != nil { return false, err } @@ -42,10 +42,11 @@ func tableExistsInChunkSource(ctx context.Context, s3 *s3ObjectReader, al awsLim return bytes.Equal(magic, []byte(magicNumber)), nil } +// NM4 - Rename to newAWSTableFileChunkSource, maybe? func newAWSChunkSource(ctx context.Context, s3 *s3ObjectReader, al awsLimits, name hash.Hash, chunkCount uint32, q MemoryQuotaProvider, stats *Stats) (cs chunkSource, err error) { var tra tableReaderAt index, err := loadTableIndex(ctx, stats, chunkCount, q, func(p []byte) error { - n, _, err := s3.ReadFromEnd(ctx, name, p, stats) + n, err := readS3TableFileFromEnd(ctx, s3, name.String(), p, stats) if err != nil { return err } diff --git a/go/store/nbs/chunk_source_adapter.go b/go/store/nbs/chunk_source_adapter.go index 013351ef6c5..98f2db30e94 100644 --- a/go/store/nbs/chunk_source_adapter.go +++ b/go/store/nbs/chunk_source_adapter.go @@ -20,6 +20,7 @@ import ( "github.com/dolthub/dolt/go/store/hash" ) +// NM4 - looks like this will only work for TableFiles. type chunkSourceAdapter struct { tableReader h hash.Hash @@ -33,6 +34,7 @@ func (csa chunkSourceAdapter) name() string { return csa.h.String() } +// NM4 - This is always going to be a TableFile - so use name as a hash for the moment. func newReaderFromIndexData(ctx context.Context, q MemoryQuotaProvider, idxData []byte, name hash.Hash, tra tableReaderAt, blockSize uint64) (cs chunkSource, err error) { index, err := parseTableIndexByCopy(ctx, idxData, q) if err != nil { diff --git a/go/store/nbs/s3_object_reader.go b/go/store/nbs/s3_object_reader.go new file mode 100644 index 00000000000..3e3cac10432 --- /dev/null +++ b/go/store/nbs/s3_object_reader.go @@ -0,0 +1,160 @@ +// Copyright 2025 Dolthub, Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// This file incorporates work covered by the following copyright and +// permission notice: +// +// Copyright 2016 Attic Labs, Inc. All rights reserved. +// Licensed under the Apache License, version 2.0: +// http://www.apache.org/licenses/LICENSE-2.0 + +package nbs + +import ( + "context" + "fmt" + "io" + "net" + "os" + "strconv" + "strings" + "syscall" + "time" + + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/service/s3" + "github.com/aws/aws-sdk-go/service/s3/s3iface" + "github.com/jpillora/backoff" +) + +// s3ObjectReader is a wrapper for S3 that gives us some nice to haves for reading objects from S3. +// TODO: Bring all the multipart upload and remote-conjoin stuff over here and make this a better analogue to ddbTableStore +type s3ObjectReader struct { + s3 s3iface.S3API + bucket string + readRl chan struct{} + ns string +} + +// s3RangeHeader returns a string for the HTTP range header ("bytes=23-42") for a range starting at |off| and ending at |length| +// Intended to be used with the |readRange| method. +func s3RangeHeader(off, length int64) string { + lastByte := off + length - 1 // insanely, the HTTP range header specifies ranges inclusively. + return fmt.Sprintf("%s=%d-%d", s3RangePrefix, off, lastByte) +} + +func (s3or *s3ObjectReader) key(name string) string { + if s3or.ns != "" { + return s3or.ns + "/" + name + } + return name +} + +// ReadAt gets the named object, and reads |len(p)| bytes into |p| starting at |off|. The number of bytes read is returned, +// along with an error if one occurs. +func (s3or *s3ObjectReader) ReadAt(ctx context.Context, name string, p []byte, off int64, stats *Stats) (n int, err error) { + t1 := time.Now() + + defer func() { + stats.S3BytesPerRead.Sample(uint64(len(p))) + stats.S3ReadLatency.SampleTimeSince(t1) + }() + + n, _, err = s3or.readRange(ctx, name, p, s3RangeHeader(off, int64(len(p)))) + return +} + +// reader gets the full object from S3 as a ReadCloser. Useful when downloading the entire object. +func (s3or *s3ObjectReader) reader(ctx context.Context, name string) (io.ReadCloser, error) { + input := &s3.GetObjectInput{ + Bucket: aws.String(s3or.bucket), + Key: aws.String(s3or.key(name)), + } + result, err := s3or.s3.GetObjectWithContext(ctx, input) + if err != nil { + return nil, err + } + return result.Body, nil +} + +// readRange implements the raw calls to S3 for the purpose of reading a range of bytes from an |name| object. Contents +// are read into |p| and the range is specified as a string, which you should get using the |s3RangeHeader| function. +// The return value is the number of bytes |n| read and the total size |sz| of the object. The size of the object comes from the Content-Range +// HTTP header, and can be used if manually breaking of the file into range chunks +func (s3or *s3ObjectReader) readRange(ctx context.Context, name string, p []byte, rangeHeader string) (n int, sz uint64, err error) { + read := func() (int, uint64, error) { + if s3or.readRl != nil { + s3or.readRl <- struct{}{} + defer func() { + <-s3or.readRl + }() + } + + input := &s3.GetObjectInput{ + Bucket: aws.String(s3or.bucket), + Key: aws.String(s3or.key(name)), + Range: aws.String(rangeHeader), + } + + result, err := s3or.s3.GetObjectWithContext(ctx, input) + if err != nil { + return 0, 0, err + } + defer result.Body.Close() + + if *result.ContentLength != int64(len(p)) { + return 0, 0, fmt.Errorf("failed to read entire range, key: %v, len(p): %d, rangeHeader: %s, ContentLength: %d", s3or.key(name), len(p), rangeHeader, *result.ContentLength) + } + + sz := uint64(0) + if result.ContentRange != nil { + i := strings.Index(*result.ContentRange, "/") + if i != -1 { + sz, err = strconv.ParseUint((*result.ContentRange)[i+1:], 10, 64) + if err != nil { + return 0, 0, err + } + } + } + n, err = io.ReadFull(result.Body, p) + return n, sz, err + } + + n, sz, err = read() + // We hit the point of diminishing returns investigating #3255, so add retries. In conversations with AWS people, it's not surprising to get transient failures when talking to S3, though SDKs are intended to have their own retrying. The issue may be that, in Go, making the S3 request and reading the data are separate operations, and the SDK kind of can't do its own retrying to handle failures in the latter. + if isConnReset(err) { + // We are backing off here because its possible and likely that the rate of requests to S3 is the underlying issue. + b := &backoff.Backoff{ + Min: 128 * time.Microsecond, + Max: 1024 * time.Millisecond, + Factor: 2, + Jitter: true, + } + for ; isConnReset(err); n, sz, err = read() { + dur := b.Duration() + time.Sleep(dur) + } + } + + return n, sz, err +} + +func isConnReset(err error) bool { + nErr, ok := err.(*net.OpError) + if !ok { + return false + } + scErr, ok := nErr.Err.(*os.SyscallError) + return ok && scErr.Err == syscall.ECONNRESET +} diff --git a/go/store/nbs/s3_table_reader.go b/go/store/nbs/s3_table_reader.go index 30887544e02..cf365b5e71e 100644 --- a/go/store/nbs/s3_table_reader.go +++ b/go/store/nbs/s3_table_reader.go @@ -25,18 +25,9 @@ import ( "context" "fmt" "io" - "net" - "os" - "strconv" - "strings" "sync/atomic" - "syscall" "time" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/service/s3" - "github.com/aws/aws-sdk-go/service/s3/s3iface" - "github.com/jpillora/backoff" "golang.org/x/sync/errgroup" "github.com/dolthub/dolt/go/store/hash" @@ -61,53 +52,17 @@ func (s3tra *s3TableReaderAt) clone() (tableReaderAt, error) { } func (s3tra *s3TableReaderAt) Reader(ctx context.Context) (io.ReadCloser, error) { - return s3tra.s3.Reader(ctx, s3tra.h) + return s3tra.s3.reader(ctx, s3tra.h.String()) } func (s3tra *s3TableReaderAt) ReadAtWithStats(ctx context.Context, p []byte, off int64, stats *Stats) (n int, err error) { - return s3tra.s3.ReadAt(ctx, s3tra.h, p, off, stats) -} - -// TODO: Bring all the multipart upload and remote-conjoin stuff over here and make this a better analogue to ddbTableStore -type s3ObjectReader struct { - s3 s3iface.S3API - bucket string - readRl chan struct{} - ns string -} - -func (s3or *s3ObjectReader) key(k string) string { - if s3or.ns != "" { - return s3or.ns + "/" + k - } - return k -} - -func (s3or *s3ObjectReader) Reader(ctx context.Context, name hash.Hash) (io.ReadCloser, error) { - return s3or.reader(ctx, name) -} - -func (s3or *s3ObjectReader) ReadAt(ctx context.Context, name hash.Hash, p []byte, off int64, stats *Stats) (n int, err error) { - t1 := time.Now() - - defer func() { - stats.S3BytesPerRead.Sample(uint64(len(p))) - stats.S3ReadLatency.SampleTimeSince(t1) - }() - - n, _, err = s3or.readRange(ctx, name, p, s3RangeHeader(off, int64(len(p)))) - return -} - -func s3RangeHeader(off, length int64) string { - lastByte := off + length - 1 // insanely, the HTTP range header specifies ranges inclusively. - return fmt.Sprintf("%s=%d-%d", s3RangePrefix, off, lastByte) + return s3tra.s3.ReadAt(ctx, s3tra.h.String(), p, off, stats) } const maxS3ReadFromEndReqSize = 256 * 1024 * 1024 // 256MB const preferredS3ReadFromEndReqSize = 128 * 1024 * 1024 // 128MB -func (s3or *s3ObjectReader) ReadFromEnd(ctx context.Context, name hash.Hash, p []byte, stats *Stats) (n int, sz uint64, err error) { +func readS3TableFileFromEnd(ctx context.Context, s3or *s3ObjectReader, name string, p []byte, stats *Stats) (n int, err error) { defer func(t1 time.Time) { stats.S3BytesPerRead.Sample(uint64(len(p))) stats.S3ReadLatency.SampleTimeSince(t1) @@ -118,7 +73,7 @@ func (s3or *s3ObjectReader) ReadFromEnd(ctx context.Context, name hash.Hash, p [ // Read the footer first and capture the size of the entire table file. n, sz, err := s3or.readRange(ctx, name, p[len(p)-footerSize:], fmt.Sprintf("%s=-%d", s3RangePrefix, footerSize)) if err != nil { - return n, sz, err + return n, err } totalN += uint64(n) eg, egctx := errgroup.WithContext(ctx) @@ -144,88 +99,10 @@ func (s3or *s3ObjectReader) ReadFromEnd(ctx context.Context, name hash.Hash, p [ } err = eg.Wait() if err != nil { - return 0, 0, err + return 0, err } - return int(totalN), sz, nil - } - return s3or.readRange(ctx, name, p, fmt.Sprintf("%s=-%d", s3RangePrefix, len(p))) -} - -func (s3or *s3ObjectReader) reader(ctx context.Context, name hash.Hash) (io.ReadCloser, error) { - input := &s3.GetObjectInput{ - Bucket: aws.String(s3or.bucket), - Key: aws.String(s3or.key(name.String())), - } - result, err := s3or.s3.GetObjectWithContext(ctx, input) - if err != nil { - return nil, err - } - return result.Body, nil -} - -func (s3or *s3ObjectReader) readRange(ctx context.Context, name hash.Hash, p []byte, rangeHeader string) (n int, sz uint64, err error) { - read := func() (int, uint64, error) { - if s3or.readRl != nil { - s3or.readRl <- struct{}{} - defer func() { - <-s3or.readRl - }() - } - - input := &s3.GetObjectInput{ - Bucket: aws.String(s3or.bucket), - Key: aws.String(s3or.key(name.String())), - Range: aws.String(rangeHeader), - } - - result, err := s3or.s3.GetObjectWithContext(ctx, input) - if err != nil { - return 0, 0, err - } - defer result.Body.Close() - - if *result.ContentLength != int64(len(p)) { - return 0, 0, fmt.Errorf("failed to read entire range, key: %v, len(p): %d, rangeHeader: %s, ContentLength: %d", s3or.key(name.String()), len(p), rangeHeader, *result.ContentLength) - } - - sz := uint64(0) - if result.ContentRange != nil { - i := strings.Index(*result.ContentRange, "/") - if i != -1 { - sz, err = strconv.ParseUint((*result.ContentRange)[i+1:], 10, 64) - if err != nil { - return 0, 0, err - } - } - } - n, err = io.ReadFull(result.Body, p) - return n, sz, err - } - - n, sz, err = read() - // We hit the point of diminishing returns investigating #3255, so add retries. In conversations with AWS people, it's not surprising to get transient failures when talking to S3, though SDKs are intended to have their own retrying. The issue may be that, in Go, making the S3 request and reading the data are separate operations, and the SDK kind of can't do its own retrying to handle failures in the latter. - if isConnReset(err) { - // We are backing off here because its possible and likely that the rate of requests to S3 is the underlying issue. - b := &backoff.Backoff{ - Min: 128 * time.Microsecond, - Max: 1024 * time.Millisecond, - Factor: 2, - Jitter: true, - } - for ; isConnReset(err); n, sz, err = read() { - dur := b.Duration() - time.Sleep(dur) - } - } - - return n, sz, err -} - -func isConnReset(err error) bool { - nErr, ok := err.(*net.OpError) - if !ok { - return false + return int(totalN), nil } - scErr, ok := nErr.Err.(*os.SyscallError) - return ok && scErr.Err == syscall.ECONNRESET + n, _, err = s3or.readRange(ctx, name, p, fmt.Sprintf("%s=-%d", s3RangePrefix, len(p))) + return n, err }