blockqueue.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  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. "sync"
  11. "github.com/syncthing/protocol"
  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) {
  18. var wg sync.WaitGroup
  19. wg.Add(workers)
  20. for i := 0; i < workers; i++ {
  21. go func() {
  22. hashFiles(dir, blockSize, outbox, inbox)
  23. wg.Done()
  24. }()
  25. }
  26. go func() {
  27. wg.Wait()
  28. close(outbox)
  29. }()
  30. }
  31. func HashFile(path string, blockSize int) ([]protocol.BlockInfo, error) {
  32. fd, err := os.Open(path)
  33. if err != nil {
  34. if debug {
  35. l.Debugln("open:", err)
  36. }
  37. return []protocol.BlockInfo{}, err
  38. }
  39. fi, err := fd.Stat()
  40. if err != nil {
  41. fd.Close()
  42. if debug {
  43. l.Debugln("stat:", err)
  44. }
  45. return []protocol.BlockInfo{}, err
  46. }
  47. defer fd.Close()
  48. return Blocks(fd, blockSize, fi.Size())
  49. }
  50. func hashFiles(dir string, blockSize int, outbox, inbox chan protocol.FileInfo) {
  51. for f := range inbox {
  52. if f.IsDirectory() || f.IsDeleted() || f.IsSymlink() {
  53. outbox <- f
  54. continue
  55. }
  56. blocks, err := HashFile(filepath.Join(dir, f.Name), blockSize)
  57. if err != nil {
  58. if debug {
  59. l.Debugln("hash error:", f.Name, err)
  60. }
  61. continue
  62. }
  63. f.Blocks = blocks
  64. outbox <- f
  65. }
  66. }