Skip to content

operations: Add a download flag to hashsum and related commands to force rclone to download and hash files locally - #4803

Merged
ncw merged 1 commit into
rclone:masterfrom
lostheli:download_hash
Dec 27, 2020
Merged

ncw merged 1 commit into
rclone:masterfrom
lostheli:download_hash

Conversation

@lostheli

@lostheli lostheli commented Nov 24, 2020 •

Copy link
Copy Markdown

Add a download flag to hashsum and related commands to force rclone to download and hash files locally

This commit modifies the operations.hashSum function by adding an alternate code path. This code path is triggered by passing downloadFlag = True. When activated, rclone will download files from the remote and hash them locally. downloadFlag = False preserves the existing behavior of using the remote to retrieve the hash.

This commit modifies HashLister to support the new hashSum method as well as consolidating the roles of HashLister, HashListerBase64, Md5sum, and Sha1sum.

The unit test operations_test.TestHashSums is modified to support this change and test the download functionality.

The command functions hashsum, md5sum, sha1sum, and dbhashsum are modified to support this change.

Was the change discussed in an issue or in the forum before?

https://forum.rclone.org/t/force-download-hash/20333

Checklist

  • I have read the contribution guidelines.
  • I have added tests for all changes in this PR if appropriate.
  • I have added documentation for the changes if appropriate.
  • All commit messages are in house style.
  • I'm done, this Pull Request is ready for review :-)

This pull request requires functionality and project best practices review before finalization.

@ivandeex

Copy link
Copy Markdown
Member

Fixes #3923

Comment thread fs/operations/operations.go Resolved
Comment thread fs/operations/operations.go Resolved
Comment thread fs/operations/operations.go Resolved
Comment thread fs/operations/operations.go Resolved
Comment thread fs/operations/operations.go Resolved
Comment thread fs/operations/operations.go Resolved
@lostheli

lostheli commented Nov 25, 2020 •

Copy link
Copy Markdown
Author

Ivan, thank you for flagging the related open issues. When I was originally trying to accomplish my task with existing rclone functions, I looked at the forum and didn't anything specific. I'm both surprised and not surprised this has come up multiple times before!

All, I've added comments where review is most needed. I realized the pull request version doesn't have the cleaned up comments I posted to the forum. Comments will be revised when finalizing the code anyway.

I am not close enough to understand the check results - specifically why linux is failing while others pass. I'd also appreciate insight into what's failing and how to resolve the build issue.

@ivandeex
ivandeex requested a review from ncw November 25, 2020 20:20
@ivandeex

ivandeex commented Nov 25, 2020 •

Copy link
Copy Markdown
Member

Re build issue: file not goimports-ed is just a bad wording for golang source code formatting needs improvement. It's not about linux, it's just a test group that happens to check the code style too.
Run

gofmt -w ./cmd/dbhashsum/dbhashsum.go
gofmt -w ./fs/operations/operations.go

and commit the result. It will change some indenting or sort imports by name or smth like that.

fs/operations/operations.go:856: File is not goimports-ed (goimports)
cmd/dbhashsum/dbhashsum.go:9: File is not goimports-ed (goimports)
"github.com/rclone/rclone/fs/config/flags"
Makefile:86: recipe for target 'check' failed
make: *** [check] Error 1

@ivandeex

Copy link
Copy Markdown
Member

An example of how this very flag was added to check in 2017 and how it looks now.

@ncw ncw left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looking good :-)

Please see inline for a first pass review!

Hopefully I've answered your questions.

Can you remove the dead code and questions from the code to make it easier to read.

You'll have a few small fix-ups if you rebase on master - I suggest you do that now.

Thank you

Comment thread cmd/dbhashsum/dbhashsum.go Resolved
Comment thread cmd/sha1sum/sha1sum.go Resolved
Comment thread fs/operations/operations.go Resolved
Comment thread fs/operations/operations.go Resolved
Comment thread fs/operations/operations.go Resolved
Comment thread fs/operations/operations.go Resolved
Comment thread fs/operations/operations.go Resolved
Comment thread fs/operations/operations.go Resolved
Comment thread fs/operations/operations.go Resolved
Comment thread fs/operations/operations.go Resolved
@lostheli

Copy link
Copy Markdown
Author

Thanks for the review! I have a few follow up questions, and there are a few still pending.

As I move to the parallel part of this, I wanted to better understand the suggestion to implement by making the anonymous function in HashLister parallel. If I understand correctly,

  • ListFn will wrap this with a .ForObject call and then pass to walk.ListR
  • In the simple case, walk.ListR will pass to to walk.listRwalk
  • Walk will pass to one of several functions, but let's assume walkListDirSorted
  • walkListDirSorted passes to walk
  • walk finally calls the function, but does so within a mutex

Somewhere fn gets wrapped to take a remote and error variable instead of just the fs.DirEntries it takes in ListFn.

