blockqueue.go 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. // Copyright (C) 2014 Jakob Borg and Contributors (see the CONTRIBUTORS file).
  2. // All rights reserved. Use of this source code is governed by an MIT-style
  3. // license that can be found in the LICENSE file.
  4. package scanner
  5. import (
  6. "os"
  7. "path/filepath"
  8. "sync"
  9. "github.com/syncthing/syncthing/protocol"
  10. )
  11. // The parallell hasher reads FileInfo structures from the inbox, hashes the
  12. // file to populate the Blocks element and sends it to the outbox. A number of
  13. // workers are used in parallel. The outbox will become closed when the inbox
  14. // is closed and all items handled.
  15. func newParallelHasher(dir string, blockSize, workers int, outbox, inbox chan protocol.FileInfo) {
  16. var wg sync.WaitGroup
  17. wg.Add(workers)
  18. for i := 0; i < workers; i++ {
  19. go func() {
  20. hashFile(dir, blockSize, outbox, inbox)
  21. wg.Done()
  22. }()
  23. }
  24. go func() {
  25. wg.Wait()
  26. close(outbox)
  27. }()
  28. }
  29. func hashFile(dir string, blockSize int, outbox, inbox chan protocol.FileInfo) {
  30. for f := range inbox {
  31. if protocol.IsDirectory(f.Flags) || protocol.IsDeleted(f.Flags) {
  32. outbox <- f
  33. continue
  34. }
  35. fd, err := os.Open(filepath.Join(dir, f.Name))
  36. if err != nil {
  37. if debug {
  38. l.Debugln("open:", err)
  39. }
  40. continue
  41. }
  42. fi, err := fd.Stat()
  43. if err != nil {
  44. fd.Close()
  45. if debug {
  46. l.Debugln("stat:", err)
  47. }
  48. continue
  49. }
  50. blocks, err := Blocks(fd, blockSize, fi.Size())
  51. fd.Close()
  52. if err != nil {
  53. if debug {
  54. l.Debugln("hash error:", f.Name, err)
  55. }
  56. continue
  57. }
  58. f.Blocks = blocks
  59. outbox <- f
  60. }
  61. }