blockqueue.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. // Copyright (C) 2014 Jakob Borg and Contributors (see the CONTRIBUTORS file).
  2. //
  3. // This program is free software: you can redistribute it and/or modify it
  4. // under the terms of the GNU General Public License as published by the Free
  5. // Software Foundation, either version 3 of the License, or (at your option)
  6. // any later version.
  7. //
  8. // This program is distributed in the hope that it will be useful, but WITHOUT
  9. // ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  10. // FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
  11. // more details.
  12. //
  13. // You should have received a copy of the GNU General Public License along
  14. // with this program. If not, see <http://www.gnu.org/licenses/>.
  15. package scanner
  16. import (
  17. "os"
  18. "path/filepath"
  19. "sync"
  20. "github.com/syncthing/syncthing/internal/protocol"
  21. )
  22. // The parallell hasher reads FileInfo structures from the inbox, hashes the
  23. // file to populate the Blocks element and sends it to the outbox. A number of
  24. // workers are used in parallel. The outbox will become closed when the inbox
  25. // is closed and all items handled.
  26. func newParallelHasher(dir string, blockSize, workers int, outbox, inbox chan protocol.FileInfo) {
  27. var wg sync.WaitGroup
  28. wg.Add(workers)
  29. for i := 0; i < workers; i++ {
  30. go func() {
  31. hashFiles(dir, blockSize, outbox, inbox)
  32. wg.Done()
  33. }()
  34. }
  35. go func() {
  36. wg.Wait()
  37. close(outbox)
  38. }()
  39. }
  40. func HashFile(path string, blockSize int) ([]protocol.BlockInfo, error) {
  41. fd, err := os.Open(path)
  42. if err != nil {
  43. if debug {
  44. l.Debugln("open:", err)
  45. }
  46. return []protocol.BlockInfo{}, err
  47. }
  48. fi, err := fd.Stat()
  49. if err != nil {
  50. fd.Close()
  51. if debug {
  52. l.Debugln("stat:", err)
  53. }
  54. return []protocol.BlockInfo{}, err
  55. }
  56. defer fd.Close()
  57. return Blocks(fd, blockSize, fi.Size())
  58. }
  59. func hashFiles(dir string, blockSize int, outbox, inbox chan protocol.FileInfo) {
  60. for f := range inbox {
  61. if protocol.IsDirectory(f.Flags) || protocol.IsDeleted(f.Flags) {
  62. outbox <- f
  63. continue
  64. }
  65. blocks, err := HashFile(filepath.Join(dir, f.Name), blockSize)
  66. if err != nil {
  67. if debug {
  68. l.Debugln("hash error:", f.Name, err)
  69. }
  70. continue
  71. }
  72. f.Blocks = blocks
  73. outbox <- f
  74. }
  75. }