This level of function passing is tough for me to follow - a bit mind numbing actually. As far as I can tell, the parallel version of HashLister could be called but only once at a time. Inside that we'd be able to process a number of files in parallel based on the number of transfers available. However, the whole process seems very dependent on how all of these layers of walk construct the list of files to act on.

For example, what would happen if we called this on directory with 4 sub-directories and each sub-directory contained a single file. Would walk flatten the 4 files into a single fs.DirEntries and then hand that to our new HashLister? If not, why does the second file (in a separate invocation of HashLister) not get blocked by the mutex in walk?

And finally, a broader question. Are you just using the channel + WaitGroup as a semaphore? Are you avoiding semaphore because go put it in a weird non-standard package?

@ncw

ncw commented Nov 27, 2020

Copy link
Copy Markdown
Member

Thanks for the review! I have a few follow up questions, and there are a few still pending.

Pending that I haven't answered?

As I move to the parallel part of this, I wanted to better understand the suggestion to implement by making the anonymous function in HashLister parallel. If I understand correctly,

  • ListFn will wrap this with a .ForObject call and then pass to walk.ListR
  • In the simple case, walk.ListR will pass to to walk.listRwalk
  • Walk will pass to one of several functions, but let's assume walkListDirSorted
  • walkListDirSorted passes to walk
  • walk finally calls the function, but does so within a mutex

Somewhere fn gets wrapped to take a remote and error variable instead of just the fs.DirEntries it takes in ListFn.

This level of function passing is tough for me to follow - a bit mind numbing actually. As far as I can tell, the parallel version of HashLister could be called but only once at a time. Inside that we'd be able to process a number of files in parallel based on the number of transfers available. However, the whole process seems very dependent on how all of these layers of walk construct the list of files to act on.

For example, what would happen if we called this on directory with 4 sub-directories and each sub-directory contained a single file. Would walk flatten the 4 files into a single fs.DirEntries and then hand that to our new HashLister? If not, why does the second file (in a separate invocation of HashLister) not get blocked by the mutex in walk?

It depends is the answer!

If you aren't using ListR then you'll get --checkers directory threads reading directories and they will call hashlister concurrently.

However you don't need to worry about that as you are going to start a go routine to do the processing in the background and return immediately. So you'll be making your own parallelism. It therefore doesn't matter whether the listing comes in sequentially or in parallel as long as it comes in faster than you can download files (which it will).

And finally, a broader question. Are you just using the channel + WaitGroup as a semaphore? Are you avoiding semaphore because go put it in a weird non-standard package?

Ah you mean: https://godoc.org/golang.org/x/sync/semaphore

To tell you the truth I didn't know about that package! The golang.org/x packages are the Go team's place to put packages that might be considered for the standard library. Or maybe now-a-days they can be considered as standard library part 2. I quite often use golang.org/x/sync/errgroup

I've been writing Go for a long time now (since before Go 1.0) so I guess I just got used to the using the primitives Go provides out of which you can build anything at all.

Here was my suggestion from before

func HashLister(ctx context.Context, ht hash.Type, f fs.Fs, w io.Writer) error {
	concurrencyControl := make(chan struct{}, fs.Config.Transfers)
	var wg sync.WaitGroup
	err := ListFn(ctx, f, func(o fs.Object) {
		concurrencyControl <- struct{}{} // get a concurrency slot
		wg.Add(1)
		go func() {
			defer func() {
				wg.Done()
				<-concurrencyControl // return the concurrency slot
			}()
			sum, _ := hashSum(ctx, ht, o)
			syncFprintf(w, "%*s  %s\n", hash.Width(ht), sum, o.Remote())
		}()
	})
	wg.Wait()
	return err
}

Lets see what it looks like with semaphore

func HashLister2(ctx context.Context, ht hash.Type, f fs.Fs, w io.Writer) error {
	maxWorkers := int64(fs.Config.Transfers)
	concurrencyControl := semaphore.NewWeighted(maxWorkers)
	err := ListFn(ctx, f, func(o fs.Object) {
		if err := sem.Acquire(ctx, 1); err != nil {
			fs.CountError(err)
			fs.Errorf(o, "Failed to acquire semaphore: %v", err)
			return
		}
		go func() {
			defer concurrencyControl.Release(1)
			sum, _ := hashSum(ctx, ht, o)
			syncFprintf(w, "%*s  %s\n", hash.Width(ht), sum, o.Remote())
		}()
	})
	if semErr := sem.Acquire(ctx, maxWorkers); semErr != nil {
		fs.CountError(semErr)
		fs.Errorf(o, "Failed to acquire semaphore: %v", semErr)
	}
	return err
}

3 lines longer and some rather ugly error handling! It does do one
thing that the original code does though and that is exit if the
context is cancelled and that might be valuable. Though I think if you
did cancel the context you'll get one error per ListFn item which
might be quite a lot before the context cancel comes through there...

