Compare commits

..
Author SHA1 Message Date
Nick Craig-Wood 07313554bf b2: reduce default chunk size to 16M and increase upload concurrency to 8
The 96M default chunk size dates from 2016 when 100,000,000 bytes was
the minimum part size B2 allowed. The minimum is now 5,000,000 bytes.

Measurements against B2 EU on a 1 Gbit/s link show that each part has
a fixed overhead of about a second regardless of size, so throughput
is governed by chunk size multiplied by upload concurrency rather than
by chunk size alone. 16M chunks with concurrency 8 upload a 1 GiB file
as fast as 96M chunks with concurrency 4 while using a third of the
memory per transfer, and retry much less data when a part fails.

This also means that files between --multi-thread-cutoff and the chunk
size are no longer uploaded as a single part large file, which B2
rejects with "large files must have at least 2 parts", unless the
cutoff is set below 16M.
2026-09-10 15:57:25 +01:00
Nick Craig-Wood 417ecce222 docs: update sponsors 2026-09-08 15:27:44 +01:00
132 changed files with 1354 additions and 6498 deletions

No files matched your search

+1 -4
View File
@@ -35,9 +35,6 @@ RUN echo "**** Print Version Binary ****" && \
# Begin final image
FROM alpine:latest
ARG RCLONE_UID=1009
ARG RCLONE_GID=1009
RUN echo "**** Install Dependencies ****" && \
apk add --no-cache \
ca-certificates \
@@ -48,7 +45,7 @@ RUN echo "**** Install Dependencies ****" && \
COPY --from=builder /go/src/github.com/rclone/rclone/rclone /usr/local/bin/
RUN addgroup -g "${RCLONE_GID}" rclone && adduser -u "${RCLONE_UID}" -Ds /bin/sh -G rclone rclone
RUN addgroup -g 1009 rclone && adduser -u 1009 -Ds /bin/sh -G rclone rclone
ENTRYPOINT [ "rclone" ]
+8 -3
View File
@@ -64,7 +64,7 @@ const (
maxParts = 10000
maxVersions = 100 // maximum number of versions we search in --b2-versions mode
minChunkSize = 5 * fs.Mebi
defaultChunkSize = 96 * fs.Mebi
defaultChunkSize = 16 * fs.Mebi
defaultUploadCutoff = 200 * fs.Mebi
largeFileCopyCutoff = 4 * fs.Gibi // 5E9 is the max
defaultMaxAge = 24 * time.Hour
@@ -153,7 +153,12 @@ The minimum is 0 and the maximum is 4.6 GiB.`,
When uploading large files, chunk the file into this size.
Must fit in memory. These chunks are buffered in memory and there
might a maximum of "--transfers" chunks in progress at once.
might be a maximum of "--transfers" * "--b2-upload-concurrency"
chunks in progress at once.
B2 has a fixed per part overhead of about a second, so upload speed
is roughly proportional to the chunk size multiplied by
"--b2-upload-concurrency".
5,000,000 Bytes is the minimum size.`,
Default: defaultChunkSize,
@@ -168,7 +173,7 @@ concurrently.
Note that chunks are stored in memory and there may be up to
"--transfers" * "--b2-upload-concurrency" chunks stored at once
in memory.`,
Default: 4,
Default: 8,
Advanced: true,
}, {
Name: "disable_checksum",
+1 -1
View File
@@ -1461,7 +1461,7 @@ func (f *Fs) changeNotifyRunner(ctx context.Context, notifyFunc func(string, fs.
// Item in the cache has the same or newer SequenceID than
// this event. Ignore this event, it must be old.
f.itemMetaCacheMu.Unlock()
fs.Debugf(f, "%s ignored due to old SequenceID (%d)", eventDetails, itemMeta.SequenceID)
fs.Debugf(f, "%s ignored due to old SequenceID (%q)", eventDetails, itemMeta.SequenceID)
continue
}
-32
View File
@@ -1085,35 +1085,6 @@ type ObjectMetadata struct {
CompressionMetadataZstd *SzstdMetadata // Metadata for Zstd compression
}
// validate checks metadata read from the wrapped remote before it is used to
// construct a compressed reader.
func (meta *ObjectMetadata) validate() error {
if meta.Mode != Gzip {
return nil
}
if meta.CompressionMetadataGzip == nil {
return errors.New("missing gzip metadata")
}
if meta.CompressionMetadataGzip.BlockSize <= 0 {
return fmt.Errorf("invalid gzip block size %d", meta.CompressionMetadataGzip.BlockSize)
}
if meta.Size != meta.CompressionMetadataGzip.Size {
return errors.New("gzip metadata size does not match object size")
}
if meta.Size < 0 {
return errors.New("invalid gzip object size")
}
blockSize := int64(meta.CompressionMetadataGzip.BlockSize)
blocks := meta.Size / blockSize
if meta.Size%blockSize != 0 {
blocks++
}
if int64(len(meta.CompressionMetadataGzip.BlockData)) < blocks {
return errors.New("gzip block data is incomplete")
}
return nil
}
// Object with external metadata
type Object struct {
fs.Object // Wraps around data object for this object
@@ -1137,9 +1108,6 @@ func readMetadata(ctx context.Context, mo fs.Object) (meta *ObjectMetadata, err
if err = jr.Decode(meta); err != nil {
return nil, err
}
if err = meta.validate(); err != nil {
return nil, err
}
return meta, nil
}
-89
View File
@@ -6,8 +6,6 @@ import (
"path/filepath"
"testing"
"github.com/buengese/sgzip"
_ "github.com/rclone/rclone/backend/drive"
_ "github.com/rclone/rclone/backend/local"
_ "github.com/rclone/rclone/backend/s3"
@@ -16,93 +14,6 @@ import (
"github.com/rclone/rclone/fstest/fstests"
)
func TestObjectMetadataValidate(t *testing.T) {
tests := []struct {
name string
meta ObjectMetadata
want bool
}{
{
name: "nil gzip metadata",
meta: ObjectMetadata{Mode: Gzip},
want: true,
},
{
name: "zero block size",
meta: ObjectMetadata{
Mode: Gzip,
Size: 1024,
CompressionMetadataGzip: &sgzip.GzipMetadata{
BlockSize: 0,
Size: 1024,
BlockData: []uint32{0},
},
},
want: true,
},
{
name: "negative block size",
meta: ObjectMetadata{
Mode: Gzip,
Size: 1024,
CompressionMetadataGzip: &sgzip.GzipMetadata{
BlockSize: -1,
Size: 1024,
BlockData: []uint32{0},
},
},
want: true,
},
{
name: "mismatched sizes",
meta: ObjectMetadata{
Mode: Gzip,
Size: 1024,
CompressionMetadataGzip: &sgzip.GzipMetadata{
BlockSize: 512,
Size: 2048,
BlockData: []uint32{0, 1},
},
},
want: true,
},
{
name: "short block data",
meta: ObjectMetadata{
Mode: Gzip,
Size: 1025,
CompressionMetadataGzip: &sgzip.GzipMetadata{
BlockSize: 512,
Size: 1025,
BlockData: []uint32{0, 1},
},
},
want: true,
},
{
name: "valid",
meta: ObjectMetadata{
Mode: Gzip,
Size: 1025,
CompressionMetadataGzip: &sgzip.GzipMetadata{
BlockSize: 512,
Size: 1025,
BlockData: []uint32{0, 1, 2},
},
},
},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
err := test.meta.validate()
if (err != nil) != test.want {
t.Fatalf("validate() error = %v, want error: %v", err, test.want)
}
})
}
}
var defaultOpt = fstests.Opt{
RemoteName: "TestCompress:",
NilObject: (*Object)(nil),
+8 -11
View File
@@ -634,8 +634,13 @@ func NewFs(ctx context.Context, name, root string, m configmap.Mapper) (fs.Fs, e
return f, nil // our root it empty so we probably want to list shared folders
}
dir := path.Dir(f.root)
if dir == "." {
dir = f.root
}
// root is not empty so we have find the right shared folder if it exists
id, err := f.findSharedFolder(ctx, sharedFolderName(f.root))
id, err := f.findSharedFolder(ctx, dir)
if err != nil {
// if we didn't find the specified shared folder we have to bail out here
return nil, err
@@ -943,21 +948,13 @@ func (f *Fs) listSharedFolders(ctx context.Context, callback func(fs.DirEntry) e
return nil
}
// sharedFolderName returns the shared folder name in root, which is its first
// path component. root must be the trimmed root as produced by setRoot (no
// leading slash).
func sharedFolderName(root string) string {
name, _, _ := strings.Cut(root, "/")
return name
}
// findSharedFolder find the id for a given shared folder name
// somewhat annoyingly there is no endpoint to query a shared folder by it's name
// so our only option is to iterate over all shared folders
func (f *Fs) findSharedFolder(ctx context.Context, name string) (id string, err error) {
errFoundFile := errors.New("found file")
err = f.listSharedFolders(ctx, func(entry fs.DirEntry) error {
if strings.EqualFold(entry.(*fs.Dir).Remote(), name) {
if entry.(*fs.Dir).Remote() == name {
id = entry.(*fs.Dir).ID()
return errFoundFile
}
@@ -1039,7 +1036,7 @@ func (f *Fs) listReceivedFiles(ctx context.Context, callback func(fs.DirEntry) e
func (f *Fs) findSharedFile(ctx context.Context, name string) (o *Object, err error) {
errFoundFile := errors.New("found file")
err = f.listReceivedFiles(ctx, func(entry fs.DirEntry) error {
if strings.EqualFold(entry.(*Object).remote, name) {
if entry.(*Object).remote == name {
o = entry.(*Object)
return errFoundFile
}
-60
View File
@@ -188,21 +188,6 @@ func TestInternalCheckPathLength(t *testing.T) {
}
}
func TestInternalSharedFolderName(t *testing.T) {
for _, test := range []struct {
root string
want string
}{
{root: "", want: ""},
{root: "SharedFolder", want: "SharedFolder"},
{root: "SharedFolder/subdir", want: "SharedFolder"},
{root: "SharedFolder/subdir/deeper", want: "SharedFolder"},
{root: "SharedFolder/subdir/deeper/deepest", want: "SharedFolder"},
} {
assert.Equal(t, test.want, sharedFolderName(test.root), test.root)
}
}
func TestPaperExportRemote(t *testing.T) {
ctx := context.Background()
info := &files.FileMetadata{
@@ -490,48 +475,3 @@ func TestFindSharedFileResolvesDecodedName(t *testing.T) {
require.NoError(t, err)
assert.Equal(t, encodedName, o.remote)
}
// sharedFoldersHandler serves a single shared folder from list_folders.
func sharedFoldersHandler(name, id string) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if !strings.Contains(r.URL.Path, "list_folders") {
http.NotFound(w, r)
return
}
resp := sharing.ListFoldersResult{
Entries: []*sharing.SharedFolderMetadata{{Name: name, SharedFolderId: id}},
}
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(resp)
}
}
// The Dropbox backend advertises CaseInsensitive: true, so a shared folder
// lookup must match regardless of the case of the requested name.
func TestInternalFindSharedFolderCaseInsensitive(t *testing.T) {
f := newSharingTestFs(t, sharedFoldersHandler("TestFolder", "folder-id"))
for _, name := range []string{"TestFolder", "testfolder", "TESTFOLDER"} {
id, err := f.findSharedFolder(context.Background(), name)
require.NoError(t, err, name)
assert.Equal(t, "folder-id", id, name)
}
_, err := f.findSharedFolder(context.Background(), "no-such-folder")
assert.ErrorIs(t, err, fs.ErrorDirNotFound)
}
// The Dropbox backend advertises CaseInsensitive: true, so a received file
// lookup must match regardless of the case of the requested name.
func TestInternalFindSharedFileCaseInsensitive(t *testing.T) {
f := newSharingTestFs(t, receivedFilesHandler(t, "TestFile.txt"))
for _, name := range []string{"TestFile.txt", "testfile.txt", "TESTFILE.TXT"} {
o, err := f.findSharedFile(context.Background(), name)
require.NoError(t, err, name)
assert.Equal(t, "TestFile.txt", o.remote, name)
}
_, err := f.findSharedFile(context.Background(), "no-such-file.txt")
assert.ErrorIs(t, err, fs.ErrorObjectNotFound)
}
+106 -128
View File
@@ -556,95 +556,46 @@ func (f *Fs) CreateDir(ctx context.Context, pathID, leaf string) (string, error)
return resp.UUID, nil
}
// splitNameExt splits a basename into the (plainName, type) pair that Internxt
// stores a file under.
func splitNameExt(baseName string) (name, ext string) {
ext = path.Ext(baseName)
if ext == baseName {
return baseName, ""
}
return strings.TrimSuffix(baseName, ext), strings.TrimPrefix(ext, ".")
}
// preUploadCheck checks if a file exists in the given directory
// Returns the file metadata if it exists, nil if not
func (f *Fs) preUploadCheck(ctx context.Context, leaf, directoryID string) (*folders.File, error) {
// Parse name and extension from the leaf
baseName := f.opt.Encoding.FromStandardName(leaf)
name := strings.TrimSuffix(baseName, path.Ext(baseName))
ext := strings.TrimPrefix(path.Ext(baseName), ".")
// joinNameExt reassembles the basename a stored (plainName, type) pair
// displays as, the way List builds its entries.
func joinNameExt(name, ext string) string {
if ext == "" {
return name
}
return name + "." + ext
}
// legacyNameExt splits a basename at the final dot, the way this backend used
// to before it adopted the convention the other clients share. It differs from
// splitNameExt only for a name whose sole dot leads it: ".bashrc" splits into
// an empty name of type "bashrc".
func legacyNameExt(baseName string) (name, ext string) {
return strings.TrimSuffix(baseName, path.Ext(baseName)), strings.TrimPrefix(path.Ext(baseName), ".")
}
// existenceCheck builds a lookup criterion for one (plainName, type) spelling.
func existenceCheck(name, ext string) files.FileExistenceCheck {
return files.FileExistenceCheck{
PlainName: name,
Type: ext,
OriginalFile: struct{}{},
}
}
// findFile looks up a single file by name within directoryID. Returns
// (nil, nil) when the file does not exist; surfaces transport/API errors.
func (f *Fs) findFile(ctx context.Context, leaf, directoryID string) (*folders.File, error) {
encodedName := f.opt.Encoding.FromStandardName(leaf)
name, ext := splitNameExt(encodedName)
checks := []files.FileExistenceCheck{existenceCheck(name, ext)}
if encodedName != name {
checks = append(checks, existenceCheck(encodedName, ""))
}
if legacyName, legacyExt := legacyNameExt(encodedName); legacyExt != "" && legacyName != name {
checks = append(checks, existenceCheck(legacyName, legacyExt))
}
var checkResult *files.CheckFilesExistenceResponse
err := f.pacer.Call(func() (bool, error) {
var err error
checkResult, err = files.CheckFilesExistence(ctx, f.cfg, directoryID, checks)
if isNotFoundError(err) {
return true, err
}
return f.shouldRetry(ctx, err)
checkResult, err := files.CheckFilesExistence(ctx, f.cfg, directoryID, []files.FileExistenceCheck{
{
PlainName: name,
Type: ext,
OriginalFile: struct{}{},
},
})
if err != nil {
return nil, err
}
var uuid string
for _, result := range checkResult.Files {
if !result.FileExists() || result.UUID == "" {
continue
}
if joinNameExt(result.PlainName, result.Type) == encodedName {
uuid = result.UUID
break
}
}
if uuid == "" {
if err != nil {
// If existence check fails, assume file doesn't exist to allow upload to proceed
return nil, nil
}
var fileMeta *files.FileMeta
err = f.pacer.Call(func() (bool, error) {
var err error
fileMeta, err = files.GetFileMeta(ctx, f.cfg, uuid)
return f.shouldRetry(ctx, err)
})
if err != nil {
return nil, err
if len(checkResult.Files) > 0 && checkResult.Files[0].FileExists() {
result := checkResult.Files[0]
if result.Type != ext {
return nil, nil
}
existingUUID := result.UUID
if existingUUID != "" {
fileMeta, err := files.GetFileMeta(ctx, f.cfg, existingUUID)
if err == nil && fileMeta != nil {
return convertFileMetaToFile(fileMeta), nil
}
if err != nil {
return nil, err
}
}
}
if fileMeta == nil {
return nil, nil
}
return convertFileMetaToFile(fileMeta), nil
return nil, nil
}
// convertFileMetaToFile converts files.FileMeta to folders.File
@@ -723,7 +674,8 @@ func (f *Fs) Put(ctx context.Context, in io.Reader, src fs.ObjectInfo, options .
return nil, err
}
existingFile, err := f.findFile(ctx, leaf, directoryID)
// Check if file already exists
existingFile, err := f.preUploadCheck(ctx, leaf, directoryID)
if err != nil {
return nil, err
}
@@ -775,23 +727,40 @@ func (f *Fs) Remove(ctx context.Context, remote string) error {
return nil
}
// NewObject creates a new object by looking up a single file's metadata.
// NewObject creates a new object
func (f *Fs) NewObject(ctx context.Context, remote string) (fs.Object, error) {
leaf, directoryID, err := f.dirCache.FindPath(ctx, remote, false)
if err != nil {
if err == fs.ErrorDirNotFound {
return nil, fs.ErrorObjectNotFound
}
return nil, err
parentDir := path.Dir(remote)
if parentDir == "." {
parentDir = ""
}
file, err := f.findFile(ctx, leaf, directoryID)
dirID, err := f.dirCache.FindDir(ctx, parentDir, false)
if err != nil {
return nil, err
}
if file == nil {
return nil, fs.ErrorObjectNotFound
}
return newObjectWithFile(f, remote, file), nil
var files []folders.File
err = f.pacer.Call(func() (bool, error) {
var err error
files, err = folders.ListAllFiles(ctx, f.cfg, dirID)
return f.shouldRetry(ctx, err)
})
if err != nil {
return nil, err
}
targetName := path.Base(remote)
for _, e := range files {
name := e.PlainName
if len(e.Type) > 0 {
name += "." + e.Type
}
decodedName := f.opt.Encoding.ToStandardName(name)
if decodedName == targetName {
return newObjectWithFile(f, remote, &e), nil
}
}
return nil, fs.ErrorObjectNotFound
}
// newObjectWithFile returns a new object by file info
@@ -895,7 +864,10 @@ func (f *Fs) Move(ctx context.Context, src fs.Object, remote string) (fs.Object,
return nil, err
}
newName, newType := splitNameExt(f.opt.Encoding.FromStandardName(leaf))
// Parse name and extension from the leaf
baseName := f.opt.Encoding.FromStandardName(leaf)
newName := strings.TrimSuffix(baseName, path.Ext(baseName))
newType := strings.TrimPrefix(path.Ext(baseName), ".")
// Move the file server-side
err = f.pacer.Call(func() (bool, error) {
@@ -992,7 +964,9 @@ func (o *Object) Open(ctx context.Context, options ...fs.OpenOption) (io.ReadClo
func (o *Object) Update(ctx context.Context, in io.Reader, src fs.ObjectInfo, options ...fs.OpenOption) error {
remote := o.remote
origName, origType := splitNameExt(path.Base(remote))
origBaseName := path.Base(remote)
origName := strings.TrimSuffix(origBaseName, path.Ext(origBaseName))
origType := strings.TrimPrefix(path.Ext(origBaseName), ".")
// Create directory if it doesn't exist
_, dirID, err := o.f.dirCache.FindPath(ctx, remote, true)
@@ -1009,7 +983,11 @@ func (o *Object) Update(ctx context.Context, in io.Reader, src fs.ObjectInfo, op
// Step 1: If file exists, rename to backup (preserves old file during upload)
if oldUUID != "" {
name, ext := splitNameExt(path.Base(remote))
// Generate unique backup name
baseName := path.Base(remote)
name := strings.TrimSuffix(baseName, path.Ext(baseName))
ext := strings.TrimPrefix(path.Ext(baseName), ".")
backupSuffix := fmt.Sprintf(".rclone-backup-%s", random.String(8))
backupName = o.f.opt.Encoding.FromStandardName(name + backupSuffix)
backupType = ext
@@ -1082,11 +1060,6 @@ func (o *Object) Update(ctx context.Context, in io.Reader, src fs.ObjectInfo, op
return o.f.tooLargeError(remote, tooLarge)
}
if err != nil && isStaleReadError(err, backupUUID != "") {
o.restoreBackupFile(ctx, backupUUID, origName, origType)
return fserrors.RetryError(err)
}
if err != nil {
meta, err = o.recoverFromTimeoutConflict(ctx, err, remote, dirID)
}
@@ -1143,19 +1116,6 @@ func isTimeoutError(err error) bool {
return false
}
// isNotFoundError reports whether err is a 404 from the API.
func isNotFoundError(err error) bool {
var httpErr *sdkerrors.HTTPError
return errors.As(err, &httpErr) && httpErr.StatusCode() == 404
}
// isStaleReadError reports whether err is the API contradicting a write this
// backend has already made, which it does because lookups are served by read
// replicas that lag behind the primary.
func isStaleReadError(err error, renamed bool) bool {
return isNotFoundError(err) || (renamed && isConflictError(err))
}
// isConflictError checks if an error indicates a file conflict (409)
func isConflictError(err error) bool {
errMsg := err.Error()
@@ -1196,22 +1156,40 @@ func (o *Object) recoverFromTimeoutConflict(ctx context.Context, uploadErr error
}
baseName := path.Base(remote)
encodedName := o.f.opt.Encoding.FromStandardName(baseName)
existingFile, err := o.f.findFile(ctx, baseName, dirID)
if err != nil || existingFile == nil {
var meta *buckets.CreateMetaResponse
checkErr := o.f.pacer.Call(func() (bool, error) {
existingFile, err := o.f.preUploadCheck(ctx, encodedName, dirID)
if err != nil {
return o.f.shouldRetry(ctx, err)
}
if existingFile != nil {
name := strings.TrimSuffix(baseName, path.Ext(baseName))
ext := strings.TrimPrefix(path.Ext(baseName), ".")
meta = &buckets.CreateMetaResponse{
UUID: existingFile.UUID,
FileID: existingFile.FileID,
Name: name,
PlainName: name,
Type: ext,
Size: existingFile.Size,
}
o.id = existingFile.FileID
}
return false, nil
})
if checkErr != nil {
return nil, uploadErr
}
name, ext := splitNameExt(baseName)
o.id = existingFile.FileID
return &buckets.CreateMetaResponse{
UUID: existingFile.UUID,
FileID: existingFile.FileID,
Name: name,
PlainName: name,
Type: ext,
Size: existingFile.Size,
}, nil
if meta != nil {
return meta, nil
}
return nil, uploadErr
}
// restoreBackupFile restores a backup file after upload failure
-167
View File
@@ -1,167 +0,0 @@
package internxt
import (
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"strings"
"testing"
"github.com/internxt/rclone-adapter/config"
"github.com/internxt/rclone-adapter/endpoints"
"github.com/rclone/rclone/fs"
"github.com/rclone/rclone/lib/encoder"
"github.com/rclone/rclone/lib/pacer"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// storedFile is a file as the service holds it: a (plainName, type) pair
// split however the client that uploaded it chose to split it.
type storedFile struct {
uuid string
plainName string
fileType string
}
// wireType renders a stored type the way the service does: a file with no
// extension comes back as JSON null, not an empty string.
func wireType(fileType string) any {
if fileType == "" {
return nil
}
return fileType
}
// existenceServer answers the existence check and file meta endpoints from
// files, matching plainName exactly and only constraining type when the
// criterion supplies one, as the service does.
func existenceServer(t *testing.T, stored []storedFile) *httptest.Server {
t.Helper()
return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
if strings.HasSuffix(r.URL.Path, "/meta") {
uuid := strings.Split(strings.TrimPrefix(r.URL.Path, "/drive/files/"), "/")[0]
for _, f := range stored {
if f.uuid == uuid {
require.NoError(t, json.NewEncoder(w).Encode(map[string]any{
"uuid": f.uuid, "plainName": f.plainName, "type": wireType(f.fileType),
}))
return
}
}
w.WriteHeader(http.StatusNotFound)
return
}
var req struct {
Files []struct {
PlainName string `json:"plainName"`
Type string `json:"type"`
} `json:"files"`
}
require.NoError(t, json.NewDecoder(r.Body).Decode(&req))
var existent []map[string]any
for _, f := range stored {
for _, c := range req.Files {
if c.PlainName == f.plainName && (c.Type == "" || c.Type == f.fileType) {
existent = append(existent, map[string]any{
"exists": true, "status": "EXISTS",
"uuid": f.uuid, "plainName": f.plainName, "type": wireType(f.fileType),
})
break
}
}
}
require.NoError(t, json.NewEncoder(w).Encode(map[string]any{"existentFiles": existent}))
}))
}
func testFs(t *testing.T, server *httptest.Server) *Fs {
t.Helper()
f := &Fs{
opt: Options{Encoding: encoder.EncodeInvalidUtf8},
cfg: &config.Config{
HTTPClient: server.Client(),
Endpoints: endpoints.NewConfig(server.URL),
},
}
f.pacer = fs.NewPacer(context.Background(), pacer.NewDefault(pacer.MinSleep(minSleep), pacer.MaxSleep(maxSleep), pacer.DecayConstant(decayConstant)))
return f
}
func TestSplitJoinNameExt(t *testing.T) {
for _, test := range []struct {
baseName string
name string
ext string
}{
{"foo.txt", "foo", "txt"},
{"foo.tar.gz", "foo.tar", "gz"},
{"README", "README", ""},
{".bashrc", ".bashrc", ""},
{"..hidden", ".", "hidden"},
{"", "", ""},
} {
name, ext := splitNameExt(test.baseName)
assert.Equal(t, test.name, name, test.baseName)
assert.Equal(t, test.ext, ext, test.baseName)
assert.Equal(t, test.baseName, joinNameExt(name, ext), test.baseName)
}
}
func TestFindFile(t *testing.T) {
for _, test := range []struct {
what string
stored []storedFile
leaf string
wantUUID string
}{{
what: "split as rclone splits it",
stored: []storedFile{{"uuid-1", "foo.tar", "gz"}},
leaf: "foo.tar.gz",
wantUUID: "uuid-1",
}, {
what: "whole name stored as plainName by another client",
stored: []storedFile{{"uuid-2", "foo.tar.gz", ""}},
leaf: "foo.tar.gz",
wantUUID: "uuid-2",
}, {
what: "extensionless name is not confused with an extended one",
stored: []storedFile{{"uuid-3", "README", "md"}, {"uuid-4", "README", ""}},
leaf: "README",
wantUUID: "uuid-4",
}, {
what: "dotfile stored the way the web client splits it",
stored: []storedFile{{"uuid-6", ".bashrc", ""}},
leaf: ".bashrc",
wantUUID: "uuid-6",
}, {
what: "dotfile stored the way older rclone versions split it",
stored: []storedFile{{"uuid-7", "", "bashrc"}},
leaf: ".bashrc",
wantUUID: "uuid-7",
}, {
what: "trailing dot kept in plainName by a rename",
stored: []storedFile{{"uuid-8", "trailing.", ""}},
leaf: "trailing.",
wantUUID: "uuid-8",
}, {
what: "missing file",
stored: []storedFile{{"uuid-5", "other", "txt"}},
leaf: "foo.txt",
}} {
t.Run(test.what, func(t *testing.T) {
server := existenceServer(t, test.stored)
defer server.Close()
file, err := testFs(t, server).findFile(context.Background(), test.leaf, "dir-uuid")
require.NoError(t, err)
if test.wantUUID == "" {
assert.Nil(t, file)
return
}
require.NotNil(t, file)
assert.Equal(t, test.wantUUID, file.UUID)
})
}
}
+4 -1
View File
@@ -7,6 +7,7 @@ import (
"io"
"path"
"sort"
"strings"
"sync"
"github.com/internxt/rclone-adapter/buckets"
@@ -262,7 +263,9 @@ func (w *internxtChunkWriter) Close(ctx context.Context) error {
}
// Create file metadata in Internxt Drive
name, ext := splitNameExt(w.f.opt.Encoding.FromStandardName(path.Base(w.remote)))
baseName := w.f.opt.Encoding.FromStandardName(path.Base(w.remote))
name := strings.TrimSuffix(baseName, path.Ext(baseName))
ext := strings.TrimPrefix(path.Ext(baseName), ".")
var meta *buckets.CreateMetaResponse
err = w.f.pacer.Call(func() (bool, error) {
+9 -35
View File
@@ -311,10 +311,10 @@ set this flag.`,
Name: "fatal_if_no_space",
Help: `Make out-of-space errors fatal during transfers.
When enabled, an out of space error while writing, creating a directory,
or creating a file returns a fatal error so that rclone aborts rather
than retrying the operation. Useful for backup scripts that should halt
loudly on a full disk rather than spin retrying.`,
When enabled, an ENOSPC error during a write returns a fatal error so
that rclone aborts rather than retrying the operation. Useful for
backup scripts that should halt loudly on a full disk rather than spin
retrying.`,
Default: false,
Advanced: true,
},
@@ -1634,17 +1634,12 @@ func isDiskFullError(err error) bool {
return errors.Is(err, file.ErrDiskFull) || fserrors.IsErrNoSpace(err)
}
func wrapFatalIfNoSpace(err error, enabled bool) error {
if err != nil && enabled && isDiskFullError(err) {
return fserrors.FatalError(err)
}
return err
}
// Update the object from in with modTime and size
func (o *Object) Update(ctx context.Context, in io.Reader, src fs.ObjectInfo, options ...fs.OpenOption) (err error) {
defer func() {
err = wrapFatalIfNoSpace(err, o.fs.opt.FatalIfNoSpace)
if err != nil && o.fs.opt.FatalIfNoSpace && isDiskFullError(err) {
err = fserrors.FatalError(err)
}
}()
var out io.WriteCloser
var hasher *hash.MultiHasher
@@ -1767,30 +1762,12 @@ func (o *Object) Update(ctx context.Context, in io.Reader, src fs.ObjectInfo, op
var sparseWarning sync.Once
type fatalIfNoSpaceWriterAt struct {
fs.WriterAtCloser
enabled bool
}
func (w *fatalIfNoSpaceWriterAt) WriteAt(p []byte, off int64) (n int, err error) {
n, err = w.WriterAtCloser.WriteAt(p, off)
return n, wrapFatalIfNoSpace(err, w.enabled)
}
func (w *fatalIfNoSpaceWriterAt) Close() error {
return wrapFatalIfNoSpace(w.WriterAtCloser.Close(), w.enabled)
}
// OpenWriterAt opens with a handle for random access writes
//
// Pass in the remote desired and the size if known.
//
// It truncates any existing object
func (f *Fs) OpenWriterAt(ctx context.Context, remote string, size int64) (writer fs.WriterAtCloser, err error) {
defer func() {
err = wrapFatalIfNoSpace(err, f.opt.FatalIfNoSpace)
}()
func (f *Fs) OpenWriterAt(ctx context.Context, remote string, size int64) (fs.WriterAtCloser, error) {
// Temporary Object under construction
o, err := f.newObject(remote)
if err != nil {
@@ -1828,10 +1805,7 @@ func (f *Fs) OpenWriterAt(ctx context.Context, remote string, size int64) (write
}
}
return &fatalIfNoSpaceWriterAt{
WriterAtCloser: out,
enabled: f.opt.FatalIfNoSpace,
}, nil
return out, nil
}
// setMetadata sets the file info from the os.FileInfo passed in
+1 -85
View File
@@ -60,7 +60,7 @@ func TestIsDiskFullError(t *testing.T) {
// FatalIfNoSpace setting, returning the error from Update.
func updateWithReader(t *testing.T, fatalIfNoSpace bool, readerErr error) error {
t.Helper()
r := fstest.NewRunIndividual(t)
r := fstest.NewRun(t)
f := r.Flocal.(*Fs)
f.opt.FatalIfNoSpace = fatalIfNoSpace
@@ -96,87 +96,3 @@ func TestUpdateFatalIfNoSpaceOnButNotDiskFull(t *testing.T) {
require.Error(t, err)
assert.False(t, fserrors.IsFatalError(err), "non-disk-full errors must not be fatal regardless of option")
}
type diskFullWriterAtCloser struct {
writeErr error
closeErr error
n int
data []byte
offset int64
closed bool
}
func (w *diskFullWriterAtCloser) WriteAt(p []byte, off int64) (int, error) {
w.data = append([]byte(nil), p...)
w.offset = off
return w.n, w.writeErr
}
func (w *diskFullWriterAtCloser) Close() error {
w.closed = true
return w.closeErr
}
func testOpenWriterAtError(t *testing.T, injected error, diskFull bool) {
t.Helper()
for _, enabled := range []bool{false, true} {
t.Run(fmt.Sprintf("enabled=%v", enabled), func(t *testing.T) {
r := fstest.NewRunIndividual(t)
f := r.Flocal.(*Fs)
f.opt.FatalIfNoSpace = enabled
f.opt.NoPreAllocate = true
writer, err := f.OpenWriterAt(context.Background(), "test.txt", 0)
require.NoError(t, err)
wrapped, ok := writer.(*fatalIfNoSpaceWriterAt)
require.True(t, ok)
require.NoError(t, wrapped.WriterAtCloser.Close())
wantN := 2
if injected == nil {
wantN = 4
}
underlying := &diskFullWriterAtCloser{writeErr: injected, closeErr: injected, n: wantN}
wrapped.WriterAtCloser = underlying
n, err := writer.WriteAt([]byte("data"), 17)
assert.Equal(t, wantN, n)
assert.Equal(t, []byte("data"), underlying.data)
assert.Equal(t, int64(17), underlying.offset)
assert.ErrorIs(t, err, injected)
assert.Equal(t, enabled && diskFull, fserrors.IsFatalError(err))
err = writer.Close()
assert.True(t, underlying.closed)
assert.ErrorIs(t, err, injected)
assert.Equal(t, enabled && diskFull, fserrors.IsFatalError(err))
})
}
}
func TestOpenWriterAtFatalIfNoSpace(t *testing.T) {
for _, test := range []struct {
name string
err error
diskFull bool
}{
{"success", nil, false},
{"unrelated", syscall.EPERM, false},
{"ENOSPC", syscall.ENOSPC, true},
{"ErrDiskFull", file.ErrDiskFull, true},
{"wrapped", fmt.Errorf("write: %w", syscall.ENOSPC), true},
} {
t.Run(test.name, func(t *testing.T) { testOpenWriterAtError(t, test.err, test.diskFull) })
}
}
func TestOpenWriterAtSetupError(t *testing.T) {
for _, enabled := range []bool{false, true} {
t.Run(fmt.Sprintf("enabled=%v", enabled), func(t *testing.T) {
r := fstest.NewRunIndividual(t)
f := r.Flocal.(*Fs)
f.opt.FatalIfNoSpace = enabled
require.NoError(t, os.WriteFile(filepath.Join(r.LocalName, "parent"), nil, 0600))
writer, err := f.OpenWriterAt(context.Background(), "parent/child", 0)
require.Error(t, err)
assert.Nil(t, writer)
assert.False(t, fserrors.IsFatalError(err))
})
}
}
@@ -1,52 +0,0 @@
//go:build windows
package local
import (
"os"
"testing"
"github.com/rclone/rclone/fs/fserrors"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"golang.org/x/sys/windows"
)
func TestUpdateFatalIfNoSpaceWindows(t *testing.T) {
tests := []struct {
name string
err error
}{
{"ERROR_DISK_FULL", windows.ERROR_DISK_FULL},
{"openat PathError", &os.PathError{Op: "openat", Path: "test.txt", Err: windows.ERROR_DISK_FULL}},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
t.Run("off", func(t *testing.T) {
err := updateWithReader(t, false, test.err)
require.Error(t, err)
assert.False(t, fserrors.IsFatalError(err))
})
t.Run("on", func(t *testing.T) {
err := updateWithReader(t, true, test.err)
require.Error(t, err)
assert.True(t, fserrors.IsFatalError(err))
})
})
}
}
func TestOpenWriterAtFatalIfNoSpaceWindows(t *testing.T) {
for _, test := range []struct {
name string
err error
diskFull bool
}{
{"ERROR_DISK_FULL", windows.ERROR_DISK_FULL, true},
{"ERROR_HANDLE_DISK_FULL", windows.ERROR_HANDLE_DISK_FULL, true},
{"PathError", &os.PathError{Op: "write", Path: "test.txt", Err: windows.ERROR_DISK_FULL}, true},
{"ERROR_ACCESS_DENIED", windows.ERROR_ACCESS_DENIED, false},
} {
t.Run(test.name, func(t *testing.T) { testOpenWriterAtError(t, test.err, test.diskFull) })
}
}
+6 -13
View File
@@ -56,15 +56,7 @@ const (
driveTypeSharepoint = "documentLibrary"
defaultChunkSize = 10 * fs.Mebi
chunkSizeMultiple = 320 * fs.Kibi
// maxSinglePartSize is the size at which Graph stops accepting an upload in a
// single request (PUT /items/{id}/content). Microsoft documents this as
// "250 MB", see
// https://learn.microsoft.com/en-us/graph/api/driveitem-put-content
// Measured against SharePoint Online the figure is binary and exclusive: a
// body of 262143999 bytes is accepted, one of 262144000 is not. That matches
// upload_cutoff being an exclusive threshold in Update below, so a cutoff of
// exactly 250Mi sends everything the server would refuse to multipart.
maxSinglePartSize = 250 * fs.Mebi
maxSinglePartSize = 4 * fs.Mebi
regionGlobal = "global"
regionUS = "us"
@@ -302,7 +294,8 @@ this flag there.
Normally files will get sent to the recycle bin on deletion. Setting
this flag causes them to be permanently deleted. Use with care.
This works with OneDrive for Business, SharePoint document libraries, and OneDrive personal accounts, including free accounts.
OneDrive personal accounts do not support the permanentDelete API,
it only applies to OneDrive for Business and SharePoint document libraries.
`,
Advanced: true,
Default: false,
@@ -2793,13 +2786,13 @@ func (o *Object) uploadMultipart(ctx context.Context, in io.Reader, src fs.Objec
return info, o.setMetaData(info)
}
// Update the content of a remote file smaller than maxSinglePartSize in one single request
// Update the content of a remote file within 4 MiB size in one single request
// (currently only used when size is exactly 0)
// This function will set modtime and metadata after uploading, which will create a new version for the remote file
func (o *Object) uploadSinglepart(ctx context.Context, in io.Reader, src fs.ObjectInfo, options ...fs.OpenOption) (info *api.Item, err error) {
size := src.Size()
if size < 0 || size >= int64(maxSinglePartSize) {
return nil, fmt.Errorf("size passed into uploadSinglepart must be >= 0 and < %v", maxSinglePartSize)
if size < 0 || size > int64(maxSinglePartSize) {
return nil, fmt.Errorf("size passed into uploadSinglepart must be >= 0 and <= %v", maxSinglePartSize)
}
fs.Debugf(o, "Starting singlepart upload")
@@ -516,30 +516,6 @@ func (f *Fs) resetTestDefaults(r *fstest.Run) {
r.Finalise()
}
// TestCheckUploadCutoff checks the bounds of the --onedrive-upload-cutoff
// validation, in particular that the documented API maximum is accepted.
func TestCheckUploadCutoff(t *testing.T) {
for _, test := range []struct {
in fs.SizeSuffix
wantErr bool
}{
{in: 0, wantErr: false},
{in: 4 * fs.Mebi, wantErr: false},
// maxSinglePartSize is a legal cutoff even though the server refuses a
// body of that size, because the cutoff is an exclusive threshold: at
// this setting a file of exactly maxSinglePartSize goes multipart.
{in: maxSinglePartSize, wantErr: false},
{in: maxSinglePartSize + 1, wantErr: true},
} {
err := checkUploadCutoff(test.in)
if test.wantErr {
assert.Error(t, err, test.in.String())
} else {
assert.NoError(t, err, test.in.String())
}
}
}
// InternalTest dispatches all internal tests
func (f *Fs) InternalTest(t *testing.T) {
newTestF := func() (*Fs, *fstest.Run) {
-3
View File
@@ -115,14 +115,11 @@ func useBYOKCopyObject(fs *Fs, request *objectstorage.CopyObjectRequest) {
}
if fs.opt.SSECustomerAlgorithm != "" {
request.OpcSseCustomerAlgorithm = new(fs.opt.SSECustomerAlgorithm)
request.OpcSourceSseCustomerAlgorithm = new(fs.opt.SSECustomerAlgorithm)
}
if fs.opt.SSECustomerKey != "" {
request.OpcSseCustomerKey = new(fs.opt.SSECustomerKey)
request.OpcSourceSseCustomerKey = new(fs.opt.SSECustomerKey)
}
if fs.opt.SSECustomerKeySha256 != "" {
request.OpcSseCustomerKeySha256 = new(fs.opt.SSECustomerKeySha256)
request.OpcSourceSseCustomerKeySha256 = new(fs.opt.SSECustomerKeySha256)
}
}
-25
View File
@@ -1,25 +0,0 @@
//go:build !plan9 && !solaris && !js
package oracleobjectstorage
import (
"testing"
"github.com/oracle/oci-go-sdk/v65/objectstorage"
"github.com/stretchr/testify/assert"
)
func TestUseBYOKCopyObject(t *testing.T) {
f := &Fs{opt: Options{
SSECustomerAlgorithm: "AES256",
SSECustomerKey: "customer-key",
SSECustomerKeySha256: "customer-key-sha256",
}}
req := &objectstorage.CopyObjectRequest{}
useBYOKCopyObject(f, req)
assert.Equal(t, &f.opt.SSECustomerAlgorithm, req.OpcSourceSseCustomerAlgorithm)
assert.Equal(t, &f.opt.SSECustomerKey, req.OpcSourceSseCustomerKey)
assert.Equal(t, &f.opt.SSECustomerKeySha256, req.OpcSourceSseCustomerKeySha256)
}
+17 -1
View File
@@ -11,6 +11,7 @@ import (
"sync"
"time"
"github.com/oracle/oci-go-sdk/v65/common"
"github.com/oracle/oci-go-sdk/v65/objectstorage"
"github.com/rclone/rclone/fs"
"github.com/rclone/rclone/fs/operations"
@@ -196,7 +197,22 @@ func (f *Fs) rename(ctx context.Context, remote, newName string) (any, error) {
}
return nil, fs.ErrorNotAFile
}
err = f.renameObject(ctx, bucketName, objectPath, newName)
details := objectstorage.RenameObjectDetails{
SourceName: new(objectPath),
NewName: new(newName),
}
request := objectstorage.RenameObjectRequest{
NamespaceName: new(f.opt.Namespace),
BucketName: new(bucketName),
RenameObjectDetails: details,
OpcClientRequestId: nil,
RequestMetadata: common.RequestMetadata{},
}
var response objectstorage.RenameObjectResponse
err = f.pacer.Call(func() (bool, error) {
response, err = f.srv.RenameObject(ctx, request)
return shouldRetry(ctx, response.HTTPResponse(), err)
})
if err != nil {
return nil, err
}
-49
View File
@@ -40,55 +40,6 @@ func (f *Fs) Copy(ctx context.Context, src fs.Object, remote string) (fs.Object,
return f.NewObject(ctx, remote)
}
// ------------------------------------------------------------
// Implement Mover is an optional interface for Fs
//------------------------------------------------------------
// Move src to this remote using server-side rename operations.
//
// This is stored with the remote path given.
// It returns the destination Object and a possible error.
// Will only be called if src.Fs().Name() == f.Name().
// If it isn't possible then return fs.ErrorCantMove.
func (f *Fs) Move(ctx context.Context, src fs.Object, remote string) (fs.Object, error) {
srcObj, ok := src.(*Object)
if !ok {
return nil, fs.ErrorCantMove
}
srcBucket, srcPath := srcObj.split()
dstBucket, dstPath := f.split(remote)
if srcBucket != dstBucket {
return nil, fs.ErrorCantMove
}
err := f.renameObject(ctx, srcBucket, srcPath, dstPath)
if err != nil {
return nil, err
}
return f.NewObject(ctx, remote)
}
// renameObject renames sourceName to newName in bucketName.
func (f *Fs) renameObject(ctx context.Context, bucketName, sourceName, newName string) error {
req := objectstorage.RenameObjectRequest{
NamespaceName: new(f.opt.Namespace),
BucketName: new(bucketName),
RenameObjectDetails: objectstorage.RenameObjectDetails{
SourceName: new(sourceName),
NewName: new(newName),
},
}
var resp objectstorage.RenameObjectResponse
err := f.pacer.Call(func() (bool, error) {
var err error
resp, err = f.srv.RenameObject(ctx, req)
return shouldRetry(ctx, resp.HTTPResponse(), err)
})
if err != nil {
return err
}
return nil
}
// copy does a server-side copy from dstObj <- srcObj
//
// If newInfo is nil then the metadata will be copied otherwise it
-4
View File
@@ -3,7 +3,6 @@
package oracleobjectstorage
import (
"bufio"
"bytes"
"context"
"encoding/base64"
@@ -397,9 +396,6 @@ func isZeroLength(streamReader io.Reader) bool {
return v.Len() == 0
case *strings.Reader:
return v.Len() == 0
case *bufio.Reader:
_, err := v.Peek(1)
return err == io.EOF
case *os.File:
fi, err := v.Stat()
if err != nil {
+1 -2
View File
@@ -257,8 +257,7 @@ to start uploading.`,
// so that OSS keys are always valid file names
Default: encoder.EncodeInvalidUtf8 |
encoder.EncodeSlash |
encoder.EncodeDot |
encoder.EncodeCrLf,
encoder.EncodeDot,
}, {
Name: "leave_parts_on_error",
Help: `If true avoid calling abort upload on a failure, leaving all successfully uploaded parts for manual recovery.
@@ -4,9 +4,7 @@
package oracleobjectstorage
import (
"bufio"
"context"
"errors"
"fmt"
"io"
"net/http"
@@ -304,28 +302,17 @@ func (f *Fs) ListP(ctx context.Context, dir string, callback fs.ListRCallback) e
// listFn is called from list to handle an object.
type listFn func(remote string, object *objectstorage.ObjectSummary, isDirectory bool) error
// list calls fn for objects in bucket and directory.
//
// ctx controls the API requests.
// bucket is the bucket to list.
// directory is the path to list within bucket.
// list the objects into the function supplied from
// the bucket and root supplied
// (bucket, directory) is the starting directory
// If prefix is set then it is removed from all file names
// If addBucket is set then it adds the bucket to the start of the remotes generated
// If recurse is set the function will recursively list
// If limit is > 0 then it limits to that many files (must be less than 1000)
// includeDirectoryMarkers includes zero-length objects with names ending in a slash.
// fn receives each listed object.
func (f *Fs) list(
ctx context.Context,
bucket string,
directory string,
prefix string,
addBucket bool,
recurse bool,
limit int,
includeDirectoryMarkers bool,
fn listFn,
) (err error) {
// If hidden is set then it will list the hidden (deleted) files too.
// if findFile is set it will look for files called (bucket, directory)
func (f *Fs) list(ctx context.Context, bucket, directory, prefix string, addBucket bool, recurse bool, limit int,
fn listFn) (err error) {
if prefix != "" {
prefix += "/"
}
@@ -420,7 +407,7 @@ func (f *Fs) list(
remote = path.Join(bucket, remote)
}
// is this a directory marker?
if isDirectory && object.Size != nil && *object.Size == 0 && !includeDirectoryMarkers {
if isDirectory && object.Size != nil && *object.Size == 0 {
continue // skip directory marker
}
if isDirectory && len(remote) > 1 {
@@ -469,7 +456,7 @@ func (f *Fs) listDir(ctx context.Context, bucket, directory, prefix string, addB
}
return nil
}
err = f.list(ctx, bucket, directory, prefix, addBucket, false, 0, false, fn)
err = f.list(ctx, bucket, directory, prefix, addBucket, false, 0, fn)
if err != nil {
return err
}
@@ -566,7 +553,7 @@ func (f *Fs) Put(ctx context.Context, in io.Reader, src fs.ObjectInfo, options .
// PutStream uploads to the remote path with the modTime given of indeterminate size
func (f *Fs) PutStream(ctx context.Context, in io.Reader, src fs.ObjectInfo, options ...fs.OpenOption) (fs.Object, error) {
return f.Put(ctx, bufio.NewReader(in), src, options...)
return f.Put(ctx, in, src, options...)
}
// Mkdir creates the bucket if it doesn't exist
@@ -654,66 +641,6 @@ func (f *Fs) Rmdir(ctx context.Context, dir string) error {
})
}
// ------------------------------------------------------------
// Implement Purger is an optional interfaces for Fs
//------------------------------------------------------------
// Purge deletes all the files in dir.
//
// It implements fs.Purger, using OCI batch requests rather than removing each
// object returned by List. It also removes directory markers and, when dir is
// a bucket root, removes the empty bucket.
func (f *Fs) Purge(ctx context.Context, dir string) error {
bucketName, directory := f.split(dir)
if bucketName == "" {
return fs.ErrorListBucketRequired
}
const batchSize = 1000
objects := make([]objectstorage.BatchDeleteObjectIdentifier, 0, batchSize)
deleteObjects := func() error {
if len(objects) == 0 {
return nil
}
req := objectstorage.BatchDeleteObjectsRequest{
NamespaceName: new(f.opt.Namespace),
BucketName: new(bucketName),
BatchDeleteObjectsDetails: objectstorage.BatchDeleteObjectsDetails{
Objects: objects,
IsSkipDeletedResult: new(true),
},
}
var resp objectstorage.BatchDeleteObjectsResponse
err := f.pacer.Call(func() (bool, error) {
var err error
resp, err = f.srv.BatchDeleteObjects(ctx, req)
return shouldRetry(ctx, resp.HTTPResponse(), err)
})
if err != nil {
return err
}
var errs []error
for _, failed := range resp.Failed {
errs = append(errs, fmt.Errorf("failed to delete object %q: %s", *failed.ObjectName, *failed.ErrorMessage))
}
objects = objects[:0]
return errors.Join(errs...)
}
err := f.list(ctx, bucketName, directory, f.rootDirectory, false, true, 0, true, func(_ string, object *objectstorage.ObjectSummary, _ bool) error {
objects = append(objects, objectstorage.BatchDeleteObjectIdentifier{ObjectName: object.Name})
if len(objects) == batchSize {
return deleteObjects()
}
return nil
})
if err != nil {
return err
}
if err = deleteObjects(); err != nil {
return err
}
return f.Rmdir(ctx, dir)
}
func (f *Fs) abortMultiPartUpload(ctx context.Context, bucketName, bucketPath, uploadID *string) (err error) {
if uploadID == nil || *uploadID == "" {
return nil
@@ -801,7 +728,7 @@ func (f *Fs) ListR(ctx context.Context, dir string, callback fs.ListRCallback) (
bucketName, directory := f.split(dir)
list := list.NewHelper(callback)
listR := func(bucket, directory, prefix string, addBucket bool) error {
return f.list(ctx, bucket, directory, prefix, addBucket, true, 0, false, func(remote string, object *objectstorage.ObjectSummary, isDirectory bool) error {
return f.list(ctx, bucket, directory, prefix, addBucket, true, 0, func(remote string, object *objectstorage.ObjectSummary, isDirectory bool) error {
entry, err := f.itemToDirEntry(ctx, remote, object, isDirectory)
if err != nil {
return err
@@ -874,13 +801,11 @@ func (o *Object) Metadata(ctx context.Context) (metadata fs.Metadata, err error)
var (
_ fs.Fs = &Fs{}
_ fs.Copier = &Fs{}
_ fs.Mover = &Fs{}
_ fs.PutStreamer = &Fs{}
_ fs.ListRer = &Fs{}
_ fs.ListPer = &Fs{}
_ fs.Commander = &Fs{}
_ fs.CleanUpper = &Fs{}
_ fs.Purger = &Fs{}
_ fs.OpenChunkWriter = &Fs{}
_ fs.Object = &Object{}
@@ -3,28 +3,18 @@
package oracleobjectstorage
import (
"bufio"
"bytes"
"compress/gzip"
"context"
"crypto/md5"
"errors"
"fmt"
"io"
"os"
"strings"
"sync"
"testing"
"time"
"github.com/oracle/oci-go-sdk/v65/objectstorage"
"github.com/rclone/rclone/fs"
"github.com/rclone/rclone/fs/hash"
"github.com/rclone/rclone/fs/object"
"github.com/rclone/rclone/fstest"
"github.com/rclone/rclone/fstest/fstests"
"github.com/rclone/rclone/lib/random"
"github.com/rclone/rclone/lib/readers"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
@@ -41,51 +31,6 @@ func TestIntegration(t *testing.T) {
})
}
func TestIsZeroLength(t *testing.T) {
newFile := func(contents string) *os.File {
file, err := os.CreateTemp(t.TempDir(), "stream")
require.NoError(t, err)
_, err = file.WriteString(contents)
require.NoError(t, err)
_, err = file.Seek(0, io.SeekStart)
require.NoError(t, err)
t.Cleanup(func() { _ = file.Close() })
return file
}
closedFile := newFile("")
require.NoError(t, closedFile.Close())
for _, test := range []struct {
name string
in io.Reader
want bool
wantContents string
}{
{name: "EmptyBuffer", in: bytes.NewBuffer(nil), want: true},
{name: "NonEmptyBuffer", in: bytes.NewBufferString("contents"), want: false},
{name: "EmptyBytesReader", in: bytes.NewReader(nil), want: true},
{name: "NonEmptyBytesReader", in: bytes.NewReader([]byte("contents")), want: false},
{name: "EmptyStringsReader", in: strings.NewReader(""), want: true},
{name: "NonEmptyStringsReader", in: strings.NewReader("contents"), want: false},
{name: "EmptyBufferedStream", in: bufio.NewReader(io.TeeReader(bytes.NewReader(nil), io.Discard)), want: true},
{name: "NonEmptyBufferedStream", in: bufio.NewReader(io.TeeReader(bytes.NewBufferString("contents"), io.Discard)), want: false, wantContents: "contents"},
{name: "BufferedStreamError", in: bufio.NewReader(readers.ErrorReader{Err: errors.New("stream error")}), want: false},
{name: "EmptyFile", in: newFile(""), want: true},
{name: "NonEmptyFile", in: newFile("contents"), want: false},
{name: "ClosedFile", in: closedFile, want: false},
{name: "OpaqueEmptyStream", in: io.TeeReader(bytes.NewReader(nil), io.Discard), want: false},
} {
t.Run(test.name, func(t *testing.T) {
assert.Equal(t, test.want, isZeroLength(test.in))
if test.wantContents != "" {
contents, err := io.ReadAll(test.in)
require.NoError(t, err)
assert.Equal(t, test.wantContents, string(contents))
}
})
}
}
func gz(t *testing.T, s string) string {
var buf bytes.Buffer
zw := gzip.NewWriter(&buf)
@@ -136,99 +81,9 @@ func (f *Fs) InternalTestGzipEncoding(t *testing.T) {
})
}
// InternalTestPurgeBatches tests purging more objects than fit in one batch.
func (f *Fs) InternalTestPurgeBatches(t *testing.T) {
ctx := context.Background()
const (
dir = "purge-batches"
objectCount = 1001
uploadConcurrency = 16
)
defer func() { _ = f.Purge(ctx, dir) }()
jobs := make(chan int)
errs := make(chan error, objectCount)
var wg sync.WaitGroup
for range uploadConcurrency {
wg.Go(func() {
for i := range jobs {
remote := fmt.Sprintf("%s/%04d", dir, i)
src := object.NewStaticObjectInfo(remote, time.Time{}, 0, true, nil, f)
_, err := f.Put(ctx, bytes.NewReader(nil), src)
if err != nil {
errs <- err
}
}
})
}
for i := range objectCount {
jobs <- i
}
close(jobs)
wg.Wait()
close(errs)
for err := range errs {
require.NoError(t, err)
}
require.NoError(t, f.Purge(ctx, dir))
entries, err := f.List(ctx, dir)
require.NoError(t, err)
assert.Empty(t, entries)
}
// InternalTestPurgeDirectoryMarkers tests purging directory marker objects.
func (f *Fs) InternalTestPurgeDirectoryMarkers(t *testing.T) {
ctx := context.Background()
const dir = "purge-directory-markers"
bucketName, directory := f.split(dir)
objectNames := []string{
directory + "/",
directory + "/child/",
directory + "/child/object",
}
defer func() { _ = f.Purge(ctx, dir) }()
for _, objectName := range objectNames {
req := objectstorage.PutObjectRequest{
NamespaceName: new(f.opt.Namespace),
BucketName: new(bucketName),
ObjectName: new(objectName),
PutObjectBody: io.NopCloser(bytes.NewReader(nil)),
}
err := f.pacer.Call(func() (bool, error) {
resp, err := f.srv.PutObject(ctx, req)
return shouldRetry(ctx, resp.HTTPResponse(), err)
})
require.NoError(t, err)
}
// Use the SDK directly because normal OOS listings hide directory markers.
listObjectNames := func() []string {
req := objectstorage.ListObjectsRequest{
NamespaceName: new(f.opt.Namespace),
BucketName: new(bucketName),
Prefix: new(directory + "/"),
}
var resp objectstorage.ListObjectsResponse
err := f.pacer.Call(func() (bool, error) {
var err error
resp, err = f.srv.ListObjects(ctx, req)
return shouldRetry(ctx, resp.HTTPResponse(), err)
})
require.NoError(t, err)
names := make([]string, 0, len(resp.Objects))
for _, object := range resp.Objects {
names = append(names, *object.Name)
}
return names
}
assert.ElementsMatch(t, objectNames, listObjectNames())
require.NoError(t, f.Purge(ctx, dir))
assert.Empty(t, listObjectNames())
}
// InternalTest is called by fstests.Run to extra tests
func (f *Fs) InternalTest(t *testing.T) {
t.Run("GzipEncoding", f.InternalTestGzipEncoding)
t.Run("PurgeBatches", f.InternalTestPurgeBatches)
t.Run("PurgeDirectoryMarkers", f.InternalTestPurgeDirectoryMarkers)
}
func (f *Fs) SetUploadChunkSize(cs fs.SizeSuffix) (fs.SizeSuffix, error) {
-4
View File
@@ -19,7 +19,3 @@ quirks:
force_path_style: true
list_url_encode: false
use_already_exists: false
# Ceph RGW (and reverse proxies such as Cloudflare in front of it) can
# mutate Accept-Encoding and break SigV4 when that header is signed.
# See: https://github.com/rclone/rclone/issues/8206
sign_accept_encoding: false
-5
View File
@@ -24,8 +24,3 @@ endpoint:
us-iad-10.linodeobjects.com: Washington, DC, US (us-iad-10)
acl: {}
bucket_acl: true
quirks:
# Linode Object Storage is Ceph-backed; signing Accept-Encoding causes
# SignatureDoesNotMatch with rclone 1.68+. Match the Ceph quirk.
# See: https://github.com/rclone/rclone/issues/8206
sign_accept_encoding: false
+5 -80
View File
@@ -3303,10 +3303,6 @@ func (f *Fs) Hashes() hash.Set {
// PublicLink generates a public link to the remote path (usually readable by anyone)
func (f *Fs) PublicLink(ctx context.Context, remote string, expire fs.Duration, unlink bool) (link string, err error) {
return f.publicLink(ctx, remote, expire, &s3.GetObjectInput{})
}
func (f *Fs) publicLink(ctx context.Context, remote string, expire fs.Duration, req *s3.GetObjectInput) (link string, err error) {
if strings.HasSuffix(remote, "/") {
return "", fs.ErrorCantShareDirectories
}
@@ -3320,10 +3316,11 @@ func (f *Fs) publicLink(ctx context.Context, remote string, expire fs.Duration,
expire = maxExpireDuration
}
bucket, bucketPath := f.split(remote)
req.Bucket = &bucket
req.Key = &bucketPath
req.VersionId = o.versionID
httpReq, err := s3.NewPresignClient(f.c).PresignGetObject(ctx, req, s3.WithPresignExpires(time.Duration(expire)))
httpReq, err := s3.NewPresignClient(f.c).PresignGetObject(ctx, &s3.GetObjectInput{
Bucket: &bucket,
Key: &bucketPath,
VersionId: o.versionID,
}, s3.WithPresignExpires(time.Duration(expire)))
if err != nil {
return "", err
}
@@ -3331,40 +3328,6 @@ func (f *Fs) publicLink(ctx context.Context, remote string, expire fs.Duration,
}
var commandHelp = []fs.CommandHelp{{
Name: "link",
Short: "Generate a signed link with response header overrides.",
Long: `This command generates a signed download link for one file, with optional
overrides for the HTTP response headers. Pass the file path as a separate
argument, relative to the remote path.
Usage examples:
` + "```console" + `
rclone backend link s3:bucket path/to/file -o expire=1h
rclone backend link s3:bucket path/to/file -o response-expires="Thu, 01 Jan 1970 00:00:00 GMT"
rclone backend link s3:bucket path/to/file -o response-content-disposition='attachment; filename="download.txt"'
` + "```" + `
The link expires after 7 days by default. Use ` + "`-o expire=1h`" + ` to change
its lifetime. Durations must be at least 1 second; values above 7 days are
limited to 7 days, as with ` + "`rclone link`" + `.
The ` + "`response-expires`" + ` option sets the HTTP Expires response header,
not the lifetime of the signed link. It must be an HTTP date, such as
` + "`Thu, 01 Jan 1970 00:00:00 GMT`" + `.
The overrides are included in the signature and must not be changed in the
returned URL. They do not modify the object's stored metadata.`,
Opts: map[string]string{
"expire": "How long the link will be valid (default 7d, maximum 7d).",
"response-cache-control": "Set the Cache-Control response header.",
"response-content-disposition": "Set the Content-Disposition response header.",
"response-content-encoding": "Set the Content-Encoding response header.",
"response-content-language": "Set the Content-Language response header.",
"response-content-type": "Set the Content-Type response header.",
"response-expires": "Set the Expires response header to an HTTP date.",
},
}, {
Name: "restore",
Short: "Restore objects from GLACIER or INTELLIGENT-TIERING archive tier.",
Long: `This command can be used to restore one or more objects from GLACIER to normal
@@ -3592,44 +3555,6 @@ It doesn't return anything.`,
// otherwise it will be JSON encoded and shown to the user like that
func (f *Fs) Command(ctx context.Context, name string, arg []string, opt map[string]string) (out any, err error) {
switch name {
case "link":
if len(arg) != 1 || arg[0] == "" {
return nil, errors.New("link requires exactly one file path argument")
}
req := s3.GetObjectInput{}
expire := maxExpireDuration
for key, value := range opt {
switch key {
case "expire":
duration, err := fs.ParseDuration(value)
if err != nil {
return nil, fmt.Errorf("invalid expire: %w", err)
}
if duration < time.Second {
return nil, errors.New("expire must be at least 1 second")
}
expire = fs.Duration(duration)
case "response-cache-control":
req.ResponseCacheControl = aws.String(value)
case "response-content-disposition":
req.ResponseContentDisposition = aws.String(value)
case "response-content-encoding":
req.ResponseContentEncoding = aws.String(value)
case "response-content-language":
req.ResponseContentLanguage = aws.String(value)
case "response-content-type":
req.ResponseContentType = aws.String(value)
case "response-expires":
date, err := http.ParseTime(value)
if err != nil {
return nil, fmt.Errorf("invalid response-expires: %w", err)
}
req.ResponseExpires = &date
default:
return nil, fmt.Errorf("unknown link option %q", key)
}
}
return f.publicLink(ctx, arg[0], expire, &req)
case "restore":
req := s3.RestoreObjectInput{
//Bucket: &f.rootBucket,
-227
View File
@@ -1,227 +0,0 @@
package s3
import (
"context"
"io"
"net/http"
"net/http/httptest"
"net/url"
"strings"
"testing"
"time"
"github.com/aws/aws-sdk-go-v2/aws"
v4 "github.com/aws/aws-sdk-go-v2/aws/signer/v4"
"github.com/rclone/rclone/fs"
"github.com/rclone/rclone/lib/bucket"
"github.com/rclone/rclone/lib/pacer"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func newLinkTestFs(t *testing.T) *Fs {
t.Helper()
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Query().Has("versions") {
assert.Equal(t, http.MethodGet, r.Method)
assert.Equal(t, "prefix/file", r.URL.Query().Get("prefix"))
_, err := io.WriteString(w, `<ListVersionsResult xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
<IsTruncated>false</IsTruncated>
<Version><Key>prefix/file</Key><VersionId>version+id/1</VersionId><IsLatest>false</IsLatest>
<LastModified>2024-01-01T00:00:00Z</LastModified><Size>1</Size></Version>
</ListVersionsResult>`)
assert.NoError(t, err)
return
}
assert.Equal(t, http.MethodHead, r.Method)
if strings.HasSuffix(r.URL.Path, "/missing") {
w.WriteHeader(http.StatusNotFound)
return
}
w.Header().Set("Content-Length", "1")
w.Header().Set("Last-Modified", "Wed, 01 Jan 2025 00:00:00 GMT")
}))
t.Cleanup(server.Close)
ctx, opt, client := SetupS3Test(t)
opt.Endpoint = server.URL
opt.ForcePathStyle = true
opt.Region = "us-east-1"
opt.AccessKeyID = "test-access-key"
opt.SecretAccessKey = "test-secret-key"
opt.SessionToken = "test-token+/="
c, _, err := s3Connection(ctx, opt, client)
require.NoError(t, err)
f := &Fs{
name: "s3test",
opt: *opt,
ctx: ctx,
c: c,
pacer: fs.NewPacer(ctx, pacer.NewS3(pacer.MinSleep(minSleep))),
cache: bucket.NewCache(),
}
f.setRoot("bucket/prefix")
return f
}
func linkSignature(t *testing.T, u *url.URL) string {
t.Helper()
q := u.Query()
signingTime, err := time.Parse("20060102T150405Z", q.Get("X-Amz-Date"))
require.NoError(t, err)
q.Del("X-Amz-Signature")
unsigned := *u
unsigned.RawQuery = q.Encode()
req, err := http.NewRequestWithContext(context.Background(), http.MethodGet, unsigned.String(), nil)
require.NoError(t, err)
signed, _, err := v4.NewSigner().PresignHTTP(context.Background(), aws.Credentials{
AccessKeyID: "test-access-key",
SecretAccessKey: "test-secret-key",
SessionToken: "test-token+/=",
}, req, "UNSIGNED-PAYLOAD", "s3", "us-east-1", signingTime, func(opt *v4.SignerOptions) {
opt.DisableURIPathEscaping = true
})
require.NoError(t, err)
result, err := url.Parse(signed)
require.NoError(t, err)
return result.Query().Get("X-Amz-Signature")
}
func TestCommandLink(t *testing.T) {
f := newLinkTestFs(t)
remote := "dir/a file +&?%\u2603.txt"
overrides := map[string]string{
"response-cache-control": "private, max-age=0",
"response-content-disposition": `attachment; filename="a +&?.txt"`,
"response-content-encoding": "identity",
"response-content-language": "en-US",
"response-content-type": "text/plain; charset=utf-8",
"response-expires": "Thu, 01 Jan 1970 00:00:00 GMT",
}
opts := map[string]string{"expire": "1h"}
for k, v := range overrides {
opts[k] = v
}
out, err := f.Command(context.Background(), "link", []string{remote}, opts)
require.NoError(t, err)
link, ok := out.(string)
require.True(t, ok)
u, err := url.Parse(link)
require.NoError(t, err)
assert.Equal(t, "/bucket/prefix/"+remote, u.Path)
assert.NotContains(t, u.RawQuery, " ")
q := u.Query()
assert.Equal(t, "3600", q.Get("X-Amz-Expires"))
assert.Equal(t, "test-token+/=", q.Get("X-Amz-Security-Token"))
assert.Equal(t, "AWS4-HMAC-SHA256", q.Get("X-Amz-Algorithm"))
assert.Equal(t, "host", q.Get("X-Amz-SignedHeaders"))
for k, v := range overrides {
assert.Equal(t, v, q.Get(k), k)
}
signature := q.Get("X-Amz-Signature")
require.NotEmpty(t, signature)
assert.Equal(t, signature, linkSignature(t, u))
for k := range overrides {
t.Run("Signed/"+k, func(t *testing.T) {
tampered := *u
changed := u.Query()
changed.Set(k, "changed")
tampered.RawQuery = changed.Encode()
assert.NotEqual(t, signature, linkSignature(t, &tampered))
})
}
}
func TestCommandLinkExpire(t *testing.T) {
f := newLinkTestFs(t)
for _, test := range []struct {
name string
opts map[string]string
expire string
}{
{"Default", nil, "604800"},
{"Minimum", map[string]string{"expire": "1s"}, "1"},
{"Maximum", map[string]string{"expire": "7d"}, "604800"},
{"Clamped", map[string]string{"expire": "8d"}, "604800"},
{"Off", map[string]string{"expire": "off"}, "604800"},
} {
t.Run(test.name, func(t *testing.T) {
out, err := f.Command(context.Background(), "link", []string{"file"}, test.opts)
require.NoError(t, err)
u, err := url.Parse(out.(string))
require.NoError(t, err)
assert.Equal(t, test.expire, u.Query().Get("X-Amz-Expires"))
for key := range u.Query() {
assert.False(t, strings.HasPrefix(key, "response-"))
}
assert.Equal(t, u.Query().Get("X-Amz-Signature"), linkSignature(t, u))
})
}
}
func TestCommandLinkErrors(t *testing.T) {
f := newLinkTestFs(t)
for _, test := range []struct {
name string
args []string
opts map[string]string
}{
{"NoPath", nil, nil},
{"TooManyPaths", []string{"one", "two"}, nil},
{"EmptyPath", []string{""}, nil},
{"Directory", []string{"dir/"}, nil},
{"Missing", []string{"missing"}, nil},
{"UnknownOption", []string{"file"}, map[string]string{"response-unknown": "value"}},
{"InvalidDate", []string{"file"}, map[string]string{"response-expires": "tomorrow"}},
{"InvalidExpire", []string{"file"}, map[string]string{"expire": "invalid"}},
{"EmptyExpire", []string{"file"}, map[string]string{"expire": ""}},
{"ZeroExpire", []string{"file"}, map[string]string{"expire": "0"}},
{"NegativeExpire", []string{"file"}, map[string]string{"expire": "-1s"}},
{"SubsecondExpire", []string{"file"}, map[string]string{"expire": "500ms"}},
} {
t.Run(test.name, func(t *testing.T) {
_, err := f.Command(context.Background(), "link", test.args, test.opts)
require.Error(t, err)
assert.NotErrorIs(t, err, fs.ErrorCommandNotFound)
})
}
}
func TestCommandLinkVersionAt(t *testing.T) {
f := newLinkTestFs(t)
f.opt.VersionAt = fs.Time(time.Date(2025, time.January, 1, 0, 0, 0, 0, time.UTC))
for _, command := range []bool{false, true} {
var link string
if command {
out, err := f.Command(context.Background(), "link", []string{"file"}, map[string]string{
"response-content-type": "text/plain",
})
require.NoError(t, err)
link = out.(string)
} else {
var err error
link, err = f.PublicLink(context.Background(), "file", fs.DurationOff, false)
require.NoError(t, err)
}
u, err := url.Parse(link)
require.NoError(t, err)
assert.Equal(t, "/bucket/prefix/file", u.Path)
assert.Equal(t, "version+id/1", u.Query().Get("versionId"))
assert.Equal(t, u.Query().Get("X-Amz-Signature"), linkSignature(t, u))
}
}
func TestPublicLink(t *testing.T) {
f := newLinkTestFs(t)
link, err := f.PublicLink(context.Background(), "file", fs.DurationOff, false)
require.NoError(t, err)
u, err := url.Parse(link)
require.NoError(t, err)
assert.Equal(t, "/bucket/prefix/file", u.Path)
assert.Equal(t, "604800", u.Query().Get("X-Amz-Expires"))
assert.Equal(t, u.Query().Get("X-Amz-Signature"), linkSignature(t, u))
_, err = f.PublicLink(context.Background(), "dir/", fs.DurationOff, false)
assert.ErrorIs(t, err, fs.ErrorCantShareDirectories)
_, err = f.PublicLink(context.Background(), "missing", fs.DurationOff, false)
assert.ErrorIs(t, err, fs.ErrorObjectNotFound)
}
+4 -5
View File
@@ -60,11 +60,10 @@ func (f *Fs) dial(ctx context.Context, network, addr string) (c *conn, err error
}
} else {
d.Initiator = &smb2.NTLMInitiator{
User: f.opt.User,
Password: pass,
Domain: f.opt.Domain,
Workstation: f.opt.Workstation,
TargetSPN: f.opt.SPN,
User: f.opt.User,
Password: pass,
Domain: f.opt.Domain,
TargetSPN: f.opt.SPN,
}
}
-12
View File
@@ -79,17 +79,6 @@ authentication, and it often needs to be set for clusters. For example:
Leave blank if not sure.
`,
Sensitive: true,
}, {
Name: "workstation",
Help: `Workstation name sent in NTLM authentication.
The NetBIOS name sent as the client workstation in the NTLM AUTHENTICATE
message. Some servers (e.g. domain-joined Windows servers with per-account
workstation restrictions or NTLM allow-lists) require this to match a
specific name. Leave blank to send no workstation name (the default).
`,
Advanced: true,
Sensitive: true,
}, {
Name: "use_kerberos",
Help: `Use Kerberos authentication.
@@ -164,7 +153,6 @@ type Options struct {
Pass string `config:"pass"`
Domain string `config:"domain"`
SPN string `config:"spn"`
Workstation string `config:"workstation"`
UseKerberos bool `config:"use_kerberos"`
KerberosCCache string `config:"kerberos_ccache"`
HideSpecial bool `config:"hide_special_share"`
-29
View File
@@ -12,8 +12,6 @@ import (
"time"
"github.com/rclone/rclone/fs"
"github.com/rclone/rclone/fs/config/configmap"
"github.com/rclone/rclone/fs/config/configstruct"
"github.com/rclone/rclone/fs/object"
"github.com/rclone/rclone/fstest"
"github.com/stretchr/testify/assert"
@@ -95,33 +93,6 @@ func TestUploadConnectionReuse(t *testing.T) {
assert.Equal(t, 1, pooled, "upload should leave exactly one connection in the pool")
}
// TestOptionsWorkstationConfig verifies the workstation config key is backwards compatible
func TestOptionsWorkstationConfig(t *testing.T) {
tests := []struct {
name string
workstation string
}{
{"named workstation", "MYWORKSTATION"},
{"empty workstation sends no name", ""},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
m := configmap.Simple{
"host": "example.com",
"workstation": tt.workstation,
}
opt := new(Options)
if err := configstruct.Set(m, opt); err != nil {
t.Fatalf("configstruct.Set failed: %v", err)
}
if opt.Workstation != tt.workstation {
t.Errorf("opt.Workstation = %q, want %q", opt.Workstation, tt.workstation)
}
})
}
}
// TestIsPathDir tests the isPathDir function logic
func TestIsPathDir(t *testing.T) {
tests := []struct {
+2 -10
View File
@@ -365,11 +365,7 @@ func (f *Fs) readMetaDataForPath(ctx context.Context, path string) (info *api.Pr
var result api.Multistatus
var resp *http.Response
err = f.pacer.Call(func() (bool, error) {
var attempt api.Multistatus
resp, err = f.srv.CallXML(ctx, &opts, nil, &attempt)
if err == nil {
result = attempt
}
resp, err = f.srv.CallXML(ctx, &opts, nil, &result)
return f.shouldRetry(ctx, resp, err)
})
if apiErr, ok := err.(*api.Error); ok {
@@ -819,11 +815,7 @@ func (f *Fs) listAll(ctx context.Context, dir string, directoriesOnly bool, file
var result api.Multistatus
var resp *http.Response
err = f.pacer.Call(func() (bool, error) {
var attempt api.Multistatus
resp, err = f.srv.CallXML(ctx, &opts, nil, &attempt)
if err == nil {
result = attempt
}
resp, err = f.srv.CallXML(ctx, &opts, nil, &result)
return f.shouldRetry(ctx, resp, err)
})
if err != nil {
-70
View File
@@ -284,73 +284,3 @@ func TestCopyFallsBackWhenRangeIgnored(t *testing.T) {
assert.LessOrEqual(t, rangeRequests.Load(), int32(3))
assert.Equal(t, int32(1), fullRequests.Load())
}
// TestListAllRetryDoesNotConcatenate verifies that when a listing PROPFIND
// fails after having partially decoded and is retried, the final listing is
// exactly the retried response, with no entries carried over from the
// failed attempt.
func TestListAllRetryDoesNotConcatenate(t *testing.T) {
entryXML := func(i int) string {
name := fmt.Sprintf("file-%03d.bin", i)
return "<d:response><d:href>/" + name + "</d:href><d:propstat><d:prop>" +
"<d:displayname>" + name + "</d:displayname><d:getcontentlength>1024</d:getcontentlength>" +
"</d:prop><d:status>HTTP/1.1 200 OK</d:status></d:propstat></d:response>\n"
}
head := `<?xml version="1.0" encoding="utf-8"?><d:multistatus xmlns:d="DAV:">`
self := head + `<d:response><d:href>/</d:href><d:propstat><d:prop><d:resourcetype><d:collection xmlns:d="DAV:"/></d:resourcetype></d:prop><d:status>HTTP/1.1 200 OK</d:status></d:propstat></d:response></d:multistatus>`
writeEntries := func(w http.ResponseWriter, from, to int) {
_, err := fmt.Fprint(w, head)
require.NoError(t, err)
for i := from; i <= to; i++ {
_, err := fmt.Fprint(w, entryXML(i))
require.NoError(t, err)
}
}
var listCalls atomic.Int64
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
require.Equal(t, "PROPFIND", r.Method)
w.Header().Set("Content-Type", "application/xml; charset=utf-8")
if r.Header.Get("Depth") == "0" {
w.WriteHeader(207)
_, err := fmt.Fprint(w, self)
require.NoError(t, err)
return
}
if listCalls.Add(1) == 1 {
// return file-000..file-010 but kill the response before it
// completes, so the client has parsed those entries when it
// hits an unexpected EOF
w.Header().Set("Content-Length", "1000000")
w.WriteHeader(207)
writeEntries(w, 0, 10)
return
}
// return the disjoint file-011..file-030 as a complete listing
w.WriteHeader(207)
writeEntries(w, 11, 30)
_, err := fmt.Fprint(w, "</d:multistatus>")
require.NoError(t, err)
}))
defer ts.Close()
configfile.Install()
m := configmap.Simple{
"type": "webdav",
"url": ts.URL,
}
f, err := webdav.NewFs(context.Background(), remoteName, "", m)
require.NoError(t, err)
entries, err := f.List(context.Background(), "")
require.NoError(t, err)
var remotes []string
for _, e := range entries {
remotes = append(remotes, e.Remote())
}
var want []string
for i := 11; i <= 30; i++ {
want = append(want, fmt.Sprintf("file-%03d.bin", i))
}
assert.ElementsMatch(t, want, remotes)
}
+17 -45
View File
@@ -100,20 +100,6 @@ normally enough to stop them, at the cost of slowing down uploads.
Yandex support recommend a value of 1.5s - 3s.`,
Default: fs.Duration(0),
Advanced: true,
}, {
Name: "app_folder",
Help: `Use the application folder as the root.
If you registered your own OAuth application with Yandex with only
the "Application Folder" permission (cloud_api:disk.app_folder)
instead of full disk access, then rclone needs to address paths with
the "app:/" prefix instead of the usual "disk:/" prefix, otherwise
all requests fail with a 403 Forbidden error.
Set this to true if your OAuth token only has access to the
application folder.`,
Default: false,
Advanced: true,
}}...),
})
}
@@ -125,20 +111,18 @@ type Options struct {
Enc encoder.MultiEncoder `config:"encoding"`
SpoofUserAgent bool `config:"spoof_ua"`
UploadWait fs.Duration `config:"upload_wait"`
AppFolder bool `config:"app_folder"`
}
// Fs represents a remote yandex
type Fs struct {
name string
root string // root path
opt Options // parsed options
ci *fs.ConfigInfo // global config
features *fs.Features // optional features
srv *rest.Client // the connection to the yandex server
pacer *fs.Pacer // pacer for API calls
diskRoot string // root path with the container prefix, e.g. "disk:/" or "app:/"
container string // container prefix in use, e.g. "disk:" or "app:"
name string
root string // root path
opt Options // parsed options
ci *fs.ConfigInfo // global config
features *fs.Features // optional features
srv *rest.Client // the connection to the yandex server
pacer *fs.Pacer // pacer for API calls
diskRoot string // root path with "disk:/" container name
}
// Object describes a swift object
@@ -225,21 +209,13 @@ func errorHandler(resp *http.Response) error {
func (f *Fs) setRoot(root string) {
//Set root path
f.root = strings.Trim(root, "/")
//Set the container prefix. This is "disk:" normally, or "app:" if the
//OAuth token only has access to the application folder (see the
//app_folder option).
if f.opt.AppFolder {
f.container = "app:"
} else {
f.container = "disk:"
}
//Set disk root path.
//Adding the container prefix to root path as all paths on disk start with it
//Adding "disk:" to root path as all paths on disk start with it
var diskRoot string
if f.root == "" {
diskRoot = f.container + "/"
diskRoot = "disk:/"
} else {
diskRoot = f.container + "/" + f.root + "/"
diskRoot = "disk:/" + f.root + "/"
}
f.diskRoot = diskRoot
}
@@ -518,13 +494,9 @@ func (f *Fs) CreateDir(ctx context.Context, path string) (err error) {
NoResponse: true,
}
if f.opt.AppFolder {
// Bare relative paths are not resolved under the app folder root,
// unlike the disk root, so the "app:" prefix is always required.
path = f.container + path
} else if strings.ContainsRune(path, ':') {
// If creating a directory with a : use (undocumented) disk: prefix
path = f.container + path
// If creating a directory with a : use (undocumented) disk: prefix
if strings.ContainsRune(path, ':') {
path = "disk:" + path
}
opts.Parameters.Set("path", f.opt.Enc.FromStandardPath(path))
@@ -546,8 +518,8 @@ func (f *Fs) CreateDir(ctx context.Context, path string) (err error) {
func (f *Fs) mkDirs(ctx context.Context, path string) (err error) {
//trim filename from path
//dirString := strings.TrimSuffix(path, filepath.Base(path))
//trim the container prefix, e.g. "disk:" or "app:", from path
dirString := strings.TrimPrefix(path, f.container)
//trim "disk:" from path
dirString := strings.TrimPrefix(path, "disk:")
if dirString == "" {
return nil
}
@@ -836,7 +808,7 @@ func (f *Fs) DirMove(ctx context.Context, src fs.Fs, srcRemote, dstRemote string
//fmt.Printf("Move src: %s (FullPath: %s), dst: %s (FullPath: %s)\n", srcRemote, srcPath, dstRemote, dstPath)
// Refuse to move to or from the root
if srcPath == srcFs.container+"/" || dstPath == f.container+"/" {
if srcPath == "disk:/" || dstPath == "disk:/" {
fs.Debugf(src, "DirMove error: Can't move root")
return errors.New("can't move root directory")
}
-88
View File
@@ -1,88 +0,0 @@
package yandex
import (
"context"
"net/http"
"net/http/httptest"
"testing"
"time"
"github.com/rclone/rclone/fs"
"github.com/rclone/rclone/lib/pacer"
"github.com/rclone/rclone/lib/rest"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// TestSetRoot checks that setRoot addresses paths with the "disk:/" prefix
// by default, and with the "app:/" prefix when app_folder is set.
func TestSetRoot(t *testing.T) {
for _, test := range []struct {
appFolder bool
root string
wantDiskRoot string
wantFilePath string
}{
{false, "", "disk:/", "disk:/file.txt"},
{false, "backups", "disk:/backups/", "disk:/backups/file.txt"},
{true, "", "app:/", "app:/file.txt"},
{true, "backups", "app:/backups/", "app:/backups/file.txt"},
} {
f := &Fs{opt: Options{AppFolder: test.appFolder}}
f.setRoot(test.root)
assert.Equal(t, test.wantDiskRoot, f.diskRoot, "diskRoot for root=%q app_folder=%v", test.root, test.appFolder)
assert.Equal(t, test.wantFilePath, f.filePath("file.txt"), "filePath for root=%q app_folder=%v", test.root, test.appFolder)
}
}
// TestCreateDir checks the path CreateDir sends to the API, both for the
// default disk:/ root and for the app:/ root used when app_folder is set.
// Yandex Disk does not resolve bare relative paths under the app folder
// root, so those must be sent with an explicit "app:/" prefix, but the
// default disk:/ behaviour (relying on the API's implicit disk root for
// bare relative paths, only prefixing when the path itself contains a ':')
// must stay unchanged for existing users.
func TestCreateDir(t *testing.T) {
for _, test := range []struct {
appFolder bool
path string
wantPath string
}{
{false, "/backups/", "/backups/"},
{false, "/foo:bar/", "disk:/foo:bar/"},
{true, "/backups/", "app:/backups/"},
{true, "/foo:bar/", "app:/foo:bar/"},
} {
var gotPath string
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
gotPath = r.URL.Query().Get("path")
w.WriteHeader(http.StatusCreated)
}))
ctx := context.Background()
f := &Fs{
opt: Options{AppFolder: test.appFolder},
srv: rest.NewClient(server.Client()).SetRoot(server.URL),
pacer: fs.NewPacer(ctx, pacer.NewDefault(pacer.MinSleep(time.Millisecond), pacer.MaxSleep(10*time.Millisecond))),
}
f.setRoot("")
err := f.CreateDir(ctx, test.path)
require.NoError(t, err, "path=%q app_folder=%v", test.path, test.appFolder)
assert.Equal(t, test.wantPath, gotPath, "path=%q app_folder=%v", test.path, test.appFolder)
server.Close()
}
}
// TestDirMoveRoot checks that DirMove refuses to move a directory to the
// container root, both for the default disk:/ root and for the app:/ root
// used when app_folder is set.
func TestDirMoveRoot(t *testing.T) {
for _, appFolder := range []bool{false, true} {
f := &Fs{opt: Options{AppFolder: appFolder}}
f.setRoot("")
err := f.DirMove(context.Background(), f, "somedir", "")
assert.EqualError(t, err, "can't move root directory", "app_folder=%v", appFolder)
}
}
+6 -22
View File
@@ -17,28 +17,15 @@ def load(filename):
authors = fd.read()
return set(re.findall(r"<(.*?)>", authors))
def add_email(added, name, email):
def add_email(name, email):
"""
adds the email passed in to the end of authors.md and records it in added
adds the email passed in to the end of authors.md
"""
print("Adding %s <%s>" % (name, email))
with open(AUTHORS, "a+") as fd:
print("- %s <%s>" % (name, email), file=fd)
added.append((name, email))
def commit(added):
"""
commits authors.md with a message describing the names in added
"""
if not added:
return
if len(added) == 1:
message = "Add %s to contributors" % added[0][0]
else:
message = "Add %d new contributors\n\n" % len(added)
message += "".join("- %s\n" % name for name, _ in added)
subprocess.check_call(["git", "commit", "-m", message, AUTHORS])
subprocess.check_call(["git", "commit", "-m", "Add %s to contributors" % name, AUTHORS])
def main():
# Add emails from authors
out = subprocess.check_output(["git", "log", '--reverse', '--format=%an|%ae', "master"])
@@ -47,7 +34,6 @@ def main():
ignored = load(IGNORE)
previous = load(AUTHORS)
previous.update(ignored)
added = []
for line in out.split("\n"):
line = line.strip()
if line == "":
@@ -56,7 +42,7 @@ def main():
if email in previous:
continue
previous.add(email)
add_email(added, name, email)
add_email(name, email)
# Add emails from Co-authored-by: lines
out = subprocess.check_output(["git", "log", '-i', '--grep', 'Co-authored-by:', "master"])
@@ -74,9 +60,7 @@ def main():
if email in previous:
continue
previous.add(email)
add_email(added, name, email)
commit(added)
add_email(name, email)
if __name__ == "__main__":
main()
-43
View File
@@ -4,8 +4,6 @@ import (
"archive/zip"
"bytes"
"context"
"os"
"path/filepath"
"strings"
"testing"
@@ -136,47 +134,6 @@ func testArchiveRemote(t *testing.T, fromLocal bool, subDir string, extension st
fstest.CheckListingWithPrecision(t, src, items, nil, fs.ModTimeNotSupported)
}
// test archiving to stdout when no destination is given
func TestArchiveStdout(t *testing.T) {
ctx := context.Background()
r := fstest.NewRun(t)
f1 := r.WriteObject(ctx, "file1.txt", "content 1", t1)
f2 := r.WriteObject(ctx, "dir1/sub1.txt", "sub content 1", t1)
fstest.CheckItems(t, r.Fremote, f1, f2)
// redirect stdout into a file on the local fs
archiveName := "stdout.zip"
require.NoError(t, r.Flocal.Mkdir(ctx, ""))
out, err := os.Create(filepath.Join(r.LocalName, archiveName))
require.NoError(t, err)
oldStdout := os.Stdout
os.Stdout = out
err = create.ArchiveCreate(ctx, nil, "", r.Fremote, "zip", "")
os.Stdout = oldStdout
require.NoError(t, out.Close())
require.NoError(t, err)
// check the archive written to stdout is readable
expected := map[string]bool{
"file1.txt": true,
"dir1/": true,
"dir1/sub1.txt": true,
}
listFile := func(ctx context.Context, f archives.FileInfo) error {
name := f.NameInArchive
if f.IsDir() && !strings.HasSuffix(name, "/") {
name += "/"
}
assert.True(t, expected[name], name)
delete(expected, name)
return nil
}
err = list.ArchiveList(ctx, r.Flocal, archiveName, listFile)
require.NoError(t, err)
assert.Equal(t, 0, len(expected), expected)
}
func testArchive(t *testing.T) {
var extensions = []string{
"zip",
+5 -6
View File
@@ -118,6 +118,7 @@ will make an archive with the contents:
cmd.CheckArgs(1, 2, command, args)
}
cmd.Run(false, false, command, func() error {
fmt.Printf("dst=%v, dstFile=%q, src=%v, format=%q, prefix=%q\n", dst, dstFile, src, format, prefix)
if prefix != "" {
return ArchiveCreate(context.Background(), dst, dstFile, src, format, prefix)
} else if fullPath {
@@ -300,12 +301,10 @@ func ArchiveCreate(ctx context.Context, dst fs.Fs, dstFile string, src fs.Fs, fo
var compArchive archives.CompressedArchive
var totalLength int64
// check if dst is valid, nil dst means write to stdout
if dst != nil {
err = CheckValidDestination(ctx, dst, dstFile)
if err != nil {
return err
}
// check id dst is valid
err = CheckValidDestination(ctx, dst, dstFile)
if err != nil {
return err
}
ci := fs.GetConfig(ctx)
+1 -1
View File
@@ -69,7 +69,7 @@ var initDate = time.Date(2000, time.January, 1, 0, 0, 0, 0, bisync.TZ)
// go run ./fstest/test_all -remotes local,TestCrypt:,TestDrive:,TestOneDrive:,TestOneDriveBusiness:,TestDropbox:,TestCryptDrive:,TestOpenDrive:,TestChunker:,:memory:,TestCryptNoEncryption:,TestCombine:DirA,TestFTPRclone:,TestWebdavRclone:,TestS3Rclone:,TestSFTPRclone:,TestSFTPRcloneSSH:,TestNextcloud:,TestChunkerNometaLocal:,TestChunkerChunk3bLocal:,TestChunkerLocal:,TestChunkerChunk3bNometaLocal:,TestStorj: -run '^TestBisync.*$' -timeout 3h -verbose -maxtries 5
// go test -timeout 3h -run '^TestBisync.*$' github.com/rclone/rclone/cmd/bisync -remote TestDrive:Bisync -v
// go test -timeout 3h -run '^TestBisyncRemoteRemote/basic$' github.com/rclone/rclone/cmd/bisync -remote TestDropbox:Bisync -v
// TestFTPProftpd:,TestFTPPureftpd:,TestFTPRclone:,TestFTPVsftpd:,TestHdfs:,TestS3Minio:,TestS3Rclone:,TestSeafile:,TestSeafileEncrypted:,TestSeafileV6:,TestSFTPOpenssh:,TestSFTPRclone:,TestSFTPRcloneSSH:,TestSia:,TestSwiftAIO:,TestWebdavNextcloud:,TestWebdavOwncloud:,TestWebdavRclone:
// TestFTPProftpd:,TestFTPPureftpd:,TestFTPRclone:,TestFTPVsftpd:,TestHdfs:,TestS3Minio:,TestS3MinioEdge:,TestS3Rclone:,TestSeafile:,TestSeafileEncrypted:,TestSeafileV6:,TestSFTPOpenssh:,TestSFTPRclone:,TestSFTPRcloneSSH:,TestSia:,TestSwiftAIO:,TestWebdavNextcloud:,TestWebdavOwncloud:,TestWebdavRclone:
// logReplacements make modern test logs comparable with golden dir.
// It is a string slice of even length with this structure:
+648
View File
@@ -26785,6 +26785,654 @@
"program": "./cmd/bisync",
"args": ["-remote", "TestS3Minio:", "-remote2", "TestS3Minio:", "-case", "test_volatile", "-no-cleanup"]
},
{
"name": "Test TestS3MinioEdge: test_all_changed LocalRemote",
"type": "go",
"request": "launch",
"mode": "test",
"program": "./cmd/bisync",
"args": ["-remote", "local", "-remote2", "TestS3MinioEdge:", "-case", "test_all_changed", "-no-cleanup"]
},
{
"name": "Test TestS3MinioEdge: test_all_changed RemoteLocal",
"type": "go",
"request": "launch",
"mode": "test",
"program": "./cmd/bisync",
"args": ["-remote", "TestS3MinioEdge:", "-remote2", "local", "-case", "test_all_changed", "-no-cleanup"]
},
{
"name": "Test TestS3MinioEdge: test_all_changed RemoteRemote",
"type": "go",
"request": "launch",
"mode": "test",
"program": "./cmd/bisync",
"args": ["-remote", "TestS3MinioEdge:", "-remote2", "TestS3MinioEdge:", "-case", "test_all_changed", "-no-cleanup"]
},
{
"name": "Test TestS3MinioEdge: test_backupdir LocalRemote",
"type": "go",
"request": "launch",
"mode": "test",
"program": "./cmd/bisync",
"args": ["-remote", "local", "-remote2", "TestS3MinioEdge:", "-case", "test_backupdir", "-no-cleanup"]
},
{
"name": "Test TestS3MinioEdge: test_backupdir RemoteLocal",
"type": "go",
"request": "launch",
"mode": "test",
"program": "./cmd/bisync",
"args": ["-remote", "TestS3MinioEdge:", "-remote2", "local", "-case", "test_backupdir", "-no-cleanup"]
},
{
"name": "Test TestS3MinioEdge: test_backupdir RemoteRemote",
"type": "go",
"request": "launch",
"mode": "test",
"program": "./cmd/bisync",
"args": ["-remote", "TestS3MinioEdge:", "-remote2", "TestS3MinioEdge:", "-case", "test_backupdir", "-no-cleanup"]
},
{
"name": "Test TestS3MinioEdge: test_basic LocalRemote",
"type": "go",
"request": "launch",
"mode": "test",
"program": "./cmd/bisync",
"args": ["-remote", "local", "-remote2", "TestS3MinioEdge:", "-case", "test_basic", "-no-cleanup"]
},
{
"name": "Test TestS3MinioEdge: test_basic RemoteLocal",
"type": "go",
"request": "launch",
"mode": "test",
"program": "./cmd/bisync",
"args": ["-remote", "TestS3MinioEdge:", "-remote2", "local", "-case", "test_basic", "-no-cleanup"]
},
{
"name": "Test TestS3MinioEdge: test_basic RemoteRemote",
"type": "go",
"request": "launch",
"mode": "test",
"program": "./cmd/bisync",
"args": ["-remote", "TestS3MinioEdge:", "-remote2", "TestS3MinioEdge:", "-case", "test_basic", "-no-cleanup"]
},
{
"name": "Test TestS3MinioEdge: test_changes LocalRemote",
"type": "go",
"request": "launch",
"mode": "test",
"program": "./cmd/bisync",
"args": ["-remote", "local", "-remote2", "TestS3MinioEdge:", "-case", "test_changes", "-no-cleanup"]
},
{
"name": "Test TestS3MinioEdge: test_changes RemoteLocal",
"type": "go",
"request": "launch",
"mode": "test",
"program": "./cmd/bisync",
"args": ["-remote", "TestS3MinioEdge:", "-remote2", "local", "-case", "test_changes", "-no-cleanup"]
},
{
"name": "Test TestS3MinioEdge: test_changes RemoteRemote",
"type": "go",
"request": "launch",
"mode": "test",
"program": "./cmd/bisync",
"args": ["-remote", "TestS3MinioEdge:", "-remote2", "TestS3MinioEdge:", "-case", "test_changes", "-no-cleanup"]
},
{
"name": "Test TestS3MinioEdge: test_check_access LocalRemote",
"type": "go",
"request": "launch",
"mode": "test",
"program": "./cmd/bisync",
"args": ["-remote", "local", "-remote2", "TestS3MinioEdge:", "-case", "test_check_access", "-no-cleanup"]
},
{
"name": "Test TestS3MinioEdge: test_check_access RemoteLocal",
"type": "go",
"request": "launch",
"mode": "test",
"program": "./cmd/bisync",
"args": ["-remote", "TestS3MinioEdge:", "-remote2", "local", "-case", "test_check_access", "-no-cleanup"]
},
{
"name": "Test TestS3MinioEdge: test_check_access RemoteRemote",
"type": "go",
"request": "launch",
"mode": "test",
"program": "./cmd/bisync",
"args": ["-remote", "TestS3MinioEdge:", "-remote2", "TestS3MinioEdge:", "-case", "test_check_access", "-no-cleanup"]
},
{
"name": "Test TestS3MinioEdge: test_check_access_filters LocalRemote",
"type": "go",
"request": "launch",
"mode": "test",
"program": "./cmd/bisync",
"args": ["-remote", "local", "-remote2", "TestS3MinioEdge:", "-case", "test_check_access_filters", "-no-cleanup"]
},
{
"name": "Test TestS3MinioEdge: test_check_access_filters RemoteLocal",
"type": "go",
"request": "launch",
"mode": "test",
"program": "./cmd/bisync",
"args": ["-remote", "TestS3MinioEdge:", "-remote2", "local", "-case", "test_check_access_filters", "-no-cleanup"]
},
{
"name": "Test TestS3MinioEdge: test_check_access_filters RemoteRemote",
"type": "go",
"request": "launch",
"mode": "test",
"program": "./cmd/bisync",
"args": ["-remote", "TestS3MinioEdge:", "-remote2", "TestS3MinioEdge:", "-case", "test_check_access_filters", "-no-cleanup"]
},
{
"name": "Test TestS3MinioEdge: test_check_filename LocalRemote",
"type": "go",
"request": "launch",
"mode": "test",
"program": "./cmd/bisync",
"args": ["-remote", "local", "-remote2", "TestS3MinioEdge:", "-case", "test_check_filename", "-no-cleanup"]
},
{
"name": "Test TestS3MinioEdge: test_check_filename RemoteLocal",
"type": "go",
"request": "launch",
"mode": "test",
"program": "./cmd/bisync",
"args": ["-remote", "TestS3MinioEdge:", "-remote2", "local", "-case", "test_check_filename", "-no-cleanup"]
},
{
"name": "Test TestS3MinioEdge: test_check_filename RemoteRemote",
"type": "go",
"request": "launch",
"mode": "test",
"program": "./cmd/bisync",
"args": ["-remote", "TestS3MinioEdge:", "-remote2", "TestS3MinioEdge:", "-case", "test_check_filename", "-no-cleanup"]
},
{
"name": "Test TestS3MinioEdge: test_check_sync LocalRemote",
"type": "go",
"request": "launch",
"mode": "test",
"program": "./cmd/bisync",
"args": ["-remote", "local", "-remote2", "TestS3MinioEdge:", "-case", "test_check_sync", "-no-cleanup"]
},
{
"name": "Test TestS3MinioEdge: test_check_sync RemoteLocal",
"type": "go",
"request": "launch",
"mode": "test",
"program": "./cmd/bisync",
"args": ["-remote", "TestS3MinioEdge:", "-remote2", "local", "-case", "test_check_sync", "-no-cleanup"]
},
{
"name": "Test TestS3MinioEdge: test_check_sync RemoteRemote",
"type": "go",
"request": "launch",
"mode": "test",
"program": "./cmd/bisync",
"args": ["-remote", "TestS3MinioEdge:", "-remote2", "TestS3MinioEdge:", "-case", "test_check_sync", "-no-cleanup"]
},
{
"name": "Test TestS3MinioEdge: test_compare_all LocalRemote",
"type": "go",
"request": "launch",
"mode": "test",
"program": "./cmd/bisync",
"args": ["-remote", "local", "-remote2", "TestS3MinioEdge:", "-case", "test_compare_all", "-no-cleanup"]
},
{
"name": "Test TestS3MinioEdge: test_compare_all RemoteLocal",
"type": "go",
"request": "launch",
"mode": "test",
"program": "./cmd/bisync",
"args": ["-remote", "TestS3MinioEdge:", "-remote2", "local", "-case", "test_compare_all", "-no-cleanup"]
},
{
"name": "Test TestS3MinioEdge: test_compare_all RemoteRemote",
"type": "go",
"request": "launch",
"mode": "test",
"program": "./cmd/bisync",
"args": ["-remote", "TestS3MinioEdge:", "-remote2", "TestS3MinioEdge:", "-case", "test_compare_all", "-no-cleanup"]
},
{
"name": "Test TestS3MinioEdge: test_createemptysrcdirs LocalRemote",
"type": "go",
"request": "launch",
"mode": "test",
"program": "./cmd/bisync",
"args": ["-remote", "local", "-remote2", "TestS3MinioEdge:", "-case", "test_createemptysrcdirs", "-no-cleanup"]
},
{
"name": "Test TestS3MinioEdge: test_createemptysrcdirs RemoteLocal",
"type": "go",
"request": "launch",
"mode": "test",
"program": "./cmd/bisync",
"args": ["-remote", "TestS3MinioEdge:", "-remote2", "local", "-case", "test_createemptysrcdirs", "-no-cleanup"]
},
{
"name": "Test TestS3MinioEdge: test_createemptysrcdirs RemoteRemote",
"type": "go",
"request": "launch",
"mode": "test",
"program": "./cmd/bisync",
"args": ["-remote", "TestS3MinioEdge:", "-remote2", "TestS3MinioEdge:", "-case", "test_createemptysrcdirs", "-no-cleanup"]
},
{
"name": "Test TestS3MinioEdge: test_dry_run LocalRemote",
"type": "go",
"request": "launch",
"mode": "test",
"program": "./cmd/bisync",
"args": ["-remote", "local", "-remote2", "TestS3MinioEdge:", "-case", "test_dry_run", "-no-cleanup"]
},
{
"name": "Test TestS3MinioEdge: test_dry_run RemoteLocal",
"type": "go",
"request": "launch",
"mode": "test",
"program": "./cmd/bisync",
"args": ["-remote", "TestS3MinioEdge:", "-remote2", "local", "-case", "test_dry_run", "-no-cleanup"]
},
{
"name": "Test TestS3MinioEdge: test_dry_run RemoteRemote",
"type": "go",
"request": "launch",
"mode": "test",
"program": "./cmd/bisync",
"args": ["-remote", "TestS3MinioEdge:", "-remote2", "TestS3MinioEdge:", "-case", "test_dry_run", "-no-cleanup"]
},
{
"name": "Test TestS3MinioEdge: test_equal LocalRemote",
"type": "go",
"request": "launch",
"mode": "test",
"program": "./cmd/bisync",
"args": ["-remote", "local", "-remote2", "TestS3MinioEdge:", "-case", "test_equal", "-no-cleanup"]
},
{
"name": "Test TestS3MinioEdge: test_equal RemoteLocal",
"type": "go",
"request": "launch",
"mode": "test",
"program": "./cmd/bisync",
"args": ["-remote", "TestS3MinioEdge:", "-remote2", "local", "-case", "test_equal", "-no-cleanup"]
},
{
"name": "Test TestS3MinioEdge: test_equal RemoteRemote",
"type": "go",
"request": "launch",
"mode": "test",
"program": "./cmd/bisync",
"args": ["-remote", "TestS3MinioEdge:", "-remote2", "TestS3MinioEdge:", "-case", "test_equal", "-no-cleanup"]
},
{
"name": "Test TestS3MinioEdge: test_ext_paths LocalRemote",
"type": "go",
"request": "launch",
"mode": "test",
"program": "./cmd/bisync",
"args": ["-remote", "local", "-remote2", "TestS3MinioEdge:", "-case", "test_ext_paths", "-no-cleanup"]
},
{
"name": "Test TestS3MinioEdge: test_ext_paths RemoteLocal",
"type": "go",
"request": "launch",
"mode": "test",
"program": "./cmd/bisync",
"args": ["-remote", "TestS3MinioEdge:", "-remote2", "local", "-case", "test_ext_paths", "-no-cleanup"]
},
{
"name": "Test TestS3MinioEdge: test_ext_paths RemoteRemote",
"type": "go",
"request": "launch",
"mode": "test",
"program": "./cmd/bisync",
"args": ["-remote", "TestS3MinioEdge:", "-remote2", "TestS3MinioEdge:", "-case", "test_ext_paths", "-no-cleanup"]
},
{
"name": "Test TestS3MinioEdge: test_extended_filenames LocalRemote",
"type": "go",
"request": "launch",
"mode": "test",
"program": "./cmd/bisync",
"args": ["-remote", "local", "-remote2", "TestS3MinioEdge:", "-case", "test_extended_filenames", "-no-cleanup"]
},
{
"name": "Test TestS3MinioEdge: test_extended_filenames RemoteLocal",
"type": "go",
"request": "launch",
"mode": "test",
"program": "./cmd/bisync",
"args": ["-remote", "TestS3MinioEdge:", "-remote2", "local", "-case", "test_extended_filenames", "-no-cleanup"]
},
{
"name": "Test TestS3MinioEdge: test_extended_filenames RemoteRemote",
"type": "go",
"request": "launch",
"mode": "test",
"program": "./cmd/bisync",
"args": ["-remote", "TestS3MinioEdge:", "-remote2", "TestS3MinioEdge:", "-case", "test_extended_filenames", "-no-cleanup"]
},
{
"name": "Test TestS3MinioEdge: test_filters LocalRemote",
"type": "go",
"request": "launch",
"mode": "test",
"program": "./cmd/bisync",
"args": ["-remote", "local", "-remote2", "TestS3MinioEdge:", "-case", "test_filters", "-no-cleanup"]
},
{
"name": "Test TestS3MinioEdge: test_filters RemoteLocal",
"type": "go",
"request": "launch",
"mode": "test",
"program": "./cmd/bisync",
"args": ["-remote", "TestS3MinioEdge:", "-remote2", "local", "-case", "test_filters", "-no-cleanup"]
},
{
"name": "Test TestS3MinioEdge: test_filters RemoteRemote",
"type": "go",
"request": "launch",
"mode": "test",
"program": "./cmd/bisync",
"args": ["-remote", "TestS3MinioEdge:", "-remote2", "TestS3MinioEdge:", "-case", "test_filters", "-no-cleanup"]
},
{
"name": "Test TestS3MinioEdge: test_filtersfile_checks LocalRemote",
"type": "go",
"request": "launch",
"mode": "test",
"program": "./cmd/bisync",
"args": ["-remote", "local", "-remote2", "TestS3MinioEdge:", "-case", "test_filtersfile_checks", "-no-cleanup"]
},
{
"name": "Test TestS3MinioEdge: test_filtersfile_checks RemoteLocal",
"type": "go",
"request": "launch",
"mode": "test",
"program": "./cmd/bisync",
"args": ["-remote", "TestS3MinioEdge:", "-remote2", "local", "-case", "test_filtersfile_checks", "-no-cleanup"]
},
{
"name": "Test TestS3MinioEdge: test_filtersfile_checks RemoteRemote",
"type": "go",
"request": "launch",
"mode": "test",
"program": "./cmd/bisync",
"args": ["-remote", "TestS3MinioEdge:", "-remote2", "TestS3MinioEdge:", "-case", "test_filtersfile_checks", "-no-cleanup"]
},
{
"name": "Test TestS3MinioEdge: test_ignorelistingchecksum LocalRemote",
"type": "go",
"request": "launch",
"mode": "test",
"program": "./cmd/bisync",
"args": ["-remote", "local", "-remote2", "TestS3MinioEdge:", "-case", "test_ignorelistingchecksum", "-no-cleanup"]
},
{
"name": "Test TestS3MinioEdge: test_ignorelistingchecksum RemoteLocal",
"type": "go",
"request": "launch",
"mode": "test",
"program": "./cmd/bisync",
"args": ["-remote", "TestS3MinioEdge:", "-remote2", "local", "-case", "test_ignorelistingchecksum", "-no-cleanup"]
},
{
"name": "Test TestS3MinioEdge: test_ignorelistingchecksum RemoteRemote",
"type": "go",
"request": "launch",
"mode": "test",
"program": "./cmd/bisync",
"args": ["-remote", "TestS3MinioEdge:", "-remote2", "TestS3MinioEdge:", "-case", "test_ignorelistingchecksum", "-no-cleanup"]
},
{
"name": "Test TestS3MinioEdge: test_max_delete_path1 LocalRemote",
"type": "go",
"request": "launch",
"mode": "test",
"program": "./cmd/bisync",
"args": ["-remote", "local", "-remote2", "TestS3MinioEdge:", "-case", "test_max_delete_path1", "-no-cleanup"]
},
{
"name": "Test TestS3MinioEdge: test_max_delete_path1 RemoteLocal",
"type": "go",
"request": "launch",
"mode": "test",
"program": "./cmd/bisync",
"args": ["-remote", "TestS3MinioEdge:", "-remote2", "local", "-case", "test_max_delete_path1", "-no-cleanup"]
},
{
"name": "Test TestS3MinioEdge: test_max_delete_path1 RemoteRemote",
"type": "go",
"request": "launch",
"mode": "test",
"program": "./cmd/bisync",
"args": ["-remote", "TestS3MinioEdge:", "-remote2", "TestS3MinioEdge:", "-case", "test_max_delete_path1", "-no-cleanup"]
},
{
"name": "Test TestS3MinioEdge: test_max_delete_path2_force LocalRemote",
"type": "go",
"request": "launch",
"mode": "test",
"program": "./cmd/bisync",
"args": ["-remote", "local", "-remote2", "TestS3MinioEdge:", "-case", "test_max_delete_path2_force", "-no-cleanup"]
},
{
"name": "Test TestS3MinioEdge: test_max_delete_path2_force RemoteLocal",
"type": "go",
"request": "launch",
"mode": "test",
"program": "./cmd/bisync",
"args": ["-remote", "TestS3MinioEdge:", "-remote2", "local", "-case", "test_max_delete_path2_force", "-no-cleanup"]
},
{
"name": "Test TestS3MinioEdge: test_max_delete_path2_force RemoteRemote",
"type": "go",
"request": "launch",
"mode": "test",
"program": "./cmd/bisync",
"args": ["-remote", "TestS3MinioEdge:", "-remote2", "TestS3MinioEdge:", "-case", "test_max_delete_path2_force", "-no-cleanup"]
},
{
"name": "Test TestS3MinioEdge: test_nomodtime LocalRemote",
"type": "go",
"request": "launch",
"mode": "test",
"program": "./cmd/bisync",
"args": ["-remote", "local", "-remote2", "TestS3MinioEdge:", "-case", "test_nomodtime", "-no-cleanup"]
},
{
"name": "Test TestS3MinioEdge: test_nomodtime RemoteLocal",
"type": "go",
"request": "launch",
"mode": "test",
"program": "./cmd/bisync",
"args": ["-remote", "TestS3MinioEdge:", "-remote2", "local", "-case", "test_nomodtime", "-no-cleanup"]
},
{
"name": "Test TestS3MinioEdge: test_nomodtime RemoteRemote",
"type": "go",
"request": "launch",
"mode": "test",
"program": "./cmd/bisync",
"args": ["-remote", "TestS3MinioEdge:", "-remote2", "TestS3MinioEdge:", "-case", "test_nomodtime", "-no-cleanup"]
},
{
"name": "Test TestS3MinioEdge: test_normalization LocalRemote",
"type": "go",
"request": "launch",
"mode": "test",
"program": "./cmd/bisync",
"args": ["-remote", "local", "-remote2", "TestS3MinioEdge:", "-case", "test_normalization", "-no-cleanup"]
},
{
"name": "Test TestS3MinioEdge: test_normalization RemoteLocal",
"type": "go",
"request": "launch",
"mode": "test",
"program": "./cmd/bisync",
"args": ["-remote", "TestS3MinioEdge:", "-remote2", "local", "-case", "test_normalization", "-no-cleanup"]
},
{
"name": "Test TestS3MinioEdge: test_normalization RemoteRemote",
"type": "go",
"request": "launch",
"mode": "test",
"program": "./cmd/bisync",
"args": ["-remote", "TestS3MinioEdge:", "-remote2", "TestS3MinioEdge:", "-case", "test_normalization", "-no-cleanup"]
},
{
"name": "Test TestS3MinioEdge: test_rclone_args LocalRemote",
"type": "go",
"request": "launch",
"mode": "test",
"program": "./cmd/bisync",
"args": ["-remote", "local", "-remote2", "TestS3MinioEdge:", "-case", "test_rclone_args", "-no-cleanup"]
},
{
"name": "Test TestS3MinioEdge: test_rclone_args RemoteLocal",
"type": "go",
"request": "launch",
"mode": "test",
"program": "./cmd/bisync",
"args": ["-remote", "TestS3MinioEdge:", "-remote2", "local", "-case", "test_rclone_args", "-no-cleanup"]
},
{
"name": "Test TestS3MinioEdge: test_rclone_args RemoteRemote",
"type": "go",
"request": "launch",
"mode": "test",
"program": "./cmd/bisync",
"args": ["-remote", "TestS3MinioEdge:", "-remote2", "TestS3MinioEdge:", "-case", "test_rclone_args", "-no-cleanup"]
},
{
"name": "Test TestS3MinioEdge: test_resolve LocalRemote",
"type": "go",
"request": "launch",
"mode": "test",
"program": "./cmd/bisync",
"args": ["-remote", "local", "-remote2", "TestS3MinioEdge:", "-case", "test_resolve", "-no-cleanup"]
},
{
"name": "Test TestS3MinioEdge: test_resolve RemoteLocal",
"type": "go",
"request": "launch",
"mode": "test",
"program": "./cmd/bisync",
"args": ["-remote", "TestS3MinioEdge:", "-remote2", "local", "-case", "test_resolve", "-no-cleanup"]
},
{
"name": "Test TestS3MinioEdge: test_resolve RemoteRemote",
"type": "go",
"request": "launch",
"mode": "test",
"program": "./cmd/bisync",
"args": ["-remote", "TestS3MinioEdge:", "-remote2", "TestS3MinioEdge:", "-case", "test_resolve", "-no-cleanup"]
},
{
"name": "Test TestS3MinioEdge: test_resync LocalRemote",
"type": "go",
"request": "launch",
"mode": "test",
"program": "./cmd/bisync",
"args": ["-remote", "local", "-remote2", "TestS3MinioEdge:", "-case", "test_resync", "-no-cleanup"]
},
{
"name": "Test TestS3MinioEdge: test_resync RemoteLocal",
"type": "go",
"request": "launch",
"mode": "test",
"program": "./cmd/bisync",
"args": ["-remote", "TestS3MinioEdge:", "-remote2", "local", "-case", "test_resync", "-no-cleanup"]
},
{
"name": "Test TestS3MinioEdge: test_resync RemoteRemote",
"type": "go",
"request": "launch",
"mode": "test",
"program": "./cmd/bisync",
"args": ["-remote", "TestS3MinioEdge:", "-remote2", "TestS3MinioEdge:", "-case", "test_resync", "-no-cleanup"]
},
{
"name": "Test TestS3MinioEdge: test_resync_modes LocalRemote",
"type": "go",
"request": "launch",
"mode": "test",
"program": "./cmd/bisync",
"args": ["-remote", "local", "-remote2", "TestS3MinioEdge:", "-case", "test_resync_modes", "-no-cleanup"]
},
{
"name": "Test TestS3MinioEdge: test_resync_modes RemoteLocal",
"type": "go",
"request": "launch",
"mode": "test",
"program": "./cmd/bisync",
"args": ["-remote", "TestS3MinioEdge:", "-remote2", "local", "-case", "test_resync_modes", "-no-cleanup"]
},
{
"name": "Test TestS3MinioEdge: test_resync_modes RemoteRemote",
"type": "go",
"request": "launch",
"mode": "test",
"program": "./cmd/bisync",
"args": ["-remote", "TestS3MinioEdge:", "-remote2", "TestS3MinioEdge:", "-case", "test_resync_modes", "-no-cleanup"]
},
{
"name": "Test TestS3MinioEdge: test_rmdirs LocalRemote",
"type": "go",
"request": "launch",
"mode": "test",
"program": "./cmd/bisync",
"args": ["-remote", "local", "-remote2", "TestS3MinioEdge:", "-case", "test_rmdirs", "-no-cleanup"]
},
{
"name": "Test TestS3MinioEdge: test_rmdirs RemoteLocal",
"type": "go",
"request": "launch",
"mode": "test",
"program": "./cmd/bisync",
"args": ["-remote", "TestS3MinioEdge:", "-remote2", "local", "-case", "test_rmdirs", "-no-cleanup"]
},
{
"name": "Test TestS3MinioEdge: test_rmdirs RemoteRemote",
"type": "go",
"request": "launch",
"mode": "test",
"program": "./cmd/bisync",
"args": ["-remote", "TestS3MinioEdge:", "-remote2", "TestS3MinioEdge:", "-case", "test_rmdirs", "-no-cleanup"]
},
{
"name": "Test TestS3MinioEdge: test_volatile LocalRemote",
"type": "go",
"request": "launch",
"mode": "test",
"program": "./cmd/bisync",
"args": ["-remote", "local", "-remote2", "TestS3MinioEdge:", "-case", "test_volatile", "-no-cleanup"]
},
{
"name": "Test TestS3MinioEdge: test_volatile RemoteLocal",
"type": "go",
"request": "launch",
"mode": "test",
"program": "./cmd/bisync",
"args": ["-remote", "TestS3MinioEdge:", "-remote2", "local", "-case", "test_volatile", "-no-cleanup"]
},
{
"name": "Test TestS3MinioEdge: test_volatile RemoteRemote",
"type": "go",
"request": "launch",
"mode": "test",
"program": "./cmd/bisync",
"args": ["-remote", "TestS3MinioEdge:", "-remote2", "TestS3MinioEdge:", "-case", "test_volatile", "-no-cleanup"]
},
{
"name": "Test TestS3Wasabi: test_all_changed LocalRemote",
"type": "go",
-29
View File
@@ -536,56 +536,27 @@ func (fsys *FS) Fsyncdir(path string, datasync bool, fh uint64) (errc int) {
return 0
}
// #9908: simulate macFUSE behaviour (discard setxattr calls) - otherwise Finder cannot copy files onto the mount
func shouldIgnoreAppleXattr(opt *mountlib.Options) bool {
if !opt.NoAppleXattr {
return false
}
if runtime.GOOS != "darwin" {
return false
}
// only flip the behaviour on FSKit
for _, o := range opt.ExtraOptions {
if strings.TrimSpace(o) == "backend=fskit" {
return true
}
}
return false
}
// Setxattr sets extended attributes.
func (fsys *FS) Setxattr(path string, name string, value []byte, flags int) (errc int) {
defer log.Trace(path, "name=%q, value=%q, flags=%d", name, value, flags)("errc=%d", &errc)
if shouldIgnoreAppleXattr(fsys.opt) && strings.HasPrefix(name, "com.apple.") {
return 0
}
return -fuse.ENOSYS
}
// Getxattr gets extended attributes.
func (fsys *FS) Getxattr(path string, name string) (errc int, value []byte) {
defer log.Trace(path, "name=%q", name)("errc=%d, value=%q", &errc, &value)
if shouldIgnoreAppleXattr(fsys.opt) && strings.HasPrefix(name, "com.apple.") {
return -fuse.ENOATTR, nil
}
return -fuse.ENOSYS, nil
}
// Removexattr removes extended attributes.
func (fsys *FS) Removexattr(path string, name string) (errc int) {
defer log.Trace(path, "name=%q", name)("errc=%d", &errc)
if shouldIgnoreAppleXattr(fsys.opt) && strings.HasPrefix(name, "com.apple.") {
return 0
}
return -fuse.ENOSYS
}
// Listxattr lists extended attributes.
func (fsys *FS) Listxattr(path string, fill func(name string) bool) (errc int) {
defer log.Trace(path, "fill=%p", fill)("errc=%d", &errc)
if shouldIgnoreAppleXattr(fsys.opt) {
return 0
}
return -fuse.ENOSYS
}
-4
View File
@@ -26,10 +26,6 @@ Note that |ls| and |lsl| recurse by default - use |--max-depth 1| to stop the re
The other list commands |lsd|,|lsf|,|lsjson| do not recurse by default -
use |-R| to make them recurse.
On the bucket-based remotes (e.g. s3, gcs, b2) a directory is a key prefix
rather than an object, so a listing without |-R| shows each prefix as one
directory entry and not the objects stored under it.
List commands prefer a recursive method that uses more memory but fewer
transactions by default. Use |--disable ListR| to suppress the behavior.
See [|--fast-list|](/docs/#fast-list) for more details.
+1 -6
View File
@@ -208,12 +208,7 @@ func doCall(ctx context.Context, path string, in rc.Params) (out rc.Params, err
}
_, out, err := jobs.NewJob(ctx, call.Fn, in)
if err != nil {
out, err = errorf(http.StatusInternalServerError, path, "loopback: call failed: %w", err)
var logsErr *rc.ErrorWithLogs
if errors.As(err, &logsErr) {
out["_logs"] = logsErr.Logs
}
return out, err
return errorf(http.StatusInternalServerError, path, "loopback: call failed: %w", err)
}
// Reshape (serialize then deserialize) the data so it is in the form expected
err = rc.Reshape(&out, out)
-4
View File
@@ -49,10 +49,6 @@ See the [rc documentation](/rc/) for more info on the rc flags.
rc.Opt.Files = args[0]
}
// Print the stats periodically if --stats is in use, as
// the serve and mount commands do
defer cmd.StartStats()()
s, err := rcserver.Start(context.Background(), &rc.Opt)
if err != nil {
fs.Fatalf(nil, "Failed to start remote control: %v", err)
+1 -7
View File
@@ -56,12 +56,6 @@ func TestInstallOnLinux(t *testing.T) {
testDir := t.TempDir()
path := filepath.Join(testDir, "rclone")
// Pin the running version so the checks below do not depend on
// whether this build happens to be the latest beta.
oldVersion := fs.Version
fs.Version = "v1.0.0"
t.Cleanup(func() { fs.Version = oldVersion })
regexVer := regexp.MustCompile(`v[0-9]\S+`)
betaVer, _, err := GetVersion(ctx, true, "")
@@ -77,7 +71,7 @@ func TestInstallOnLinux(t *testing.T) {
_ = os.Chmod(path, 0644)
}()
err = (InstallUpdate(ctx, &Options{Beta: true, Output: path}))
require.Error(t, err)
assert.Error(t, err)
assert.Contains(t, err.Error(), "run self-update as root")
// Must keep non-standard permissions
-3
View File
@@ -140,9 +140,6 @@ func (vol *Volume) restoreState(ctx context.Context, drv *Driver) error {
volOpt := vol.Options
volOpt["fs"] = vol.Fs
volOpt["type"] = vol.Type
// applyOptions consumes "path" into vol.Path rather than leaving it in
// vol.Options, so it must be fed back explicitly like fs and type.
volOpt["path"] = vol.Path
if err := vol.applyOptions(volOpt); err != nil {
return err
}
-99
View File
@@ -1,99 +0,0 @@
package docker
import (
"context"
"encoding/json"
"fmt"
"os"
"path/filepath"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
_ "github.com/rclone/rclone/backend/local"
)
// persistedCopy returns vol as it comes back from the plugin state file:
// only the exported fields survive being marshalled and reloaded.
func persistedCopy(t *testing.T, vol *Volume) *Volume {
t.Helper()
vol.prepareState()
data, err := json.Marshal(vol)
require.NoError(t, err)
restored := &Volume{}
require.NoError(t, json.Unmarshal(data, restored))
return restored
}
// TestRestoreStatePath checks that the on-remote path of a volume survives
// being reloaded from the plugin state file, for each of the option
// combinations that can carry one.
func TestRestoreStatePath(t *testing.T) {
ctx := context.Background()
for _, test := range []struct {
name string
volOpt VolOpts
fsString string
}{{
name: "type and path",
volOpt: VolOpts{"type": "local", "path": "/tmp/path"},
fsString: ":local:/tmp/path",
}, {
name: "remote only",
volOpt: VolOpts{"remote": "/tmp/remote"},
fsString: ":local:/tmp/remote",
}, {
// an explicit path overrides the path of the connection string,
// and must keep doing so after a restart
name: "remote and path",
volOpt: VolOpts{"remote": "/tmp/remote", "path": "/tmp/path"},
fsString: ":local:/tmp/path",
}, {
name: "type only",
volOpt: VolOpts{"type": "local"},
fsString: ":local:",
}} {
t.Run(test.name, func(t *testing.T) {
drv := &Driver{
root: t.TempDir(),
volumes: map[string]*Volume{},
dummy: true,
}
vol, err := newVolume(ctx, "vol1", test.volOpt, drv)
require.NoError(t, err)
require.Equal(t, test.fsString, vol.fsString)
restored := persistedCopy(t, vol)
require.NoError(t, restored.restoreState(ctx, drv))
assert.Equal(t, test.fsString, restored.fsString)
assert.Equal(t, vol.Path, restored.Path)
})
}
}
// TestDriverRestoreStatePath checks the same through the real state file: a
// volume persisted by a previous plugin instance is reloaded with its path.
func TestDriverRestoreStatePath(t *testing.T) {
ctx := context.Background()
testDir := t.TempDir()
state := fmt.Sprintf(`[{"name":"vol1","mountpoint":%q,"created":%q,"fs":"","type":"local","path":"/tmp/path","options":{},"mounts":[]}]`,
filepath.Join(testDir, "vol1"), time.Now().Format(time.RFC3339))
statePath := filepath.Join(testDir, stateFile)
require.NoError(t, os.WriteFile(statePath, []byte(state), 0600))
drv := &Driver{
root: testDir,
statePath: statePath,
volumes: map[string]*Volume{},
dummy: true,
}
require.NoError(t, drv.restoreState(ctx))
vol, err := drv.getVolume("vol1")
require.NoError(t, err)
assert.Equal(t, ":local:/tmp/path", vol.fsString)
assert.Equal(t, "/tmp/path", vol.Path)
}
+9 -50
View File
@@ -13,7 +13,6 @@ import (
"path"
"regexp"
"strings"
"sync"
"time"
"github.com/go-chi/chi/v5"
@@ -284,28 +283,19 @@ func checkPrivate(next http.Handler) http.Handler {
})
}
// uploadLock serializes uploads to one remote.
type uploadLock struct {
uploadingMu sync.Mutex
refs int // protected by server.uploadLocksMu
}
// server contains everything to run the server
type server struct {
server *libhttp.Server
f fs.Fs
cache *cache
opt Options
uploadLocksMu sync.Mutex
uploadLocks map[string]*uploadLock
server *libhttp.Server
f fs.Fs
cache *cache
opt Options
}
func newServer(ctx context.Context, f fs.Fs, opt *Options) (s *server, err error) {
s = &server{
f: f,
cache: newCache(opt.CacheObjects),
opt: *opt,
uploadLocks: make(map[string]*uploadLock),
f: f,
cache: newCache(opt.CacheObjects),
opt: *opt,
}
// Don't bind any HTTP listeners if running with --stdio
if opt.Stdio {
@@ -323,30 +313,6 @@ func newServer(ctx context.Context, f fs.Fs, opt *Options) (s *server, err error
return s, nil
}
// lockUpload locks uploads to remote and returns its unlock function.
func (s *server) lockUpload(remote string) func() {
s.uploadLocksMu.Lock()
lock := s.uploadLocks[remote]
if lock == nil {
lock = new(uploadLock)
s.uploadLocks[remote] = lock
}
lock.refs++
s.uploadLocksMu.Unlock()
lock.uploadingMu.Lock()
return func() {
lock.uploadingMu.Unlock()
s.uploadLocksMu.Lock()
lock.refs--
if lock.refs == 0 {
delete(s.uploadLocks, remote)
}
s.uploadLocksMu.Unlock()
}
}
// Serve restic until the server is shutdown
func (s *server) Serve() error {
s.server.Serve()
@@ -456,19 +422,12 @@ func (s *server) postObject(w http.ResponseWriter, r *http.Request) {
return
}
if s.opt.AppendOnly {
unlock := s.lockUpload(remote)
defer unlock()
// Only a definitive not-found result permits creating the object.
// make sure the file does not exist yet
_, err := s.newObject(r.Context(), remote)
if err == nil {
fs.Errorf(remote, "Post request: file already exists, refusing to overwrite in append-only mode")
http.Error(w, http.StatusText(http.StatusForbidden), http.StatusForbidden)
return
}
if !errors.Is(err, fs.ErrorObjectNotFound) {
fs.Errorf(remote, "Post request: failed to check whether file exists: %v", err)
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
}
}
@@ -4,17 +4,13 @@ import (
"context"
"crypto/rand"
"encoding/hex"
"errors"
"io"
"net/http"
"net/http/httptest"
"strings"
"testing"
"github.com/rclone/rclone/cmd"
"github.com/rclone/rclone/fs"
"github.com/rclone/rclone/fs/config/configfile"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
@@ -139,60 +135,3 @@ func TestResticHandler(t *testing.T) {
})
}
}
func TestAppendOnlyFailsClosedOnLookupError(t *testing.T) {
ctx := context.Background()
configfile.Install()
underlying := cmd.NewFsSrc([]string{t.TempDir()})
f := &newObjectErrorFs{
Fs: underlying,
err: errors.New("lookup failed"),
}
opt := newOpt()
opt.AppendOnly = true
s, err := newServer(ctx, f, &opt)
require.NoError(t, err)
req := newRequest(t, "POST", "/config", strings.NewReader("replacement"))
checkRequest(t, s.server.Router().ServeHTTP, req, []wantFunc{wantCode(http.StatusInternalServerError)})
_, err = underlying.NewObject(ctx, "config")
assert.ErrorIs(t, err, fs.ErrorObjectNotFound)
}
func TestAppendOnlyConcurrentUploads(t *testing.T) {
configfile.Install()
opt := newOpt()
opt.AppendOnly = true
f := cmd.NewFsSrc([]string{t.TempDir()})
s, err := newServer(context.Background(), f, &opt)
require.NoError(t, err)
handler := s.server.Router().ServeHTTP
const uploads = 10
start := make(chan struct{})
results := make(chan int, uploads)
for range uploads {
go func() {
req := newRequest(t, "POST", "/config", strings.NewReader("config data"))
recorder := httptest.NewRecorder()
<-start
handler(recorder, req)
results <- recorder.Code
}()
}
close(start)
succeeded := 0
for range uploads {
if code := <-results; code == http.StatusOK {
succeeded++
} else {
assert.Equal(t, http.StatusForbidden, code)
}
}
assert.Equal(t, 1, succeeded)
checkRequest(t, handler, newRequest(t, "GET", "/config", nil),
[]wantFunc{wantCode(http.StatusOK), wantBody("config data")})
}
+3 -3
View File
@@ -26,10 +26,10 @@ func (l logger) Print(level gofakes3.LogLevel, v ...any) {
default:
fallthrough
case gofakes3.LogErr:
fs.Errorf("serve s3", "%s", s)
fs.Errorf("serve s3", s)
case gofakes3.LogWarn:
fs.Infof("serve s3", "%s", s)
fs.Infof("serve s3", s)
case gofakes3.LogInfo:
fs.Debugf("serve s3", "%s", s)
fs.Debugf("serve s3", s)
}
}
+10 -24
View File
@@ -26,19 +26,10 @@ var (
const (
defaultLayout string = "060102"
layoutDate string = "2006-01-02"
layoutDateWithTime string = "2006-01-02T15:04:05"
layoutDateWithTimeNano string = "2006-01-02T15:04:05.999999999"
)
var timeLayouts = []string{
time.RFC3339Nano,
layoutDateWithTimeNano,
layoutDateWithTime,
layoutDate,
defaultLayout,
}
func init() {
cmd.Root.AddCommand(commandDefinition)
cmdFlags := commandDefinition.Flags()
@@ -65,11 +56,9 @@ This will touch ` + "`--transfers`" + ` files concurrently.
If ` + "`--timestamp`" + ` is used then sets the modification time to that
time instead of the current time. Times may be specified as one of:
- 'YYMMDD' - e.g. 171030
- 'YYYY-MM-DD' - e.g. 2006-01-02
- 'YYMMDD' - e.g. 17.10.30
- 'YYYY-MM-DDTHH:MM:SS' - e.g. 2006-01-02T15:04:05
- 'YYYY-MM-DDTHH:MM:SS.SSS' - e.g. 2006-01-02T15:04:05.123456789
- 'YYYY-MM-DDTHH:MM:SSZ' - e.g. 2006-01-02T15:04:05Z
Note that value of ` + "`--timestamp`" + ` is in UTC. If you want local time
then add the ` + "`--localtime`" + ` flag.
@@ -111,19 +100,16 @@ func newFsDst(args []string) (f fs.Fs, remote string) {
// parseTimeArgument parses a timestamp string according to specific layouts
func parseTimeArgument(timeString string) (time.Time, error) {
var err error
for _, layout := range timeLayouts {
var t time.Time
if localTime {
t, err = time.ParseInLocation(layout, timeString, time.Local)
} else {
t, err = time.Parse(layout, timeString)
}
if err == nil {
return t, nil
}
layout := defaultLayout
if len(timeString) == len(layoutDateWithTime) {
layout = layoutDateWithTime
} else if len(timeString) > len(layoutDateWithTime) {
layout = layoutDateWithTimeNano
}
return time.Time{}, err
if localTime {
return time.ParseInLocation(layout, timeString, time.Local)
}
return time.Parse(layout, timeString)
}
// timeOfTouch returns the time value set on files
-27
View File
@@ -3,7 +3,6 @@ package touch
import (
"context"
"testing"
"time"
_ "github.com/rclone/rclone/backend/local"
"github.com/rclone/rclone/fs"
@@ -22,32 +21,6 @@ func checkFile(t *testing.T, r fs.Fs, path string, content string) {
fstest.CheckItems(t, r, file1)
}
func TestParseTimeArgument(t *testing.T) {
oldLocalTime := localTime
localTime = false
t.Cleanup(func() {
localTime = oldLocalTime
})
for _, test := range []struct {
in string
want time.Time
}{
{"171030", fstest.Time("2017-10-30T00:00:00Z")},
{"2024-05-01", fstest.Time("2024-05-01T00:00:00Z")},
{"2024-05-01T12:00:00", fstest.Time("2024-05-01T12:00:00Z")},
{"2024-05-01T12:00:00.123456789", fstest.Time("2024-05-01T12:00:00.123456789Z")},
{"2024-05-01T12:00:00Z", fstest.Time("2024-05-01T12:00:00Z")},
{"2024-05-01T12:00:00.123456789Z", fstest.Time("2024-05-01T12:00:00.123456789Z")},
} {
t.Run(test.in, func(t *testing.T) {
got, err := parseTimeArgument(test.in)
require.NoError(t, err)
require.Equal(t, test.want, got)
})
}
}
// TestMain drives the tests
func TestMain(m *testing.M) {
fstest.TestMain(m)
-570
View File
@@ -1,570 +0,0 @@
---
title: "WebDAV"
description: "Rclone docs for WebDAV"
versionIntroduced: "v1.39"
---
# WebDAV
Paths are specified as `remote:path`
Paths may be as deep as required, e.g. `remote:directory/subdirectory`.
## Configuration
To configure the WebDAV remote you will need to have a URL for it, and
a username and password. If you know what kind of system you are
connecting to then rclone can enable extra features.
Here is an example of how to make a remote called `remote`. First run:
```console
rclone config
```
This will guide you through an interactive setup process:
```text
No remotes found, make a new one?
n) New remote
s) Set configuration password
q) Quit config
n/s/q> n
name> remote
Type of storage to configure.
Choose a number from below, or type in your own value
[snip]
XX / WebDAV
\ "webdav"
[snip]
Storage> webdav
URL of http host to connect to
Choose a number from below, or type in your own value
1 / Connect to example.com
\ "https://example.com"
url> https://example.com/remote.php/webdav/
Name of the WebDAV site/service/software you are using
Choose a number from below, or type in your own value
1 / Fastmail Files
\ (fastmail)
2 / Nextcloud
\ (nextcloud)
3 / Owncloud
\ (owncloud)
4 / Sharepoint Online, authenticated by Microsoft account
\ (sharepoint)
5 / Sharepoint with NTLM authentication, usually self-hosted or on-premises
\ (sharepoint-ntlm)
6 / rclone WebDAV server to serve a remote over HTTP via the WebDAV protocol
\ (rclone)
7 / Other site/service or software
\ (other)
vendor> 2
User name
user> user
Password.
y) Yes type in my own password
g) Generate random password
n) No leave this optional password blank
y/g/n> y
Enter the password:
password:
Confirm the password:
password:
Bearer token instead of user/pass (e.g. a Macaroon)
bearer_token>
Remote config
Configuration complete.
Options:
- type: webdav
- url: https://example.com/remote.php/webdav/
- vendor: nextcloud
- user: user
- pass: *** ENCRYPTED ***
- bearer_token:
Keep this "remote" remote?
y) Yes this is OK
e) Edit this remote
d) Delete this remote
y/e/d> y
```
Once configured you can then use `rclone` like this (replace `remote` with the
name you gave your remote):
List directories in top level of your WebDAV
```console
rclone lsd remote:
```
List all the files in your WebDAV
```console
rclone ls remote:
```
To copy a local directory to an WebDAV directory called backup
```console
rclone copy /home/source remote:backup
```
### Modification times and hashes
Plain WebDAV does not support modified times. However when used with
Fastmail Files, ownCloud or Nextcloud rclone will support modified times.
Likewise plain WebDAV does not support hashes, however when used with
Fastmail Files, ownCloud or Nextcloud rclone will support SHA1 and MD5 hashes.
Depending on the exact version of ownCloud or Nextcloud hashes may
appear on all objects, or only on objects which had a hash uploaded
with them. With Nextcloud, rclone asks the server to calculate the SHA1
of uploads which had no hash to send, such as streamed uploads, and
after setting the modification time, which discards the stored hash.
<!-- autogenerated options start - DO NOT EDIT - instead edit fs.RegInfo in backend/webdav/webdav.go and run make backenddocs to verify --> <!-- markdownlint-disable-line line-length -->
### Standard options
Here are the Standard options specific to webdav (WebDAV).
#### --webdav-url
URL of http host to connect to.
E.g. https://example.com.
Properties:
- Config: url
- Env Var: RCLONE_WEBDAV_URL
- Type: string
- Required: true
#### --webdav-vendor
Name of the WebDAV site/service/software you are using.
Properties:
- Config: vendor
- Env Var: RCLONE_WEBDAV_VENDOR
- Type: string
- Required: false
- Examples:
- "fastmail"
- Fastmail Files
- "nextcloud"
- Nextcloud
- "owncloud"
- Owncloud 10 PHP based WebDAV server
- "infinitescale"
- ownCloud Infinite Scale
- "sharepoint"
- Sharepoint Online, authenticated by Microsoft account
- "sharepoint-ntlm"
- Sharepoint with NTLM authentication, usually self-hosted or on-premises
- "rclone"
- rclone WebDAV server to serve a remote over HTTP via the WebDAV protocol
- "other"
- Other site/service or software
#### --webdav-user
User name.
In case NTLM authentication is used, the username should be in the format 'Domain\User'.
Properties:
- Config: user
- Env Var: RCLONE_WEBDAV_USER
- Type: string
- Required: false
#### --webdav-pass
Password.
**NB** Input to this must be obscured - see [rclone obscure](/commands/rclone_obscure/).
Properties:
- Config: pass
- Env Var: RCLONE_WEBDAV_PASS
- Type: string
- Required: false
#### --webdav-bearer-token
Bearer token instead of user/pass (e.g. a Macaroon).
Properties:
- Config: bearer_token
- Env Var: RCLONE_WEBDAV_BEARER_TOKEN
- Type: string
- Required: false
### Advanced options
Here are the Advanced options specific to webdav (WebDAV).
#### --webdav-bearer-token-command
Command to run to get a bearer token.
Properties:
- Config: bearer_token_command
- Env Var: RCLONE_WEBDAV_BEARER_TOKEN_COMMAND
- Type: string
- Required: false
#### --webdav-encoding
The encoding for the backend.
See the [encoding section in the overview](/overview/#encoding) for more info.
Default encoding is Slash,LtGt,DoubleQuote,Colon,Question,Asterisk,Pipe,Hash,Percent,BackSlash,Del,Ctl,LeftSpace,LeftTilde,RightSpace,RightPeriod,InvalidUtf8 for sharepoint-ntlm or identity otherwise.
Properties:
- Config: encoding
- Env Var: RCLONE_WEBDAV_ENCODING
- Type: string
- Required: false
#### --webdav-headers
Set HTTP headers for all transactions.
Use this to set additional HTTP headers for all transactions
The input format is comma separated list of key,value pairs. Standard
[CSV encoding](https://godoc.org/encoding/csv) may be used.
For example, to set a Cookie use 'Cookie,name=value', or '"Cookie","name=value"'.
You can set multiple headers, e.g. '"Cookie","name=value","Authorization","xxx"'.
Properties:
- Config: headers
- Env Var: RCLONE_WEBDAV_HEADERS
- Type: CommaSepList
- Default:
#### --webdav-pacer-min-sleep
Minimum time to sleep between API calls.
Properties:
- Config: pacer_min_sleep
- Env Var: RCLONE_WEBDAV_PACER_MIN_SLEEP
- Type: Duration
- Default: 10ms
#### --webdav-nextcloud-chunk-size
Nextcloud upload chunk size.
We recommend configuring your NextCloud instance to increase the max chunk size to 1 GB for better upload performances.
See https://docs.nextcloud.com/server/latest/admin_manual/configuration_files/big_file_upload_configuration.html#adjust-chunk-size-on-nextcloud-side
Set to 0 to disable chunked uploading.
Properties:
- Config: nextcloud_chunk_size
- Env Var: RCLONE_WEBDAV_NEXTCLOUD_CHUNK_SIZE
- Type: SizeSuffix
- Default: 10Mi
#### --webdav-owncloud-exclude-shares
Exclude ownCloud shares
Properties:
- Config: owncloud_exclude_shares
- Env Var: RCLONE_WEBDAV_OWNCLOUD_EXCLUDE_SHARES
- Type: bool
- Default: false
#### --webdav-owncloud-exclude-mounts
Exclude ownCloud mounted storages
Properties:
- Config: owncloud_exclude_mounts
- Env Var: RCLONE_WEBDAV_OWNCLOUD_EXCLUDE_MOUNTS
- Type: bool
- Default: false
#### --webdav-unix-socket
Path to a unix domain socket to dial to, instead of opening a TCP connection directly
Properties:
- Config: unix_socket
- Env Var: RCLONE_WEBDAV_UNIX_SOCKET
- Type: string
- Required: false
#### --webdav-auth-redirect
Preserve authentication on redirect.
If the server redirects rclone to a new domain when it is trying to
read a file then normally rclone will drop the Authorization: header
from the request.
This is standard security practice to avoid sending your credentials
to an unknown webserver.
However this is desirable in some circumstances. If you are getting
an error like "401 Unauthorized" when rclone is attempting to read
files from the webdav server then you can try this option.
Note that enabling this also permits sending your credentials over a
plaintext HTTP connection if the server redirects from HTTPS to HTTP,
which rclone otherwise refuses to do.
Properties:
- Config: auth_redirect
- Env Var: RCLONE_WEBDAV_AUTH_REDIRECT
- Type: bool
- Default: false
#### --webdav-description
Description of the remote.
Properties:
- Config: description
- Env Var: RCLONE_WEBDAV_DESCRIPTION
- Type: string
- Required: false
<!-- autogenerated options stop -->
## Provider notes
See below for notes on specific providers.
### Fastmail Files
Use `https://webdav.fastmail.com/` or a subdirectory as the URL,
and your Fastmail email `username@domain.tld` as the username.
Follow [this documentation](https://www.fastmail.help/hc/en-us/articles/360058752854-App-passwords)
to create an app password with access to `Files (WebDAV)` and use
this as the password.
Fastmail supports modified times using the `X-OC-Mtime` header.
### ownCloud
Click on the settings cog in the bottom right of the page and this
will show the WebDAV URL that rclone needs in the config step. It
will look something like `https://example.com/remote.php/webdav/`.
ownCloud supports modified times using the `X-OC-Mtime` header.
### Nextcloud
This is configured in an identical way to ownCloud. Note that
Nextcloud initially did not support streaming of files (`rcat`) whereas
ownCloud did, but [this](https://github.com/nextcloud/nextcloud-snap/issues/365)
seems to be fixed as of 2020-11-27 (tested with rclone v1.53.1 and Nextcloud
Server v19).
### ownCloud Infinite Scale
The WebDAV URL for Infinite Scale can be found in the details panel of
any space in Infinite Scale, if the display was enabled in the personal
settings of the user through a checkbox there.
Infinite Scale works with the chunking [tus](https://tus.io) upload protocol.
The chunk size is currently fixed 10 MB.
### Sharepoint Online
Rclone can be used with Sharepoint provided by OneDrive for Business
or Office365 Education Accounts.
This feature is only needed for a few of these Accounts,
mostly Office365 Education ones. These accounts are sometimes not
verified by the domain owner [github#1975](https://github.com/rclone/rclone/issues/1975)
This means that these accounts can't be added using the official
API (other Accounts should work with the "onedrive" option). However,
it is possible to access them using webdav.
To use a sharepoint remote with rclone, add it like this:
First, you need to get your remote's URL:
- Go [here](https://onedrive.live.com/about/en-us/signin/)
to open your OneDrive or to sign in
- Now take a look at your address bar, the URL should look like this:
`https://[YOUR-DOMAIN]-my.sharepoint.com/personal/[YOUR-EMAIL]/_layouts/15/onedrive.aspx`
You'll only need this URL up to the email address. After that, you'll
most likely want to add "/Documents". That subdirectory contains
the actual data stored on your OneDrive.
Add the remote to rclone like this:
Configure the `url` as `https://[YOUR-DOMAIN]-my.sharepoint.com/personal/[YOUR-EMAIL]/Documents`
and use your normal account email and password for `user` and `pass`.
If you have 2FA enabled, you have to generate an app password.
Set the `vendor` to `sharepoint`.
Your config file should look like this:
```ini
[sharepoint]
type = webdav
url = https://[YOUR-DOMAIN]-my.sharepoint.com/personal/[YOUR-EMAIL]/Documents
vendor = sharepoint
user = YourEmailAddress
pass = encryptedpassword
```
### Sharepoint with NTLM Authentication
Use this option in case your (hosted) Sharepoint is not tied to OneDrive
accounts and uses NTLM authentication.
To get the `url` configuration, similarly to the above, first navigate to the
desired directory in your browser to get the URL, then strip everything after
the name of the opened directory.
Example:
If the URL is:
<https://example.sharepoint.com/sites/12345/Documents/Forms/AllItems.aspx>
The configuration to use would be:
<https://example.sharepoint.com/sites/12345/Documents>
Set the `vendor` to `sharepoint-ntlm`.
NTLM uses domain and user name combination for authentication,
set `user` to `DOMAIN\username`.
Your config file should look like this:
```ini
[sharepoint]
type = webdav
url = https://[YOUR-DOMAIN]/some-path-to/Documents
vendor = sharepoint-ntlm
user = DOMAIN\user
pass = encryptedpassword
```
#### Required Flags for SharePoint
As SharePoint does some special things with uploaded documents, you won't be
able to use the documents size or the documents hash to compare if a file has
been changed since the upload / which file is newer.
For Rclone calls copying files (especially Office files such as .docx, .xlsx, etc.)
from/to SharePoint (like copy, sync, etc.), you should append these flags to ensure
Rclone uses the "Last Modified" datetime property to compare your documents:
```text
--ignore-size --ignore-checksum --update
```
## Rclone
Use this option if you are hosting remotes over WebDAV provided by rclone.
Read [rclone serve webdav](commands/rclone_serve_webdav/) for more details.
rclone serve supports modified times using the `X-OC-Mtime` header.
### dCache
dCache is a storage system that supports many protocols and
authentication/authorisation schemes. For WebDAV clients, it allows
users to authenticate with username and password (BASIC), X.509,
Kerberos, and various bearer tokens, including
[Macaroons](https://www.dcache.org/manuals/workshop-2017-05-29-Umea/000-Final/anupam_macaroons_v02.pdf)
and [OpenID-Connect](https://en.wikipedia.org/wiki/OpenID_Connect)
access tokens.
Configure as normal using the `other` type. Don't enter a username or
password, instead enter your Macaroon as the `bearer_token`.
The config will end up looking something like this.
```ini
[dcache]
type = webdav
url = https://dcache...
vendor = other
user =
pass =
bearer_token = your-macaroon
```
There is a [script](https://github.com/sara-nl/GridScripts/blob/master/get-macaroon)
that obtains a Macaroon from a dCache WebDAV endpoint, and creates an rclone config
file.
Macaroons may also be obtained from the dCacheView
web-browser/JavaScript client that comes with dCache.
### OpenID-Connect
dCache also supports authenticating with OpenID-Connect access tokens.
OpenID-Connect is a protocol (based on OAuth 2.0) that allows services
to identify users who have authenticated with some central service.
Support for OpenID-Connect in rclone is currently achieved using
another software package called
[oidc-agent](https://github.com/indigo-dc/oidc-agent). This is a
command-line tool that facilitates obtaining an access token. Once
installed and configured, an access token is obtained by running the
`oidc-token` command. The following example shows a (shortened)
access token obtained from the *XDC* OIDC Provider.
```text
paul@celebrimbor:~$ oidc-token XDC
eyJraWQ[...]QFXDt0
paul@celebrimbor:~$
```
**Note** Before the `oidc-token` command will work, the refresh token
must be loaded into the oidc agent. This is done with the `oidc-add`
command (e.g., `oidc-add XDC`). This is typically done once per login
session. Full details on this and how to register oidc-agent with
your OIDC Provider are provided in the [oidc-agent
documentation](https://indigo-dc.gitbooks.io/oidc-agent/).
The rclone `bearer_token_command` configuration option is used to
fetch the access token from oidc-agent.
Configure as a normal WebDAV endpoint, using the 'other' vendor,
leaving the username and password empty. When prompted, choose to
edit the advanced config and enter the command to get a bearer token
(e.g., `oidc-agent XDC`).
The following example config shows a WebDAV endpoint that uses
oidc-agent to supply an access token from the *XDC* OIDC Provider.
```ini
[dcache]
type = webdav
url = https://dcache.example.org/
vendor = other
bearer_token_command = oidc-token XDC
```
-21
View File
@@ -1225,24 +1225,3 @@ put them back in again. -->
- PSR94 <88868390+PSR94@users.noreply.github.com>
- Shane McCarron <shane.mccarron@corvexconnect.com>
- Dhevenddra K G <121691114+Dhevenddra@users.noreply.github.com>
- Vaibhav Mashal <110161673+vaibhavmashal@users.noreply.github.com>
- Murat Topcu <murat-topcu@outlook.com>
- tomaszni <tomaszni@users.noreply.github.com>
- eliotee <17210244+eliotee@users.noreply.github.com>
- Aditya <f20220497@goa.bits-pilani.ac.in>
- Nicholas Velten <nikvelten@gmail.com>
- youdie006 <xncb135@korea.ac.kr>
- subomi <86053854+ubmids@users.noreply.github.com>
- Can Arslan <138895927+mc2rcanarslan@users.noreply.github.com>
- Can Arslan <carslan@viyaenv.com>
- ZRHann <2829442630@qq.com>
- enkvadrat <123565769+enkvadrat@users.noreply.github.com>
- Vladimir Babin <vovababin@gmail.com>
- Eugene <inbox@null.page>
- Kunpeng Xie <68572236+pentaoa@users.noreply.github.com>
- foecmke <221832573+foecmke@users.noreply.github.com>
- Vasek Sraier <git@vakabus.cz>
- Kalin Stoyanov <kalin.stoyanov@kiteworks.com>
- NytePlus <nyte_plus@sjtu.edu.cn>
- Jeremy Schoemaker <jeremy@shoemoney.com>
- solunolab <solunolab@outlook.com>
+3 -2
View File
@@ -169,8 +169,9 @@ to load your computer, etc. The default of `--transfers 4` is
definitely too low for Backblaze B2 though.
Note that uploading big files (bigger than 200 MiB by default) will use
a 96 MiB RAM buffer by default. There can be at most `--transfers` of
these in use at any moment, so this sets the upper limit on the memory
`--b2-upload-concurrency` (8 by default) buffers of `--b2-chunk-size`
(16 MiB by default) each. There can be at most `--transfers` files
uploading at any moment, so this sets the upper limit on the memory
used.
### Versions
+1 -1
View File
@@ -323,7 +323,7 @@ Time stamps and file contents for `RCLONE_TEST` files are not important, just
the names and locations. If you have symbolic links in your sync tree it is
recommended to place `RCLONE_TEST` files in the linked-to directory tree to
protect against bisync assuming a bunch of deleted files if the linked-to tree
should not be accessible. See also the [--check-filename](#check-filename) flag.
should not be accessible. See also the [--check-filename](--check-filename) flag.
### --check-filename
+1 -3
View File
@@ -24,11 +24,9 @@ This will touch `--transfers` files concurrently.
If `--timestamp` is used then sets the modification time to that
time instead of the current time. Times may be specified as one of:
- 'YYMMDD' - e.g. 171030
- 'YYYY-MM-DD' - e.g. 2006-01-02
- 'YYMMDD' - e.g. 17.10.30
- 'YYYY-MM-DDTHH:MM:SS' - e.g. 2006-01-02T15:04:05
- 'YYYY-MM-DDTHH:MM:SS.SSS' - e.g. 2006-01-02T15:04:05.123456789
- 'YYYY-MM-DDTHH:MM:SSZ' - e.g. 2006-01-02T15:04:05Z
Note that value of `--timestamp` is in UTC. If you want local time
then add the `--localtime` flag.
+3 -34
View File
@@ -1725,32 +1725,6 @@ will only work well for the bucket based backends (eg s3, b2,
azureblob, swift) but these are the only backends likely to have
millions of entries in a directory.
### --log-buffer-size SizeSuffix
Keep this much of the most recent logs in memory so that they can be
read with the rc call [core/log](/rc/#core-log) or returned from rc
calls with the [_logs](/rc/#logs) parameter. For example
`--log-buffer-size 1M`.
When the log buffer is full the oldest log entries are dropped, and
making it smaller keeps the most recent entries. Note that when a
client is polling the rc the calls it makes are logged too, so size
this for the poll rate as well as the amount of data being
transferred, or turn the logging of the calls off with
[--rc-log-calls=false](/rc/#--rc-log-calls).
This is disabled by default (`--log-buffer-size 0`). Enabling it
causes every log entry to be formatted as JSON as well as its normal
format which will use a little more CPU.
Note that the log buffer only contains logs at the current
`--log-level`.
**Warning**: anyone who can authenticate to the rc can read the log
buffer, including logs made before they connected. If you use `--dump
auth` or `--dump bodies` then the log buffer will contain credentials
and file contents.
### --log-file string
Log all of rclone's output to a file. This is not active by default.
@@ -1904,10 +1878,7 @@ here for clarity.
Completed data transfer logs will have extra `size` information. Logs
which are about a particular object will have `object` and
`objectType` fields also. Logs which rclone can attribute to the rc job which
made them will have `jobid` and `group` fields with the ID of the job
and the name of its stats group. Note that the text log format has no
equivalent of these fields.
`objectType` fields also.
```json
{
@@ -2483,9 +2454,8 @@ setting the config password for the first time.
The argument to this should be a command with a space separated list
of arguments. If one of the arguments has a space in then enclose it
in `"`, if you want a literal `"` in an argument then enclose the
argument in `"` and double the `"`. This includes the command itself:
if the path to the executable contains a space, it must be quoted too.
See [CSV encoding](https://godoc.org/encoding/csv) for more info.
argument in `"` and double the `"`. See [CSV encoding](https://godoc.org/encoding/csv)
for more info.
Eg
@@ -2493,7 +2463,6 @@ Eg
--password-command "echo hello"
--password-command 'echo "hello with space"'
--password-command 'echo "hello with ""quotes"" and space"'
--password-command '"/path with a space/get-password.sh"'
```
Note that when changing the configuration password the environment
+3
View File
@@ -9,6 +9,9 @@ type: page
Rclone is single executable (`rclone`, or `rclone.exe` on Windows) that you can
simply download as a zip archive and extract into a location of your choosing.
See the [install](https://rclone.org/install/) documentation for more details.
We also offer a secure [enterprise-grade, zero CVE docker
image](https://securebuild.com/images/rclone) through our partner
[SecureBuild](https://securebuild.com/blog/introducing-securebuild).
## Release {{% version %}} OS requirements {#osrequirements}
+6
View File
@@ -261,6 +261,12 @@ package is here.
The rclone developers maintain a [docker image for rclone](https://hub.docker.com/r/rclone/rclone).
**Note:** We also now offer a paid version of rclone with
enterprise-grade security and zero CVEs through our partner
[SecureBuild](https://securebuild.com/blog/introducing-securebuild).
If you are interested, check out their website and the [Rclone
SecureBuild Image](https://securebuild.com/images/rclone).
These images are built as part of the release process based on a
minimal Alpine Linux.
-137
View File
@@ -210,24 +210,6 @@ Expire finished async jobs older than DURATION (default 60s).
Interval duration to check for expired async jobs (default 10s).
### --rc-log-calls
By default rclone logs each rc call and its reply at `DEBUG` level.
A client which reads the logs over the rc, with
[core/events](#core-events) or [core/log](#core-log), sees the logs of
its own calls this way, which can drown out everything else. Set this
to false to stop rclone logging the calls.
This can be changed while rclone is running with
[options/set](#options-set):
```console
$ rclone rc options/set --json '{"rc": {"LogCalls": false}}'
```
Default On.
### --rc-no-auth
By default rclone will require authorisation to have been set up on
@@ -580,125 +562,6 @@ $ rclone rc --json '{ "group": "job/1" }' core/stats
}
```
### Returning the logs of a call with _logs = true {#logs}
If `_logs` is set then the logs made while the call was running will
be returned along with its result. This needs the log buffer to be
enabled with [--log-buffer-size](/docs/#log-buffer-size-sizesuffix)
otherwise the call will return an error.
`_logs` can be set to `true` to return all the logs, or to a log level
(e.g. `"INFO"` or `"ERROR"`) to return only the logs at that level or
more severe.
It can also be set to an object to control what is returned:
- `level` - only return the logs at this level or more severe - optional
- `unattributed` - set this to `false` to leave out the logs which
aren't attributed to a job - optional, defaults to `true`
```console
$ rclone rc sync/copy srcFs=/tmp/src dstFs=/tmp/dst \
--json '{"_logs": {"level": "INFO", "unattributed": false}}'
```
The logs are returned as a `_logs` key in the result of the call, or
in the error response if the call failed. It has the following keys:
- `entries` - array of logs, oldest first, in the same format
as returned by [core/log](#core-log).
- `next` - the sequence number after the last entry which can be passed
as `since` to [core/log](#core-log) to read the logs made after the call.
- `lost` - the number of log entries which were made while the call was
running but had been dropped from the log buffer as it was too small.
```console
$ rclone rc sync/copy srcFs=/tmp/src dstFs=/tmp/dst _logs=true
{
"_logs": {
"entries": [
{
"group": "job/1",
"jobid": 1,
"level": "info",
"msg": "Copied (new)",
"object": "file.txt",
"objectType": "*local.Object",
"seq": 2,
"size": 3,
"source": "operations/copy.go:385",
"time": "2026-09-17T12:43:42.736052334+01:00"
}
],
"lost": 0,
"next": 3
}
}
```
If the call was started with `_async` then the logs made so far are
returned as `_logs` in the `output` of [job/status](#job-status), so
the `output` is the same as would have been returned if the call was
made synchronously. This returns at most 1000 entries by default -
pass the `next` value returned as `since` to `job/status` to read
more, or `limit` to change the number of entries returned.
Note that:
- Where rclone knows which rc job made a log entry it records the job's
ID as `jobid` and its stats group as `group` in the entry. This is
the case for the logs made by the sync, copy, move, check and the
other operations, such as the per file `Copied (new)` logs, and for
the directory listings they do.
- Logs from the backends, from the filters, from the retries made by
the rate limiter, and from `sync/bisync` are **not** attributed
yet. Neither are the logs of anything which isn't an rc job, such as
a mount.
- `_logs` returns the entries for the job and the unattributed entries
made **while** the job was running. The unattributed entries may have
come from other jobs, or other rclone activity, running at the same
time - set `unattributed` to `false` to leave them out. Entries
attributed to other jobs are always left out.
- The log buffer only contains logs at the current `--log-level`. This
is currently a global setting so it can't be changed for a call with
`_config`. Use [options/set](#options-set) to change it.
- `_logs` can't be used on an rc server without authentication unless
`--rc-no-auth` is in use.
### Following the logs with core/events {#events}
[core/events](#core-events) streams the logs over a single HTTP
connection as they happen, which avoids polling
[core/log](#core-log). It doesn't need `--log-buffer-size` to be set
as nothing is stored - the logs are sent as they are made.
The response is newline delimited JSON - one object per line, each
with a `type`:
```console
$ curl -u user:pass -N -X POST http://127.0.0.1:5572/core/events
{"type":"start","seq":42}
{"type":"log","seq":42,"time":"2026-09-21T12:16:41.134507+01:00","level":"info","msg":"Copied (new)","object":"file.txt","objectType":"*local.Object","size":3,"source":"operations/copy.go:385","jobid":1,"group":"job/1"}
{"type":"heartbeat","time":"2026-09-21T12:17:11.134507+01:00"}
```
The `log` events are in the same format as the entries returned by
[core/log](#core-log), so they carry `jobid` and `group` where rclone
can attribute them - see [_logs](#logs) for what can be attributed.
The stream can be filtered with `level`, `group`, `jobid` and
`unattributed` as `core/log` is.
If the client doesn't read the stream fast enough then events are
dropped and a `dropped` event says how many. If `--log-buffer-size` is
set then passing `since` with the `seq` of the last entry seen sends
the entries from the buffer first, so a client which reconnects
doesn't miss anything.
Note that every rc call is logged at `DEBUG` level, so a client
streaming at that level sees the logs of its own polling. Use
[--rc-log-calls=false](#--rc-log-calls) to turn that off.
## Data types {#data-types}
When the API returns types, these will mostly be straight forward
-10
View File
@@ -5159,12 +5159,6 @@ parameter `--s3-upload-cutoff 0` or put this in the config file as
`upload_cutoff 0` to work around a bug which causes uploading of small
files to fail.
Rclone defaults `sign_accept_encoding` to false for the Ceph provider.
That avoids `SignatureDoesNotMatch` errors when a reverse proxy (for
example Cloudflare) rewrites the `Accept-Encoding` request header. You
can override this with `--s3-sign-accept-encoding` / `sign_accept_encoding`
if needed.
Note also that Ceph sometimes puts `/` in the passwords it gives
users. If you read the secret access key using the command line tools
you will get a JSON blob with the `/` escaped as `\/`. Make sure you
@@ -7483,10 +7477,6 @@ secret_access_key = SECRET_ACCESS_KEY
endpoint = eu-central-1.linodeobjects.com
```
Linode Object Storage is Ceph-backed. Rclone defaults
`sign_accept_encoding` to false for this provider so SigV4 requests do
not fail with `SignatureDoesNotMatch` (see the [Ceph](#ceph) section).
### Magalu {#magalu}
Here is an example of making a [Magalu Object Storage](https://magalu.cloud/object-storage/)
-10
View File
@@ -125,16 +125,6 @@ are replaced.
Invalid UTF-8 bytes will also be [replaced](/overview/#invalid-utf8),
as they can't be used in JSON strings.
### Application folder
If you registered your own OAuth application with Yandex and only granted
it the "Application Folder" permission (`cloud_api:disk.app_folder`)
instead of full disk access, then you must set the `app_folder` option to
`true`. Yandex Disk requires paths to be addressed with an `app:/` prefix
instead of the usual `disk:/` prefix when using this restricted scope, and
rclone will return a 403 Forbidden error on every request if this option
isn't set correctly for the token in use.
<!-- autogenerated options start - DO NOT EDIT - instead edit fs.RegInfo in backend/yandex/yandex.go and run make backenddocs to verify --> <!-- markdownlint-disable-line line-length -->
### Standard options
@@ -20,9 +20,7 @@ features:
- GetTier
- ListP
- ListR
- Move
- OpenChunkWriter
- Purge
- PutStream
- ReadMetadata
- ReadMimeType
+1 -1
View File
@@ -61,7 +61,7 @@
<footer>
<div class="row">
<div class="col-footer{{ if not (and (gt .WordCount 200) (not (.Params.notoc))) }} col-footer-notoc{{ end }}">
<div class="card card-body card-body-padded">
<div class="card card-body">
<p style="font-size: 90%;">
&copy; <a href="https://www.craig-wood.com/nick/" target="blank">Nick Craig-Wood</a> 2014-{{ now.Format "2006" }}<br>
{{ if .File}}{{ with $path := strings.TrimPrefix "/" .File.Path }}Source file <a href="https://github.com/rclone/rclone/blob/master/docs/content/{{ $path }}" target="blank">{{ $path }}</a>{{ end }}
+7 -8
View File
@@ -548,12 +548,14 @@ func (s *StatsInfo) Transferred() []TransferSnapshot {
}
// Log outputs the StatsInfo to the log
//
// The stats are attached as a hidden structured field so they appear
// in JSON log output but not in the text.
func (s *StatsInfo) Log() {
out, _ := s.RemoteStats(false)
fs.LogLevelPrintf(s.ci.StatsLogLevel, nil, "%v%v\n", s, fs.LogValueHide("stats", out))
if s.ci.UseJSONLog {
out, _ := s.RemoteStats(false)
fs.LogLevelPrintf(s.ci.StatsLogLevel, nil, "%v%v\n", s, fs.LogValueHide("stats", out))
} else {
fs.LogLevelPrintf(s.ci.StatsLogLevel, nil, "%v\n", s)
}
}
// Bytes updates the stats for bytes bytes
@@ -829,9 +831,6 @@ func (s *StatsInfo) DoneChecking(remote string) {
s.checking.del(remote)
s.mu.Lock()
s.checks++
if s.transferring.empty() && s.checking.empty() {
s._stopAverageLoop()
}
s.mu.Unlock()
}
-3
View File
@@ -17,9 +17,6 @@ var groups *statsGroups
func init() {
// Init stats container
groups = newStatsGroups()
// Attribute logs to stats groups
fs.StatsGroupFromContext = StatsGroupFromContext
}
func rcListStats(ctx context.Context, in rc.Params) (rc.Params, error) {
-10
View File
@@ -310,13 +310,3 @@ func TestNewStatsGroupDoesNotStartAverageLoop(t *testing.T) {
assert.False(t, startedAfterDone,
"averageLoop should stop when the last transfer is done")
}
// Check fs can read the stats group to attribute logs to it
func TestFsStatsGroupFromContext(t *testing.T) {
ctx := context.Background()
_, ok := fs.StatsGroupFromContext(ctx)
assert.False(t, ok)
group, ok := fs.StatsGroupFromContext(WithStatsGroup(ctx, "job/1"))
assert.True(t, ok)
assert.Equal(t, "job/1", group)
}
-51
View File
@@ -1,44 +1,18 @@
package accounting
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"log/slog"
"testing"
"time"
"github.com/rclone/rclone/fs"
"github.com/rclone/rclone/fs/fserrors"
"github.com/rclone/rclone/fstest/mockobject"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestAverageLoopStopsAfterLastCheck(t *testing.T) {
ctx := context.Background()
stats := NewStats(ctx)
t.Cleanup(func() {
stats.mu.Lock()
defer stats.mu.Unlock()
stats._stopAverageLoop()
})
transfer := stats.NewTransferRemoteSize("transfer", 0, nil, nil)
firstCheck := stats.NewCheckingTransfer(mockobject.New("first"), "checking")
lastCheck := stats.NewCheckingTransfer(mockobject.New("last"), "checking")
transfer.Done(ctx, nil)
firstCheck.Done(ctx, nil)
assert.True(t, stats.average.started, "a check is still active")
lastCheck.Done(ctx, nil)
assert.False(t, stats.average.started, "completed checks must release the averaging goroutine")
assert.Equal(t, int64(2), stats.GetChecks())
assert.Equal(t, int64(1), stats.GetTransfers())
}
func TestETA(t *testing.T) {
for _, test := range []struct {
size, total int64
@@ -515,28 +489,3 @@ func TestRemoveDoneTransfers(t *testing.T) {
assert.Equal(t, transfers, len(s.startedTransfers))
s.mu.Unlock()
}
// Check the log has the stats attached as a structured field for
// JSON output regardless of --use-json-log but that they don't
// appear in the text.
func TestStatsLog(t *testing.T) {
ctx, ci := fs.AddConfig(context.Background())
ci.StatsLogLevel = fs.LogLevelNotice
for _, useJSONLog := range []bool{false, true} {
t.Run(fmt.Sprintf("UseJSONLog=%v", useJSONLog), func(t *testing.T) {
ci.UseJSONLog = useJSONLog
var buf bytes.Buffer
fs.SetLogger(slog.NewJSONHandler(&buf, nil))
defer fs.SetLogger(slog.NewTextHandler(io.Discard, nil))
s := NewStats(ctx)
s.Log()
var out struct {
Msg string `json:"msg"`
Stats map[string]any `json:"stats"`
}
require.NoError(t, json.Unmarshal(buf.Bytes(), &out), buf.String())
assert.Equal(t, s.String()+"\n", out.Msg)
assert.Contains(t, out.Stats, "totalTransfers")
})
}
}
+2 -40
View File
@@ -35,30 +35,9 @@ type tokenBucket struct {
curr buckets
prev buckets
toggledOff bool
started bool
currLimit fs.BwTimeSlot
}
func init() {
// Apply --bwlimit when the config is reloaded, e.g. by the rc
fs.BwLimitReload = TokenBucket.reload
}
// reload applies a changed --bwlimit to the token bucket.
//
// This does nothing before the token bucket is started as
// StartTokenBucket reads the limit itself.
func (tb *tokenBucket) reload(ci *fs.ConfigInfo) error {
limitNow := ci.BwLimit.LimitAt(time.Now())
tb.mu.Lock()
defer tb.mu.Unlock()
if !tb.started || tb.currLimit.Bandwidth == limitNow.Bandwidth {
return nil
}
tb._setBwLimit(limitNow.Bandwidth)
return nil
}
// Return true if limit is disabled
//
// Call with lock held
@@ -132,7 +111,6 @@ func (tb *tokenBucket) StartTokenBucket(ctx context.Context) {
tb.mu.Lock()
defer tb.mu.Unlock()
ci := fs.GetConfig(ctx)
tb.started = true
tb.currLimit = ci.BwLimit.LimitAt(time.Now())
if tb.currLimit.Bandwidth.IsSet() {
tb.curr = newTokenBucket(tb.currLimit.Bandwidth)
@@ -212,29 +190,13 @@ func (tb *tokenBucket) LimitBandwidth(i TokenBucketSlot, n int) {
func (tb *tokenBucket) SetBwLimit(bandwidth fs.BwPair) {
tb.mu.Lock()
defer tb.mu.Unlock()
tb._setBwLimit(bandwidth)
}
// Set the current bandwidth limit
//
// Call with lock held
func (tb *tokenBucket) _setBwLimit(bandwidth fs.BwPair) {
// If the limits are toggled off then the change should only
// become active on the next toggle, which swaps curr and prev
targetBucket := &tb.curr
if tb.toggledOff {
targetBucket = &tb.prev
}
if bandwidth.IsSet() {
*targetBucket = newTokenBucket(bandwidth)
tb.curr = newTokenBucket(bandwidth)
fs.Logf(nil, "Bandwidth limit set to %v", bandwidth)
} else {
targetBucket._setOff()
tb.curr._setOff()
fs.Logf(nil, "Bandwidth limit reset to unlimited")
}
// Record the limit so the SIGUSR2 toggle knows there is one
// and a scheduled change knows what it is replacing
tb.currLimit.Bandwidth = bandwidth
}
// read and set the bandwidth limits
-73
View File
@@ -114,76 +114,3 @@ func TestRcBwLimit(t *testing.T) {
}, out)
}
// Check options/set applies a changed --bwlimit to the token bucket
func TestBwLimitOptionsSet(t *testing.T) {
ctx := context.Background()
ci := fs.GetConfig(ctx)
oldBwLimit, oldStarted, oldCurr, oldCurrLimit := ci.BwLimit, TokenBucket.started, TokenBucket.curr, TokenBucket.currLimit
defer func() {
ci.BwLimit = oldBwLimit
TokenBucket.started, TokenBucket.curr, TokenBucket.currLimit = oldStarted, oldCurr, oldCurrLimit
}()
setBwLimit := func(rate string) {
t.Helper()
call := rc.Calls.Get("options/set")
require.NotNil(t, call)
_, err := call.Fn(ctx, rc.Params{"main": rc.Params{"BwLimit": rate}})
require.NoError(t, err)
}
// Nothing happens before the token bucket is started
TokenBucket.started = false
TokenBucket.curr = buckets{}
setBwLimit("100k")
assert.Nil(t, TokenBucket.curr[TokenBucketSlotAccounting])
// Once started the limit is applied
TokenBucket.started = true
TokenBucket.currLimit = fs.BwTimeSlot{}
setBwLimit("200k")
require.NotNil(t, TokenBucket.curr[TokenBucketSlotTransportTx])
assert.Equal(t, rate.Limit(200*1024), TokenBucket.curr[TokenBucketSlotTransportTx].Limit())
// and changed again
setBwLimit("300k")
assert.Equal(t, rate.Limit(300*1024), TokenBucket.curr[TokenBucketSlotTransportTx].Limit())
// and turned off
setBwLimit("off")
assert.Nil(t, TokenBucket.curr[TokenBucketSlotTransportTx])
}
// Check setting the limit records it and respects the SIGUSR2 toggle
func TestSetBwLimitToggledOff(t *testing.T) {
oldCurr, oldPrev, oldToggledOff, oldCurrLimit := TokenBucket.curr, TokenBucket.prev, TokenBucket.toggledOff, TokenBucket.currLimit
defer func() {
TokenBucket.curr, TokenBucket.prev = oldCurr, oldPrev
TokenBucket.toggledOff, TokenBucket.currLimit = oldToggledOff, oldCurrLimit
}()
TokenBucket.curr, TokenBucket.prev = buckets{}, buckets{}
TokenBucket.toggledOff, TokenBucket.currLimit = false, fs.BwTimeSlot{}
// Normally the limit is set straight away
TokenBucket.SetBwLimit(fs.BwPair{Tx: 1024, Rx: 1024})
require.NotNil(t, TokenBucket.curr[TokenBucketSlotTransportTx])
assert.Equal(t, rate.Limit(1024), TokenBucket.curr[TokenBucketSlotTransportTx].Limit())
// The limit is recorded, otherwise SIGUSR2 ignores it
assert.True(t, TokenBucket.currLimit.Bandwidth.IsSet())
// Toggled off with SIGUSR2 - curr is off and prev holds the limits
TokenBucket.toggledOff = true
TokenBucket.curr, TokenBucket.prev = TokenBucket.prev, TokenBucket.curr
// Setting a limit now must not turn the limits back on
TokenBucket.SetBwLimit(fs.BwPair{Tx: 2048, Rx: 2048})
assert.Nil(t, TokenBucket.curr[TokenBucketSlotTransportTx], "limits toggled off must stay off")
// It becomes active on the next toggle
TokenBucket.toggledOff = false
TokenBucket.curr, TokenBucket.prev = TokenBucket.prev, TokenBucket.curr
require.NotNil(t, TokenBucket.curr[TokenBucketSlotTransportTx])
assert.Equal(t, rate.Limit(2048), TokenBucket.curr[TokenBucketSlotTransportTx].Limit())
}
+2 -5
View File
@@ -150,8 +150,6 @@ func (x *BwTimetable) Set(s string) error {
return nil
}
var newTimetable BwTimetable
// Split the timetable string by both spaces and semicolons
for tok := range strings.FieldsFuncSeq(s, func(r rune) bool {
return r == ' ' || r == ';'
@@ -180,7 +178,7 @@ func (x *BwTimetable) Set(s string) error {
if err := ts.Bandwidth.Set(tv[1]); err != nil {
return err
}
newTimetable = append(newTimetable, ts)
*x = append(*x, ts)
}
} else {
timespec := strings.Split(tv[0], "-")
@@ -207,10 +205,9 @@ func (x *BwTimetable) Set(s string) error {
if err := ts.Bandwidth.Set(tv[1]); err != nil {
return err
}
newTimetable = append(newTimetable, ts)
*x = append(*x, ts)
}
}
*x = newTimetable
return nil
}
-46
View File
@@ -316,52 +316,6 @@ func TestBwTimetableSet(t *testing.T) {
}
}
func TestBwTimetableSetReplaces(t *testing.T) {
for _, test := range []struct {
first string
second string
want string
}{
{"Sun-00:00,10M", "Mon-10:00,1M", "Mon-10:00,1Mi"},
{"Mon-10:00,1M", "Mon-10:00,1M", "Mon-10:00,1Mi"},
{"Mon-10:00,1M", "2M", "2Mi"},
{"2M", "Mon-10:00,1M", "Mon-10:00,1Mi"},
{"11:00,333;13:40,666", "Mon-10:00,1M", "Mon-10:00,1Mi"},
} {
tt := BwTimetable{}
require.NoError(t, tt.Set(test.first), test.first)
require.NoError(t, tt.Set(test.second), test.second)
assert.Equal(t, test.want, tt.String(), "%q then %q", test.first, test.second)
var want BwTimetable
require.NoError(t, want.Set(test.second))
assert.Equal(t, want, tt, "%q then %q", test.first, test.second)
}
}
func TestBwTimetableSetErrorKeepsPrevious(t *testing.T) {
for _, in := range []string{
"Mon-11:00,333 bad",
"Mon-11:00,333 Tue-13:40,bad",
"Mon-11:00,333 24:01,666",
"11:00,333;bad",
} {
tt := BwTimetable{}
require.NoError(t, tt.Set("Sun-20:00,10M"))
require.Error(t, tt.Set(in), in)
assert.Equal(t, "Sun-20:00,10Mi", tt.String(), in)
}
}
func TestBwTimetableUnmarshalJSONReplaces(t *testing.T) {
var tt BwTimetable
require.NoError(t, json.Unmarshal([]byte(`"Sun-00:00,10M"`), &tt))
require.NoError(t, json.Unmarshal([]byte(`"Mon-10:00,1M"`), &tt))
assert.Equal(t, BwTimetable{
BwTimeSlot{DayOfTheWeek: 1, HHMM: 1000, Bandwidth: BwPair{Tx: 1024 * 1024, Rx: 1024 * 1024}},
}, tt)
}
func TestBwTimetableLimitAt(t *testing.T) {
for _, test := range []struct {
tt BwTimetable
-24
View File
@@ -43,22 +43,6 @@ var (
// implementation from the fs
CountError = func(ctx context.Context, err error) error { return err }
// StatsGroupFromContext returns the stats group from ctx if set.
//
// This is used to attribute logs to stats groups.
//
// This is a function pointer to decouple the accounting
// implementation from the fs
StatsGroupFromContext = func(ctx context.Context) (string, bool) { return "", false }
// JobIDFromContext returns the ID of the rc job in ctx if set.
//
// This is used to attribute logs to the rc job which made them.
//
// This is a function pointer to decouple the rc jobs
// implementation from the fs
JobIDFromContext = func(ctx context.Context) (int64, bool) { return 0, false }
// ConfigProvider is the config key used for provider options
ConfigProvider = "provider"
@@ -713,10 +697,6 @@ func init() {
// be there but we can't move due to them being visible here in the rc.
var LogReload = func(*ConfigInfo) error { return nil }
// BwLimitReload is written by fs/accounting to apply --bwlimit when
// the config is reloaded, e.g. by the rc options/set.
var BwLimitReload = func(*ConfigInfo) error { return nil }
// Reload assumes the config has been edited and does what is necessary to make it live
func (ci *ConfigInfo) Reload(ctx context.Context) error {
// Set -vv if --dump is in use
@@ -769,10 +749,6 @@ func (ci *ConfigInfo) Reload(ctx context.Context) error {
nonZero(&ci.Transfers)
nonZero(&ci.Checkers)
if err := BwLimitReload(ci); err != nil {
return err
}
return LogReload(ci)
}
+2 -6
View File
@@ -85,9 +85,7 @@ func Decrypt(b io.ReadSeeker) (io.Reader, error) {
return b, nil
}
// A key file named by _RCLONE_CONFIG_KEY_FILE is a key handed over by a
// parent process, so the password must not be asked for again here.
if len(configKey) == 0 && os.Getenv("_RCLONE_CONFIG_KEY_FILE") == "" {
if len(configKey) == 0 {
pass, err := GetPasswordCommand(ctx)
if err != nil {
return nil, err
@@ -132,9 +130,7 @@ func Decrypt(b io.ReadSeeker) (io.Reader, error) {
var out []byte
for {
// Only a process without a key of its own consumes the key file, so
// that a process which wrote one for its child leaves it in place.
if envKeyFile := os.Getenv("_RCLONE_CONFIG_KEY_FILE"); len(configKey) == 0 && len(envKeyFile) > 0 {
if envKeyFile := os.Getenv("_RCLONE_CONFIG_KEY_FILE"); len(envKeyFile) > 0 {
fs.Debugf(nil, "attempting to obtain configKey from temp file %s", envKeyFile)
obscuredKey, err := os.ReadFile(envKeyFile)
if err != nil {
-42
View File
@@ -70,48 +70,6 @@ func TestConfigLoadEncryptedWithValidPassCommand(t *testing.T) {
assert.Equal(t, expect, keys)
}
// TestConfigLoadEncryptedWithPassCommandAndDaemon checks the configKey handoff
// that --daemon relies on: the parent process leaves the obscured key in the
// temp file named by _RCLONE_CONFIG_KEY_FILE, and the daemon process uses that
// instead of running --password-command a second time.
func TestConfigLoadEncryptedWithPassCommandAndDaemon(t *testing.T) {
ctx := context.Background()
ci := fs.GetConfig(ctx)
oldConfigPath := config.GetConfigPath()
oldConfig := *ci
require.NoError(t, config.SetConfigPath("./testdata/encrypted.conf"))
config.PassConfigKeyForDaemonization = true
t.Setenv("_RCLONE_CONFIG_KEY_FILE", "")
defer func() {
assert.NoError(t, config.SetConfigPath(oldConfigPath))
config.ClearConfigPassword()
config.PassConfigKeyForDaemonization = false
*ci = oldConfig
ci.PasswordCommand = nil
}()
// The parent reads the password and saves the key for the daemon.
ci.PasswordCommand = fs.SpaceSepList{"echo", "asdf"}
config.ClearConfigPassword()
require.NoError(t, config.Data().Load())
keyFile := os.Getenv("_RCLONE_CONFIG_KEY_FILE")
require.NotEmpty(t, keyFile)
_, err := os.Stat(keyFile)
require.NoError(t, err, "parent must leave the key file for the daemon")
// The daemon inherits the environment but not the key. Running
// --password-command again would yield this wrong password.
config.ClearConfigPassword()
ci.PasswordCommand = fs.SpaceSepList{"echo", "not-the-password"}
require.NoError(t, config.Data().Load())
assert.Equal(t, []string{"nounc", "unc"}, config.Data().GetSectionList())
_, err = os.Stat(keyFile)
assert.True(t, os.IsNotExist(err), "daemon must delete the key file once used")
}
func TestConfigLoadEncryptedWithInvalidPassCommand(t *testing.T) {
ctx := context.Background()
ci := fs.GetConfig(ctx)
+2 -2
View File
@@ -583,7 +583,7 @@ func (f *Filter) IncludeObject(ctx context.Context, o fs.Object) bool {
var err error
metadata, err = fs.GetMetadata(ctx, o)
if err != nil {
fs.ErrorfCtx(ctx, o, "Failed to read metadata: %v", err)
fs.Errorf(o, "Failed to read metadata: %v", err)
metadata = nil
}
@@ -653,7 +653,7 @@ func (f *Filter) MakeListR(ctx context.Context, NewObject func(ctx context.Conte
// Count and log the error but carry on so that one
// unreadable file (e.g. permission denied) doesn't stop
// the other --files-from files being processed.
fs.ErrorfCtx(ctx, remote, "--files-from failed to read file: %v", err)
fs.Errorf(remote, "--files-from failed to read file: %v", err)
_ = fs.CountError(gCtx, err)
} else {
err = callback(entries)
+2 -10
View File
@@ -3,24 +3,16 @@
package fserrors
import (
"slices"
"syscall"
liberrors "github.com/rclone/rclone/lib/errors"
)
// noSpaceErrors are the errors which mean the disk is full.
//
// Platform specific files add to this list in their init functions.
var noSpaceErrors = []error{
syscall.ENOSPC,
}
// IsErrNoSpace checks a possibly wrapped error to
// see if it contains an out of space error.
// see if it contains a ENOSPC error
func IsErrNoSpace(cause error) (isNoSpc bool) {
liberrors.Walk(cause, func(c error) bool {
if slices.Contains(noSpaceErrors, c) {
if c == syscall.ENOSPC {
isNoSpc = true
return true
}
-17
View File
@@ -1,17 +0,0 @@
//go:build windows
package fserrors
import (
"golang.org/x/sys/windows"
)
func init() {
// Windows does not return syscall.ENOSPC, which Go defines here as a
// value in its application reserved range. A full disk reports these.
// https://learn.microsoft.com/en-us/windows/win32/debug/system-error-codes--0-499-
noSpaceErrors = append(noSpaceErrors,
windows.ERROR_DISK_FULL,
windows.ERROR_HANDLE_DISK_FULL,
)
}
-35
View File
@@ -1,35 +0,0 @@
//go:build windows
package fserrors
import (
"os"
"syscall"
"testing"
"github.com/stretchr/testify/assert"
"golang.org/x/sys/windows"
)
func TestIsErrNoSpaceWindows(t *testing.T) {
tests := []struct {
name string
err error
want bool
}{
{"syscall.ENOSPC", syscall.ENOSPC, true},
{"ERROR_DISK_FULL", windows.ERROR_DISK_FULL, true},
{"ERROR_HANDLE_DISK_FULL", windows.ERROR_HANDLE_DISK_FULL, true},
{"openat PathError", &os.PathError{Op: "openat", Path: "file", Err: windows.ERROR_DISK_FULL}, true},
{"mkdirat PathError", &os.PathError{Op: "mkdirat", Path: "dir", Err: windows.ERROR_DISK_FULL}, true},
{"SyscallError", os.NewSyscallError("write", windows.ERROR_HANDLE_DISK_FULL), true},
{"ERROR_ACCESS_DENIED", windows.ERROR_ACCESS_DENIED, false},
{"access denied PathError", &os.PathError{Op: "openat", Path: "file", Err: windows.ERROR_ACCESS_DENIED}, false},
{"nil", nil, false},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
assert.Equal(t, test.want, IsErrNoSpace(test.err))
})
}
}
+7 -7
View File
@@ -67,7 +67,7 @@ func DirSorted(ctx context.Context, f fs.Fs, includeAll bool, dir string) (entri
// called.
fi := filter.GetConfig(ctx)
if !includeAll && fi.ListContainsExcludeFile(entries) {
fs.DebugfCtx(ctx, dir, "Excluded")
fs.Debugf(dir, "Excluded")
return nil, nil
}
return filterAndSortDir(ctx, entries, includeAll, dir, fi.IncludeObject, fi.IncludeDirectory(ctx, f))
@@ -113,7 +113,7 @@ func DirSortedFn(ctx context.Context, f fs.Fs, includeAll bool, dir string, call
// starting directory, otherwise ListDirSorted should not be
// called.
if !includeAll && fi.ListContainsExcludeFile(entries) {
fs.DebugfCtx(ctx, dir, "Excluded")
fs.Debugf(dir, "Excluded")
return nil
}
@@ -150,7 +150,7 @@ func filterDir(ctx context.Context, entries fs.DirEntries, includeAll bool, dir
// Make sure we don't delete excluded files if not required
if !includeAll && !IncludeObject(ctx, x) {
ok = false
fs.DebugfCtx(ctx, x, "Excluded")
fs.Debugf(x, "Excluded")
}
case fs.Directory:
if !includeAll {
@@ -160,7 +160,7 @@ func filterDir(ctx context.Context, entries fs.DirEntries, includeAll bool, dir
}
if !include {
ok = false
fs.DebugfCtx(ctx, x, "Excluded")
fs.Debugf(x, "Excluded")
}
}
default:
@@ -173,13 +173,13 @@ func filterDir(ctx context.Context, entries fs.DirEntries, includeAll bool, dir
// ignore
case !strings.HasPrefix(remote, prefix):
ok = false
fs.ErrorfCtx(ctx, entry, "Entry doesn't belong in directory %q (too short) - ignoring", dir)
fs.Errorf(entry, "Entry doesn't belong in directory %q (too short) - ignoring", dir)
case remote == dir:
ok = false
fs.ErrorfCtx(ctx, entry, "Entry doesn't belong in directory %q (same as directory) - ignoring", dir)
fs.Errorf(entry, "Entry doesn't belong in directory %q (same as directory) - ignoring", dir)
case strings.ContainsRune(remote[len(prefix):], '/') && !bucket.IsAllSlashes(remote[len(prefix):]):
ok = false
fs.ErrorfCtx(ctx, entry, "Entry doesn't belong in directory %q (contains subdir) - ignoring", dir)
fs.Errorf(entry, "Entry doesn't belong in directory %q (contains subdir) - ignoring", dir)
default:
// ok
}
+4 -4
View File
@@ -111,7 +111,7 @@ func (ls *Sorter) keyToEntry(ctx context.Context, key string) (entry fs.DirEntry
} else {
obj, err := ls.f.NewObject(ctx, remote)
if err != nil {
fs.ErrorfCtx(ctx, ls.f, "sorter: failed to re-create object %q: %v", remote, err)
fs.Errorf(ls.f, "sorter: failed to re-create object %q: %v", remote, err)
return nil, fmt.Errorf("sorter: failed to re-create object: %w", err)
}
entry = obj
@@ -137,7 +137,7 @@ func (ls *Sorter) sendEntriesToExtSort(entries fs.DirEntries) (err error) {
}
func (ls *Sorter) startExtSort() (err error) {
fs.LogfCtx(ls.ctx, ls.f, "Switching to on disk sorting as more than %d entries in one directory detected", ls.cutoff)
fs.Logf(ls.f, "Switching to on disk sorting as more than %d entries in one directory detected", ls.cutoff)
ls.inputChan = make(chan string, 100)
// Options to control the extsort
opt := extsort.Config{
@@ -171,9 +171,9 @@ func (ls *Sorter) startExtSort() (err error) {
ls.extSort = true
// Send the accumulated entries to the sorter
fs.DebugfCtx(ls.ctx, ls.f, "Sending accumulated directory entries to disk")
fs.Debugf(ls.f, "Sending accumulated directory entries to disk")
err = ls.sendEntriesToExtSort(ls.entries)
fs.DebugfCtx(ls.ctx, ls.f, "Done sending accumulated directory entries to disk")
fs.Debugf(ls.f, "Done sending accumulated directory entries to disk")
clear(ls.entries)
ls.entries = nil
return err
+16 -61
View File
@@ -140,16 +140,11 @@ func LogLevelToSlog(level LogLevel) slog.Level {
return slogLevel
}
func logSlog(ctx context.Context, level LogLevel, text string, attrs []any) {
if ctx == nil {
ctx = context.Background()
}
// ctx is passed to the log handler which uses it to attribute
// the log to the rc job and stats group it was made by.
logger.Log(ctx, LogLevelToSlog(level), text, attrs...)
func logSlog(level LogLevel, text string, attrs []any) {
logger.Log(context.Background(), LogLevelToSlog(level), text, attrs...)
}
func logSlogWithObject(ctx context.Context, level LogLevel, o any, text string, attrs []any) {
func logSlogWithObject(level LogLevel, o any, text string, attrs []any) {
if o != nil {
var object string
switch o.(type) {
@@ -165,46 +160,24 @@ func logSlogWithObject(ctx context.Context, level LogLevel, o any, text string,
"objectType", fmt.Sprintf("%T", o),
})
}
logSlog(ctx, level, text, attrs)
logSlog(level, text, attrs)
}
func logPrintf(ctx context.Context, level LogLevel, o any, text string, args ...any) {
// Note that text isn't assigned to here so go vet can see this
// is a printf wrapper and check the format strings of the
// callers.
msg := fmt.Sprintf(text, args...)
// LogPrint produces a log string from the arguments passed in
func LogPrint(level LogLevel, o any, text string) {
logSlogWithObject(level, o, text, nil)
}
// LogPrintf produces a log string from the arguments passed in
func LogPrintf(level LogLevel, o any, text string, args ...any) {
text = fmt.Sprintf(text, args...)
var fields []any
for _, arg := range args {
if item, ok := arg.(LogValueItem); ok {
fields = append(fields, item.key, item.value)
}
}
logSlogWithObject(ctx, level, o, msg, fields)
}
func logLevelPrintf(ctx context.Context, level LogLevel, o any, text string, args ...any) {
// This uses the global log level, not the one in ctx, as the
// log handler filters on the global log level.
if GetConfig(context.TODO()).LogLevel >= level {
logPrintf(ctx, level, o, text, args...)
}
}
// LogPrint produces a log string from the arguments passed in
func LogPrint(level LogLevel, o any, text string) {
logSlogWithObject(context.Background(), level, o, text, nil)
}
// LogPrintf produces a log string from the arguments passed in
func LogPrintf(level LogLevel, o any, text string, args ...any) {
logPrintf(context.Background(), level, o, text, args...)
}
// LogPrintfCtx produces a log string from the arguments passed in.
//
// The log is attributed to the stats group in ctx, if any.
func LogPrintfCtx(ctx context.Context, level LogLevel, o any, text string, args ...any) {
logPrintf(ctx, level, o, text, args...)
logSlogWithObject(level, o, text, fields)
}
// LogLevelPrint writes logs at the given level
@@ -216,7 +189,9 @@ func LogLevelPrint(level LogLevel, o any, text string) {
// LogLevelPrintf writes logs at the given level
func LogLevelPrintf(level LogLevel, o any, text string, args ...any) {
logLevelPrintf(context.Background(), level, o, text, args...)
if GetConfig(context.TODO()).LogLevel >= level {
LogPrintf(level, o, text, args...)
}
}
// Panic writes alert log output for this Object or Fs and calls panic().
@@ -298,11 +273,6 @@ func Errorf(o any, text string, args ...any) {
LogLevelPrintf(LogLevelError, o, text, args...)
}
// ErrorfCtx is Errorf with the log attributed to the stats group in ctx, if any.
func ErrorfCtx(ctx context.Context, o any, text string, args ...any) {
logLevelPrintf(ctx, LogLevelError, o, text, args...)
}
// Print writes log output for this Object or Fs, same as Logf.
func Print(o any, text string) {
LogLevelPrint(LogLevelNotice, o, text)
@@ -331,11 +301,6 @@ func Logf(o any, text string, args ...any) {
LogLevelPrintf(LogLevelNotice, o, text, args...)
}
// LogfCtx is Logf with the log attributed to the stats group in ctx, if any.
func LogfCtx(ctx context.Context, o any, text string, args ...any) {
logLevelPrintf(ctx, LogLevelNotice, o, text, args...)
}
// Infoc writes info on transfers for this Object or Fs. Use this
// level for logging transfers, deletions and things which should
// appear with the -v flag.
@@ -351,11 +316,6 @@ func Infof(o any, text string, args ...any) {
LogLevelPrintf(LogLevelInfo, o, text, args...)
}
// InfofCtx is Infof with the log attributed to the stats group in ctx, if any.
func InfofCtx(ctx context.Context, o any, text string, args ...any) {
logLevelPrintf(ctx, LogLevelInfo, o, text, args...)
}
// Debug writes debugging output for this Object or Fs. Use this for
// debug only. The user must have to specify -vv to see this.
func Debug(o any, text string) {
@@ -368,11 +328,6 @@ func Debugf(o any, text string, args ...any) {
LogLevelPrintf(LogLevelDebug, o, text, args...)
}
// DebugfCtx is Debugf with the log attributed to the stats group in ctx, if any.
func DebugfCtx(ctx context.Context, o any, text string, args ...any) {
logLevelPrintf(ctx, LogLevelDebug, o, text, args...)
}
// LogDirName returns an object for the logger, logging a root
// directory which would normally be "" as the Fs
func LogDirName(f Fs, dir string) any {
-404
View File
@@ -1,404 +0,0 @@
package log
import (
"context"
"encoding/json"
"errors"
"fmt"
"log/slog"
"math"
"sort"
"strconv"
"strings"
"sync"
"sync/atomic"
"github.com/rclone/rclone/fs"
"github.com/rclone/rclone/fs/rc"
)
// ErrBufferDisabled is returned when the recent logs are needed but
// --log-buffer-size has not been set.
var ErrBufferDisabled = rc.NewErrParamInvalid(errors.New("log buffer not enabled - set --log-buffer-size"))
// Recent holds the most recent log entries if --log-buffer-size is set.
var Recent = &Buffer{}
// Maximum number of entries Get looks at when a limit is in force.
const maxExamine = 100_000
// bufferEntry is a single log entry in the Buffer.
type bufferEntry struct {
seq int64
level slog.Level
attribution Attribution
json json.RawMessage
}
// Filter selects which entries Buffer.Get returns.
//
// Note that the zero value of Level is INFO, so the zero value
// returns the entries at INFO or more severe.
type Filter struct {
Level slog.Level // only return entries at this level or more severe - note the zero value is INFO
JobID int64 // if set, only return entries attributed to this rc job
Group string // if set, only return entries attributed to this stats group
Unattributed bool // if set with JobID or Group, also return entries which aren't attributed
}
// match returns true if an entry at level attributed to attribution
// should be returned.
func (f *Filter) match(level slog.Level, attribution Attribution) bool {
if level < f.Level {
return false
}
if f.JobID == 0 && f.Group == "" {
return true
}
if f.JobID != 0 && attribution.JobID == f.JobID {
return true
}
if f.Group != "" && attribution.Group == f.Group {
return true
}
return f.Unattributed && !attribution.Attributed()
}
// Entries is a list of log entries in JSON format as returned by Buffer.Get.
type Entries []json.RawMessage
// String returns a summary of the entries.
//
// The entries aren't rendered as they are logged when rc replies
// are logged at DEBUG level and that would cause the log to feed
// back into itself.
func (e Entries) String() string {
return fmt.Sprintf("%d log entries", len(e))
}
// Buffer is a size limited in memory store of the most recent log
// entries in JSON format.
//
// Each entry is given a sequence number starting from 0 which
// increases by one for each entry added. This is included in the
// entry as the "seq" field.
type Buffer struct {
mu sync.Mutex
entries []bufferEntry // oldest first in increasing sequence number
size int64 // total size of the JSON in entries
maxSize int64 // drop old entries to keep size <= this - disabled if <= 0
}
// SetSize sets the maximum size in bytes of the log entries kept.
//
// Setting this <= 0 disables the Buffer and discards its entries.
func (b *Buffer) SetSize(maxSize int64) {
b.mu.Lock()
defer b.mu.Unlock()
b.maxSize = maxSize
b.trim()
}
// Enabled returns whether the Buffer is storing log entries.
func (b *Buffer) Enabled() bool {
b.mu.Lock()
defer b.mu.Unlock()
return b.maxSize > 0
}
// Seq returns the sequence number the next log entry will be given.
func (b *Buffer) Seq() int64 {
return nextSeq.Load()
}
// trim drops the oldest entries until the Buffer is within its size.
//
// Call with the mutex held.
func (b *Buffer) trim() {
for len(b.entries) > 0 && b.size > b.maxSize {
b.size -= int64(len(b.entries[0].json))
b.entries[0] = bufferEntry{} // release the memory
b.entries = b.entries[1:]
}
if len(b.entries) == 0 {
b.entries = nil
}
}
// add adds a log entry made by makeEntry to the Buffer.
//
// This is called with the log handler's mutex held so it must not log.
func (b *Buffer) add(seq int64, level slog.Level, attribution Attribution, entry json.RawMessage) {
b.mu.Lock()
defer b.mu.Unlock()
if b.maxSize <= 0 {
return
}
// Don't store an entry bigger than the buffer as it would evict
// everything else - it will show up as lost
if int64(len(entry)) > b.maxSize {
return
}
b.entries = append(b.entries, bufferEntry{seq: seq, level: level, attribution: attribution, json: entry})
b.size += int64(len(entry))
b.trim()
}
// Get returns the entries with sequence numbers from <= seq < to
// which match filter, oldest first.
//
// If limit > 0 then at most limit entries are returned and at most
// maxExamine entries are looked at, so Get may return early with next
// short of to.
//
// It returns next which is the sequence number to pass as from to
// carry on reading where this call finished, and lost which is the
// number of entries in the range which are no longer in the Buffer,
// either because they were dropped to make space or because they
// were too big to store.
func (b *Buffer) Get(from, to int64, filter Filter, limit int) (entries Entries, next, lost int64) {
b.mu.Lock()
defer b.mu.Unlock()
// Sequence numbers are given out for every log entry, whether
// it is stored or not, so use that as the end of the log
end := nextSeq.Load()
to = min(to, end)
from = min(max(from, 0), end)
entries = Entries{}
next = max(to, from)
// Find the first entry with seq >= from
i := sort.Search(len(b.entries), func(i int) bool {
return b.entries[i].seq >= from
})
examined := 0
for ; i < len(b.entries) && b.entries[i].seq < to; i++ {
entry := &b.entries[i]
// Stop when we have enough entries, or have looked at
// enough of them, so this doesn't hold the lock for
// too long when the filter matches very little.
if limit > 0 && (len(entries) >= limit || examined >= maxExamine) {
next = entry.seq
break
}
examined++
if filter.match(entry.level, entry.attribution) {
entries = append(entries, entry.json)
}
}
lost = max(next-from, 0) - int64(examined)
return entries, next, lost
}
// setBufferSize sets the size of Recent from the options.
func setBufferSize() {
Recent.SetSize(int64(Opt.BufferSize))
updateOutput()
}
// nextSeq is the sequence number the next log entry will be given.
var nextSeq atomic.Int64
// makeEntry makes the JSON for a log entry from the JSON formatted
// log text, adding the sequence number to it.
func makeEntry(seq int64, text string) json.RawMessage {
text = strings.TrimSpace(text)
if !(strings.HasPrefix(text, `{"`) && strings.HasSuffix(text, "}")) {
// This shouldn't happen but make sure we always make valid JSON
msg, _ := json.Marshal(text)
text = `{"msg":` + string(msg) + `}`
}
// Build the entry with the sequence number added in a single allocation
const prefix = `{"seq":`
entry := make(json.RawMessage, 0, len(prefix)+20+len(text))
entry = append(entry, prefix...)
entry = strconv.AppendInt(entry, seq, 10)
entry = append(entry, ',')
entry = append(entry, text[1:]...)
return entry
}
// logOutput is the log output which feeds the log buffer and the
// core/events subscribers.
//
// This is called with the log handler's mutex held so it must not log.
func logOutput(r slog.Record, attribution Attribution, text string) {
seq := nextSeq.Add(1) - 1
entry := makeEntry(seq, text)
Recent.add(seq, r.Level, attribution, entry)
publish(r.Level, attribution, entry)
}
// updateOutput connects logOutput to the log handler if the log
// buffer or any subscriber needs it and disconnects it if not.
//
// The output is only connected when needed as it causes every log
// entry to be formatted as JSON.
func updateOutput() {
outputMu.Lock()
defer outputMu.Unlock()
needed := Recent.Enabled() || subscribed()
if needed && outputRemove == nil {
outputRemove = Handler.addRecordOutput(true, logOutput)
} else if !needed && outputRemove != nil {
outputRemove()
outputRemove = nil
}
}
// outputRemove disconnects logOutput from the log handler if not nil.
var (
outputMu sync.Mutex
outputRemove func()
)
func init() {
rc.Add(rc.Call{
Path: "core/log",
Fn: rcLog,
Title: "Returns the most recent log entries.",
Help: strings.ReplaceAll(`
This returns the most recent log entries from the in memory log buffer.
The log buffer must be enabled with the |--log-buffer-size| flag
otherwise this will return an error.
Note that the log buffer only contains logs which were output at the
current |--log-level|.
Parameters:
- since - return entries with sequence numbers starting from this - optional
- Defaults to 0 which returns the oldest entries first.
- If negative, e.g. -N then this starts from the most recent N entries.
- It is an error for this to be beyond the end of the log (which will
happen if rclone has been restarted).
- limit - maximum number of entries to return - optional, defaults to 1000, 0 for no limit
- level - only return entries at this level or more severe, e.g. "INFO" - optional
- group - only return entries attributed to this stats group, e.g. "job/1" - optional
- jobid - only return entries attributed to this rc job, e.g. 1 - optional
Returns:
- entries - array of log entries, oldest first.
- next - pass this as |since| to carry on reading the log from where this call finished.
- lost - the number of entries from |since| onwards which had already been dropped from the log buffer.
Each entry is an object in the same format as used by |--use-json-log|
with an additional |seq| entry which is the sequence number of
the log entry. Sequence numbers start from 0 and increase by one for
each log entry.
Entries which rclone can attribute to the rc job which made them, such
as the per file logs made by a job doing a sync or copy, have a
|jobid| entry with the ID of the job and a |group| entry with the name
of its stats group, e.g. "job/1" or the value of |_group| passed to
the rc call.
Not all logs can be attributed - see the [_logs](/rc/#logs) docs for
which can.
Example:
|||sh
rclone rc core/log since=-2
|||
Returns:
|||json
{
"entries": [
{
"level": "notice",
"msg": "Serving remote control on http://127.0.0.1:5572/",
"seq": 1,
"source": "rcserver/rcserver.go:119",
"time": "2026-09-17T12:39:29.875104149+01:00"
},
{
"level": "info",
"msg": "Copied (new)",
"object": "file.txt",
"objectType": "*local.Object",
"seq": 2,
"size": 3,
"source": "operations/copy.go:385",
"time": "2026-09-17T12:39:29.960848893+01:00"
}
],
"lost": 0,
"next": 3
}
|||
To follow the log, call this repeatedly passing in the |next| value
returned as the |since| parameter. If |lost| is non zero then the log
buffer was too small to hold all the entries since the last call and
that many entries were missed.
Sequence numbers restart from 0 when rclone restarts, but not when the
log buffer is turned off and on again - the entries made while it was
off show up as |lost|.
Note that this filters strictly, so |core/log jobid=N| returns fewer
entries than that job's [_logs](/rc/#logs), which also returns the
entries which aren't attributed to any job.
`, "|", "`"),
})
}
// ParseLevel parses a log level as used in the rc, e.g. "INFO", into a slog.Level.
func ParseLevel(s string) (slog.Level, error) {
var level fs.LogLevel
if err := level.Set(s); err != nil {
return 0, err
}
return fs.LogLevelToSlog(level), nil
}
// rcLog returns the most recent log entries.
func rcLog(ctx context.Context, in rc.Params) (out rc.Params, err error) {
if !Recent.Enabled() {
return nil, ErrBufferDisabled
}
since, err := in.GetInt64("since")
if rc.NotErrParamNotFound(err) {
return nil, err
}
seq := Recent.Seq()
if since < 0 {
since = max(seq+since, 0)
} else if since > seq {
return nil, rc.NewErrParamInvalid(fmt.Errorf("since %d is beyond the end of the log %d - has rclone been restarted?", since, seq))
}
limit, err := in.GetInt64("limit")
if rc.IsErrParamNotFound(err) {
limit = 1000
} else if err != nil {
return nil, err
}
level := slog.LevelDebug
levelString, err := in.GetString("level")
if err == nil {
level, err = ParseLevel(levelString)
if err != nil {
return nil, rc.NewErrParamInvalid(err)
}
} else if rc.NotErrParamNotFound(err) {
return nil, err
}
group, err := in.GetString("group")
if rc.NotErrParamNotFound(err) {
return nil, err
}
jobID, err := in.GetInt64("jobid")
if rc.NotErrParamNotFound(err) {
return nil, err
}
filter := Filter{Level: level, Group: group, JobID: jobID}
entries, next, lost := Recent.Get(since, math.MaxInt64, filter, int(min(limit, math.MaxInt32)))
return rc.Params{
"entries": entries,
"next": next,
"lost": lost,
}, nil
}
-471
View File
@@ -1,471 +0,0 @@
package log
import (
"context"
"encoding/json"
"fmt"
"io"
"log/slog"
"math"
"sync"
"testing"
"github.com/rclone/rclone/fs"
"github.com/rclone/rclone/fs/rc"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
type testAttributionKey struct{}
// testAttributionCtx is attributed to rc job 1 in stats group "job/1"
var testAttributionCtx = context.WithValue(context.Background(), testAttributionKey{}, Attribution{JobID: 1, Group: "job/1"})
func init() {
// Attribute logs in these tests from the context value above,
// in place of the fs/accounting and fs/rc/jobs implementations.
fs.StatsGroupFromContext = func(ctx context.Context) (string, bool) {
attribution, _ := ctx.Value(testAttributionKey{}).(Attribution)
return attribution.Group, attribution.Group != ""
}
fs.JobIDFromContext = func(ctx context.Context) (int64, bool) {
attribution, _ := ctx.Value(testAttributionKey{}).(Attribution)
return attribution.JobID, attribution.JobID != 0
}
}
// testEntry is a decoded log entry from the Buffer.
type testEntry struct {
Seq int64 `json:"seq"`
Level string `json:"level"`
Msg string `json:"msg"`
}
// decodeEntries decodes entries checking they are all valid JSON.
func decodeEntries(t *testing.T, entries Entries) (out []testEntry) {
t.Helper()
for _, entry := range entries {
var e testEntry
require.NoError(t, json.Unmarshal(entry, &e), string(entry))
out = append(out, e)
}
return out
}
// addEntry adds a log entry in the same format as the JSON log to b.
func addEntry(b *Buffer, level slog.Level, msg string) {
add(b, level, Attribution{}, fmt.Sprintf(`{"level":%q,"msg":%q}`+"\n", slogLevelToString(level), msg))
}
// add adds a log entry to b the way the log output does.
func add(b *Buffer, level slog.Level, attribution Attribution, text string) {
seq := nextSeq.Add(1) - 1
b.add(seq, level, attribution, makeEntry(seq, text))
}
// newTestBuffer makes an empty buffer of size with sequence numbers starting from 0.
func newTestBuffer(size int64) *Buffer {
nextSeq.Store(0)
b := &Buffer{}
b.SetSize(size)
return b
}
func TestBufferDisabled(t *testing.T) {
b := newTestBuffer(0)
assert.False(t, b.Enabled())
addEntry(b, slog.LevelInfo, "dropped")
// The entry used up a sequence number but wasn't stored
assert.Equal(t, int64(1), b.Seq())
entries, next, lost := b.Get(0, math.MaxInt64, Filter{Level: slog.LevelDebug}, 0)
assert.Equal(t, Entries{}, entries)
assert.Equal(t, int64(1), next)
assert.Equal(t, int64(1), lost)
}
func TestBufferGet(t *testing.T) {
b := newTestBuffer(1024)
assert.True(t, b.Enabled())
for i := range 10 {
level := slog.LevelInfo
if i%2 == 1 {
level = slog.LevelError
}
addEntry(b, level, fmt.Sprintf("msg%d", i))
}
assert.Equal(t, int64(10), b.Seq())
for _, test := range []struct {
name string
from, to int64
level slog.Level
limit int
wantSeqs []int64
wantNext int64
wantLost int64
}{
{name: "all", from: 0, to: math.MaxInt64, level: slog.LevelDebug, wantSeqs: []int64{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}, wantNext: 10},
{name: "range", from: 3, to: 6, level: slog.LevelDebug, wantSeqs: []int64{3, 4, 5}, wantNext: 6},
{name: "level", from: 0, to: math.MaxInt64, level: slog.LevelError, wantSeqs: []int64{1, 3, 5, 7, 9}, wantNext: 10},
{name: "limit", from: 2, to: math.MaxInt64, level: slog.LevelDebug, limit: 3, wantSeqs: []int64{2, 3, 4}, wantNext: 5},
{name: "limit and level", from: 0, to: math.MaxInt64, level: slog.LevelError, limit: 2, wantSeqs: []int64{1, 3}, wantNext: 4},
{name: "negative from", from: -5, to: 2, level: slog.LevelDebug, wantSeqs: []int64{0, 1}, wantNext: 2},
{name: "from the end", from: 10, to: math.MaxInt64, level: slog.LevelDebug, wantNext: 10},
{name: "from past the end", from: 100, to: math.MaxInt64, level: slog.LevelDebug, wantNext: 10},
{name: "to before from", from: 5, to: 2, level: slog.LevelDebug, wantNext: 5},
} {
t.Run(test.name, func(t *testing.T) {
entries, next, lost := b.Get(test.from, test.to, Filter{Level: test.level}, test.limit)
var gotSeqs []int64
for _, e := range decodeEntries(t, entries) {
gotSeqs = append(gotSeqs, e.Seq)
assert.Equal(t, fmt.Sprintf("msg%d", e.Seq), e.Msg)
}
assert.Equal(t, test.wantSeqs, gotSeqs)
assert.Equal(t, test.wantNext, next)
assert.Equal(t, test.wantLost, lost)
})
}
}
func TestBufferDropsOldEntries(t *testing.T) {
b := newTestBuffer(1024)
for i := range 100 {
addEntry(b, slog.LevelInfo, fmt.Sprintf("message number %d", i))
}
assert.LessOrEqual(t, b.size, int64(1024))
entries, next, lost := b.Get(0, math.MaxInt64, Filter{Level: slog.LevelDebug}, 0)
decoded := decodeEntries(t, entries)
require.NotEmpty(t, decoded)
assert.Greater(t, lost, int64(0))
assert.Equal(t, lost, decoded[0].Seq, "lost should be the number of entries dropped")
assert.Equal(t, int64(100), next)
assert.Equal(t, int64(99), decoded[len(decoded)-1].Seq)
assert.Equal(t, int(100-lost), len(decoded))
// The window is entirely in the dropped entries
entries, next, gotLost := b.Get(1, 3, Filter{Level: slog.LevelDebug}, 0)
assert.Empty(t, entries)
assert.Equal(t, int64(2), gotLost)
assert.Equal(t, int64(3), next)
// An entry bigger than the Buffer uses a sequence number but
// isn't stored and doesn't evict the other entries
addEntry(b, slog.LevelInfo, string(make([]byte, 2048)))
assert.Equal(t, int64(101), b.Seq())
entries, next, lost = b.Get(0, math.MaxInt64, Filter{Level: slog.LevelDebug}, 0)
assert.Equal(t, len(decoded), len(entries))
assert.Equal(t, int64(101), next)
assert.Equal(t, decoded[0].Seq+1, lost, "dropped entries plus the oversized one")
entries, next, lost = b.Get(100, math.MaxInt64, Filter{Level: slog.LevelDebug}, 0)
assert.Empty(t, entries)
assert.Equal(t, int64(101), next)
assert.Equal(t, int64(1), lost)
// A gap in the middle of the range is counted as lost too
addEntry(b, slog.LevelInfo, "after the gap")
entries, next, lost = b.Get(99, math.MaxInt64, Filter{Level: slog.LevelDebug}, 0)
assert.Len(t, entries, 2)
assert.Equal(t, int64(102), next)
assert.Equal(t, int64(1), lost)
// Limit stops before the gap
entries, next, lost = b.Get(99, math.MaxInt64, Filter{Level: slog.LevelDebug}, 1)
assert.Len(t, entries, 1)
assert.Equal(t, int64(101), next)
assert.Equal(t, int64(1), lost)
// Disabling discards the entries
addEntry(b, slog.LevelInfo, "kept")
b.SetSize(0)
assert.False(t, b.Enabled())
entries, _, _ = b.Get(0, math.MaxInt64, Filter{Level: slog.LevelDebug}, 0)
assert.Empty(t, entries)
assert.Equal(t, int64(103), b.Seq(), "sequence numbers carry on")
}
// Get shouldn't scan the whole buffer when the filter matches very little
func TestBufferGetMaxExamine(t *testing.T) {
b := newTestBuffer(int64(16 * fs.Mebi))
for i := range maxExamine + 10 {
add(b, slog.LevelInfo, Attribution{JobID: 2}, fmt.Sprintf(`{"msg":"msg%d"}`, i))
}
add(b, slog.LevelInfo, Attribution{JobID: 1}, `{"msg":"wanted"}`)
// Nothing matches in the first maxExamine entries so Get stops there
entries, next, lost := b.Get(0, math.MaxInt64, Filter{Level: slog.LevelDebug, JobID: 1}, 10)
assert.Empty(t, entries)
assert.Equal(t, int64(maxExamine), next)
assert.Equal(t, int64(0), lost)
// Carrying on from next finds it
entries, next, _ = b.Get(next, math.MaxInt64, Filter{Level: slog.LevelDebug, JobID: 1}, 10)
decoded := decodeEntries(t, entries)
require.Len(t, decoded, 1)
assert.Equal(t, "wanted", decoded[0].Msg)
assert.Equal(t, int64(maxExamine+11), next)
// With no limit everything is examined
entries, _, _ = b.Get(0, math.MaxInt64, Filter{Level: slog.LevelDebug, JobID: 1}, 0)
assert.Len(t, entries, 1)
}
func TestBufferInvalidJSON(t *testing.T) {
b := newTestBuffer(1024)
for _, text := range []string{
"not \"JSON\"\n",
"control chars \a\x00\xff\U0001F600",
"{",
"{ }",
"{}",
} {
add(b, slog.LevelInfo, Attribution{}, text)
}
entries, _, _ := b.Get(0, math.MaxInt64, Filter{Level: slog.LevelDebug}, 0)
decoded := decodeEntries(t, entries)
require.Len(t, decoded, 5)
assert.Equal(t, `not "JSON"`, decoded[0].Msg)
assert.Equal(t, "control chars \a\x00\ufffd\U0001F600", decoded[1].Msg)
assert.Equal(t, "{", decoded[2].Msg)
assert.Equal(t, "{ }", decoded[3].Msg)
assert.Equal(t, "{}", decoded[4].Msg)
// Check they can all be marshalled
_, err := json.Marshal(entries)
require.NoError(t, err)
}
func TestEntriesString(t *testing.T) {
entries := Entries{json.RawMessage(`{"seq":0}`), json.RawMessage(`{"seq":1}`)}
assert.Equal(t, "2 log entries", entries.String())
// Check that the entries aren't rendered when logging an rc reply
assert.Equal(t, "map[_logs:map[entries:2 log entries]]", fmt.Sprintf("%+v", rc.Params{"_logs": rc.Params{"entries": entries}}))
// but that they marshal as JSON
out, err := json.Marshal(entries)
require.NoError(t, err)
assert.Equal(t, `[{"seq":0},{"seq":1}]`, string(out))
}
// Check setting the option connects and disconnects the buffer
func TestSetBufferSize(t *testing.T) {
oldOpt := Opt.BufferSize
defer func() {
Opt.BufferSize = oldOpt
setBufferSize()
}()
outputs := func() int {
Handler.mu.Lock()
defer Handler.mu.Unlock()
return len(Handler.outputExtra)
}
Opt.BufferSize = 0
setBufferSize()
assert.False(t, Recent.Enabled())
start := outputs()
fs.Errorf(nil, "not buffered")
Opt.BufferSize = 64 * 1024
setBufferSize()
assert.True(t, Recent.Enabled())
assert.Equal(t, start+1, outputs())
seq := Recent.Seq()
fs.Errorf(nil, "buffered")
entries, _, _ := Recent.Get(seq, math.MaxInt64, Filter{Level: slog.LevelDebug}, 0)
decoded := decodeEntries(t, entries)
require.Len(t, decoded, 1)
assert.Equal(t, "buffered", decoded[0].Msg)
// Setting again shouldn't connect again
setBufferSize()
assert.Equal(t, start+1, outputs())
Opt.BufferSize = 0
setBufferSize()
assert.False(t, Recent.Enabled())
assert.Equal(t, start, outputs())
fs.Errorf(nil, "not buffered")
entries, _, _ = Recent.Get(0, math.MaxInt64, Filter{Level: slog.LevelDebug}, 0)
assert.Empty(t, entries)
}
// Check the Buffer works as an output of the handler.
func TestBufferFromHandler(t *testing.T) {
b := newTestBuffer(64 * 1024)
h := NewOutputHandler(io.Discard, nil, logFormatDate|logFormatTime)
h.addRecordOutput(true, func(r slog.Record, attribution Attribution, text string) {
seq := nextSeq.Add(1) - 1
b.add(seq, r.Level, attribution, makeEntry(seq, text))
})
r := slog.NewRecord(t0, fs.SlogLevelNotice, "hello", 0)
r.AddAttrs(slog.String("object", "file.txt"))
require.NoError(t, h.Handle(testAttributionCtx, r))
require.NoError(t, h.Handle(context.Background(), slog.NewRecord(t0, slog.LevelError, "oops", 0)))
entries, next, lost := b.Get(0, math.MaxInt64, Filter{Level: slog.LevelDebug}, 0)
assert.Equal(t, int64(2), next)
assert.Equal(t, int64(0), lost)
decoded := decodeEntries(t, entries)
require.Len(t, decoded, 2)
assert.Equal(t, testEntry{Seq: 0, Level: "notice", Msg: "hello"}, decoded[0])
assert.Equal(t, testEntry{Seq: 1, Level: "error", Msg: "oops"}, decoded[1])
var full map[string]any
require.NoError(t, json.Unmarshal(entries[0], &full))
assert.Equal(t, "file.txt", full["object"])
assert.Equal(t, "job/1", full["group"])
assert.Equal(t, float64(1), full["jobid"])
assert.Contains(t, full, "time")
assert.Contains(t, full, "source")
// Check the group was recorded for filtering
entries, _, _ = b.Get(0, math.MaxInt64, Filter{Level: slog.LevelDebug, Group: "job/1"}, 0)
decoded = decodeEntries(t, entries)
require.Len(t, decoded, 1)
assert.Equal(t, "hello", decoded[0].Msg)
}
func TestBufferGetGroup(t *testing.T) {
b := newTestBuffer(1024)
for i, jobID := range []int64{0, 1, 2, 1, 0, 2} {
attribution := Attribution{}
if jobID != 0 {
attribution = Attribution{JobID: jobID, Group: fmt.Sprintf("job/%d", jobID)}
}
add(b, slog.LevelInfo, attribution, fmt.Sprintf(`{"msg":"msg%d"}`, i))
}
add(b, slog.LevelDebug, Attribution{JobID: 1, Group: "job/1"}, `{"msg":"msg6"}`)
for _, test := range []struct {
name string
filter Filter
want []int64
}{
{"all", Filter{Level: slog.LevelDebug}, []int64{0, 1, 2, 3, 4, 5, 6}},
{"group", Filter{Level: slog.LevelDebug, Group: "job/1"}, []int64{1, 3, 6}},
{"group and unattributed", Filter{Level: slog.LevelDebug, Group: "job/1", Unattributed: true}, []int64{0, 1, 3, 4, 6}},
{"group and level", Filter{Level: slog.LevelInfo, Group: "job/1"}, []int64{1, 3}},
{"unknown group", Filter{Level: slog.LevelDebug, Group: "job/3"}, nil},
{"unknown group and unattributed", Filter{Level: slog.LevelDebug, Group: "job/3", Unattributed: true}, []int64{0, 4}},
{"job", Filter{Level: slog.LevelDebug, JobID: 1}, []int64{1, 3, 6}},
{"job and unattributed", Filter{Level: slog.LevelDebug, JobID: 2, Unattributed: true}, []int64{0, 2, 4, 5}},
{"job or group", Filter{Level: slog.LevelDebug, JobID: 2, Group: "job/1"}, []int64{1, 2, 3, 5, 6}},
} {
t.Run(test.name, func(t *testing.T) {
entries, next, lost := b.Get(0, math.MaxInt64, test.filter, 0)
var got []int64
for _, e := range decodeEntries(t, entries) {
got = append(got, e.Seq)
}
assert.Equal(t, test.want, got)
assert.Equal(t, int64(7), next)
assert.Equal(t, int64(0), lost, "filtered entries aren't lost")
})
}
}
func TestBufferConcurrency(t *testing.T) {
b := newTestBuffer(4096)
var wg sync.WaitGroup
for range 4 {
wg.Go(func() {
for i := range 500 {
addEntry(b, slog.LevelInfo, fmt.Sprintf("msg%d", i))
}
})
}
wg.Go(func() {
var from int64
for range 500 {
var entries []json.RawMessage
entries, from, _ = b.Get(from, math.MaxInt64, Filter{Level: slog.LevelDebug}, 10)
_ = decodeEntries(t, entries)
_ = b.Seq()
}
})
wg.Wait()
assert.Equal(t, int64(2000), b.Seq())
}
func TestRcLog(t *testing.T) {
call := rc.Calls.Get("core/log")
require.NotNil(t, call)
ctx := context.Background()
oldRecent := Recent
defer func() { Recent = oldRecent }()
Recent = newTestBuffer(0)
_, err := call.Fn(ctx, rc.Params{})
assert.Equal(t, ErrBufferDisabled, err)
assert.True(t, rc.IsErrParamInvalid(err), err)
Recent = newTestBuffer(64 * 1024)
for i := range 10 {
level := slog.LevelInfo
if i%2 == 1 {
level = slog.LevelError
}
addEntry(Recent, level, fmt.Sprintf("msg%d", i))
}
seqs := func(out rc.Params) (seqs []int64) {
for _, e := range decodeEntries(t, out["entries"].(Entries)) {
seqs = append(seqs, e.Seq)
}
return seqs
}
out, err := call.Fn(ctx, rc.Params{})
require.NoError(t, err)
assert.Equal(t, []int64{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}, seqs(out))
assert.Equal(t, int64(10), out["next"])
assert.Equal(t, int64(0), out["lost"])
out, err = call.Fn(ctx, rc.Params{"since": 4, "limit": 2})
require.NoError(t, err)
assert.Equal(t, []int64{4, 5}, seqs(out))
assert.Equal(t, int64(6), out["next"])
out, err = call.Fn(ctx, rc.Params{"since": -3})
require.NoError(t, err)
assert.Equal(t, []int64{7, 8, 9}, seqs(out))
out, err = call.Fn(ctx, rc.Params{"since": -100, "level": "error"})
require.NoError(t, err)
assert.Equal(t, []int64{1, 3, 5, 7, 9}, seqs(out))
_, err = call.Fn(ctx, rc.Params{"level": "potato"})
require.Error(t, err)
assert.True(t, rc.IsErrParamInvalid(err), err)
// since at the end is OK but beyond the end is an error
out, err = call.Fn(ctx, rc.Params{"since": 10})
require.NoError(t, err)
assert.Empty(t, out["entries"])
assert.Equal(t, int64(10), out["next"])
_, err = call.Fn(ctx, rc.Params{"since": 11})
require.Error(t, err)
assert.True(t, rc.IsErrParamInvalid(err), err)
assert.Contains(t, err.Error(), "beyond the end")
// Check the output can be serialized
out, err = call.Fn(ctx, rc.Params{"since": 9})
require.NoError(t, err)
var buf []byte
buf, err = json.Marshal(out)
require.NoError(t, err)
assert.JSONEq(t, `{"entries":[{"seq":9,"level":"ERROR","msg":"msg9"}],"next":10,"lost":0}`, string(buf))
// Filter by group
addEntry(Recent, slog.LevelInfo, "not in a group")
add(Recent, slog.LevelInfo, Attribution{JobID: 1, Group: "job/1"}, `{"msg":"in job/1"}`)
out, err = call.Fn(ctx, rc.Params{"since": 10, "group": "job/1"})
require.NoError(t, err)
assert.Equal(t, []int64{11}, seqs(out))
assert.Equal(t, int64(12), out["next"])
// Filter by rc job
out, err = call.Fn(ctx, rc.Params{"since": 10, "jobid": 1})
require.NoError(t, err)
assert.Equal(t, []int64{11}, seqs(out))
}
-344
View File
@@ -1,344 +0,0 @@
package log
import (
"context"
"encoding/json"
"fmt"
"log/slog"
"net/http"
"strconv"
"strings"
"sync"
"time"
"github.com/rclone/rclone/fs"
"github.com/rclone/rclone/fs/rc"
)
// Number of frames buffered for each subscriber before they get dropped.
const subscriberBacklog = 1024
// newline ends each frame in the stream
var newline = []byte{'\n'}
// subscriber receives log entries as they are made.
type subscriber struct {
filter Filter
frames chan json.RawMessage
mu sync.Mutex
dropped int64 // frames dropped because frames was full
}
// subscribers receiving log entries
var (
subscribersMu sync.Mutex
subscribers = map[*subscriber]struct{}{}
)
// subscribed returns whether anything is subscribed to the log.
func subscribed() bool {
subscribersMu.Lock()
defer subscribersMu.Unlock()
return len(subscribers) > 0
}
// subscribe returns a subscriber receiving the log entries which
// match filter and a function to unsubscribe it again.
func subscribe(filter Filter) (*subscriber, func()) {
s := &subscriber{
filter: filter,
frames: make(chan json.RawMessage, subscriberBacklog),
}
subscribersMu.Lock()
subscribers[s] = struct{}{}
subscribersMu.Unlock()
updateOutput()
return s, func() {
subscribersMu.Lock()
delete(subscribers, s)
subscribersMu.Unlock()
updateOutput()
}
}
// takeDropped returns the number of frames dropped since it was last called.
func (s *subscriber) takeDropped() int64 {
s.mu.Lock()
defer s.mu.Unlock()
dropped := s.dropped
s.dropped = 0
return dropped
}
// send queues frame for the subscriber, dropping it if it isn't
// keeping up. It never blocks as it is called while logging.
//
// Any frames dropped earlier are reported first so the client is
// told where the gap in the stream is.
func (s *subscriber) send(frame json.RawMessage) {
s.mu.Lock()
defer s.mu.Unlock()
if s.dropped > 0 {
select {
case s.frames <- droppedFrame(s.dropped):
s.dropped = 0
default:
s.dropped++
return
}
}
select {
case s.frames <- frame:
default:
s.dropped++
}
}
// logFrame makes the frame sent to the subscribers for a log entry.
func logFrame(entry json.RawMessage) json.RawMessage {
const prefix = `{"type":"log",`
frame := make(json.RawMessage, 0, len(prefix)+len(entry))
frame = append(frame, prefix...)
frame = append(frame, entry[1:]...)
return frame
}
// publish sends a log entry to the subscribers which want it.
//
// This is called with the log handler's mutex held so it must not log
// or block.
func publish(level slog.Level, attribution Attribution, entry json.RawMessage) {
subscribersMu.Lock()
defer subscribersMu.Unlock()
var frame json.RawMessage
for s := range subscribers {
if !s.filter.match(level, attribution) {
continue
}
if frame == nil {
frame = logFrame(entry)
}
s.send(frame)
}
}
func init() {
rc.Add(rc.Call{
Path: "core/events",
Fn: rcEvents,
NeedsResponse: true,
WritesResponse: true,
Title: "Streams events, such as the logs, as they happen.",
Help: strings.ReplaceAll(`
This streams events as they happen until the connection is closed. It
is only available over HTTP.
Events are returned as newline delimited JSON objects, one per line,
each with a |type| saying what it is. The types are:
- |start| - sent when the stream starts
- seq - the sequence number the next log entry will be given
- jobid - the rc job of the stream, which [job/stop](#job-stop) stops
- |log| - a log entry in the format used by [core/log](#core-log)
- |dropped| - sent if the client isn't reading the stream fast enough
- count - the number of events dropped
- |heartbeat| - sent when the stream is idle so it doesn't time out
Unlike [core/log](#core-log) this doesn't need |--log-buffer-size| to
be set as the events are not stored - they are sent as they happen.
Parameters:
- level - only stream logs at this level or more severe, e.g. "INFO" - optional
- group - only stream logs attributed to this stats group, e.g. "job/1" - optional
- jobid - only stream logs attributed to this rc job, e.g. 1 - optional
- unattributed - if set with group or jobid, also stream the logs which
aren't attributed to a job - optional
- since - send the entries from this sequence number before streaming
the new ones - optional
- This needs the log buffer to be enabled with |--log-buffer-size|.
- Use it with the |seq| from the last entry seen to carry on where a
previous stream left off.
- heartbeat - seconds between heartbeats, 0 to disable - optional, defaults to 30
Example:
|||sh
curl -u user:pass -N -X POST http://127.0.0.1:5572/core/events
|||
Returns
|||json
{"type":"start","seq":42}
{"type":"log","seq":42,"time":"2026-09-21T12:16:41.134507+01:00","level":"info","msg":"Copied (new)","object":"file.txt","objectType":"*local.Object","size":3,"source":"operations/copy.go:385","jobid":1,"group":"job/1"}
{"type":"heartbeat","time":"2026-09-21T12:17:11.134507+01:00"}
|||
Note that the rc calls made by the client reading the stream are
logged at DEBUG level like any other, so a client streaming at that
level sees its own polling. Use |--rc-log-calls=false| to turn that
off.
`, "|", "`"),
})
}
// rcEvents streams the events to the HTTP response until the
// connection is closed.
func rcEvents(ctx context.Context, in rc.Params) (out rc.Params, err error) {
w, err := in.GetHTTPResponseWriter()
if err != nil {
return nil, fmt.Errorf("response object is required: %w", err)
}
filter, err := eventsFilter(in)
if err != nil {
return nil, err
}
since, err := in.GetInt64("since")
if rc.NotErrParamNotFound(err) {
return nil, err
}
replay := err == nil
if replay && !Recent.Enabled() {
return nil, ErrBufferDisabled
}
heartbeat := 30 * time.Second
if seconds, err := in.GetInt64("heartbeat"); err == nil {
heartbeat = time.Duration(seconds) * time.Second
} else if rc.NotErrParamNotFound(err) {
return nil, err
}
// Subscribe before reading the buffer so no entry is missed
// between the two - the ones sent from the buffer are skipped
// from the stream below.
s, unsubscribe := subscribe(filter)
defer unsubscribe()
startSeq := Recent.Seq()
// The write deadline is cleared as this runs until the client
// goes away, then set for each write so a stuck client doesn't
// block forever.
rcw := http.NewResponseController(w)
if err := rcw.SetWriteDeadline(time.Time{}); err != nil {
return nil, fmt.Errorf("can't stream events: %w", err)
}
w.Header().Set("Content-Type", "application/x-ndjson")
w.Header().Set("Cache-Control", "no-store")
w.Header().Set("X-Content-Type-Options", "nosniff")
w.WriteHeader(http.StatusOK)
// The frames are shared between the subscribers so they must
// not be written to - the newline goes in a separate write.
write := func(frame json.RawMessage) error {
if err := rcw.SetWriteDeadline(time.Now().Add(time.Minute)); err != nil {
return err
}
if _, err := w.Write(frame); err != nil {
return err
}
if _, err := w.Write(newline); err != nil {
return err
}
return rcw.Flush()
}
start := `{"type":"start","seq":` + strconv.FormatInt(startSeq, 10)
if jobID, ok := fs.JobIDFromContext(ctx); ok {
start += `,"jobid":` + strconv.FormatInt(jobID, 10)
}
if err := write(json.RawMessage(start + `}`)); err != nil {
return nil, nil
}
if replay {
entries, _, lost := Recent.Get(since, startSeq, filter, 0)
if lost > 0 {
if err := write(droppedFrame(lost)); err != nil {
return nil, nil
}
}
for _, entry := range entries {
if err := write(logFrame(entry)); err != nil {
return nil, nil
}
}
}
var ticker *time.Ticker
tick := make(<-chan time.Time)
if heartbeat > 0 {
ticker = time.NewTicker(heartbeat)
defer ticker.Stop()
tick = ticker.C
}
for {
select {
case <-ctx.Done():
return nil, nil
case frame := <-s.frames:
// Skip the entries already sent from the buffer
if replay && frameSeq(frame) < startSeq {
continue
}
if err := write(frame); err != nil {
return nil, nil
}
case now := <-tick:
// Report any drops which the log going quiet left
// unreported
if dropped := s.takeDropped(); dropped > 0 {
if err := write(droppedFrame(dropped)); err != nil {
return nil, nil
}
}
frame := `{"type":"heartbeat","time":` + strconv.Quote(now.Format(time.RFC3339Nano)) + `}`
if err := write(json.RawMessage(frame)); err != nil {
return nil, nil
}
}
}
}
// droppedFrame makes a frame saying count events were dropped.
func droppedFrame(count int64) json.RawMessage {
return json.RawMessage(`{"type":"dropped","count":` + strconv.FormatInt(count, 10) + `}`)
}
// frameSeq returns the sequence number of a log frame or -1 if it doesn't have one.
func frameSeq(frame json.RawMessage) int64 {
var entry struct {
Seq *int64 `json:"seq"`
}
if err := json.Unmarshal(frame, &entry); err != nil || entry.Seq == nil {
return -1
}
return *entry.Seq
}
// eventsFilter reads the log filter from the parameters.
func eventsFilter(in rc.Params) (filter Filter, err error) {
filter.Level = slog.LevelDebug
levelString, err := in.GetString("level")
if err == nil {
filter.Level, err = ParseLevel(levelString)
if err != nil {
return filter, rc.NewErrParamInvalid(err)
}
} else if rc.NotErrParamNotFound(err) {
return filter, err
}
filter.Group, err = in.GetString("group")
if rc.NotErrParamNotFound(err) {
return filter, err
}
filter.JobID, err = in.GetInt64("jobid")
if rc.NotErrParamNotFound(err) {
return filter, err
}
filter.Unattributed, err = in.GetBool("unattributed")
if rc.NotErrParamNotFound(err) {
return filter, err
}
return filter, nil
}
-266
View File
@@ -1,266 +0,0 @@
package log
import (
"bufio"
"context"
"encoding/json"
"fmt"
"log/slog"
"net/http"
"net/http/httptest"
"sync"
"testing"
"time"
"github.com/rclone/rclone/fs"
"github.com/rclone/rclone/fs/rc"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// frame is a decoded event from the stream.
type frame struct {
Type string `json:"type"`
Seq int64 `json:"seq"`
Msg string `json:"msg"`
JobID int64 `json:"jobid"`
Count int64 `json:"count"`
}
// eventServer serves core/events and returns a function to read the
// frames from it one at a time and a function to stop it.
func eventServer(t *testing.T, in rc.Params) (next func() frame, stop func()) {
call := rc.Calls.Get("core/events")
require.NotNil(t, call)
assert.True(t, call.NeedsResponse)
assert.True(t, call.WritesResponse)
done := make(chan struct{})
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
params := rc.Params{"_response": w}
for k, v := range in {
params[k] = v
}
_, err := call.Fn(r.Context(), params)
assert.NoError(t, err)
close(done)
}))
resp, err := http.Get(server.URL)
require.NoError(t, err)
require.Equal(t, http.StatusOK, resp.StatusCode)
assert.Equal(t, "application/x-ndjson", resp.Header.Get("Content-Type"))
scanner := bufio.NewScanner(resp.Body)
next = func() frame {
t.Helper()
require.True(t, scanner.Scan(), "no more frames: %v", scanner.Err())
var f frame
require.NoError(t, json.Unmarshal(scanner.Bytes(), &f), scanner.Text())
return f
}
stop = func() {
_ = resp.Body.Close()
server.CloseClientConnections()
server.Close()
select {
case <-done:
case <-time.After(30 * time.Second):
t.Error("core/events didn't return after the client went away")
}
}
return next, stop
}
// logAt logs msg via the real log handler so it goes through the
// output to the subscribers.
func logAt(ctx context.Context, level fs.LogLevel, msg string) {
fs.LogPrintfCtx(ctx, level, nil, "%s", msg)
}
func TestRcEvents(t *testing.T) {
ctx := context.Background()
setTestLogLevel(t, fs.LogLevelInfo)
next, stop := eventServer(t, rc.Params{"heartbeat": 0})
defer stop()
start := next()
assert.Equal(t, "start", start.Type)
logAt(ctx, fs.LogLevelNotice, "first")
f := next()
assert.Equal(t, "log", f.Type)
assert.Equal(t, "first", f.Msg)
assert.Equal(t, start.Seq, f.Seq, "the stream starts at the sequence number in the start frame")
logAt(testAttributionCtx, fs.LogLevelNotice, "attributed")
f = next()
assert.Equal(t, "attributed", f.Msg)
assert.Equal(t, int64(1), f.JobID)
// Logs below the requested level aren't sent
logAt(ctx, fs.LogLevelDebug, "debug")
logAt(ctx, fs.LogLevelNotice, "second")
f = next()
assert.Equal(t, "second", f.Msg)
}
func TestRcEventsFilter(t *testing.T) {
ctx := context.Background()
setTestLogLevel(t, fs.LogLevelInfo)
next, stop := eventServer(t, rc.Params{"heartbeat": 0, "jobid": 1})
defer stop()
assert.Equal(t, "start", next().Type)
// Only the logs of job 1 are sent
logAt(ctx, fs.LogLevelNotice, "unattributed")
logAt(testAttributionCtx, fs.LogLevelNotice, "job 1")
f := next()
assert.Equal(t, "job 1", f.Msg)
assert.Equal(t, int64(1), f.JobID)
}
func TestRcEventsHeartbeat(t *testing.T) {
setTestLogLevel(t, fs.LogLevelInfo)
next, stop := eventServer(t, rc.Params{"heartbeat": 1})
defer stop()
assert.Equal(t, "start", next().Type)
assert.Equal(t, "heartbeat", next().Type)
}
func TestRcEventsSince(t *testing.T) {
ctx := context.Background()
setTestLogLevel(t, fs.LogLevelInfo)
// Needs the log buffer for the replay
_, err := rc.Calls.Get("core/events").Fn(ctx, rc.Params{"_response": httptest.NewRecorder(), "since": 0})
assert.Equal(t, ErrBufferDisabled, err)
oldRecent, oldSize := Recent, Opt.BufferSize
t.Cleanup(func() {
Recent, Opt.BufferSize = oldRecent, oldSize
setBufferSize()
})
Recent = newTestBuffer(0)
Opt.BufferSize = 64 * fs.Kibi
setBufferSize()
logAt(ctx, fs.LogLevelNotice, "before the stream")
since := Recent.Seq() - 1
next, stop := eventServer(t, rc.Params{"heartbeat": 0, "since": since})
defer stop()
assert.Equal(t, "start", next().Type)
// The entry from before the stream started is replayed first
f := next()
assert.Equal(t, "log", f.Type)
assert.Equal(t, "before the stream", f.Msg)
assert.Equal(t, since, f.Seq)
// then the new ones follow with no repeats
logAt(ctx, fs.LogLevelNotice, "during the stream")
f = next()
assert.Equal(t, "during the stream", f.Msg)
assert.Equal(t, since+1, f.Seq)
}
// Check a subscriber which isn't reading gets told what it missed
func TestRcEventsDropped(t *testing.T) {
ctx := context.Background()
setTestLogLevel(t, fs.LogLevelInfo)
s, unsubscribe := subscribe(Filter{Level: slog.LevelDebug})
defer unsubscribe()
for i := range subscriberBacklog + 10 {
logAt(ctx, fs.LogLevelNotice, fmt.Sprintf("msg%d", i))
}
assert.Equal(t, subscriberBacklog, len(s.frames))
assert.Equal(t, int64(10), s.dropped)
// Read the backlog - the dropped marker comes after it, where
// the gap in the stream is, and not before
var msgs []string
var dropped int64
for range subscriberBacklog {
var f frame
require.NoError(t, json.Unmarshal(<-s.frames, &f))
if f.Type == "dropped" {
dropped = f.Count
} else {
msgs = append(msgs, f.Msg)
}
}
assert.Equal(t, int64(0), dropped, "nothing is reported before the backlog is read")
assert.Equal(t, "msg0", msgs[0])
// The marker is queued as soon as there is room for it
logAt(ctx, fs.LogLevelNotice, "after the gap")
var f frame
require.NoError(t, json.Unmarshal(<-s.frames, &f))
assert.Equal(t, "dropped", f.Type)
assert.Equal(t, int64(10), f.Count)
require.NoError(t, json.Unmarshal(<-s.frames, &f))
assert.Equal(t, "after the gap", f.Msg)
assert.Equal(t, int64(0), s.takeDropped())
}
// Two streams must not write to each other's frames
func TestRcEventsTwoStreams(t *testing.T) {
ctx := context.Background()
setTestLogLevel(t, fs.LogLevelInfo)
next1, stop1 := eventServer(t, rc.Params{"heartbeat": 0})
defer stop1()
next2, stop2 := eventServer(t, rc.Params{"heartbeat": 0})
defer stop2()
assert.Equal(t, "start", next1().Type)
assert.Equal(t, "start", next2().Type)
var wg sync.WaitGroup
for _, next := range []func() frame{next1, next2} {
wg.Go(func() {
for range 100 {
f := next()
assert.Equal(t, "log", f.Type)
}
})
}
for i := range 100 {
logAt(ctx, fs.LogLevelNotice, fmt.Sprintf("msg%d", i))
}
wg.Wait()
}
// Check the log output is only connected while it is needed
func TestSubscribeConnectsOutput(t *testing.T) {
outputs := func() int {
Handler.mu.Lock()
defer Handler.mu.Unlock()
return len(Handler.outputExtra)
}
before := outputs()
s1, unsubscribe1 := subscribe(Filter{Level: slog.LevelDebug})
assert.Equal(t, before+1, outputs())
_, unsubscribe2 := subscribe(Filter{Level: slog.LevelDebug})
assert.Equal(t, before+1, outputs(), "one output serves all the subscribers")
unsubscribe1()
assert.Equal(t, before+1, outputs())
unsubscribe2()
assert.Equal(t, before, outputs())
assert.Empty(t, s1.frames)
}
// setTestLogLevel sets the log level for the duration of the test
func setTestLogLevel(t *testing.T, level fs.LogLevel) {
ci := fs.GetConfig(context.Background())
oldLevel := ci.LogLevel
oldSlogLevel := Handler.SetLevel(fs.LogLevelToSlog(level))
ci.LogLevel = level
t.Cleanup(func() {
ci.LogLevel = oldLevel
Handler.SetLevel(oldSlogLevel)
})
}
+1 -13
View File
@@ -47,11 +47,6 @@ var OptionsInfo = fs.Options{{
Default: logFormatDate | logFormatTime,
Help: "Comma separated list of log format options",
Groups: "Logging",
}, {
Name: "log_buffer_size",
Default: fs.SizeSuffix(0),
Help: "Keep this much of the most recent logs in memory for reading with the rc (0 to disable)",
Groups: "Logging,RC",
}, {
Name: "syslog",
Default: false,
@@ -88,7 +83,6 @@ type Options struct {
MaxAge fs.Duration `config:"log_file_max_age"` // Max age of log file
Compress bool `config:"log_file_compress"` // Set to compress log file
Format logFormat `config:"log_format"` // Comma separated list of log format options
BufferSize fs.SizeSuffix `config:"log_buffer_size"` // Size of the in memory buffer of recent logs
UseSyslog bool `config:"syslog"` // Use Syslog for logging
SyslogFacility string `config:"syslog_facility"` // Facility for syslog, e.g. KERN,USER,...
LogSystemdSupport bool `config:"log_systemd"` // set if using systemd logging
@@ -96,13 +90,7 @@ type Options struct {
}
func init() {
fs.RegisterGlobalOptions(fs.OptionsInfo{Name: "log", Opt: &Opt, Options: OptionsInfo, Reload: optReload})
}
// optReload makes the options which can be changed at runtime live.
func optReload(ctx context.Context) error {
setBufferSize()
return nil
fs.RegisterGlobalOptions(fs.OptionsInfo{Name: "log", Opt: &Opt, Options: OptionsInfo})
}
// Opt is the options for the logger
+14 -78
View File
@@ -10,7 +10,6 @@ import (
"log/slog"
"os"
"runtime"
"slices"
"strings"
"sync"
"time"
@@ -140,9 +139,9 @@ type OutputHandler struct {
levelVar slog.LevelVar
writer io.Writer
mu sync.Mutex
output []outputFn // log to writer if empty or the last item
outputExtra []*outputExtra // log to all these additional places
format logFormat // protected by mu
output []outputFn // log to writer if empty or the last item
outputExtra []outputExtra // log to all these additional places
format logFormat // protected by mu
jsonBuf bytes.Buffer
jsonHandler *slog.JSONHandler
}
@@ -150,37 +149,7 @@ type OutputHandler struct {
// Records the type and function pointer for extra logging output.
type outputExtra struct {
json bool
output outputRecordFn
}
// Define the type of an extra logging output which is passed the
// record and what the log is attributed to
type outputRecordFn func(r slog.Record, attribution Attribution, text string)
// Attribution records what made a log entry.
//
// Logs made with the context aware log functions, e.g. fs.DebugfCtx,
// are attributed to the rc job and stats group in their context.
type Attribution struct {
JobID int64 // ID of the rc job or 0 if not from an rc job
Group string // stats group or "" if not in a stats group
}
// Attributed returns whether the log was attributed to anything.
func (a Attribution) Attributed() bool {
return a.JobID != 0 || a.Group != ""
}
// attributionFromContext works out what to attribute a log made with
// ctx to.
func attributionFromContext(ctx context.Context) (attribution Attribution) {
if group, ok := fs.StatsGroupFromContext(ctx); ok {
attribution.Group = group
}
if jobID, ok := fs.JobIDFromContext(ctx); ok {
attribution.JobID = jobID
}
return attribution
output outputFn
}
// Define the type of the override logger
@@ -244,31 +213,13 @@ func (h *OutputHandler) ResetOutput() {
}
// AddOutput adds an additional logging destination of the type specified.
//
// It returns a function which removes the destination again.
func (h *OutputHandler) AddOutput(json bool, fn outputFn) (remove func()) {
return h.addRecordOutput(json, func(r slog.Record, attribution Attribution, text string) {
fn(r.Level, text)
})
}
// addRecordOutput is AddOutput with the output passed the log record.
func (h *OutputHandler) addRecordOutput(json bool, fn outputRecordFn) (remove func()) {
func (h *OutputHandler) AddOutput(json bool, fn outputFn) {
h.mu.Lock()
defer h.mu.Unlock()
out := &outputExtra{
h.outputExtra = append(h.outputExtra, outputExtra{
json: json,
output: fn,
}
h.outputExtra = append(h.outputExtra, out)
return func() {
h.mu.Lock()
defer h.mu.Unlock()
// Make a new slice as Handle may be using the old one
h.outputExtra = slices.DeleteFunc(slices.Clone(h.outputExtra), func(x *outputExtra) bool {
return x == out
})
}
})
}
// SetLevel sets a new log level, returning the old one.
@@ -409,19 +360,17 @@ func (h *OutputHandler) Handle(ctx context.Context, r slog.Record) (err error) {
buf *bytes.Buffer
)
// Read the format and the extra outputs under the mutex once
// so they are consistent throughout this call. The mutex is
// released before calling jsonLog/textLog (which may re-acquire
// it) to avoid deadlock.
// Read the format under the mutex once so it is consistent
// throughout this call. The mutex is released before calling
// jsonLog/textLog (which may re-acquire it) to avoid deadlock.
h.mu.Lock()
format := h.format
outputExtra := h.outputExtra
h.mu.Unlock()
// Check whether we need to build Text or JSON logs or both
needJSON := format&logFormatJSON != 0
needText := !needJSON
for _, out := range outputExtra {
for _, out := range h.outputExtra {
if out.json {
needJSON = true
} else {
@@ -429,19 +378,6 @@ func (h *OutputHandler) Handle(ctx context.Context, r slog.Record) (err error) {
}
}
// Work out what this log is attributed to and record it in the
// JSON output. The text output doesn't show it.
var attribution Attribution
if needJSON {
attribution = attributionFromContext(ctx)
if attribution.JobID != 0 {
r.AddAttrs(slog.Int64("jobid", attribution.JobID))
}
if attribution.Group != "" {
r.AddAttrs(slog.String("group", attribution.Group))
}
}
if needJSON {
var bufJSONBack [256]byte
bufJSON = bytes.NewBuffer(bufJSONBack[:0])
@@ -477,11 +413,11 @@ func (h *OutputHandler) Handle(ctx context.Context, r slog.Record) (err error) {
}
// Log to any additional destinations required
for _, out := range outputExtra {
for _, out := range h.outputExtra {
if out.json {
out.output(r, attribution, bufJSON.String())
out.output(r.Level, bufJSON.String())
} else {
out.output(r, attribution, bufText.String())
out.output(r.Level, bufText.String())
}
}
return err
+1 -20
View File
@@ -182,21 +182,12 @@ func TestAddOutput(t *testing.T) {
extraText = txt
}
remove := h.AddOutput(false, out)
h.AddOutput(false, out)
r := slog.NewRecord(t0, slog.LevelInfo, "world", 0)
require.NoError(t, h.Handle(context.Background(), r))
assert.Equal(t, "2020/01/02 03:04:05 INFO : world\n", buf.String())
assert.Equal(t, "2020/01/02 03:04:05 INFO : world\n", extraText)
// Check the output can be removed again
remove()
extraText = ""
r = slog.NewRecord(t0, slog.LevelInfo, "again", 0)
require.NoError(t, h.Handle(context.Background(), r))
assert.Equal(t, "2020/01/02 03:04:05 INFO : world\n2020/01/02 03:04:05 INFO : again\n", buf.String())
assert.Equal(t, "", extraText)
assert.Empty(t, h.outputExtra)
}
// Test AddOutputJSON sends JSON to extra destinations.
@@ -355,16 +346,6 @@ func TestOutputHandlerConcurrency(t *testing.T) {
}
})
// Goroutine calling AddOutput alternating JSON and text and removing them
wg.Go(func() {
noop := func(_ slog.Level, _ string) {}
for j := range 20 {
remove := h.AddOutput(j%2 == 0, noop)
time.Sleep(time.Millisecond)
remove()
}
})
// Use a channel with a timeout to detect deadlocks
done := make(chan struct{})
go func() {
+3 -80
View File
@@ -2,7 +2,6 @@ package fs
import (
"bytes"
"context"
"encoding/json"
"fmt"
"log/slog"
@@ -42,19 +41,19 @@ func TestLogSlogWithObject(t *testing.T) {
SetLogger(slog.NewTextHandler(&buf, nil))
// Objects with a String method are rendered with it
logSlogWithObject(context.Background(), LogLevelError, withString{}, "message", nil)
logSlogWithObject(LogLevelError, withString{}, "message", nil)
assert.Contains(t, buf.String(), "object=hello")
// Plain strings are rendered as themselves
buf.Reset()
logSlogWithObject(context.Background(), LogLevelError, "potato", "message", nil)
logSlogWithObject(LogLevelError, "potato", "message", nil)
assert.Contains(t, buf.String(), "object=potato")
// Anything else shows only its type as it may contain
// sensitive data such as credentials
buf.Reset()
type secrets struct{ Password string }
logSlogWithObject(context.Background(), LogLevelError, &secrets{Password: "SECRET"}, "message", nil)
logSlogWithObject(LogLevelError, &secrets{Password: "SECRET"}, "message", nil)
assert.Contains(t, buf.String(), "object=*fs.secrets")
assert.NotContains(t, buf.String(), "SECRET")
}
@@ -120,79 +119,3 @@ func TestLogLevelUnmarshalJSON(t *testing.T) {
assert.Equal(t, test.want, logLevel, test.in)
}
}
type testGroupKey struct{}
// ctxHandler records the contexts it was called with
type ctxHandler struct {
slog.Handler
ctxs []context.Context
}
func (h *ctxHandler) Handle(ctx context.Context, r slog.Record) error {
h.ctxs = append(h.ctxs, ctx)
return h.Handler.Handle(ctx, r)
}
// The context aware log functions pass their context to the log
// handler which uses it to attribute the log.
func TestLogCtx(t *testing.T) {
var buf bytes.Buffer
oldLogger := logger
defer func() { logger = oldLogger }()
h := &ctxHandler{Handler: slog.NewJSONHandler(&buf, &slog.HandlerOptions{Level: slog.LevelDebug})}
SetLogger(h)
ci := GetConfig(context.Background())
oldLogLevel := ci.LogLevel
ci.LogLevel = LogLevelDebug
defer func() { ci.LogLevel = oldLogLevel }()
groupCtx := context.WithValue(context.Background(), testGroupKey{}, "job/1")
check := func(want string) {
t.Helper()
var got struct {
Level string `json:"level"`
Msg string `json:"msg"`
Object string `json:"object"`
Size int `json:"size"`
}
require.NoError(t, json.Unmarshal(buf.Bytes(), &got), buf.String())
assert.Equal(t, want, fmt.Sprintf("%s|%s|%s|%d", got.Level, got.Msg, got.Object, got.Size))
buf.Reset()
}
ErrorfCtx(groupCtx, "obj", "error %d", 1)
check("ERROR|error 1|obj|0")
LogfCtx(groupCtx, nil, "notice")
check("INFO+2|notice||0")
InfofCtx(groupCtx, nil, "info")
check("INFO|info||0")
DebugfCtx(groupCtx, nil, "debug")
check("DEBUG|debug||0")
LogPrintfCtx(groupCtx, LogLevelInfo, nil, "size %v", LogValue("size", 3))
check("INFO|size 3||3")
// All of those were passed the context they were called with
require.Len(t, h.ctxs, 5)
for _, ctx := range h.ctxs {
assert.Equal(t, "job/1", ctx.Value(testGroupKey{}))
}
// The non context functions and a nil context log with a
// context which isn't attributed to anything
h.ctxs = nil
Errorf(nil, "plain")
check("ERROR|plain||0")
ErrorfCtx(nil, nil, "nil ctx") //nolint:staticcheck // deliberately testing a nil context
check("ERROR|nil ctx||0")
require.Len(t, h.ctxs, 2)
for _, ctx := range h.ctxs {
require.NotNil(t, ctx)
assert.Nil(t, ctx.Value(testGroupKey{}))
}
// Logs below the log level are dropped
ci.LogLevel = LogLevelNotice
InfofCtx(groupCtx, nil, "dropped")
assert.Equal(t, "", buf.String())
}
+6 -6
View File
@@ -347,7 +347,7 @@ func (m *March) matchListings(srcChan, dstChan <-chan fs.DirEntry, dstCancel fun
}
if src != nil && srcPrev != nil {
if srcName == srcPrevName && fs.DirEntryType(srcPrev) == fs.DirEntryType(src) {
fs.LogfCtx(m.Ctx, src, "Duplicate %s found in source - ignoring", fs.DirEntryType(src))
fs.Logf(src, "Duplicate %s found in source - ignoring", fs.DirEntryType(src))
srcDone() // skip the src and retry the dst
continue
} else if srcName < srcPrevName {
@@ -357,7 +357,7 @@ func (m *March) matchListings(srcChan, dstChan <-chan fs.DirEntry, dstCancel fun
}
if dst != nil && dstPrev != nil {
if dstName == dstPrevName && fs.DirEntryType(dst) == fs.DirEntryType(dstPrev) {
fs.LogfCtx(m.Ctx, dst, "Duplicate %s found in destination - ignoring", fs.DirEntryType(dst))
fs.Logf(dst, "Duplicate %s found in destination - ignoring", fs.DirEntryType(dst))
dstDone() // skip the dst and retry the src
continue
} else if dstName < dstPrevName {
@@ -563,9 +563,9 @@ func (m *March) processJob(job listDirJob) ([]listDirJob, error) {
wg.Wait()
if srcListErr != nil {
if job.srcRemote != "" {
fs.ErrorfCtx(m.Ctx, job.srcRemote, "error reading source directory: %v", srcListErr)
fs.Errorf(job.srcRemote, "error reading source directory: %v", srcListErr)
} else {
fs.ErrorfCtx(m.Ctx, m.Fsrc, "error reading source root directory: %v", srcListErr)
fs.Errorf(m.Fsrc, "error reading source root directory: %v", srcListErr)
}
srcListErr = fs.CountError(m.Ctx, srcListErr)
return nil, srcListErr
@@ -576,9 +576,9 @@ func (m *March) processJob(job listDirJob) ([]listDirJob, error) {
// Copy the stuff anyway
} else if dstListErr != nil {
if job.dstRemote != "" {
fs.ErrorfCtx(m.Ctx, job.dstRemote, "error reading destination directory: %v", dstListErr)
fs.Errorf(job.dstRemote, "error reading destination directory: %v", dstListErr)
} else {
fs.ErrorfCtx(m.Ctx, m.Fdst, "error reading destination root directory: %v", dstListErr)
fs.Errorf(m.Fdst, "error reading destination root directory: %v", dstListErr)
}
dstListErr = fs.CountError(m.Ctx, dstListErr)
return nil, dstListErr
+30 -30
View File
@@ -83,7 +83,7 @@ func (c *checkMarch) DstOnly(dst fs.DirEntry) (recurse bool) {
return false
}
err := fmt.Errorf("file not in %v", c.opt.Fsrc)
fs.ErrorfCtx(c.ctx, dst, "%v", err)
fs.Errorf(dst, "%v", err)
_ = fs.CountError(c.ctx, err)
c.differences.Add(1)
c.srcFilesMissing.Add(1)
@@ -105,7 +105,7 @@ func (c *checkMarch) SrcOnly(src fs.DirEntry) (recurse bool) {
switch src.(type) {
case fs.Object:
err := fmt.Errorf("file not in %v", c.opt.Fdst)
fs.ErrorfCtx(c.ctx, src, "%v", err)
fs.Errorf(src, "%v", err)
_ = fs.CountError(c.ctx, err)
c.differences.Add(1)
c.dstFilesMissing.Add(1)
@@ -128,7 +128,7 @@ func (c *checkMarch) checkIdentical(ctx context.Context, dst, src fs.Object) (di
}()
if sizeDiffers(ctx, src, dst) {
err = fmt.Errorf("sizes differ")
fs.ErrorfCtx(ctx, src, "%v", err)
fs.Errorf(src, "%v", err)
return true, false, nil
}
if ci.SizeOnly {
@@ -155,7 +155,7 @@ func (c *checkMarch) Match(ctx context.Context, dst, src fs.DirEntry) (recurse b
}()
differ, noHash, err := c.checkIdentical(ctx, dstX, srcX)
if err != nil {
fs.ErrorfCtx(ctx, src, "%v", err)
fs.Errorf(src, "%v", err)
_ = fs.CountError(ctx, err)
c.report(src, c.opt.Error, '!')
} else if differ {
@@ -169,15 +169,15 @@ func (c *checkMarch) Match(ctx context.Context, dst, src fs.DirEntry) (recurse b
c.report(src, c.opt.Match, '=')
if noHash {
c.noHashes.Add(1)
fs.DebugfCtx(ctx, dstX, "OK - could not check hash")
fs.Debugf(dstX, "OK - could not check hash")
} else {
fs.DebugfCtx(ctx, dstX, "OK")
fs.Debugf(dstX, "OK")
}
}
}()
} else {
err := fmt.Errorf("is file on %v but directory on %v", c.opt.Fsrc, c.opt.Fdst)
fs.ErrorfCtx(ctx, src, "%v", err)
fs.Errorf(src, "%v", err)
_ = fs.CountError(ctx, err)
c.differences.Add(1)
c.dstFilesMissing.Add(1)
@@ -190,7 +190,7 @@ func (c *checkMarch) Match(ctx context.Context, dst, src fs.DirEntry) (recurse b
return true
}
err := fmt.Errorf("is file on %v but directory on %v", c.opt.Fdst, c.opt.Fsrc)
fs.ErrorfCtx(ctx, dst, "%v", err)
fs.Errorf(dst, "%v", err)
_ = fs.CountError(ctx, err)
c.differences.Add(1)
c.srcFilesMissing.Add(1)
@@ -230,7 +230,7 @@ func CheckFn(ctx context.Context, opt *CheckOpt) error {
NoTraverse: ci.NoTraverse,
NoUnicodeNormalization: ci.NoUnicodeNormalization,
}
fs.DebugfCtx(ctx, c.opt.Fdst, "Waiting for checks to finish")
fs.Debugf(c.opt.Fdst, "Waiting for checks to finish")
err := m.Run(ctx)
c.wg.Wait() // wait for background go-routines
@@ -239,25 +239,25 @@ func CheckFn(ctx context.Context, opt *CheckOpt) error {
func (c *checkMarch) reportResults(ctx context.Context, err error) error {
if c.dstFilesMissing.Load() > 0 {
fs.LogfCtx(ctx, c.opt.Fdst, "%d files missing", c.dstFilesMissing.Load())
fs.Logf(c.opt.Fdst, "%d files missing", c.dstFilesMissing.Load())
}
if c.srcFilesMissing.Load() > 0 {
entity := "files"
if c.opt.Fsrc == nil {
entity = "hashes"
}
fs.LogfCtx(ctx, c.opt.Fsrc, "%d %s missing", c.srcFilesMissing.Load(), entity)
fs.Logf(c.opt.Fsrc, "%d %s missing", c.srcFilesMissing.Load(), entity)
}
fs.LogfCtx(ctx, c.opt.Fdst, "%d differences found", c.differences.Load())
fs.Logf(c.opt.Fdst, "%d differences found", c.differences.Load())
if errs := accounting.Stats(ctx).GetErrors(); errs > 0 {
fs.LogfCtx(ctx, c.opt.Fdst, "%d errors while checking", errs)
fs.Logf(c.opt.Fdst, "%d errors while checking", errs)
}
if c.noHashes.Load() > 0 {
fs.LogfCtx(ctx, c.opt.Fdst, "%d hashes could not be checked", c.noHashes.Load())
fs.Logf(c.opt.Fdst, "%d hashes could not be checked", c.noHashes.Load())
}
if c.matches.Load() > 0 {
fs.LogfCtx(ctx, c.opt.Fdst, "%d matching files", c.matches.Load())
fs.Logf(c.opt.Fdst, "%d matching files", c.matches.Load())
}
if err != nil {
return err
@@ -284,7 +284,7 @@ func Check(ctx context.Context, opt *CheckOpt) error {
}
if !same {
err = fmt.Errorf("%v differ", ht)
fs.ErrorfCtx(ctx, src, "%v", err)
fs.Errorf(src, "%v", err)
return true, false, nil
}
return false, false, nil
@@ -375,7 +375,7 @@ func CheckDownload(ctx context.Context, opt *CheckOpt) error {
}
if !same {
err = errors.New("contents differ")
fs.ErrorfCtx(ctx, src, "%v", err)
fs.Errorf(src, "%v", err)
return true, false, nil
}
return false, false, nil
@@ -457,7 +457,7 @@ func CheckSum(ctx context.Context, fsrc, fsum fs.Fs, sumFile string, hashType ha
}
// filesystem missed the file, sum wasn't consumed
err := fmt.Errorf("file not in %v", opt.Fdst)
fs.ErrorfCtx(ctx, filename, "%v", err)
fs.Errorf(filename, "%v", err)
_ = fs.CountError(ctx, err)
if lastErr == nil {
lastErr = err
@@ -486,7 +486,7 @@ func (c *checkMarch) checkSum(ctx context.Context, obj fs.Object, download bool,
if !sumFound {
err := errors.New("sum not found")
_ = fs.CountError(ctx, err)
fs.ErrorfCtx(ctx, obj, "%v", err)
fs.Errorf(obj, "%v", err)
c.differences.Add(1)
c.srcFilesMissing.Add(1)
c.report(obj, c.opt.MissingOnSrc, '-')
@@ -534,29 +534,29 @@ func (c *checkMarch) matchSum(ctx context.Context, sumHash, objHash string, obj
switch {
case err != nil:
_ = fs.CountError(ctx, err)
fs.ErrorfCtx(ctx, obj, "Failed to calculate hash: %v", err)
fs.Errorf(obj, "Failed to calculate hash: %v", err)
c.report(obj, c.opt.Error, '!')
case sumHash == "":
err = errors.New("duplicate file")
_ = fs.CountError(ctx, err)
fs.ErrorfCtx(ctx, obj, "%v", err)
fs.Errorf(obj, "%v", err)
c.report(obj, c.opt.Error, '!')
case objHash == "":
fs.DebugfCtx(ctx, nil, "%v = %s (sum)", hashType, sumHash)
fs.DebugfCtx(ctx, obj, "%v - could not check hash (%v)", hashType, c.opt.Fdst)
fs.Debugf(nil, "%v = %s (sum)", hashType, sumHash)
fs.Debugf(obj, "%v - could not check hash (%v)", hashType, c.opt.Fdst)
c.noHashes.Add(1)
c.matches.Add(1)
c.report(obj, c.opt.Match, '=')
case objHash == sumHash:
fs.DebugfCtx(ctx, obj, "%v = %s OK", hashType, sumHash)
fs.Debugf(obj, "%v = %s OK", hashType, sumHash)
c.matches.Add(1)
c.report(obj, c.opt.Match, '=')
default:
err = errors.New("files differ")
_ = fs.CountError(ctx, err)
fs.DebugfCtx(ctx, nil, "%v = %s (sum)", hashType, sumHash)
fs.DebugfCtx(ctx, obj, "%v = %s (%v)", hashType, objHash, c.opt.Fdst)
fs.ErrorfCtx(ctx, obj, "%v", err)
fs.Debugf(nil, "%v = %s (sum)", hashType, sumHash)
fs.Debugf(obj, "%v = %s (%v)", hashType, objHash, c.opt.Fdst)
fs.Errorf(obj, "%v", err)
c.differences.Add(1)
c.report(obj, c.opt.Differ, '*')
}
@@ -595,7 +595,7 @@ func ParseSumFile(ctx context.Context, sumFile fs.Object) (HashSums, error) {
if fields == nil {
numWarn++
if numWarn <= maxWarn {
fs.LogfCtx(ctx, sumFile, "improperly formatted checksum line %d", lineNo)
fs.Logf(sumFile, "improperly formatted checksum line %d", lineNo)
}
continue
}
@@ -604,7 +604,7 @@ func ParseSumFile(ctx context.Context, sumFile fs.Object) (HashSums, error) {
if hashes[file] != "" {
numWarn++
if numWarn <= maxWarn {
fs.LogfCtx(ctx, sumFile, "duplicate file on checksum line %d", lineNo)
fs.Logf(sumFile, "duplicate file on checksum line %d", lineNo)
}
continue
}
@@ -614,7 +614,7 @@ func ParseSumFile(ctx context.Context, sumFile fs.Object) (HashSums, error) {
}
if numWarn > maxWarn {
fs.LogfCtx(ctx, sumFile, "%d warning(s) suppressed...", numWarn-maxWarn)
fs.Logf(sumFile, "%d warning(s) suppressed...", numWarn-maxWarn)
}
if err = rd.Close(); err != nil {
return nil, err
+16 -18
View File
@@ -12,6 +12,7 @@ import (
"io"
"path"
"strings"
"time"
"unicode/utf8"
"github.com/rclone/rclone/fs"
@@ -45,10 +46,10 @@ func (c *copy) removeFailedCopy(ctx context.Context, o fs.Object) {
if o == nil {
return
}
fs.InfofCtx(ctx, o, "Removing failed copy")
fs.Infof(o, "Removing failed copy")
err := o.Remove(ctx)
if err != nil {
fs.InfofCtx(ctx, o, "Failed to remove failed copy: %s", err)
fs.Infof(o, "Failed to remove failed copy: %s", err)
}
}
@@ -60,7 +61,7 @@ func (c *copy) removeFailedPartialCopy(ctx context.Context, f fs.Fs, remote stri
return
}
if err != nil {
fs.InfofCtx(ctx, remote, "Failed to remove failed partial copy: %s", err)
fs.Infof(remote, "Failed to remove failed partial copy: %s", err)
return
}
c.removeFailedCopy(ctx, o)
@@ -190,7 +191,7 @@ func (c *copy) rcat(ctx context.Context, in io.ReadCloser) (actionTaken string,
if c.ci.Metadata {
meta, err = fs.GetMetadata(ctx, c.src)
if err != nil {
fs.ErrorfCtx(ctx, c.src, "Failed to read metadata: %v", err)
fs.Errorf(c.src, "Failed to read metadata: %v", err)
}
}
@@ -269,7 +270,7 @@ func (c *copy) manualCopy(ctx context.Context) (actionTaken string, newDst fs.Ob
if !errors.Is(err, fs.ErrorRangeIgnored) {
return actionTaken, newDst, err
}
fs.LogfCtx(ctx, c.src, "multi-thread copy: %v: downloading in a single stream", err)
fs.Logf(c.src, "multi-thread copy: %v: downloading in a single stream", err)
c.tr.Reset(ctx)
}
@@ -335,23 +336,20 @@ func (c *copy) copy(ctx context.Context) (newDst fs.Object, err error) {
retry = false
if fserrors.IsRetryError(err) || fserrors.ShouldRetry(err) {
retry = true
} else if t, ok := pacer.IsRetryAfter(err); ok && tries+1 < c.maxTries {
fs.DebugfCtx(ctx, c.src, "Sleeping for %v (as indicated by the server) to obey Retry-After error: %v", t, err)
if sleepWithContext(ctx, t) {
retry = true
} else {
fserrors.ContextError(ctx, &err)
}
} else if t, ok := pacer.IsRetryAfter(err); ok {
fs.Debugf(c.src, "Sleeping for %v (as indicated by the server) to obey Retry-After error: %v", t, err)
time.Sleep(t)
retry = true
}
if retry {
fs.DebugfCtx(ctx, c.src, "Received error: %v - low level retry %d/%d", err, tries+1, c.maxTries)
fs.Debugf(c.src, "Received error: %v - low level retry %d/%d", err, tries, c.maxTries)
c.tr.Reset(ctx) // skip incomplete accounting - will be overwritten by retry
continue
}
}
if err != nil {
err = fs.CountError(ctx, err)
fs.ErrorfCtx(ctx, c.src, "Failed to copy: %v", err)
fs.Errorf(c.src, "Failed to copy: %v", err)
if !c.inplace {
c.removeFailedPartialCopy(ctx, c.f, c.remoteForCopy)
}
@@ -361,7 +359,7 @@ func (c *copy) copy(ctx context.Context) (newDst fs.Object, err error) {
// Verify the copy
err = c.verify(ctx, newDst)
if err != nil {
fs.ErrorfCtx(ctx, newDst, "%v", err)
fs.Errorf(newDst, "%v", err)
err = fs.CountError(ctx, err)
c.removeFailedCopy(ctx, newDst)
return nil, err
@@ -371,12 +369,12 @@ func (c *copy) copy(ctx context.Context) (newDst fs.Object, err error) {
if !c.inplace && c.remoteForCopy != c.remote {
movedNewDst, err := c.dstFeatures.Move(ctx, newDst, c.remote)
if err != nil {
fs.ErrorfCtx(ctx, newDst, "partial file rename failed: %v", err)
fs.Errorf(newDst, "partial file rename failed: %v", err)
err = fs.CountError(ctx, err)
c.removeFailedCopy(ctx, newDst)
return nil, err
}
fs.DebugfCtx(ctx, newDst, "renamed to: %s", c.remote)
fs.Debugf(newDst, "renamed to: %s", c.remote)
newDst = movedNewDst
}
@@ -384,7 +382,7 @@ func (c *copy) copy(ctx context.Context) (newDst fs.Object, err error) {
if newDst != nil && c.src.String() != newDst.String() {
actionTaken = fmt.Sprintf("%s to: %s", actionTaken, newDst.String())
}
fs.InfofCtx(ctx, c.src, "%s%s", actionTaken, fs.LogValueHide("size", fs.SizeSuffix(c.src.Size())))
fs.Infof(c.src, "%s%s", actionTaken, fs.LogValueHide("size", fs.SizeSuffix(c.src.Size())))
return newDst, nil
}
+14 -14
View File
@@ -43,7 +43,7 @@ outer:
for {
suffix++
if suffix > maxDedupeSuffix {
fs.ErrorfCtx(ctx, o, "Could not find an available new name")
fs.Errorf(o, "Could not find an available new name")
continue outer
}
newName = fmt.Sprintf("%s-%d%s", base, suffix, ext)
@@ -56,7 +56,7 @@ outer:
}
if err != nil {
err = fs.CountError(ctx, err)
fs.ErrorfCtx(ctx, o, "Failed to check for existing object: %v", err)
fs.Errorf(o, "Failed to check for existing object: %v", err)
continue outer
}
files[newName] = append(files[newName], existing)
@@ -65,10 +65,10 @@ outer:
newObj, err := doMove(ctx, o, newName)
if err != nil {
err = fs.CountError(ctx, err)
fs.ErrorfCtx(ctx, o, "Failed to rename: %v", err)
fs.Errorf(o, "Failed to rename: %v", err)
continue
}
fs.InfofCtx(ctx, newObj, "renamed from: %v", o)
fs.Infof(newObj, "renamed from: %v", o)
files[newName] = append(files[newName], newObj)
}
}
@@ -87,7 +87,7 @@ func dedupeDeleteAllButOne(ctx context.Context, keep int, remote string, objs []
}
}
if count > 0 {
fs.LogfCtx(ctx, remote, "Deleted %d extra copies", count)
fs.Logf(remote, "Deleted %d extra copies", count)
}
}
@@ -113,7 +113,7 @@ func dedupeDeleteIdentical(ctx context.Context, ht hash.Type, remote string, obj
if IDs[ID] <= 1 {
newObjs = append(newObjs, o)
} else {
fs.LogfCtx(ctx, o, "Ignoring as it appears %d times in the listing and deleting would lead to data loss", IDs[ID])
fs.Logf(o, "Ignoring as it appears %d times in the listing and deleting would lead to data loss", IDs[ID])
}
}
}
@@ -143,7 +143,7 @@ func dedupeDeleteIdentical(ctx context.Context, ht hash.Type, remote string, obj
for ID, dupes := range dupesByID {
remainingObjs = append(remainingObjs, dupes[0])
if len(dupes) > 1 {
fs.LogfCtx(ctx, remote, "Deleting %d/%d identical duplicates (%s)", len(dupes)-1, len(dupes), ID)
fs.Logf(remote, "Deleting %d/%d identical duplicates (%s)", len(dupes)-1, len(dupes), ID)
for _, o := range dupes[1:] {
err := DeleteFile(ctx, o)
if err != nil {
@@ -390,11 +390,11 @@ func dedupeMergeDuplicateDirs(ctx context.Context, f fs.Fs, duplicateDirs [][]*d
}
fsDirs[largestIdx], fsDirs[0] = fsDirs[0], fsDirs[largestIdx]
fs.InfofCtx(ctx, fsDirs[0], "Merging contents of duplicate directories")
fs.Infof(fsDirs[0], "Merging contents of duplicate directories")
err := mergeDirs(ctx, fsDirs)
if err != nil {
err = fs.CountError(ctx, err)
fs.ErrorfCtx(ctx, nil, "merge duplicate dirs: %v", err)
fs.Errorf(nil, "merge duplicate dirs: %v", err)
}
}
dirCacheFlush()
@@ -429,7 +429,7 @@ func Deduplicate(ctx context.Context, f fs.Fs, mode DeduplicateMode, byHash bool
}
what = ht.String() + " hashes"
}
fs.InfofCtx(ctx, f, "Looking for duplicate %s using %v mode.", what, mode)
fs.Infof(f, "Looking for duplicate %s using %v mode.", what, mode)
// Find duplicate directories first and fix them
if !byHash {
@@ -464,7 +464,7 @@ func Deduplicate(ctx context.Context, f fs.Fs, mode DeduplicateMode, byHash bool
if byHash {
remote, err = o.Hash(ctx, ht)
if err != nil {
fs.ErrorfCtx(ctx, o, "Failed to hash: %v", err)
fs.Errorf(o, "Failed to hash: %v", err)
remote = ""
}
} else {
@@ -487,11 +487,11 @@ func Deduplicate(ctx context.Context, f fs.Fs, mode DeduplicateMode, byHash bool
if len(objs) <= 1 {
continue
}
fs.LogfCtx(ctx, remote, "Found %d files with duplicate %s", len(objs), what)
fs.Logf(remote, "Found %d files with duplicate %s", len(objs), what)
if !byHash && mode != DeduplicateList {
objs = dedupeDeleteIdentical(ctx, ht, remote, objs)
if len(objs) <= 1 {
fs.LogfCtx(ctx, remote, "All duplicates removed")
fs.Logf(remote, "All duplicates removed")
continue
}
}
@@ -517,7 +517,7 @@ func Deduplicate(ctx context.Context, f fs.Fs, mode DeduplicateMode, byHash bool
sortSmallestFirst(objs)
dedupeDeleteAllButOne(ctx, 0, remote, objs)
case DeduplicateSkip:
fs.LogfCtx(ctx, remote, "Skipping %d files with duplicate %s", len(objs), what)
fs.Logf(remote, "Skipping %d files with duplicate %s", len(objs), what)
case DeduplicateList:
dedupeList(ctx, f, ht, remote, objs, byHash)
default:
+6 -6
View File
@@ -137,7 +137,7 @@ func NewDefaultLoggerFn(opt *LoggerOpt) LoggerFn {
}
if opt.Combined != nil {
SyncFprintf(opt.Combined, "%c %s\n", sigil, filename)
fs.DebugfCtx(ctx, nil, "Sync Logger: %s: %c %s\n", sigil.String(), sigil, filename)
fs.Debugf(nil, "Sync Logger: %s: %c %s\n", sigil.String(), sigil, filename)
}
if opt.DestAfter != nil {
opt.PrintDestAfter(ctx, sigil, src, dst, err)
@@ -299,7 +299,7 @@ func WinningSide(ctx context.Context, sigil Sigil, src, dst fs.DirEntry, err err
// should only make it this far if it's TransferError and both src and dst are nil
winner.Side = "none"
winner.Err = fmt.Errorf("unknown case -- can't determine winner. %v", err)
fs.DebugfCtx(ctx, winner.Obj, "%v", winner.Err)
fs.Debugf(winner.Obj, "%v", winner.Err)
return winner
}
@@ -372,13 +372,13 @@ func (opt *LoggerOpt) Init(ctx context.Context, fdst fs.Fs, cmdFlags *pflag.Flag
ci := fs.GetConfig(ctx)
if ci.NoTraverse && opt.Combined != nil {
fs.LogPrintfCtx(ctx, fs.LogLevelWarning, nil, "--no-traverse does not list any deletes (-) in --combined output\n")
fs.LogPrintf(fs.LogLevelWarning, nil, "--no-traverse does not list any deletes (-) in --combined output\n")
}
if ci.NoTraverse && opt.MissingOnSrc != nil {
fs.LogPrintfCtx(ctx, fs.LogLevelWarning, nil, "--no-traverse makes --missing-on-src produce empty output\n")
fs.LogPrintf(fs.LogLevelWarning, nil, "--no-traverse makes --missing-on-src produce empty output\n")
}
if ci.NoTraverse && opt.DestAfter != nil {
fs.LogPrintfCtx(ctx, fs.LogLevelWarning, nil, "--no-traverse makes --dest-after produce incomplete output\n")
fs.LogPrintf(fs.LogLevelWarning, nil, "--no-traverse makes --dest-after produce incomplete output\n")
}
}
@@ -441,7 +441,7 @@ func (opt *LoggerOpt) SetListFormat(ctx context.Context, cmdFlags *pflag.FlagSet
list.AddMetadata()
JSONOpt.Metadata = true
default:
fs.ErrorfCtx(ctx, nil, "unknown format character %q", char)
fs.Errorf(nil, "unknown format character %q", char)
}
}
opt.ListFormat = list
+5 -5
View File
@@ -168,7 +168,7 @@ func (lj *listJSON) entry(ctx context.Context, entry fs.DirEntry) (*ListJSONItem
return nil, nil
}
default:
fs.ErrorfCtx(ctx, nil, "Unknown type %T in listing", entry)
fs.Errorf(nil, "Unknown type %T in listing", entry)
}
item := &ListJSONItem{
@@ -192,14 +192,14 @@ func (lj *listJSON) entry(ctx context.Context, entry fs.DirEntry) (*ListJSONItem
case fs.Object:
item.EncryptedPath = lj.cipher.EncryptFileName(entry.Remote())
default:
fs.ErrorfCtx(ctx, nil, "Unknown type %T in listing", entry)
fs.Errorf(nil, "Unknown type %T in listing", entry)
}
item.Encrypted = path.Base(item.EncryptedPath)
}
if lj.opt.Metadata {
metadata, err := fs.GetMetadata(ctx, entry)
if err != nil {
fs.ErrorfCtx(ctx, entry, "Failed to read metadata: %v", err)
fs.Errorf(entry, "Failed to read metadata: %v", err)
} else if metadata != nil {
item.Metadata = metadata
}
@@ -223,7 +223,7 @@ func (lj *listJSON) entry(ctx context.Context, entry fs.DirEntry) (*ListJSONItem
for _, hashType := range lj.hashTypes {
hash, err := x.Hash(ctx, hashType)
if err != nil {
fs.ErrorfCtx(ctx, x, "Failed to read hash: %v", err)
fs.Errorf(x, "Failed to read hash: %v", err)
} else if hash != "" {
item.Hashes[hashType.String()] = hash
}
@@ -235,7 +235,7 @@ func (lj *listJSON) entry(ctx context.Context, entry fs.DirEntry) (*ListJSONItem
}
}
default:
fs.ErrorfCtx(ctx, nil, "Unknown type %T in listing in ListJSON", entry)
fs.Errorf(nil, "Unknown type %T in listing in ListJSON", entry)
}
return item, nil
}
+17 -17
View File
@@ -70,11 +70,11 @@ func (mc *multiThreadCopyState) copyChunk(ctx context.Context, chunk int, writer
fs.CheckClose(rw, &err)
}
if err != nil {
fs.DebugfCtx(ctx, mc.src, "multi-thread copy: chunk %d/%d failed: %v", chunk+1, mc.numChunks, err)
fs.Debugf(mc.src, "multi-thread copy: chunk %d/%d failed: %v", chunk+1, mc.numChunks, err)
}
}()
fs.DebugfCtx(ctx, mc.src, "multi-thread copy: chunk %d/%d (%d-%d) size %v starting", chunk+1, mc.numChunks, start, end, fs.SizeSuffix(size))
fs.Debugf(mc.src, "multi-thread copy: chunk %d/%d (%d-%d) size %v starting", chunk+1, mc.numChunks, start, end, fs.SizeSuffix(size))
rc, err := Open(ctx, mc.src, &fs.RangeOption{Start: start, End: end - 1})
if err != nil {
@@ -105,7 +105,7 @@ func (mc *multiThreadCopyState) copyChunk(ctx context.Context, chunk int, writer
return fmt.Errorf("multi-thread copy: failed to write chunk: %w", err)
}
fs.DebugfCtx(ctx, mc.src, "multi-thread copy: chunk %d/%d (%d-%d) size %v finished", chunk+1, mc.numChunks, start, end, fs.SizeSuffix(bytesWritten))
fs.Debugf(mc.src, "multi-thread copy: chunk %d/%d (%d-%d) size %v finished", chunk+1, mc.numChunks, start, end, fs.SizeSuffix(bytesWritten))
return nil
}
@@ -133,17 +133,17 @@ func multiThreadCopy(ctx context.Context, f fs.Fs, remote string, src fs.Object,
}
openChunkWriter = openChunkWriterFromOpenWriterAt(openWriterAt, int64(ci.MultiThreadChunkSize), int64(ci.MultiThreadWriteBufferSize), f)
// If we are using OpenWriterAt we don't seek the chunks so don't need to buffer
fs.DebugfCtx(ctx, src, "multi-thread copy: disabling buffering because destination uses OpenWriterAt")
fs.Debugf(src, "multi-thread copy: disabling buffering because destination uses OpenWriterAt")
noBuffering = true
usingOpenWriterAt = true
} else if src.Fs().Features().IsLocal {
// If the source fs is local we don't need to buffer
fs.DebugfCtx(ctx, src, "multi-thread copy: disabling buffering because source is local disk")
fs.Debugf(src, "multi-thread copy: disabling buffering because source is local disk")
noBuffering = true
} else if f.Features().ChunkWriterDoesntSeek {
// If the destination Fs promises not to seek its chunks
// (except for retries) then we don't need buffering.
fs.DebugfCtx(ctx, src, "multi-thread copy: disabling buffering because destination has set ChunkWriterDoesntSeek")
fs.Debugf(src, "multi-thread copy: disabling buffering because destination has set ChunkWriterDoesntSeek")
noBuffering = true
}
@@ -167,27 +167,27 @@ func multiThreadCopy(ctx context.Context, f fs.Fs, remote string, src fs.Object,
if info.LeavePartsOnError || uploadedOK {
return
}
fs.DebugfCtx(ctx, src, "multi-thread copy: cancelling transfer on exit")
fs.Debugf(src, "multi-thread copy: cancelling transfer on exit")
abortErr := chunkWriter.Abort(ctx)
if abortErr != nil {
fs.DebugfCtx(ctx, src, "multi-thread copy: abort failed: %v", abortErr)
fs.Debugf(src, "multi-thread copy: abort failed: %v", abortErr)
}
})()
if info.ChunkSize > src.Size() {
fs.DebugfCtx(ctx, src, "multi-thread copy: chunk size %v was bigger than source file size %v", fs.SizeSuffix(info.ChunkSize), fs.SizeSuffix(src.Size()))
fs.Debugf(src, "multi-thread copy: chunk size %v was bigger than source file size %v", fs.SizeSuffix(info.ChunkSize), fs.SizeSuffix(src.Size()))
info.ChunkSize = src.Size()
}
// Use the backend concurrency if it is higher than --multi-thread-streams or if --multi-thread-streams wasn't set explicitly
if !ci.MultiThreadSet || info.Concurrency > concurrency {
fs.DebugfCtx(ctx, src, "multi-thread copy: using backend concurrency of %d instead of --multi-thread-streams %d", info.Concurrency, concurrency)
fs.Debugf(src, "multi-thread copy: using backend concurrency of %d instead of --multi-thread-streams %d", info.Concurrency, concurrency)
concurrency = info.Concurrency
}
numChunks := calculateNumChunks(src.Size(), info.ChunkSize)
if concurrency > numChunks {
fs.DebugfCtx(ctx, src, "multi-thread copy: number of streams %d was bigger than number of chunks %d", concurrency, numChunks)
fs.Debugf(src, "multi-thread copy: number of streams %d was bigger than number of chunks %d", concurrency, numChunks)
concurrency = numChunks
}
@@ -210,7 +210,7 @@ func multiThreadCopy(ctx context.Context, f fs.Fs, remote string, src fs.Object,
// Make accounting
mc.acc = tr.Account(gCtx, nil)
fs.DebugfCtx(ctx, src, "Starting multi-thread copy with %d chunks of size %v with %v parallel streams", mc.numChunks, fs.SizeSuffix(mc.partSize), concurrency)
fs.Debugf(src, "Starting multi-thread copy with %d chunks of size %v with %v parallel streams", mc.numChunks, fs.SizeSuffix(mc.partSize), concurrency)
for chunk := range mc.numChunks {
// Fail fast, in case an errgroup managed function returns an error
if gCtx.Err() != nil {
@@ -271,7 +271,7 @@ func multiThreadCopy(ctx context.Context, f fs.Fs, remote string, src fs.Object,
}
setModTime = false
} else {
fs.ErrorfCtx(ctx, obj, "multi-thread copy: can't set metadata as SetMetadata isn't implemented in: %v", f)
fs.Errorf(obj, "multi-thread copy: can't set metadata as SetMetadata isn't implemented in: %v", f)
}
}
if setModTime {
@@ -284,7 +284,7 @@ func multiThreadCopy(ctx context.Context, f fs.Fs, remote string, src fs.Object,
}
}
fs.DebugfCtx(ctx, src, "Finished multi-thread copy with %d parts of size %v", mc.numChunks, fs.SizeSuffix(mc.partSize))
fs.Debugf(src, "Finished multi-thread copy with %d parts of size %v", mc.numChunks, fs.SizeSuffix(mc.partSize))
return obj, nil
}
@@ -302,7 +302,7 @@ type writerAtChunkWriter struct {
// WriteChunk writes chunkNumber from reader
func (w *writerAtChunkWriter) WriteChunk(ctx context.Context, chunkNumber int, reader io.ReadSeeker) (int64, error) {
fs.DebugfCtx(ctx, w.remote, "writing chunk %v", chunkNumber)
fs.Debugf(w.remote, "writing chunk %v", chunkNumber)
bytesToWrite := w.chunkSize
if chunkNumber == (w.chunks-1) && w.size%w.chunkSize != 0 {
@@ -344,7 +344,7 @@ func (w *writerAtChunkWriter) Close(ctx context.Context) error {
func (w *writerAtChunkWriter) Abort(ctx context.Context) error {
err := w.Close(ctx)
if err != nil {
fs.ErrorfCtx(ctx, w.remote, "multi-thread copy: failed to close file before aborting: %v", err)
fs.Errorf(w.remote, "multi-thread copy: failed to close file before aborting: %v", err)
}
obj, err := w.f.NewObject(ctx, w.remote)
if err != nil {
@@ -364,7 +364,7 @@ func openChunkWriterFromOpenWriterAt(openWriterAt fs.OpenWriterAtFn, chunkSize i
}
if writeBufferSize > 0 {
fs.DebugfCtx(ctx, src.Remote(), "multi-thread copy: write buffer set to %v", writeBufferSize)
fs.Debugf(src.Remote(), "multi-thread copy: write buffer set to %v", writeBufferSize)
}
chunkWriter := &writerAtChunkWriter{
-60
View File
@@ -10,7 +10,6 @@ import (
"time"
"github.com/rclone/rclone/fs/accounting"
"github.com/rclone/rclone/fs/fserrors"
"github.com/rclone/rclone/fs/hash"
"github.com/rclone/rclone/fs/object"
"github.com/rclone/rclone/fstest/mockfs"
@@ -343,62 +342,3 @@ func TestMultithreadCopyAbort(t *testing.T) {
require.NoError(t, o.Remove(ctx))
}
}
type errorWriterAtCloser struct {
writeErr error
closeErr error
closed bool
}
func (w *errorWriterAtCloser) WriteAt(p []byte, _ int64) (int, error) {
if w.writeErr != nil {
return 0, w.writeErr
}
return len(p), nil
}
func (w *errorWriterAtCloser) Close() error {
w.closed = true
return w.closeErr
}
// Classification belongs to the backend; this checks propagation through the consumer.
func TestMultithreadCopyWriterAtErrors(t *testing.T) {
for _, stage := range []string{"open", "write", "close"} {
for _, fatal := range []bool{false, true} {
t.Run(fmt.Sprintf("%s/fatal=%v", stage, fatal), func(t *testing.T) {
ctx, ci := fs.AddConfig(context.Background())
ci.MultiThreadChunkSize = 4
ci.MultiThreadWriteBufferSize = 0
ci.MultiThreadStreams = 2
ci.MultiThreadSet = true
f, err := mockfs.NewFs(ctx, "destination", "", nil)
require.NoError(t, err)
src := mockobject.New("file.txt").WithContent([]byte("0123456789abcdef"), mockobject.SeekModeNone)
cause := errors.New("disk full")
injected := cause
if fatal {
injected = fserrors.FatalError(injected)
}
writer := &errorWriterAtCloser{}
f.Features().OpenWriterAt = func(context.Context, string, int64) (fs.WriterAtCloser, error) {
switch stage {
case "open":
return nil, injected
case "write":
writer.writeErr = injected
case "close":
writer.closeErr = injected
}
return writer, nil
}
tr := accounting.GlobalStats().NewTransfer(src, nil)
_, err = multiThreadCopy(ctx, f, src.Remote(), src, 2, tr)
tr.Done(ctx, err)
require.ErrorIs(t, err, cause)
assert.Equal(t, fatal, fserrors.IsFatalError(err))
assert.Equal(t, stage != "open", writer.closed)
})
}
}
}
+105 -133
View File
@@ -82,7 +82,7 @@ func checkHashes(ctx context.Context, src fs.ObjectInfo, dst fs.Object, ht hash.
return srcErr
}
if srcHash == "" {
fs.DebugfCtx(ctx, src, "Src hash empty - aborting Dst hash check")
fs.Debugf(src, "Src hash empty - aborting Dst hash check")
return errNoHash
}
return nil
@@ -93,7 +93,7 @@ func checkHashes(ctx context.Context, src fs.ObjectInfo, dst fs.Object, ht hash.
return dstErr
}
if dstHash == "" {
fs.DebugfCtx(ctx, dst, "Dst hash empty - aborting Src hash check")
fs.Debugf(dst, "Dst hash empty - aborting Src hash check")
return errNoHash
}
return nil
@@ -104,21 +104,21 @@ func checkHashes(ctx context.Context, src fs.ObjectInfo, dst fs.Object, ht hash.
}
if srcErr != nil {
err = fs.CountError(ctx, srcErr)
fs.ErrorfCtx(ctx, src, "Failed to calculate src hash: %v", err)
fs.Errorf(src, "Failed to calculate src hash: %v", err)
}
if dstErr != nil {
err = fs.CountError(ctx, dstErr)
fs.ErrorfCtx(ctx, dst, "Failed to calculate dst hash: %v", err)
fs.Errorf(dst, "Failed to calculate dst hash: %v", err)
}
if err != nil {
return false, ht, srcHash, dstHash, err
}
if srcHash != dstHash {
fs.DebugfCtx(ctx, src, "%v = %s (%v)", ht, srcHash, src.Fs())
fs.DebugfCtx(ctx, dst, "%v = %s (%v)", ht, dstHash, dst.Fs())
fs.Debugf(src, "%v = %s (%v)", ht, srcHash, src.Fs())
fs.Debugf(dst, "%v = %s (%v)", ht, dstHash, dst.Fs())
return false, ht, srcHash, dstHash, nil
}
fs.DebugfCtx(ctx, src, "%v = %s OK", ht, srcHash)
fs.Debugf(src, "%v = %s OK", ht, srcHash)
return true, ht, srcHash, dstHash, nil
}
@@ -168,11 +168,11 @@ func DirsEqual(ctx context.Context, src, dst fs.Directory, opt DirsEqualOpt) (eq
}
dt := dstModTime.Sub(srcModTime)
if dt < opt.ModifyWindow && dt > -opt.ModifyWindow {
fs.DebugfCtx(ctx, dst, "Directory modification time the same (differ by %s, within tolerance %s)", dt, opt.ModifyWindow)
fs.Debugf(dst, "Directory modification time the same (differ by %s, within tolerance %s)", dt, opt.ModifyWindow)
return true
}
if ci.UpdateOlder && dt >= opt.ModifyWindow {
fs.DebugfCtx(ctx, dst, "Destination directory is newer than source, skipping")
fs.Debugf(dst, "Destination directory is newer than source, skipping")
return true
}
return false
@@ -186,11 +186,11 @@ func sizeDiffers(ctx context.Context, src, dst fs.ObjectInfo) bool {
return false
}
if src.Size() == dst.Size() {
fs.DebugfCtx(ctx, dst, "size = %d OK", dst.Size())
fs.Debugf(dst, "size = %d OK", dst.Size())
return false
}
fs.DebugfCtx(ctx, src, "size = %d (%v)", src.Size(), src.Fs())
fs.DebugfCtx(ctx, dst, "size = %d (%v)", dst.Size(), dst.Fs())
fs.Debugf(src, "size = %d (%v)", src.Size(), src.Fs())
fs.Debugf(dst, "size = %d (%v)", dst.Size(), dst.Fs())
return true
}
@@ -248,12 +248,12 @@ func equal(ctx context.Context, src fs.ObjectInfo, dst fs.Object, opt equalOpt)
ci := fs.GetConfig(ctx)
logger, _ := GetLogger(ctx)
if sizeDiffers(ctx, src, dst) {
fs.DebugfCtx(ctx, src, "Sizes differ")
fs.Debug(src, "Sizes differ")
logger(ctx, Differ, src, dst, nil)
return false
}
if opt.sizeOnly {
fs.DebugfCtx(ctx, src, "Sizes identical")
fs.Debugf(src, "Sizes identical")
logger(ctx, Match, src, dst, nil)
return true
}
@@ -265,7 +265,7 @@ func equal(ctx context.Context, src fs.ObjectInfo, dst fs.Object, opt equalOpt)
// Check the hash
same, ht, _ := CheckHashes(ctx, src, dst)
if !same {
fs.DebugfCtx(ctx, src, "%v differ", ht)
fs.Debugf(src, "%v differ", ht)
logger(ctx, Differ, src, dst, nil)
return false
}
@@ -273,12 +273,12 @@ func equal(ctx context.Context, src fs.ObjectInfo, dst fs.Object, opt equalOpt)
common := src.Fs().Hashes().Overlap(dst.Fs().Hashes())
if common.Count() == 0 {
checksumWarning.Do(func() {
fs.LogfCtx(ctx, dst.Fs(), "--checksum is in use but the source and destination have no hashes in common; falling back to --size-only")
fs.Logf(dst.Fs(), "--checksum is in use but the source and destination have no hashes in common; falling back to --size-only")
})
}
fs.DebugfCtx(ctx, src, "Size of src and dst objects identical")
fs.Debugf(src, "Size of src and dst objects identical")
} else {
fs.DebugfCtx(ctx, src, "Size and %v of src and dst objects identical", ht)
fs.Debugf(src, "Size and %v of src and dst objects identical", ht)
}
logger(ctx, Match, src, dst, nil)
return true
@@ -289,25 +289,25 @@ func equal(ctx context.Context, src fs.ObjectInfo, dst fs.Object, opt equalOpt)
// Sizes the same so check the mtime
modifyWindow := fs.GetModifyWindow(ctx, src.Fs(), dst.Fs())
if modifyWindow == fs.ModTimeNotSupported {
fs.DebugfCtx(ctx, src, "Sizes identical")
fs.Debugf(src, "Sizes identical")
logger(ctx, Match, src, dst, nil)
return true
}
dstModTime := dst.ModTime(ctx)
dt := dstModTime.Sub(srcModTime)
if dt < modifyWindow && dt > -modifyWindow {
fs.DebugfCtx(ctx, src, "Size and modification time the same (differ by %s, within tolerance %s)", dt, modifyWindow)
fs.Debugf(src, "Size and modification time the same (differ by %s, within tolerance %s)", dt, modifyWindow)
logger(ctx, Match, src, dst, nil)
return true
}
fs.DebugfCtx(ctx, src, "Modification times differ by %s: %v, %v", dt, srcModTime, dstModTime)
fs.Debugf(src, "Modification times differ by %s: %v, %v", dt, srcModTime, dstModTime)
}
// Check if the hashes are the same
same, ht, _ := CheckHashes(ctx, src, dst)
if !same {
fs.DebugfCtx(ctx, src, "%v differ", ht)
fs.Debugf(src, "%v differ", ht)
logger(ctx, Differ, src, dst, nil)
return false
}
@@ -323,7 +323,7 @@ func equal(ctx context.Context, src fs.ObjectInfo, dst fs.Object, opt equalOpt)
// Size and hash the same but mtime different
// Error if objects are treated as immutable
if ci.Immutable {
fs.ErrorfCtx(ctx, dst, "Timestamp mismatch between immutable objects")
fs.Errorf(dst, "Timestamp mismatch between immutable objects")
logger(ctx, Differ, src, dst, nil)
return false
}
@@ -331,27 +331,27 @@ func equal(ctx context.Context, src fs.ObjectInfo, dst fs.Object, opt equalOpt)
err := dst.SetModTime(ctx, srcModTime)
if errors.Is(err, fs.ErrorCantSetModTime) {
logModTimeUpload(dst)
fs.InfofCtx(ctx, dst, "src and dst identical but can't set mod time without re-uploading")
fs.Infof(dst, "src and dst identical but can't set mod time without re-uploading")
logger(ctx, Differ, src, dst, nil)
return false
} else if errors.Is(err, fs.ErrorCantSetModTimeWithoutDelete) {
logModTimeUpload(dst)
fs.InfofCtx(ctx, dst, "src and dst identical but can't set mod time without deleting and re-uploading")
fs.Infof(dst, "src and dst identical but can't set mod time without deleting and re-uploading")
// Remove the file if BackupDir isn't set. If BackupDir is set we would rather have the old file
// put in the BackupDir than deleted which is what will happen if we don't delete it.
if ci.BackupDir == "" {
err = dst.Remove(ctx)
if err != nil {
fs.ErrorfCtx(ctx, dst, "failed to delete before re-upload: %v", err)
fs.Errorf(dst, "failed to delete before re-upload: %v", err)
}
}
logger(ctx, Differ, src, dst, nil)
return false
} else if err != nil {
err = fs.CountError(ctx, err)
fs.ErrorfCtx(ctx, dst, "Failed to set modification time: %v", err)
fs.Errorf(dst, "Failed to set modification time: %v", err)
} else {
fs.InfofCtx(ctx, src, "Updated modification time in destination")
fs.Infof(src, "Updated modification time in destination")
}
}
}
@@ -491,19 +491,19 @@ func move(ctx context.Context, fdst fs.Fs, dst fs.Object, remote string, src fs.
switch err {
case nil:
if newDst != nil && src.String() != newDst.String() {
fs.InfofCtx(ctx, src, "Moved (server-side) to: %s", newDst.String())
fs.Infof(src, "Moved (server-side) to: %s", newDst.String())
} else {
fs.InfofCtx(ctx, src, "Moved (server-side)")
fs.Infof(src, "Moved (server-side)")
}
in.ServerSideMoveEnd(newDst.Size()) // account the bytes for the server-side transfer
_ = in.Close()
return newDst, nil
case fs.ErrorCantMove:
fs.DebugfCtx(ctx, src, "Can't move, switching to copy")
fs.Debugf(src, "Can't move, switching to copy")
_ = in.Close()
default:
err = fs.CountError(ctx, err)
fs.ErrorfCtx(ctx, src, "Couldn't move: %v", err)
fs.Errorf(src, "Couldn't move: %v", err)
_ = in.Close()
return newDst, err
}
@@ -514,7 +514,7 @@ func move(ctx context.Context, fdst fs.Fs, dst fs.Object, remote string, src fs.
}
newDst, err = Copy(ctx, fdst, dst, origRemote, src)
if err != nil {
fs.ErrorfCtx(ctx, src, "Not deleting source as copy failed: %v", err)
fs.Errorf(src, "Not deleting source as copy failed: %v", err)
return newDst, err
}
// Delete src if no error on copy
@@ -576,10 +576,10 @@ func DeleteFileWithBackupDir(ctx context.Context, dst fs.Object, backupDir fs.Fs
err = dst.Remove(ctx)
}
if err != nil {
fs.ErrorfCtx(ctx, dst, "Couldn't %s: %v", action, err)
fs.Errorf(dst, "Couldn't %s: %v", action, err)
err = fs.CountError(ctx, err)
} else if !skip {
fs.InfofCtx(ctx, dst, "%s", actioned)
fs.Infof(dst, "%s", actioned)
}
return err
}
@@ -607,8 +607,6 @@ func DeleteFilesWithBackupDir(ctx context.Context, toBeDeleted fs.ObjectsChan, b
for range ci.Checkers {
go func() {
defer wg.Done()
// Every object must be received, even after a fatal error,
// otherwise the sender blocks when the channel fills up
for dst := range toBeDeleted {
err := DeleteFileWithBackupDir(ctx, dst, backupDir)
if err != nil {
@@ -616,14 +614,15 @@ func DeleteFilesWithBackupDir(ctx context.Context, toBeDeleted fs.ObjectsChan, b
logger, _ := GetLogger(ctx)
logger(ctx, TransferError, nil, dst, err)
if fserrors.IsFatalError(err) {
fs.ErrorfCtx(ctx, dst, "Got fatal error on delete: %s", err)
fs.Errorf(dst, "Got fatal error on delete: %s", err)
fatalErrorCount.Add(1)
return
}
}
}
}()
}
fs.DebugfCtx(ctx, nil, "Waiting for deletions to finish")
fs.Debugf(nil, "Waiting for deletions to finish")
wg.Wait()
if errorCount.Load() > 0 {
err := fmt.Errorf("failed to delete %d files", errorCount.Load())
@@ -726,7 +725,7 @@ func filterCheck(ctx context.Context, f fs.Fs, dir string) bool {
includeDirectory := fi.IncludeDirectory(ctx, f)
include, err := includeDirectory(dir)
if err != nil {
fs.ErrorfCtx(ctx, f, "Failed to discover whether directory is included: %v", err)
fs.Errorf(f, "Failed to discover whether directory is included: %v", err)
return true
}
return include
@@ -743,19 +742,6 @@ func SameDir(fdst, fsrc fs.Info) bool {
return fdstRootFolded == fsrcRootFolded
}
// sleepWithContext sleeps for d returning true, or false if ctx
// finishes first.
func sleepWithContext(ctx context.Context, d time.Duration) bool {
timer := time.NewTimer(d)
defer timer.Stop()
select {
case <-timer.C:
return true
case <-ctx.Done():
return false
}
}
// Retry runs fn up to maxTries times if it returns a retriable error
func Retry(ctx context.Context, o any, maxTries int, fn func() error) (err error) {
for tries := 1; tries <= maxTries; tries++ {
@@ -770,17 +756,11 @@ func Retry(ctx context.Context, o any, maxTries int, fn func() error) (err error
}
// Retry if err returned a retry error
if fserrors.IsRetryError(err) || fserrors.ShouldRetry(err) {
fs.DebugfCtx(ctx, o, "Received error: %v - low level retry %d/%d", err, tries, maxTries)
fs.Debugf(o, "Received error: %v - low level retry %d/%d", err, tries, maxTries)
continue
} else if t, ok := pacer.IsRetryAfter(err); ok {
if tries >= maxTries {
break
}
fs.DebugfCtx(ctx, o, "Sleeping for %v (as indicated by the server) to obey Retry-After error: %v", t, err)
if !sleepWithContext(ctx, t) {
fserrors.ContextError(ctx, &err)
break
}
fs.Debugf(o, "Sleeping for %v (as indicated by the server) to obey Retry-After error: %v", t, err)
time.Sleep(t)
continue
}
break
@@ -1005,7 +985,7 @@ func HashLister(ctx context.Context, ht hash.Type, outputBase64 bool, downloadFl
}()
sum, err := HashSum(ctx, ht, outputBase64, downloadFlag, o)
if err != nil {
fs.ErrorfCtx(ctx, o, "%v", fs.CountError(ctx, err))
fs.Errorf(o, "%v", fs.CountError(ctx, err))
return
}
SyncFprintf(w, "%*s %s\n", width, sum, o.Remote())
@@ -1085,7 +1065,7 @@ func Mkdir(ctx context.Context, f fs.Fs, dir string) (err error) {
if SkipDestructive(ctx, fs.LogDirName(f, dir), "make directory") {
return nil
}
fs.InfofCtx(ctx, fs.LogDirName(f, dir), "Making directory")
fs.Infof(fs.LogDirName(f, dir), "Making directory")
err = f.Mkdir(ctx, dir)
if err != nil {
err = fs.CountError(ctx, err)
@@ -1111,7 +1091,7 @@ func MkdirMetadata(ctx context.Context, f fs.Fs, dir string, metadata fs.Metadat
if SkipDestructive(ctx, logName, "make directory") {
return nil, nil
}
fs.DebugfCtx(ctx, fs.LogDirName(f, dir), "Making directory with metadata")
fs.Debugf(fs.LogDirName(f, dir), "Making directory with metadata")
newDst, err = do(ctx, dir, metadata)
if err != nil {
err = fs.CountError(ctx, err)
@@ -1119,9 +1099,9 @@ func MkdirMetadata(ctx context.Context, f fs.Fs, dir string, metadata fs.Metadat
}
accounting.Stats(ctx).UpdatedDirs(1)
if mtime, ok := metadata["mtime"]; ok {
fs.InfofCtx(ctx, logName, "Made directory with metadata (mtime=%s)", mtime)
fs.Infof(logName, "Made directory with metadata (mtime=%s)", mtime)
} else {
fs.InfofCtx(ctx, logName, "Made directory with metadata")
fs.Infof(logName, "Made directory with metadata")
}
return newDst, err
}
@@ -1165,7 +1145,7 @@ func TryRmdir(ctx context.Context, f fs.Fs, dir string) error {
if SkipDestructive(ctx, fs.LogDirName(f, dir), "remove directory") {
return nil
}
fs.InfofCtx(ctx, fs.LogDirName(f, dir), "Removing directory")
fs.Infof(fs.LogDirName(f, dir), "Removing directory")
return f.Rmdir(ctx, dir)
}
@@ -1257,23 +1237,23 @@ func RemoveExisting(ctx context.Context, f fs.Fs, remote string, operation strin
remoteSaved = remote + suffix
}
fs.DebugfCtx(ctx, existingObj, "%s: renaming existing object to %q before starting", operation, remoteSaved)
fs.Debugf(existingObj, "%s: renaming existing object to %q before starting", operation, remoteSaved)
existingObj, err = doMove(ctx, existingObj, remoteSaved)
if err != nil {
return nil, fmt.Errorf("%s: failed to rename existing file: %w", operation, err)
}
return func(perr *error) {
if *perr == nil {
fs.DebugfCtx(ctx, existingObj, "%s: removing renamed existing file after operation", operation)
fs.Debugf(existingObj, "%s: removing renamed existing file after operation", operation)
err := existingObj.Remove(ctx)
if err != nil {
*perr = fmt.Errorf("%s: failed to remove renamed existing file: %w", operation, err)
}
} else {
fs.DebugfCtx(ctx, existingObj, "%s: renaming existing back after failed operation", operation)
fs.Debugf(existingObj, "%s: renaming existing back after failed operation", operation)
_, renameErr := doMove(ctx, existingObj, remote)
if renameErr != nil {
fs.ErrorfCtx(ctx, existingObj, "%s: failed to restore existing file after failed operation: %v", operation, renameErr)
fs.Errorf(existingObj, "%s: failed to restore existing file after failed operation: %v", operation, renameErr)
}
}
}, nil
@@ -1299,7 +1279,7 @@ func listToChan(ctx context.Context, f fs.Fs, dir string) fs.ObjectsChan {
if err != nil && err != fs.ErrorDirNotFound {
err = fmt.Errorf("failed to list: %w", err)
err = fs.CountError(ctx, err)
fs.ErrorfCtx(ctx, nil, "%v", err)
fs.Errorf(nil, "%v", err)
}
}()
return o
@@ -1338,13 +1318,13 @@ func Cat(ctx context.Context, f fs.Fs, w io.Writer, offset, count int64, sep []b
defer mu.Unlock()
err := catObject(ctx, o, w, offset, count)
if err != nil {
fs.ErrorfCtx(ctx, o, "Failed to send to output: %v", err)
fs.Errorf(o, "Failed to send to output: %v", err)
return
}
if len(sep) > 0 {
if _, err := w.Write(sep); err != nil {
err = fs.CountError(ctx, err)
fs.ErrorfCtx(ctx, o, "Failed to send separator to output: %v", err)
fs.Errorf(o, "Failed to send separator to output: %v", err)
}
}
})
@@ -1453,8 +1433,6 @@ func rcatSrc(ctx context.Context, fdst fs.Fs, dstFileName string, in io.ReadClos
if n, err := io.ReadFull(trackingIn, buf); err == io.EOF || err == io.ErrUnexpectedEOF {
fileIsSmall = true
buf = buf[:n]
} else if err != nil {
return nil, fmt.Errorf("failed to read upload input: %w", err)
}
// Read the data we have already read in buf and any further unread
@@ -1466,10 +1444,10 @@ func rcatSrc(ctx context.Context, fdst fs.Fs, dstFileName string, in io.ReadClos
if fileIsSmall || doPutStream == nil {
var rs io.ReadSeeker
if fileIsSmall {
fs.DebugfCtx(ctx, fdst, "File to upload is small (%d bytes), uploading instead of streaming", len(buf))
fs.Debugf(fdst, "File to upload is small (%d bytes), uploading instead of streaming", len(buf))
rs = bytes.NewReader(buf)
} else {
fs.DebugfCtx(ctx, fdst, "Target remote doesn't support streaming uploads, creating temporary local FS to spool file")
fs.Debugf(fdst, "Target remote doesn't support streaming uploads, creating temporary local FS to spool file")
spool, err := os.CreateTemp("", "rclone-spool")
if err != nil {
return nil, fmt.Errorf("failed to create temporary spool file: %v", err)
@@ -1478,11 +1456,11 @@ func rcatSrc(ctx context.Context, fdst fs.Fs, dstFileName string, in io.ReadClos
defer func() {
err := spool.Close()
if err != nil {
fs.ErrorfCtx(ctx, fileName, "Failed to close temporary spool file: %v", err)
fs.Errorf(fileName, "Failed to close temporary spool file: %v", err)
}
err = os.Remove(fileName)
if err != nil {
fs.ErrorfCtx(ctx, fileName, "Failed to delete temporary spool file: %v", err)
fs.Errorf(fileName, "Failed to delete temporary spool file: %v", err)
}
}()
_, err = io.Copy(spool, streamIn)
@@ -1523,7 +1501,7 @@ func rcatSrc(ctx context.Context, fdst fs.Fs, dstFileName string, in io.ReadClos
if !equal(ctx, src, dst, opt) {
err = fmt.Errorf("corrupted on transfer")
err = fs.CountError(ctx, err)
fs.ErrorfCtx(ctx, dst, "%v", err)
fs.Errorf(dst, "%v", err)
return dst, err
}
return dst, nil
@@ -1550,7 +1528,7 @@ func Rmdirs(ctx context.Context, f fs.Fs, dir string, leaveRoot bool) error {
err := walk.Walk(ctx, f, dir, false, ci.MaxDepth, func(dirPath string, entries fs.DirEntries, err error) error {
if err != nil {
err = fs.CountError(ctx, err)
fs.ErrorfCtx(ctx, f, "Failed to list %q: %v", dirPath, err)
fs.Errorf(f, "Failed to list %q: %v", dirPath, err)
return nil
}
for _, entry := range entries {
@@ -1611,7 +1589,7 @@ func Rmdirs(ctx context.Context, f fs.Fs, dir string, leaveRoot bool) error {
if len(dirs) == 0 {
continue
}
fs.DebugfCtx(ctx, nil, "removing %d level %d directories", len(dirs), level)
fs.Debugf(nil, "removing %d level %d directories", len(dirs), level)
sort.Strings(dirs)
g, gCtx := errgroup.WithContext(ctx)
g.SetLimit(ci.Checkers)
@@ -1625,7 +1603,7 @@ func Rmdirs(ctx context.Context, f fs.Fs, dir string, leaveRoot bool) error {
err := TryRmdir(gCtx, f, dir)
if err != nil {
err = fs.CountError(ctx, err)
fs.ErrorfCtx(gCtx, dir, "Failed to rmdir: %v", err)
fs.Errorf(dir, "Failed to rmdir: %v", err)
errCount.Add(err)
}
return nil // don't return errors, just count them
@@ -1672,7 +1650,7 @@ func compareDest(ctx context.Context, dst, src fs.Object, CompareDest fs.Fs) (No
opt := defaultEqualOpt(ctx)
opt.updateModTime = false
if equal(ctx, src, CompareDestFile, opt) {
fs.DebugfCtx(ctx, src, "Destination found in --compare-dest, skipping")
fs.Debugf(src, "Destination found in --compare-dest, skipping")
return true, nil
}
return false, nil
@@ -1731,16 +1709,16 @@ func copyDest(ctx context.Context, fdst fs.Fs, dst, src fs.Object, CopyDest, bac
}
_, err := Copy(ctx, fdst, dst, remote, CopyDestFile)
if err != nil {
fs.ErrorfCtx(ctx, src, "Destination found in --copy-dest, error copying")
fs.Errorf(src, "Destination found in --copy-dest, error copying")
return false, nil
}
fs.DebugfCtx(ctx, src, "Destination found in --copy-dest, using server-side copy")
fs.Debugf(src, "Destination found in --copy-dest, using server-side copy")
return true, nil
}
fs.DebugfCtx(ctx, src, "Unchanged skipping")
fs.Debugf(src, "Unchanged skipping")
return true, nil
}
fs.DebugfCtx(ctx, src, "Destination not found in --copy-dest")
fs.Debugf(src, "Destination not found in --copy-dest")
return false, nil
}
@@ -1777,19 +1755,19 @@ func NeedTransfer(ctx context.Context, dst, src fs.Object) bool {
ci := fs.GetConfig(ctx)
logger, _ := GetLogger(ctx)
if dst == nil {
fs.DebugfCtx(ctx, src, "Need to transfer - File not found at Destination")
fs.Debugf(src, "Need to transfer - File not found at Destination")
logger(ctx, MissingOnDst, src, nil, nil)
return true
}
// If we should ignore existing files, don't transfer
if ci.IgnoreExisting {
fs.DebugfCtx(ctx, src, "Destination exists, skipping")
fs.Debugf(src, "Destination exists, skipping")
logger(ctx, Match, src, dst, nil)
return false
}
// If we should upload unconditionally
if ci.IgnoreTimes {
fs.DebugfCtx(ctx, src, "Transferring unconditionally as --ignore-times is in use")
fs.Debugf(src, "Transferring unconditionally as --ignore-times is in use")
logger(ctx, Differ, src, dst, nil)
return true
}
@@ -1808,7 +1786,7 @@ func NeedTransfer(ctx context.Context, dst, src fs.Object) bool {
}
switch {
case dt >= modifyWindow:
fs.DebugfCtx(ctx, src, "Destination is newer than source, skipping")
fs.Debugf(src, "Destination is newer than source, skipping")
logger(ctx, Match, src, dst, nil)
return false
case dt <= -modifyWindow:
@@ -1816,7 +1794,7 @@ func NeedTransfer(ctx context.Context, dst, src fs.Object) bool {
opt := defaultEqualOpt(ctx)
opt.forceModTimeMatch = true
if equal(ctx, src, dst, opt) {
fs.DebugfCtx(ctx, src, "Unchanged skipping")
fs.Debugf(src, "Unchanged skipping")
return false
}
default:
@@ -1824,10 +1802,10 @@ func NeedTransfer(ctx context.Context, dst, src fs.Object) bool {
opt := defaultEqualOpt(ctx)
opt.sizeOnly = !ci.CheckSum
if equal(ctx, src, dst, opt) {
fs.DebugfCtx(ctx, src, "Destination mod time is within %v of source and files identical, skipping", modifyWindow)
fs.Debugf(src, "Destination mod time is within %v of source and files identical, skipping", modifyWindow)
return false
}
fs.DebugfCtx(ctx, src, "Destination mod time is within %v of source but files differ, transferring", modifyWindow)
fs.Debugf(src, "Destination mod time is within %v of source but files differ, transferring", modifyWindow)
}
} else {
// Check to see if changed or not
@@ -1836,7 +1814,7 @@ func NeedTransfer(ctx context.Context, dst, src fs.Object) bool {
return !equalFn(ctx, src, dst)
}
if Equal(ctx, src, dst) && !SameObject(src, dst) {
fs.DebugfCtx(ctx, src, "Unchanged skipping")
fs.Debugf(src, "Unchanged skipping")
return false
}
}
@@ -1883,7 +1861,7 @@ func RcatSize(ctx context.Context, fdst fs.Fs, dstFileName string, in io.ReadClo
info := object.NewStaticObjectInfo(dstFileName, modTime, size, true, nil, fdst).WithMetadata(meta)
obj, err = fdst.Put(ctx, in, info, options...)
if err != nil {
fs.ErrorfCtx(ctx, dstFileName, "Post request put error: %v", err)
fs.Errorf(dstFileName, "Post request put error: %v", err)
return nil, err
}
@@ -1901,10 +1879,10 @@ func RcatSize(ctx context.Context, fdst fs.Fs, dstFileName string, in io.ReadClo
}
if err != nil {
err = fs.CountError(ctx, err)
fs.ErrorfCtx(ctx, obj, "%v", err)
fs.InfofCtx(ctx, obj, "Removing failed copy")
fs.Errorf(obj, "%v", err)
fs.Infof(obj, "Removing failed copy")
if removeErr := obj.Remove(ctx); removeErr != nil {
fs.InfofCtx(ctx, obj, "Failed to remove failed copy: %s", removeErr)
fs.Infof(obj, "Failed to remove failed copy: %s", removeErr)
}
return nil, err
}
@@ -1912,7 +1890,7 @@ func RcatSize(ctx context.Context, fdst fs.Fs, dstFileName string, in io.ReadClo
// Size unknown use Rcat
obj, err = Rcat(ctx, fdst, dstFileName, in, modTime, meta)
if err != nil {
fs.ErrorfCtx(ctx, dstFileName, "Post request rcat error: %v", err)
fs.Errorf(dstFileName, "Post request rcat error: %v", err)
return nil, err
}
@@ -1953,7 +1931,7 @@ func copyURLFn(ctx context.Context, dstFileName string, url string, autoFilename
if err != nil || headerFilename == "" {
return fmt.Errorf("CopyURL failed: filename not found in the Content-Disposition header")
}
fs.DebugfCtx(ctx, headerFilename, "filename found in Content-Disposition header.")
fs.Debugf(headerFilename, "filename found in Content-Disposition header.")
return fn(ctx, headerFilename, resp.Body, resp.ContentLength, modTime)
}
@@ -1961,7 +1939,7 @@ func copyURLFn(ctx context.Context, dstFileName string, url string, autoFilename
if dstFileName == "." || dstFileName == "/" {
return fmt.Errorf("CopyURL failed: file name wasn't found in url")
}
fs.DebugfCtx(ctx, dstFileName, "File name found in url")
fs.Debugf(dstFileName, "File name found in url")
}
return fn(ctx, dstFileName, resp.Body, resp.ContentLength, modTime)
}
@@ -2075,13 +2053,13 @@ func MoveCaseInsensitive(ctx context.Context, fdst fs.Fs, fsrc fs.Fs, dstFileNam
logger(ctx, TransferError, nil, tmpObjFail, err)
return nil, fmt.Errorf("error while attempting to move file to a temporary location: %w", err)
}
fs.DebugfCtx(ctx, srcObj, "moving to %v", tmpObjName)
fs.Debugf(srcObj, "moving to %v", tmpObjName)
tmpObj, err := Op(ctx, fdst, nil, tmpObjName, srcObj)
if err != nil {
logger(ctx, TransferError, srcObj, tmpObj, err)
return nil, fmt.Errorf("error while moving file to temporary location: %w", err)
}
fs.DebugfCtx(ctx, srcObj, "moving to %v", dstFileName)
fs.Debugf(srcObj, "moving to %v", dstFileName)
newDst, err = Op(ctx, fdst, nil, dstFileName, tmpObj)
logger(ctx, MissingOnDst, tmpObj, nil, err)
return newDst, err
@@ -2094,7 +2072,7 @@ func moveOrCopyFile(ctx context.Context, fdst fs.Fs, fsrc fs.Fs, dstFileName str
dstFilePath := path.Join(fdst.Root(), dstFileName)
srcFilePath := path.Join(fsrc.Root(), srcFileName)
if fdst.Name() == fsrc.Name() && dstFilePath == srcFilePath && !allowOverlap {
fs.DebugfCtx(ctx, fdst, "don't need to copy/move %s, it is already at target location", dstFileName)
fs.Debugf(fdst, "don't need to copy/move %s, it is already at target location", dstFileName)
if usingLogger {
srcObj, _ := fsrc.NewObject(ctx, srcFileName)
dstObj, _ := fsrc.NewObject(ctx, dstFileName)
@@ -2186,7 +2164,7 @@ func moveOrCopyFile(ctx context.Context, fdst fs.Fs, fsrc fs.Fs, dstFileName str
_, err = Op(ctx, fdst, dstObj, dstFileName, srcObj)
} else if !cp {
if ci.IgnoreExisting {
fs.DebugfCtx(ctx, srcObj, "Not removing source file as destination file exists and --ignore-existing is set")
fs.Debugf(srcObj, "Not removing source file as destination file exists and --ignore-existing is set")
logger(ctx, Match, srcObj, dstObj, nil)
} else if !SameObject(srcObj, dstObj) {
err = DeleteFile(ctx, srcObj)
@@ -2215,12 +2193,12 @@ func SetTier(ctx context.Context, fsrc fs.Fs, tier string) error {
return ListFn(ctx, fsrc, func(o fs.Object) {
objImpl, ok := o.(fs.SetTierer)
if !ok {
fs.ErrorfCtx(ctx, fsrc, "Remote object does not implement SetTier")
fs.Errorf(fsrc, "Remote object does not implement SetTier")
return
}
err := objImpl.SetTier(tier)
if err != nil {
fs.ErrorfCtx(ctx, fsrc, "Failed to do SetTier, %v", err)
fs.Errorf(fsrc, "Failed to do SetTier, %v", err)
}
})
}
@@ -2233,7 +2211,7 @@ func SetTierFile(ctx context.Context, o fs.Object, tier string) error {
}
err := do.SetTier(tier)
if err != nil {
fs.ErrorfCtx(ctx, o, "Failed to do SetTier, %v", err)
fs.Errorf(o, "Failed to do SetTier, %v", err)
return err
}
return nil
@@ -2248,12 +2226,12 @@ func TouchDir(ctx context.Context, f fs.Fs, remote string, t time.Time, recursiv
entries.ForObject(func(o fs.Object) {
if !SkipDestructive(ctx, o, "touch") {
g.Go(func() error {
fs.DebugfCtx(ctx, f, "Touching %q", o.Remote())
fs.Debugf(f, "Touching %q", o.Remote())
err := o.SetModTime(gCtx, t)
if err != nil {
err = fmt.Errorf("failed to touch: %w", err)
err = fs.CountError(gCtx, err)
fs.ErrorfCtx(ctx, o, "%v", err)
fs.Errorf(o, "%v", err)
}
return nil
})
@@ -2487,7 +2465,7 @@ func DirMove(ctx context.Context, f fs.Fs, srcRemote, dstRemote string) (err err
if err != fs.ErrorCantDirMove && err != fs.ErrorDirExists {
return err
}
fs.InfofCtx(ctx, f, "Can't DirMove - falling back to file moves: %v", err)
fs.Infof(f, "Can't DirMove - falling back to file moves: %v", err)
}
// Load the directory tree into memory
@@ -2514,7 +2492,7 @@ func DirMove(ctx context.Context, f fs.Fs, srcRemote, dstRemote string) (err err
newPath string
}
renames := make(chan rename, ci.Checkers)
g, gCtx := errgroup.WithContext(ctx)
g, gCtx := errgroup.WithContext(context.Background())
for range ci.Checkers {
g.Go(func() error {
for job := range renames {
@@ -2533,17 +2511,11 @@ func DirMove(ctx context.Context, f fs.Fs, srcRemote, dstRemote string) (err err
return nil
})
}
sending:
for dir, entries := range tree {
dstPath := dstRemote + dir[len(srcRemote):]
for _, entry := range entries {
if o, ok := entry.(fs.Object); ok {
select {
case renames <- rename{o, path.Join(dstPath, path.Base(o.Remote()))}:
case <-gCtx.Done():
// The workers have stopped so stop sending
break sending
}
renames <- rename{o, path.Join(dstPath, path.Base(o.Remote()))}
}
}
}
@@ -2653,18 +2625,18 @@ func skipDestructiveChoose(ctx context.Context, subject any, action string) (ski
case 's':
skip = true
skipped[action] = true
fs.LogfCtx(ctx, nil, "Skipping all %s operations from now on without asking", action)
fs.Logf(nil, "Skipping all %s operations from now on without asking", action)
case '!':
skip = false
skipped[action] = false
fs.LogfCtx(ctx, nil, "Doing all %s operations from now on without asking", action)
fs.Logf(nil, "Doing all %s operations from now on without asking", action)
case 'q':
fs.LogfCtx(ctx, nil, "Quitting rclone now")
fs.Logf(nil, "Quitting rclone now")
atexit.Run()
os.Exit(0)
default:
skip = true
fs.ErrorfCtx(ctx, nil, "Bad choice %c", i)
fs.Errorf(nil, "Bad choice %c", i)
}
return skip
}
@@ -2704,9 +2676,9 @@ func SkipDestructive(ctx context.Context, subject any, action string) (skip bool
size = do.Size()
}
if size >= 0 {
fs.LogfCtx(ctx, subject, "Skipped %s as %s is set (size %v)", fs.LogValue("skipped", action), flag, fs.LogValue("size", fs.SizeSuffix(size)))
fs.Logf(subject, "Skipped %s as %s is set (size %v)", fs.LogValue("skipped", action), flag, fs.LogValue("size", fs.SizeSuffix(size)))
} else {
fs.LogfCtx(ctx, subject, "Skipped %s as %s is set", fs.LogValue("skipped", action), flag)
fs.Logf(subject, "Skipped %s as %s is set", fs.LogValue("skipped", action), flag)
}
}
return skip
@@ -2794,7 +2766,7 @@ func CopyDirMetadata(ctx context.Context, f fs.Fs, dst fs.Directory, dir string,
return nil, err
}
accounting.Stats(ctx).UpdatedDirs(1)
fs.InfofCtx(ctx, logName, "Updated directory metadata")
fs.Infof(logName, "Updated directory metadata")
return newDst, nil
}
@@ -2810,7 +2782,7 @@ func SetDirModTime(ctx context.Context, f fs.Fs, dst fs.Directory, dir string, m
logName := dirName(f, dst, dir)
ci := fs.GetConfig(ctx)
if ci.NoUpdateDirModTime {
fs.DebugfCtx(ctx, logName, "Skipping set directory modification time as --no-update-dir-modtime is set")
fs.Debugf(logName, "Skipping set directory modification time as --no-update-dir-modtime is set")
return nil, nil
}
tr := accounting.Stats(ctx).NewCheckingTransferNoHistory(dirTransferEntry(f, dst, dir), "setting modtime")
@@ -2837,7 +2809,7 @@ func SetDirModTime(ctx context.Context, f fs.Fs, dst fs.Directory, dir string, m
return dst, err
} else {
accounting.Stats(ctx).UpdatedDirs(1)
fs.InfofCtx(ctx, logName, "Set directory modification time (using SetModTime)")
fs.Infof(logName, "Set directory modification time (using SetModTime)")
return dst, nil
}
}
@@ -2850,7 +2822,7 @@ func SetDirModTime(ctx context.Context, f fs.Fs, dst fs.Directory, dir string, m
return dst, err
}
accounting.Stats(ctx).UpdatedDirs(1)
fs.InfofCtx(ctx, logName, "Set directory modification time (using DirSetModTime)")
fs.Infof(logName, "Set directory modification time (using DirSetModTime)")
return dst, nil
}
-182
View File
@@ -427,32 +427,6 @@ func TestDelete(t *testing.T) {
r.CheckRemoteItems(t, file3)
}
// Check Delete doesn't hang when a fatal error stops the deletions
// before all the objects have been sent to the deleters
func TestDeleteFatalError(t *testing.T) {
ctx := context.Background()
ctx, ci := fs.AddConfig(ctx)
ci.Checkers = 2
ci.MaxDelete = 1
r := fstest.NewRun(t)
// More files than the deleters' channel can hold
for i := range 20 {
r.WriteObject(ctx, fmt.Sprintf("file%d", i), "x", t1)
}
done := make(chan error, 1)
go func() {
done <- operations.Delete(ctx, r.Fremote)
}()
select {
case err := <-done:
require.Error(t, err)
assert.True(t, fserrors.IsFatalError(err), err)
case <-time.After(30 * time.Second):
t.Fatal("Delete didn't return - deadlocked sending to the deleters")
}
}
func isChunker(f fs.Fs) bool {
return strings.HasPrefix(f.Name(), "TestChunker")
}
@@ -566,54 +540,6 @@ func TestRetry(t *testing.T) {
}
// Check the wait for a Retry-After error can be interrupted
func TestRetryAfterContextCancel(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
retryAfter := pacer.RetryAfterError(errors.New("BANG"), time.Hour)
calls := 0
fn := func() error {
calls++
go cancel()
return retryAfter
}
done := make(chan error, 1)
go func() {
done <- operations.Retry(ctx, nil, 5, fn)
}()
select {
case err := <-done:
// The error from the call is returned, not the context error
assert.Equal(t, retryAfter, err)
assert.Equal(t, 1, calls)
case <-time.After(30 * time.Second):
t.Fatal("Retry didn't return - still sleeping for the Retry-After")
}
}
// Check we don't wait for a Retry-After error on the last try
func TestRetryAfterLastTry(t *testing.T) {
ctx := context.Background()
retryAfter := pacer.RetryAfterError(errors.New("BANG"), time.Hour)
calls := 0
fn := func() error {
calls++
return retryAfter
}
done := make(chan error, 1)
go func() {
done <- operations.Retry(ctx, nil, 1, fn)
}()
select {
case err := <-done:
assert.Equal(t, retryAfter, err)
assert.Equal(t, 1, calls)
case <-time.After(30 * time.Second):
t.Fatal("Retry didn't return - slept for the Retry-After on the last try")
}
}
func TestCat(t *testing.T) {
ctx := context.Background()
r := fstest.NewRun(t)
@@ -1453,85 +1379,6 @@ func TestListFormat(t *testing.T) {
}
// noDirMoveFs wraps an Fs removing DirMove so operations.DirMove has
// to move the objects one by one, and allows Move to be made to fail.
type noDirMoveFs struct {
fs.Fs
features *fs.Features
moveCtxs chan context.Context
}
func (f *noDirMoveFs) Features() *fs.Features { return f.features }
func newNoDirMoveFs(t *testing.T, wrapped fs.Fs, failOn string) *noDirMoveFs {
move := wrapped.Features().Move
require.NotNil(t, move, "the test needs a backend with Move")
f := &noDirMoveFs{
Fs: wrapped,
moveCtxs: make(chan context.Context, 100),
}
features := *wrapped.Features()
features.DirMove = nil
features.Move = func(ctx context.Context, src fs.Object, remote string) (fs.Object, error) {
f.moveCtxs <- ctx
if src.Remote() == failOn {
return nil, errors.New("boom")
}
return move(ctx, src, remote)
}
f.features = &features
return f
}
// Check DirMove doesn't hang when moving the objects one by one and
// one of the moves fails
func TestDirMoveMoveError(t *testing.T) {
ctx := context.Background()
ctx, ci := fs.AddConfig(ctx)
ci.Checkers = 2
r := fstest.NewRun(t)
// More files than the renames channel can hold
for i := range 20 {
r.WriteObject(ctx, fmt.Sprintf("A/file%d", i), "x", t1)
}
f := newNoDirMoveFs(t, r.Fremote, "A/file0")
done := make(chan error, 1)
go func() {
done <- operations.DirMove(ctx, f, "A", "B")
}()
select {
case err := <-done:
require.Error(t, err)
assert.Contains(t, err.Error(), "boom")
case <-time.After(30 * time.Second):
t.Fatal("DirMove didn't return - deadlocked sending to the movers")
}
}
// Check the objects moved one by one by DirMove are moved with the
// caller's context
func TestDirMoveContext(t *testing.T) {
ctx := context.Background()
ctx, ci := fs.AddConfig(ctx)
ci.Checkers = 2
r := fstest.NewRun(t)
r.WriteObject(ctx, "A/one", "one", t1)
r.WriteObject(ctx, "A/two", "two", t1)
f := newNoDirMoveFs(t, r.Fremote, "")
require.NoError(t, operations.DirMove(accounting.WithStatsGroup(ctx, "test-dirmove"), f, "A", "B"))
close(f.moveCtxs)
moves := 0
for moveCtx := range f.moveCtxs {
group, ok := accounting.StatsGroupFromContext(moveCtx)
assert.True(t, ok, "move wasn't passed the caller's context")
assert.Equal(t, "test-dirmove", group)
moves++
}
assert.Equal(t, 2, moves)
}
func TestDirMove(t *testing.T) {
ctx := context.Background()
r := fstest.NewRun(t)
@@ -2321,32 +2168,3 @@ func TestRemoveExisting(t *testing.T) {
cleanup(&returnedError)
r.CheckRemoteItems(t)
}
func TestRcatInputFailurePreservesDestination(t *testing.T) {
ctx := context.Background()
root := t.TempDir()
require.NoError(t, os.WriteFile(root+"/target", []byte("original"), 0600))
f, err := fs.NewFs(ctx, root)
require.NoError(t, err)
calls := 0
original := f.Features().PutStream
f.Features().PutStream = func(ctx context.Context, in io.Reader, src fs.ObjectInfo, opts ...fs.OpenOption) (fs.Object, error) {
calls++
return original(ctx, in, src, opts...)
}
inputErr := errors.New("source interrupted")
for _, name := range []string{"target", "missing"} {
_, err = operations.Rcat(ctx, f, name, io.NopCloser(io.MultiReader(strings.NewReader("prefix"), rcatFailedInput{inputErr})), time.Now(), nil)
require.ErrorIs(t, err, inputErr)
require.Zero(t, calls)
b, readErr := os.ReadFile(root + "/target")
require.NoError(t, readErr)
require.Equal(t, "original", string(b))
_, statErr := os.Stat(root + "/missing")
require.True(t, os.IsNotExist(statErr))
}
}
type rcatFailedInput struct{ err error }
func (r rcatFailedInput) Read([]byte) (int, error) { return 0, r.err }
Loaded 100 of 132 files, more files were not shown because too many files have changed in this diff. Show more