Multi-thread copies from a local source hand the chunk writer an unbuffered ReOpen. Backends such as s3, azureblob and oracleobjectstorage checksum the chunk with io.Copy before uploading it, and as ReOpen didn't implement io.WriterTo, io.Copy read the file in 32 KiB pieces. ReOpen now implements io.WriterTo: - If the destination implements io.ReaderFrom, that is used so the destination's own buffering is kept. This means multi-thread downloads (bufio.Writer over an OffsetWriter, sized by --multi-thread-write-buffer-size) and HTTP request bodies behave as before and don't gain an extra buffer. - If less than 1 MiB remains it uses io.Copy as before, so small files don't take a 1 MiB buffer. - Otherwise it copies through a 1 MiB buffer from the global pool, so the memory is reused and is counted by --max-buffer-memory. This replaces the s3 specific io.CopyBuffer froma68480093(reverted in the previous commit) which allocated a fresh 1 MiB buffer for every chunk outside of --max-buffer-memory, and gives the same speedup to every backend which io.Copies from the chunk reader. Benchmarks on Linux, 16 cores, source file on tmpfs, warm cache. "orig" is master witha68480093reverted (32 KiB reads), "master" hasa68480093(make 1 MiB per chunk), "branch" is this commit. Checksum pass only - ReOpen of a local 128 MiB range into md5, 5 runs: 1 stream MB/s B/op orig 752-759 34 KiB master 751-784 1025 KiB branch 764-784 1.2 KiB 16 streams MB/s B/op orig 4772-5495 547 KiB master 4008-4607 16405 KiB branch 4525-5052 22 KiB On Linux the reads are cheap so the larger reads are worth ~2-3% for a single stream and are lost in the noise with 16 streams. The point here is that branch matches master's reads without allocating. The same benchmark on Windows 10 (VirtualBox VM, 8 vCPUs on a Ryzen 7 PRO 5850U, 64 MiB chunk per stream, 1 GiB file in the file cache), where reads are more expensive, shows the speedup. Median of 5 runs: streams orig master branch 1 560 MB/s 594 MB/s (+6.1%) 610 MB/s (+9.0%) 4 1438 MB/s 1594 MB/s (+10.9%) 1610 MB/s (+12.0%) 8 1878 MB/s 2123 MB/s (+13.0%) 2143 MB/s (+14.1%) allocated per op (all streams) 1 33 KiB 1026 KiB 1 KiB 4 134 KiB 4102 KiB 5 KiB 8 267 KiB 8204 KiB 10 KiB With 4 and 8 streams the ranges of orig and branch don't overlap. End to end - rclone copy of a 2 GiB local file to MinIO on localhost (server bound, so wall time doesn't change), mean of 4 runs, max RSS and number of GCs from GODEBUG=gctrace=1: default (5 MiB chunks, 4 streams) wall max RSS GCs orig 6.13s 84 MiB 14 master 6.29s 93 MiB 54 branch 6.30s 90 MiB 8 --s3-upload-concurrency 16 --s3-chunk-size 64M wall max RSS GCs orig 4.76s 83 MiB 6 master 4.80s 112 MiB 7 branch 4.80s 97 MiB 6 Multi-thread download of the same file from MinIO to local disk (checks the io.ReaderFrom path), mean of 4 runs: wall max RSS GCs orig 4.31s 80 MiB 5 master 4.31s 80 MiB 5 branch 4.32s 80 MiB 5 Uploads with --max-buffer-memory 2M and 4M (with --s3-upload-concurrency 16 --s3-chunk-size 64M) complete normally in 5-7s, throttled rather than stalled.
384 lines
11 KiB
Go
384 lines
11 KiB
Go
package operations
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"io"
|
|
"sync"
|
|
|
|
"github.com/rclone/rclone/fs"
|
|
"github.com/rclone/rclone/fs/fserrors"
|
|
"github.com/rclone/rclone/lib/pool"
|
|
)
|
|
|
|
// AccountFn is a function which will be called after every read
|
|
// from the ReOpen.
|
|
//
|
|
// It may return an error which will be passed back to the user.
|
|
type AccountFn func(n int) error
|
|
|
|
// ReOpen is a wrapper for an object reader which reopens the stream on error
|
|
type ReOpen struct {
|
|
ctx context.Context
|
|
mu sync.Mutex // mutex to protect the below
|
|
readAtMu sync.Mutex // mutex to serialize the ReadAt calls
|
|
src fs.Object // object to open
|
|
baseOptions []fs.OpenOption // options to pass to initial open and where offset == 0
|
|
options []fs.OpenOption // option to pass on subsequent opens where offset != 0
|
|
rangeOption fs.RangeOption // adjust this range option on re-opens
|
|
rc io.ReadCloser // underlying stream
|
|
size int64 // total size of object - can be -ve
|
|
start int64 // absolute position to start reading from
|
|
end int64 // absolute position to end reading (exclusive)
|
|
offset int64 // offset in the file we are at, offset from start
|
|
newOffset int64 // if different to offset, reopen needed
|
|
maxTries int // maximum number of retries
|
|
tries int // number of retries we've had so far in this stream
|
|
err error // if this is set then Read/Close calls will return it
|
|
opened bool // if set then rc is valid and needs closing
|
|
account AccountFn // account for a read
|
|
reads int // count how many times the data has been read
|
|
accountOn int // only account on or after this read
|
|
}
|
|
|
|
var (
|
|
errFileClosed = errors.New("file already closed")
|
|
errTooManyTries = errors.New("failed to reopen: too many retries")
|
|
errInvalidWhence = errors.New("reopen Seek: invalid whence")
|
|
errNegativeSeek = errors.New("reopen Seek: negative position")
|
|
errSeekPastEnd = errors.New("reopen Seek: attempt to seek past end of data")
|
|
errBadEndSeek = errors.New("reopen Seek: can't seek from end with unknown sized object")
|
|
)
|
|
|
|
// NewReOpen makes a handle which will reopen itself and seek to where
|
|
// it was on errors up to maxTries times.
|
|
//
|
|
// If an fs.HashesOption is set this will be applied when reading from
|
|
// the start.
|
|
//
|
|
// If an fs.RangeOption is set then this will applied when reading from
|
|
// the start, and updated on retries.
|
|
func NewReOpen(ctx context.Context, src fs.Object, maxTries int, options ...fs.OpenOption) (rc *ReOpen, err error) {
|
|
h := &ReOpen{
|
|
ctx: ctx,
|
|
src: src,
|
|
maxTries: maxTries,
|
|
baseOptions: options,
|
|
size: src.Size(),
|
|
start: 0,
|
|
offset: 0,
|
|
newOffset: -1, // -1 means no seek required
|
|
}
|
|
h.mu.Lock()
|
|
defer h.mu.Unlock()
|
|
|
|
// Filter the options for subsequent opens
|
|
h.options = make([]fs.OpenOption, 0, len(options)+1)
|
|
var limit int64 = -1
|
|
for _, option := range options {
|
|
switch x := option.(type) {
|
|
case *fs.HashesOption:
|
|
// leave hash option out when ranging
|
|
case *fs.RangeOption:
|
|
h.start, limit = x.Decode(h.end)
|
|
case *fs.SeekOption:
|
|
h.start, limit = x.Offset, -1
|
|
default:
|
|
h.options = append(h.options, option)
|
|
}
|
|
}
|
|
|
|
// Put our RangeOption on the end
|
|
h.rangeOption.Start = h.start
|
|
h.options = append(h.options, &h.rangeOption)
|
|
|
|
// If a size range is set then set the end point of the file to that
|
|
if limit >= 0 && h.size >= 0 {
|
|
h.end = h.start + limit
|
|
h.rangeOption.End = h.end - 1 // remember range options are inclusive
|
|
} else {
|
|
h.end = h.size
|
|
h.rangeOption.End = -1
|
|
}
|
|
|
|
err = h.open()
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
return h, nil
|
|
}
|
|
|
|
// Open makes a handle which will reopen itself and seek to where it
|
|
// was on errors.
|
|
//
|
|
// If an fs.HashesOption is set this will be applied when reading from
|
|
// the start.
|
|
//
|
|
// If an fs.RangeOption is set then this will applied when reading from
|
|
// the start, and updated on retries.
|
|
//
|
|
// It will obey LowLevelRetries in the ctx as the maximum number of
|
|
// tries.
|
|
//
|
|
// Use this instead of calling the Open method on fs.Objects
|
|
func Open(ctx context.Context, src fs.Object, options ...fs.OpenOption) (rc *ReOpen, err error) {
|
|
maxTries := fs.GetConfig(ctx).LowLevelRetries
|
|
return NewReOpen(ctx, src, maxTries, options...)
|
|
}
|
|
|
|
// open the underlying handle - call with lock held
|
|
//
|
|
// we don't retry here as the Open() call will itself have low level retries
|
|
func (h *ReOpen) open() error {
|
|
var opts []fs.OpenOption
|
|
if h.offset == 0 {
|
|
// if reading from the start using the initial options
|
|
opts = h.baseOptions
|
|
} else {
|
|
// otherwise use the filtered options
|
|
opts = h.options
|
|
// Adjust range start to where we have got to
|
|
h.rangeOption.Start = h.start + h.offset
|
|
}
|
|
// Make a copy of the options as fs.FixRangeOption modifies them :-(
|
|
opts = append(make([]fs.OpenOption, 0, len(opts)), opts...)
|
|
h.tries++
|
|
if h.tries > h.maxTries {
|
|
h.err = errTooManyTries
|
|
} else {
|
|
h.rc, h.err = h.src.Open(h.ctx, opts...)
|
|
}
|
|
if h.err != nil {
|
|
if h.tries > 1 {
|
|
fs.DebugfCtx(h.ctx, h.src, "Reopen failed after offset %d bytes read: %v", h.offset, h.err)
|
|
}
|
|
return h.err
|
|
}
|
|
h.opened = true
|
|
return nil
|
|
}
|
|
|
|
// reopen the underlying handle by closing it and reopening it.
|
|
func (h *ReOpen) reopen() (err error) {
|
|
// close underlying stream if needed
|
|
if h.opened {
|
|
h.opened = false
|
|
_ = h.rc.Close()
|
|
}
|
|
return h.open()
|
|
}
|
|
|
|
// account for n bytes being read
|
|
func (h *ReOpen) accountRead(n int) error {
|
|
if h.account == nil {
|
|
return nil
|
|
}
|
|
// Don't start accounting until we've reached this many reads
|
|
//
|
|
// rw.reads will be 1 the first time this is called
|
|
// rw.accountOn 2 means start accounting on the 2nd read through
|
|
if h.reads >= h.accountOn {
|
|
return h.account(n)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// Read bytes retrying as necessary
|
|
func (h *ReOpen) Read(p []byte) (n int, err error) {
|
|
h.mu.Lock()
|
|
defer h.mu.Unlock()
|
|
if h.err != nil {
|
|
// return a previous error if there is one
|
|
return n, h.err
|
|
}
|
|
|
|
// re-open if seek needed
|
|
if h.newOffset >= 0 {
|
|
if h.offset != h.newOffset {
|
|
fs.DebugfCtx(h.ctx, h.src, "Seek from %d to %d", h.offset, h.newOffset)
|
|
h.offset = h.newOffset
|
|
err = h.reopen()
|
|
if err != nil {
|
|
return 0, err
|
|
}
|
|
}
|
|
h.newOffset = -1
|
|
}
|
|
|
|
// Read a full buffer
|
|
startOffset := h.offset
|
|
var nn int
|
|
for n < len(p) && err == nil {
|
|
nn, err = h.rc.Read(p[n:])
|
|
n += nn
|
|
h.offset += int64(nn)
|
|
if err != nil && err != io.EOF {
|
|
h.err = err
|
|
if !fserrors.IsNoLowLevelRetryError(err) {
|
|
fs.DebugfCtx(h.ctx, h.src, "Reopening on read failure after offset %d bytes: retry %d/%d: %v", h.offset, h.tries, h.maxTries, err)
|
|
if h.reopen() == nil {
|
|
err = nil
|
|
}
|
|
}
|
|
}
|
|
}
|
|
// Count a read of the data if we read from the start successfully
|
|
if startOffset == 0 && n != 0 {
|
|
h.reads++
|
|
}
|
|
// Account the read
|
|
accErr := h.accountRead(n)
|
|
if err == nil {
|
|
err = accErr
|
|
}
|
|
return n, err
|
|
}
|
|
|
|
// remaining returns the number of bytes left to read or -1 if unknown
|
|
func (h *ReOpen) remaining() int64 {
|
|
h.mu.Lock()
|
|
defer h.mu.Unlock()
|
|
if h.end < 0 {
|
|
return -1
|
|
}
|
|
offset := h.offset
|
|
if h.newOffset >= 0 {
|
|
offset = h.newOffset
|
|
}
|
|
return h.end - h.start - offset
|
|
}
|
|
|
|
// WriteTo writes data to w until there's no more data to write or
|
|
// when an error occurs. The return value n is the number of bytes
|
|
// written.
|
|
//
|
|
// If w implements io.ReaderFrom then that is used so w's own
|
|
// buffering applies. Otherwise the data is copied through a buffer
|
|
// from the global pool so the source is read in large blocks.
|
|
func (h *ReOpen) WriteTo(w io.Writer) (n int64, err error) {
|
|
// Hide WriteTo so the copies below don't call back into here
|
|
r := struct{ io.Reader }{h}
|
|
if rf, ok := w.(io.ReaderFrom); ok {
|
|
return rf.ReadFrom(r)
|
|
}
|
|
// Don't use a pool buffer bigger than the data
|
|
if remaining := h.remaining(); remaining >= 0 && remaining < pool.BufferSize {
|
|
return io.Copy(w, r)
|
|
}
|
|
buf := pool.Global().Get()
|
|
defer pool.Global().Put(buf)
|
|
return io.CopyBuffer(w, r, buf)
|
|
}
|
|
|
|
// ReadAt reads len(p) bytes at absolute offset off without changing
|
|
// the read position.
|
|
//
|
|
// Note: operations are serialized; it won't behave like a truly
|
|
// concurrent ReaderAt.
|
|
func (h *ReOpen) ReadAt(p []byte, off int64) (n int, err error) {
|
|
h.readAtMu.Lock()
|
|
defer h.readAtMu.Unlock()
|
|
|
|
// Save current position
|
|
cur, err := h.Seek(0, io.SeekCurrent)
|
|
if err != nil {
|
|
return 0, err
|
|
}
|
|
// Seek to requested offset
|
|
if _, err = h.Seek(off, io.SeekStart); err != nil {
|
|
return 0, err
|
|
}
|
|
// Restore position on exit
|
|
defer func() {
|
|
if _, seekErr := h.Seek(cur, io.SeekStart); seekErr != nil && err == nil {
|
|
err = seekErr
|
|
}
|
|
}()
|
|
|
|
// Fill p fully unless EOF
|
|
return h.Read(p)
|
|
}
|
|
|
|
// Seek sets the offset for the next Read or Write to offset, interpreted
|
|
// according to whence: SeekStart means relative to the start of the file,
|
|
// SeekCurrent means relative to the current offset, and SeekEnd means relative
|
|
// to the end (for example, offset = -2 specifies the penultimate byte of the
|
|
// file). Seek returns the new offset relative to the start of the file or an
|
|
// error, if any.
|
|
//
|
|
// Seeking to an offset before the start of the file is an error. Seeking
|
|
// to any positive offset may be allowed, but if the new offset exceeds the
|
|
// size of the underlying object the behavior of subsequent I/O operations is
|
|
// implementation-dependent.
|
|
func (h *ReOpen) Seek(offset int64, whence int) (int64, error) {
|
|
h.mu.Lock()
|
|
defer h.mu.Unlock()
|
|
if h.err != nil {
|
|
// return a previous error if there is one
|
|
return 0, h.err
|
|
}
|
|
var abs int64
|
|
var size = h.end - h.start
|
|
switch whence {
|
|
case io.SeekStart:
|
|
abs = offset
|
|
case io.SeekCurrent:
|
|
if h.newOffset >= 0 {
|
|
abs = h.newOffset + offset
|
|
} else {
|
|
abs = h.offset + offset
|
|
}
|
|
case io.SeekEnd:
|
|
if h.size < 0 {
|
|
return 0, errBadEndSeek
|
|
}
|
|
abs = size + offset
|
|
default:
|
|
return 0, errInvalidWhence
|
|
}
|
|
if abs < 0 {
|
|
return 0, errNegativeSeek
|
|
}
|
|
if h.size >= 0 && abs > size {
|
|
return size, errSeekPastEnd
|
|
}
|
|
|
|
h.tries = 0 // Reset open count on seek
|
|
h.newOffset = abs // New offset - applied in Read
|
|
return abs, nil
|
|
}
|
|
|
|
// Close the stream
|
|
func (h *ReOpen) Close() error {
|
|
h.mu.Lock()
|
|
defer h.mu.Unlock()
|
|
if !h.opened {
|
|
return errFileClosed
|
|
}
|
|
h.opened = false
|
|
h.err = errFileClosed
|
|
return h.rc.Close()
|
|
}
|
|
|
|
// SetAccounting should be provided with a function which will be
|
|
// called after every read from the RW.
|
|
//
|
|
// It may return an error which will be passed back to the user.
|
|
func (h *ReOpen) SetAccounting(account AccountFn) *ReOpen {
|
|
h.account = account
|
|
return h
|
|
}
|
|
|
|
// DelayAccounting makes sure the accounting function only gets called
|
|
// on the i-th or later read of the data from this point (counting
|
|
// from 1).
|
|
//
|
|
// This is useful so that we don't account initial reads of the data
|
|
// e.g. when calculating hashes.
|
|
//
|
|
// Set this to 0 to account everything.
|
|
func (h *ReOpen) DelayAccounting(i int) {
|
|
h.accountOn = i
|
|
h.reads = 0
|
|
}
|