blockqueue.go 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  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/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. if debug {
  38. l.Debugln("open:", err)
  39. }
  40. return []protocol.BlockInfo{}, err
  41. }
  42. defer fd.Close()
  43. if sizeHint == 0 {
  44. fi, err := fd.Stat()
  45. if err != nil {
  46. if debug {
  47. l.Debugln("stat:", err)
  48. }
  49. return []protocol.BlockInfo{}, err
  50. }
  51. sizeHint = fi.Size()
  52. }
  53. return Blocks(fd, blockSize, sizeHint, counter)
  54. }
  55. func hashFiles(dir string, blockSize int, outbox, inbox chan protocol.FileInfo, counter *int64) {
  56. for f := range inbox {
  57. if f.IsDirectory() || f.IsDeleted() {
  58. panic("Bug. Asked to hash a directory or a deleted file.")
  59. }
  60. blocks, err := HashFile(filepath.Join(dir, f.Name), blockSize, f.CachedSize, counter)
  61. if err != nil {
  62. if debug {
  63. l.Debugln("hash error:", f.Name, err)
  64. }
  65. continue
  66. }
  67. f.Blocks = blocks
  68. outbox <- f
  69. }
  70. }