blockqueue.go 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  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 Counter, done, cancel 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, cancel)
  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 Counter) ([]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 Counter, cancel chan struct{}) {
  52. for {
  53. select {
  54. case f, ok := <-inbox:
  55. if !ok {
  56. return
  57. }
  58. if f.IsDirectory() || f.IsDeleted() {
  59. panic("Bug. Asked to hash a directory or a deleted file.")
  60. }
  61. blocks, err := HashFile(filepath.Join(dir, f.Name), blockSize, f.CachedSize, counter)
  62. if err != nil {
  63. l.Debugln("hash error:", f.Name, err)
  64. continue
  65. }
  66. f.Blocks = blocks
  67. select {
  68. case outbox <- f:
  69. case <-cancel:
  70. return
  71. }
  72. case <-cancel:
  73. return
  74. }
  75. }
  76. }