Looking at the semaphore code and docs a bit more the only way Acquire it can fail is if the context is cancelled, so it could be simplified to this

func HashLister3(ctx context.Context, ht hash.Type, f fs.Fs, w io.Writer) error {
	maxWorkers := int64(fs.Config.Transfers)
	concurrencyControl := semaphore.NewWeighted(maxWorkers)
	err := ListFn(ctx, f, func(o fs.Object) {
		if sem.Acquire(ctx, 1) == nil {
			go func() {
				defer concurrencyControl.Release(1)
				sum, _ := hashSum(ctx, ht, o)
				syncFprintf(w, "%*s  %s\n", hash.Width(ht), sum, o.Remote())
			}()
		}
	})
	_ = sem.Acquire(ctx, maxWorkers)
	return err
}

If you want do so it like that, then that is fine with me :-)

(All code untested!)

Comment thread fs/operations/operations.go Resolved
Comment thread fs/operations/operations_test.go Resolved
Comment thread cmd/dbhashsum/dbhashsum.go Resolved
Comment thread cmd/sha1sum/sha1sum.go Resolved
Comment thread fs/operations/operations.go Resolved
Comment thread fs/operations/operations.go Resolved
Comment thread fs/operations/operations.go Resolved
Comment thread fs/operations/operations.go Resolved
Comment thread fs/operations/operations.go Resolved
@lostheli

lostheli commented Nov 28, 2020 •

Copy link
Copy Markdown
Author

Pending that I haven't answered?

Yes, though that's my fault. I did not click the overall response submit and my in-line comments were stuck in edit mode.

For example, what would happen if we called this on directory with 4 sub-directories and each sub-directory contained a single file. Would walk flatten the 4 files into a single fs.DirEntries and then hand that to our new HashLister? If not, why does the second file (in a separate invocation of HashLister) not get blocked by the mutex in walk?

It depends is the answer!

If you aren't using ListR then you'll get --checkers directory threads reading directories and they will call hashlister concurrently.

However you don't need to worry about that as you are going to start a go routine to do the processing in the background and return immediately. So you'll be making your own parallelism. It therefore doesn't matter whether the listing comes in sequentially or in parallel as long as it comes in faster than you can download files (which it will).

Okay, I believe in the process of trying to rationalize and explain the behavior here I understood a bit of how it works. Is this correct?

  • For the sake of writing this out, I'm going to refer to the anonymous function written in HashLister and handed to ListFn as hashSumCaller. We'll assume a version of HashLister like the above where hashSumCaller starts a go routine with its own inner function that calls hashSum.
  • ListFn wraps hashSumCaller in .ForObject making it sequential across all of the objects in a single entries list (more on those later). We 'escape' this serial nature by having hashSumCaller simply kick off the go routine instead of calling hashSum directly. This causes hashSumCaller to return immediately once the go routine starts instead of waiting for hashSum.
  • Assuming transfers = 4 and an entries list of 5 or more, the first 4 invocations of hashSumCaller by .ForObject will kick off their go routine and return immediately. .ForObject will block on each object starting with number 5 until that call to hashSumCaller gets a slot, starts its go routine to call hashSum, and returns. This continues until .ForObject calls hashSumCaller for the last object in entries and hashSumCaller returns. At this point, .ForObject has started the hashing process for all objectives in entities but hashing is ongoing for roughly the last 4 objects in entities.
  • The anonymous go routine in walk calls this .ForObject loop of hashSumCaller invocations on the contents of each directory. While there are multiple 'checker' threads constructing the directory lists and calling the function, only one checker thread can actually call the function at a time because of the mutex. Checker 1 will block checker 2 until .ForObject returns, which happens when the last hash for checker 1's directory is started. This has minimal impact on us as the checker thread is freed as soon as the last hash starts. While Checker 1 is blocked by .ForObject and .ForObject by hashSumCaller and hashSumCaller by the available slots, it doesn't matter where Checker 2 is blocked.

What was weird to me, is wg.Wait() is actually 5 or so levels removed on the call stack from the hashSumCaller code on the lines immediately above it. As a result of all the function passing, hashSumCaller gets nested many levels down. wg.Wait() by contrast is sitting just one level under the command. wg.Wait() does not get called until ListFn returns, which happens after the walk stack returns, which happens (skipping a few levels of function calls in walk) after the checker threads finish, which happens after they have completed the .ForObject loop on the last batch of entities, which happens after the last hashes are started. wg.Wait() then simply blocks while those final 4 hashes finish.

And finally, a broader question. Are you just using the channel + WaitGroup as a semaphore? Are you avoiding semaphore because go put it in a weird non-standard package?

Ah you mean: https://godoc.org/golang.org/x/sync/semaphore

To tell you the truth I didn't know about that package! The golang.org/x packages are the Go team's place to put packages that might be considered for the standard library. Or maybe now-a-days they can be considered as standard library part 2. I quite often use golang.org/x/sync/errgroup

