blockmap.go 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201
  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 files provides a set type to track local/remote files with newness
  16. // checks. We must do a certain amount of normalization in here. We will get
  17. // fed paths with either native or wire-format separators and encodings
  18. // depending on who calls us. We transform paths to wire-format (NFC and
  19. // slashes) on the way to the database, and transform to native format
  20. // (varying separator and encoding) on the way back out.
  21. package files
  22. import (
  23. "bytes"
  24. "encoding/binary"
  25. "sort"
  26. "sync"
  27. "github.com/syncthing/syncthing/internal/config"
  28. "github.com/syncthing/syncthing/internal/protocol"
  29. "github.com/syndtr/goleveldb/leveldb"
  30. "github.com/syndtr/goleveldb/leveldb/util"
  31. )
  32. var blockFinder *BlockFinder
  33. type BlockMap struct {
  34. db *leveldb.DB
  35. folder string
  36. }
  37. func NewBlockMap(db *leveldb.DB, folder string) *BlockMap {
  38. return &BlockMap{
  39. db: db,
  40. folder: folder,
  41. }
  42. }
  43. // Add files to the block map, ignoring any deleted or invalid files.
  44. func (m *BlockMap) Add(files []protocol.FileInfo) error {
  45. batch := new(leveldb.Batch)
  46. buf := make([]byte, 4)
  47. for _, file := range files {
  48. if file.IsDirectory() || file.IsDeleted() || file.IsInvalid() {
  49. continue
  50. }
  51. for i, block := range file.Blocks {
  52. binary.BigEndian.PutUint32(buf, uint32(i))
  53. batch.Put(m.blockKey(block.Hash, file.Name), buf)
  54. }
  55. }
  56. return m.db.Write(batch, nil)
  57. }
  58. // Update block map state, removing any deleted or invalid files.
  59. func (m *BlockMap) Update(files []protocol.FileInfo) error {
  60. batch := new(leveldb.Batch)
  61. buf := make([]byte, 4)
  62. for _, file := range files {
  63. if file.IsDirectory() {
  64. continue
  65. }
  66. if file.IsDeleted() || file.IsInvalid() {
  67. for _, block := range file.Blocks {
  68. batch.Delete(m.blockKey(block.Hash, file.Name))
  69. }
  70. continue
  71. }
  72. for i, block := range file.Blocks {
  73. binary.BigEndian.PutUint32(buf, uint32(i))
  74. batch.Put(m.blockKey(block.Hash, file.Name), buf)
  75. }
  76. }
  77. return m.db.Write(batch, nil)
  78. }
  79. // Drop block map, removing all entries related to this block map from the db.
  80. func (m *BlockMap) Drop() error {
  81. batch := new(leveldb.Batch)
  82. iter := m.db.NewIterator(util.BytesPrefix(m.blockKey(nil, "")[:1+64]), nil)
  83. defer iter.Release()
  84. for iter.Next() {
  85. batch.Delete(iter.Key())
  86. }
  87. if iter.Error() != nil {
  88. return iter.Error()
  89. }
  90. return m.db.Write(batch, nil)
  91. }
  92. func (m *BlockMap) blockKey(hash []byte, file string) []byte {
  93. return toBlockKey(hash, m.folder, file)
  94. }
  95. type BlockFinder struct {
  96. db *leveldb.DB
  97. folders []string
  98. mut sync.RWMutex
  99. }
  100. func NewBlockFinder(db *leveldb.DB, cfg *config.ConfigWrapper) *BlockFinder {
  101. if blockFinder != nil {
  102. return blockFinder
  103. }
  104. f := &BlockFinder{
  105. db: db,
  106. }
  107. f.Changed(cfg.Raw())
  108. cfg.Subscribe(f)
  109. return f
  110. }
  111. // Implements config.Handler interface
  112. func (f *BlockFinder) Changed(cfg config.Configuration) error {
  113. folders := make([]string, len(cfg.Folders))
  114. for i, folder := range cfg.Folders {
  115. folders[i] = folder.ID
  116. }
  117. sort.Strings(folders)
  118. f.mut.Lock()
  119. f.folders = folders
  120. f.mut.Unlock()
  121. return nil
  122. }
  123. // An iterator function which iterates over all matching blocks for the given
  124. // hash. The iterator function has to return either true (if they are happy with
  125. // the block) or false to continue iterating for whatever reason.
  126. // The iterator finally returns the result, whether or not a satisfying block
  127. // was eventually found.
  128. func (f *BlockFinder) Iterate(hash []byte, iterFn func(string, string, uint32) bool) bool {
  129. f.mut.RLock()
  130. folders := f.folders
  131. f.mut.RUnlock()
  132. for _, folder := range folders {
  133. key := toBlockKey(hash, folder, "")
  134. iter := f.db.NewIterator(util.BytesPrefix(key), nil)
  135. defer iter.Release()
  136. for iter.Next() && iter.Error() == nil {
  137. folder, file := fromBlockKey(iter.Key())
  138. index := binary.BigEndian.Uint32(iter.Value())
  139. if iterFn(folder, nativeFilename(file), index) {
  140. return true
  141. }
  142. }
  143. }
  144. return false
  145. }
  146. // m.blockKey returns a byte slice encoding the following information:
  147. // keyTypeBlock (1 byte)
  148. // folder (64 bytes)
  149. // block hash (64 bytes)
  150. // file name (variable size)
  151. func toBlockKey(hash []byte, folder, file string) []byte {
  152. o := make([]byte, 1+64+64+len(file))
  153. o[0] = keyTypeBlock
  154. copy(o[1:], []byte(folder))
  155. copy(o[1+64:], []byte(hash))
  156. copy(o[1+64+64:], []byte(file))
  157. return o
  158. }
  159. func fromBlockKey(data []byte) (string, string) {
  160. if len(data) < 1+64+64+1 {
  161. panic("Incorrect key length")
  162. }
  163. if data[0] != keyTypeBlock {
  164. panic("Incorrect key type")
  165. }
  166. file := string(data[1+64+64:])
  167. slice := data[1 : 1+64]
  168. izero := bytes.IndexByte(slice, 0)
  169. if izero > -1 {
  170. return string(slice[:izero]), file
  171. }
  172. return string(slice), file
  173. }