Repository navigation
operations: Add a download flag to hashsum and related commands to force rclone to download and hash files locally - #4803
Conversation
|
Fixes #3923 |
|
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. |
|
Re build issue: and commit the result. It will change some indenting or sort imports by name or smth like that.
|
ncw
left a comment
There was a problem hiding this comment.
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
|
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,
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? |
Pending that I haven't answered?
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).
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 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!) |
Yes, though that's my fault. I did not click the overall response submit and my in-line comments were stuck in edit mode.
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?
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.
I'm coming at this from the opposite side! I want a semaphore, so I search and see what they called semaphores in Go. :) |
|
The |
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? |
Ivan |
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).
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:
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.
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.
Of course Thank you for your patience! |
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 After (only after) that we can return to BLM. |
46767c2 to
0f96592
Compare
|
Rebased on master. Please save your changes and pull to your workdir. |
|
@lostheli |
0f96592 to
6be9618
Compare
lostheli
left a comment
There was a problem hiding this comment.
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.
ncw
left a comment
There was a problem hiding this comment.
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?
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'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.
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.
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? |
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. |
I think the place to do the
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. Line 73 in 50cf97f I don't know whether it is worth doing this though, but it is possible with a bit of indirection!
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
Great Normally people put |
df459bf to
7342a91
Compare
|
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!
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?
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.
7342a91 to
4283224
Compare
|
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? |
I think this is looking great now - thank you. I shall merge it now :-)
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! |
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
This pull request requires functionality and project best practices review before finalization.