I've been writing Go for a long time now (since before Go 1.0) so I guess I just got used to the using the primitives Go provides out of which you can build anything at all.

I'm coming at this from the opposite side! I want a semaphore, so I search and see what they called semaphores in Go. :)

@ivandeex

Copy link
Copy Markdown
Member

The worker pool pattern (https://gobyexample.com/worker-pools) is one of the first language examples I did when I learned go. Check it out online using the link above. It's used widely in rclone, e.g. see https://github.com/rclone/rclone/blob/master/backend/union/union.go#L868
Semaphores are rare mostly for historic reasons, though I doubt you'll see any performance fluctuations.

@lostheli

lostheli commented Nov 28, 2020 •

Copy link
Copy Markdown
Author

The worker pool pattern (https://gobyexample.com/worker-pools) is one of the first language examples I did when I learned go. Check it out online using the link above. It's used widely in rclone, e.g. see https://github.com/rclone/rclone/blob/master/backend/union/union.go#L868
Semaphores are rare mostly for historic reasons, though I doubt you'll see any performance fluctuations.

Indeed, and walk follows that pattern. It sets up a pool of workers, hands them work through a channel, and then exits when all of the work is done. However, the total construct proposed here does not follow that pattern - at least not if I now understand it correctly. We do not set up a pool of hashSum workers and feed them work through a channel. The channel has empty concurrency tokens.

The hashSum 'workers' are instead 'fed' work in the function call when repeatedly calling hashSum (or the anonymous go routine that calls it) after handing this function to call hashSum down the call stack. Additionally, the channel in walk's worker pool / channel pattern does not provide hashSum's concurrency control or determine when the work is done and it's safe to return. Instead the concurrency control for this repeated calling of hashSum has to be provided at the top of the call stack (by the proposed concurrencyControl channel or semaphore, which I left out in my last post). The entire worker pool pattern of walk takes place between the level of concurrencyControl and the level of hashSumCaller!

Coming from outside go and this project, that's what got me. Not using a worker pool / channel pattern to give work to hashSum. Rather nesting the work pool / channel pattern of walk between the layers of another semaphore-like pattern of repeated function calls to hashSum. Even if I roughly understand how this works, I'm still not to the point where I can really reason about it's implications.

But this all rests on - is my understanding of how this would work correct?

@ivandeex

Copy link
Copy Markdown
Member
  1. There obviously will be two working pools here.
    One is already written, it walks lists.
    Another will be written by you, it will download and hash data, if --download is supplied. The former will feed jobs to latter e.g. via channel.
  2. What do you call nesting? The sketch below is not nesting. Thanks to the go word it creates a completely parallel thread of execution and continues immediately.
if flag {
  go func() {
    actions
  }()
}
  1. Forget about semaphores. They give no advantage vs wg, only distract from fulfilling the goal. If you wish, use interactive go console to play with them in a toy program.
  2. Please fix goimportsed :)

Ivan

@lostheli

lostheli commented Nov 28, 2020 •

Copy link
Copy Markdown
Author
1. There obviously will be two working pools here.
   One is already written, it walks lists.
   Another will be written by you, it will download and hash data, if --download is supplied. The former will feed jobs to latter e.g. via channel.

Okay, I'll be picky on language for a minute, and I apologize. E.g. as in 'for example this is one way it could work?' Or that is how it would work if I implemented it the way ncw suggested? Because that might be where I am stuck.

I agree we could hand work between the directory walking worker pool and a hashing worker pool with a channel. However, if we implement it the way that's suggested, I do not see where we setup a pool of hashing workers or what channel is used to hand work to them. 'Setup a pool of workers' is a little vague but the channel bit is pretty clear cut. The object (file) to be hashed is never placed into a channel to relay it to hashSum unless, potentially, go implicitly uses a channel to pass arguments to new go routines. It is instead handed to hashSum through a function call. It's a little harder to illustrate the lack of a worker pool, but maybe I can say this - there does not appear to be any reuse of hashSum workers. A new go routine is created for each object subject to a cap on how many can concurrently exist. If we were creating a worker pool and then feeding it work, I would expect to see those workers reused (as they are in walk).

2. What do you call _nesting_? The sketch below is not nesting. Thanks to the `go` word it creates a completely parallel thread of execution and continues immediately.
if flag {
  go func() {
    actions
  }()
}

My use of call stack here is almost certainly not technically correct. In your example I would say the creation of the go routine is nested between the action and whatever called this function with if flag. I don't actually know how go handles stacks for go routines.

In our case:

  1. Command calls HashLister
  2. HashLister calls ListFn; in the proposal it also provides concurrency control for hashSum
  3. HashLister calls walk.ListR
  4. ListR calls listRwalk (as one option depending on what the remote supports)
  5. listRwalk calls Walk
  6. Walk calls walkListDirSorted
  7. walkListDirSorted calls walk
  8. walk creates a worker pool of go routines to walk the directory structure and sets them running
  9. the go routines put directories into the job queue but also call a function defined in ListFn with a list of entities - and this is where files get processed
  10. that function calls entities.ForObject with the function defined in HashLister (which I called hashSumCaller in the post above)
  11. hashSumCaller starts another go routine when the concurrency control in number 2 allows
  12. this go routine calls hashSum

So, we probably don't have a single stack that contains all of these calls because of the go routines, but this is the order the functions are called in. The worker pool + channel concurrency pattern of walk exists in steps 8 and 9. The concurrency pattern used to hash four files at a time is defined by steps 2, 11, and 12. That's what I mean by nested - steps 8 and 9 are between 2, 11, and 12.

3. Forget about semaphores. They give no advantage vs `wg`, only distract from fulfilling the goal. If you wish, use interactive go console to play with them in a toy program.

Sorry, by semaphore-like I just mean filling the role of a semaphore. The pattern of using a channel with tokens and a wait group to limit the number of concurrent instances of a particular go routine by blocking the start of new instances of that go routine until below a concurrency cap appears to implement a semaphore.

4. Please fix `goimportsed` :)

