blockmap.go 6.0 KB

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