blockqueue.go 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. // Copyright (C) 2014 The Syncthing Authors.
  2. //
  3. // This Source Code Form is subject to the terms of the Mozilla Public
  4. // License, v. 2.0. If a copy of the MPL was not distributed with this file,
  5. // You can obtain one at http://mozilla.org/MPL/2.0/.
  6. package scanner
  7. import (
  8. "os"
  9. "path/filepath"
  10. "github.com/syncthing/syncthing/lib/protocol"
  11. "github.com/syncthing/syncthing/lib/sync"
  12. )
  13. // The parallell hasher reads FileInfo structures from the inbox, hashes the
  14. // file to populate the Blocks element and sends it to the outbox. A number of
  15. // workers are used in parallel. The outbox will become closed when the inbox
  16. // is closed and all items handled.
  17. func newParallelHasher(dir string, blockSize, workers int, outbox, inbox chan protocol.FileInfo, counter *int64, done chan struct{}) {
  18. wg := sync.NewWaitGroup()
  19. wg.Add(workers)
  20. for i := 0; i < workers; i++ {
  21. go func() {
  22. hashFiles(dir, blockSize, outbox, inbox, counter)
  23. wg.Done()
  24. }()
  25. }
  26. go func() {
  27. wg.Wait()
  28. if done != nil {
  29. close(done)
  30. }
  31. close(outbox)
  32. }()
  33. }
  34. func HashFile(path string, blockSize int, sizeHint int64, counter *int64) ([]protocol.BlockInfo, error) {
  35. fd, err := os.Open(path)
  36. if err != nil {
  37. l.Debugln("open:", err)
  38. return []protocol.BlockInfo{}, err
  39. }
  40. defer fd.Close()
  41. if sizeHint == 0 {
  42. fi, err := fd.Stat()
  43. if err != nil {
  44. l.Debugln("stat:", err)
  45. return []protocol.BlockInfo{}, err
  46. }
  47. sizeHint = fi.Size()
  48. }
  49. return Blocks(fd, blockSize, sizeHint, counter)
  50. }
  51. func hashFiles(dir string, blockSize int, outbox, inbox chan protocol.FileInfo, counter *int64) {
  52. for f := range inbox {
  53. if f.IsDirectory() || f.IsDeleted() {
  54. panic("Bug. Asked to hash a directory or a deleted file.")
  55. }
  56. blocks, err := HashFile(filepath.Join(dir, f.Name), blockSize, f.CachedSize, counter)
  57. if err != nil {
  58. l.Debugln("hash error:", f.Name, err)
  59. continue
  60. }
  61. f.Blocks = blocks
  62. outbox <- f
  63. }
  64. }