Of course

Thank you for your patience!

Comment thread fs/operations/operations.go Resolved
Comment thread fs/operations/operations.go Resolved
Comment thread cmd/hashsum/hashsum.go Resolved
Comment thread cmd/md5sum/md5sum.go Resolved
Comment thread cmd/md5sum/md5sum.go Resolved
Comment thread cmd/dbhashsum/dbhashsum.go Resolved
Comment thread cmd/dbhashsum/dbhashsum.go Resolved
Comment thread cmd/hashsum/hashsum.go Resolved
Comment thread cmd/hashsum/hashsum.go Resolved
Comment thread cmd/md5sum/md5sum.go Resolved
Comment thread fs/operations/operations.go Resolved
Comment thread fs/operations/operations.go Resolved
Comment thread fs/operations/operations.go Resolved
Comment thread fs/operations/operations_test.go Resolved
Comment thread fs/operations/operations.go Resolved
@ivandeex

ivandeex commented Nov 28, 2020 •

Copy link
Copy Markdown
Member

Or that is how it would work if I implemented it the way ncw suggested? Because that might be where I stuck.

Concurrency is tricky. Let's forget about working pools, semaphore patterns, channels, locking and all that black locking magic (BLM!) for a moment. It's all optimizations. It's driving FAST. We'll get back to it later.

Right now please start from addressing current review comments. Make your code compile. Make the "Some checks were unhappy" circle disappear.

You've added downloadFlag argument to hashSum, right? Now make the new hashSum pass tests. Let's drive slow but stay alive.

After (only after) that we can return to BLM.

Comment thread fs/operations/operations.go Resolved
@ivandeex

Copy link
Copy Markdown
Member

Rebased on master. Please save your changes and pull to your workdir.

@ivandeex

ivandeex commented Nov 29, 2020 •

Copy link
Copy Markdown
Member

@lostheli
At this stage please finish refactoring and close review comments after pushing commits that resolve them.
Postpone thread pools to the next round of reviews.
You may even not implement the non-threaded download now. It's enough for the moment that hashSum simply logs Errorf("Pretending to download") when it sees downloadFlag. We'll look into it later.
Thanks

@lostheli lostheli left a comment

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I've committed an updated version of the code.

Apologies if there was some misunderstanding here Ivan - you reviewed the original code thus no changes. I marked questions and comments as resolved where the next steps were clear. The updates I've made are a mix of the different suggestions and there are a few outstanding questions. Notably, I already implemented the multi-threaded version while trying to understand the suggestion, so that's what's here.

When you say I may not implement non-threaded downloads and suggest logging an error for downloadFlag, I do not follow at all. To be clear, the code works with some caveats I'm aware of and of course probably some I'm not.

Questions:

  • My question on errors is - where should the error be logged with fs.CountError and fs.Errorf. Nick said in the caller of HashLister, which is the command. That seemed an odd place for it, partially because of what I see elsewhere, so wanted to confirm if I understood correctly. If Copy hasn't been cleaned up recently and doesn't match the current coding style preference, I don't know that. I based my code as much as possible on these existing functions.
  • There are a couple of additional questions on the code I either forgot or couldn't figure out that I've flagged this time.
  • I'm unsure how to update the documentation. CONTRIBUTING.md suggests manual edits to md files in docs/content. The files in the sub-folder docs/content/commands that we'd update here say they are autogenerated and to run make commanddocs. When I run make commanddocs, I get the same docs as before and they don't contain the new flags (even the doc for hashsum where those flags are added directly). I wanted to test this because I'm concerned how the new flags will reflect in the documentation for the other commands (e.g. sha1sum). For now, I've edited them manually hoping these changes carry over when regenerating.

