blockmap.go 5.6 KB

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