Caveats I know of:

  • When using this with --progress, the output with the hash was suppressed. Once per file, the line 'Transferred: xG / y GBytes, z%, a MBytes/s, ETA 1s' is reprinted rather than updated in place. Suspect the way progress resets this line is not playing nice with having other output. It is overwriting the hashsum output rather than the Transferred line. All I thought of to resolve was move the output to the info logging system, which appears designed to work with progress but is not idea, or implement output to a file, which requires more work and is maybe a future task. If there's an easy solution that would be great.
  • The restart functionality for failed transfers may not be working correctly. In running this unattended, I had 4 files fail with an IO timeout and then the next 100 or so files fail with a TCP error 'no such host.' I suspect the problem was caused by a network hiccup not rclone itself, and I don't know how long any network interruption was. In rerunning on the same files, the issue was not reproduced. Now, rclone did produce errors on a lot of files before the remote API started working again (maybe insufficient backoff) and did not 'go back' for those files (would a different error implementation would signal rclone to do that?). Because it's not repeatable, it's difficult to verify the retry / restart functionality. Are there test cases designed to test the behavior when transfers fail?
  • It seems to ignore --bwlimit. I've not looked into this one at all but noticed it when thinking of things to help avoid IO failures.

Comment thread fs/operations/operations.go Resolved
Comment thread fs/operations/operations.go Resolved
Comment thread fs/operations/operations.go Resolved

@ncw ncw left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I've committed an updated version of the code.

Thank you. I've put a few comments inline.

I think the code is looking very good.

The multithreaded code is very in-style for rclone so is easy for me to read.

Questions:

  • My question on errors is - where should the error be logged with fs.CountError and fs.Errorf. Nick said in the caller of HashLister, which is the command.

If you call fs.CountError then rclone will return a non zero error code, even if the error didn't get bubbled up.

Calling fs.Errorf shows the error to the user.

Generally the convention is in rclone is to either return the error, *or call fs.Errorf and fs.CountError. If you do both then you run the risk of double logging of errors.

So that is the reason for the convention and why I suggested that we remove the logging there since the error is returned and make sure we make sure it is done in the caller.

That seemed an odd place for it, partially because of what I see elsewhere, so wanted to confirm if I understood correctly. If Copy hasn't been cleaned up recently and doesn't match the current coding style preference, I don't know that. I based my code as much as possible on these existing functions.

Copy is the oldest rclone function and also the most worked upon function so I would be surprised if there were inconsistencies.

  • There are a couple of additional questions on the code I either forgot or couldn't figure out that I've flagged this time.
  • I'm unsure how to update the documentation. CONTRIBUTING.md suggests manual edits to md files in docs/content. The files in the sub-folder docs/content/commands that we'd update here say they are autogenerated and to run make commanddocs. When I run make commanddocs, I get the same docs as before and they don't contain the new flags (even the doc for hashsum where those flags are added directly). I wanted to test this because I'm concerned how the new flags will reflect in the documentation for the other commands (e.g. sha1sum). For now, I've edited them manually hoping these changes carry over when regenerating.

Hmm, make commanddocs should work. It might be that you have to run make first. Changes to docs/content/commands/* will get overwritten, alas.

Caveats I know of:

  • When using this with --progress, the output with the hash was suppressed. Once per file, the line 'Transferred: xG / y GBytes, z%, a MBytes/s, ETA 1s' is reprinted rather than updated in place. Suspect the way progress resets this line is not playing nice with having other output. It is overwriting the hashsum output rather than the Transferred line. All I thought of to resolve was move the output to the info logging system, which appears designed to work with progress but is not idea, or implement output to a file, which requires more work and is maybe a future task. If there's an easy solution that would be great.

I don't think this is easily fixable. the hashsum etc write to stdout whereas progress writes to stderr. If users want to use hashsum with progress then they should redirect stdout to a file.

  • The restart functionality for failed transfers may not be working correctly. In running this unattended, I had 4 files fail with an IO timeout and then the next 100 or so files fail with a TCP error 'no such host.' I suspect the problem was caused by a network hiccup not rclone itself, and I don't know how long any network interruption was. In rerunning on the same files, the issue was not reproduced. Now, rclone did produce errors on a lot of files before the remote API started working again (maybe insufficient backoff) and did not 'go back' for those files (would a different error implementation would signal rclone to do that?). Because it's not repeatable, it's difficult to verify the retry / restart functionality. Are there test cases designed to test the behavior when transfers fail?

There are lots of test of the NewReOpen functionality. If you run with -vv then you will see the retries. However if a non-retriable error happened then rclone won't retry. no such host may be such an error, I'm not sure.

  • It seems to ignore --bwlimit. I've not looked into this one at all but noticed it when thinking of things to help avoid IO failures.

Hmm we need to fix that! This line

tr := accounting.Stats(ctx).NewTransfer(o)

and this one

in = tr.Account(ctx, in).WithBuffer()

Should be making sure we are limiting the transfer rates. You know the parameter to --bwlimit is in kBytes/s or MByte/s?

Comment thread docs/content/commands/rclone_hashsum.md Resolved
Comment thread docs/content/commands/rclone_hashsum.md Resolved
@lostheli

lostheli commented Dec 2, 2020

Copy link
Copy Markdown
Author

If you call fs.CountError then rclone will return a non zero error code, even if the error didn't get bubbled up.

Calling fs.Errorf shows the error to the user.

Generally the convention is in rclone is to either return the error, *or call fs.Errorf and fs.CountError. If you do both then you run the risk of double logging of errors.

So that is the reason for the convention and why I suggested that we remove the logging there since the error is returned and make sure we make sure it is done in the caller.

I was looking without luck for commands that do error logging in the command with the operation result - for example the existing version of hashsum only handles errors with inputs. Eventually I realized there is some general error handling in cmd.Run for returned errors. Is that the right path to go down then? Wrap and return the errors then cmd.Run will take care of the logging? How does that play out timing wise? If I am running a 12hr job, I may want to see when it starts having issues instead of waiting for the end.

Hmm, make commanddocs should work. It might be that you have to run make first. Changes to docs/content/commands/* will get overwritten, alas.

I'll take another look at make commanddocs to see if I can determine why it was not working. I did try running make and make rclone. Maybe I didn't get the order right. Once working, I can move the documentation into the function.

I don't think this is easily fixable. the hashsum etc write to stdout whereas progress writes to stderr. If users want to use hashsum with progress then they should redirect stdout to a file.

What you propose would work for my use case and likely others. Unfortunately it doesn't seem to work that way on my system; progress appears to be on stdout not stderr. Is there a flag or setting to get it on stderr? If so, we can suggest this to users in the documentation.

Hmm we need to fix that! This line

tr := accounting.Stats(ctx).NewTransfer(o)

and this one

in = tr.Account(ctx, in).WithBuffer()

Should be making sure we are limiting the transfer rates. You know the parameter to --bwlimit is in kBytes/s or MByte/s?

Looked into this one further. Running it locally, the bwlimit has an impact. Since I wasn't using progress, I was just looking at total process usage - it's possible the difference was all overhead. Where is bwlimit applied? Is it final file io or incoming packets or somewhere in between?

@lostheli

lostheli commented Dec 4, 2020

Copy link
Copy Markdown
Author

Hmm, make commanddocs should work. It might be that you have to run make first. Changes to docs/content/commands/* will get overwritten, alas.

I'll take another look at make commanddocs to see if I can determine why it was not working. I did try running make and make rclone. Maybe I didn't get the order right. Once working, I can move the documentation into the function.

I solved this mystery. make commanddocs runs 'rclone gendocs docs/content/'. For me, that's a call to the stable install in /usr/bin/rclone not a call to the development version it just built. Calling gendocs manually on the new build has the expected result. Automatically generating the documents will reflect in the next version.

Other questions remain.

@ncw

ncw commented Dec 9, 2020

Copy link
Copy Markdown
Member

If you call fs.CountError then rclone will return a non zero error code, even if the error didn't get bubbled up.
Calling fs.Errorf shows the error to the user.
Generally the convention is in rclone is to either return the error, *or call fs.Errorf and fs.CountError. If you do both then you run the risk of double logging of errors.
So that is the reason for the convention and why I suggested that we remove the logging there since the error is returned and make sure we make sure it is done in the caller.

I was looking without luck for commands that do error logging in the command with the operation result - for example the existing version of hashsum only handles errors with inputs. Eventually I realized there is some general error handling in cmd.Run for returned errors. Is that the right path to go down then? Wrap and return the errors then cmd.Run will take care of the logging? How does that play out timing wise? If I am running a 12hr job, I may want to see when it starts having issues instead of waiting for the end.

I think the place to do the fs.Errorf and the fs.CountError is in HashLister if we want that. Note that errors from HashLister currently aren't returned to the parent, however the hashlist line will have an ERROR in it which is an indication to the user that things have gone wrong.

I don't think this is easily fixable. the hashsum etc write to stdout whereas progress writes to stderr. If users want to use hashsum with progress then they should redirect stdout to a file.

What you propose would work for my use case and likely others. Unfortunately it doesn't seem to work that way on my system; progress appears to be on stdout not stderr. Is there a flag or setting to get it on stderr? If so, we can suggest this to users in the documentation.

Ah, I was wrong about that :-(

To get uncorrupted output it would be necessary to print each line with this function - that is how rclone gets logging and progress to play nice.

func printProgress(logMessage string) {

I don't know whether it is worth doing this though, but it is possible with a bit of indirection!

Looked into this one further. Running it locally, the bwlimit has an impact. Since I wasn't using progress, I was just looking at total process usage - it's possible the difference was all overhead. Where is bwlimit applied? Is it final file io or incoming packets or somewhere in between?

bwlimit is applied in the core so when reading stuff from input and writing it to output. There can often be buffering in the input and output which makes it not 100% accurate

I solved this mystery. make commanddocs runs 'rclone gendocs docs/content/'. For me, that's a call to the stable install in /usr/bin/rclone not a call to the development version it just built. Calling gendocs manually on the new build has the expected result. Automatically generating the documents will reflect in the next version.

Great

Normally people put ~/go/src/bin on the PATH so you can run go install and the binary just works.

@lostheli
lostheli force-pushed the download_hash branch 2 times, most recently from df459bf to 7342a91 Compare December 13, 2020 14:47
@lostheli

Copy link
Copy Markdown
Author

New commit with changes to the error handling and output. First try failed code quality for unnecessary use of else; hopefully second attempt will pass all tests!

I think the place to do the fs.Errorf and the fs.CountError is in HashLister if we want that. Note that errors from HashLister currently aren't returned to the parent, however the hashlist line will have an ERROR in it which is an indication to the user that things have gone wrong.

Changed the error approach to wrap the errors in hashSum and then use fs.CountError and fs.Errorf in HashLister. I believe it's important to have some errors as we go along in case the user has redirected stdout.

Note, I put CountError and Errorf in the anonymous function defined in HashLister not in the HashLister body itself (i.e. in the function that's run when walk's go routines call entities.ForObject). Not sure if that was your intent. Functionally, it doesn't seem to change much from doing it in hashSum, so I'm unsure if this avoids the double counting that raised concerns. As you said, the anonymous function does not return the error any further, so it would require significant changes handle errors elsewhere. The other goal in returning errors to the anonymous function appears to be avoiding the base64 encoding for the fake hashes 'ERROR' and 'UNSUPPORTED'. Can you confirm if my changes are what you had in mind?

Ah, I was wrong about that :-(

To get uncorrupted output it would be necessary to print each line with this function - that is how rclone gets logging and progress to play nice.

func printProgress(logMessage string) {

I don't know whether it is worth doing this though, but it is possible with a bit of indirection!

I have made several changes to address the progress issue. I changed syncFprintf to use a new wrapper function on fmt.Printf when printing to the terminal, made that function global, and then overrode that function from cmd.startProgress when the progress flag is used. The override uses printProgress as suggested in place of fmt.Printf. This is similar to how the override for the logging function is implemented. It enables hash output to terminal and the progress lines to play nicely together. While doing this I noticed that syncFprintf is well F print, and we hand a 'file' from the command to control the output location. That file was always os.Stdout. I have implemented an output-file flag for all of the hash commands to enable the user to optionally send the hashes to a text file. This enables saving the hashes to a file without redirecting stdout and thus can be used with progress. Users should see the progress information along with any actual logging (e.g. errors, no config file, etc.) in the terminal.

…o download and hash files locally

This commit modifies the operations.hashSum function by adding an alternate code path. This code path is triggered by passing downloadFlag = True. When activated, rclone will download files from the remote and hash them locally. downloadFlag = False preserves the existing behavior of using the remote to retrieve the hash.

This commit modifies HashLister to support the new hashSum method as well as consolidating the roles of HashLister, HashListerBase64, Md5sum, and Sha1sum.  The printing of hashes from the function defined in HashLister has been revised to work with --progress.  There are light changes to operations.syncFprintf and cmd.startProgress for this.

The unit test operations_test.TestHashSums is modified to support this change and test the download functionality.

The command functions hashsum, md5sum, sha1sum, and dbhashsum are modified to support this change.  A download flag has been added and an output-file flag has been added.  The output-file flag writes hashes to a file instead of stdout to avoid the need to redirect stdout.
@lostheli

Copy link
Copy Markdown
Author

golint is very particular about how comments are written on global variables and functions! The comments were slightly re-written to make it happy.

There is now a new test failure... build/mac says 'Error: No available tap local/openssl' and said it in the 'install libraries' section. That almost sounds like an issue with how the test server is setup to manage capacity rather than an issue with this code. Is there any way to simply force it to rerun the test on the same code?

@lostheli
lostheli requested a review from ncw December 18, 2020 15:24
@ncw

ncw commented Dec 27, 2020

Copy link
Copy Markdown
Member

golint is very particular about how comments are written on global variables and functions! The comments were slightly re-written to make it happy.

I think this is looking great now - thank you.

I shall merge it now :-)

There is now a new test failure... build/mac says 'Error: No available tap local/openssl' and said it in the 'install libraries' section. That almost sounds like an issue with how the test server is setup to manage capacity rather than an issue with this code. Is there any way to simply force it to rerun the test on the same code?

I've fixed the master build now - the macOS builder broke. Once this is rebased on master after the merge it should be all good!

@ncw
ncw merged commit c8cfa43 into rclone:master Dec 27, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants