blockmap.go 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225
  1. // Copyright (C) 2014 The Syncthing Authors.
  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/osutil"
  29. "github.com/syncthing/syncthing/internal/protocol"
  30. "github.com/syndtr/goleveldb/leveldb"
  31. "github.com/syndtr/goleveldb/leveldb/util"
  32. )
  33. var blockFinder *BlockFinder
  34. type BlockMap struct {
  35. db *leveldb.DB
  36. folder string
  37. }
  38. func NewBlockMap(db *leveldb.DB, folder string) *BlockMap {
  39. return &BlockMap{
  40. db: db,
  41. folder: folder,
  42. }
  43. }
  44. // Add files to the block map, ignoring any deleted or invalid files.
  45. func (m *BlockMap) Add(files []protocol.FileInfo) error {
  46. batch := new(leveldb.Batch)
  47. buf := make([]byte, 4)
  48. for _, file := range files {
  49. if file.IsDirectory() || file.IsDeleted() || file.IsInvalid() {
  50. continue
  51. }
  52. for i, block := range file.Blocks {
  53. binary.BigEndian.PutUint32(buf, uint32(i))
  54. batch.Put(m.blockKey(block.Hash, file.Name), buf)
  55. }
  56. }
  57. return m.db.Write(batch, nil)
  58. }
  59. // Update block map state, removing any deleted or invalid files.
  60. func (m *BlockMap) Update(files []protocol.FileInfo) error {
  61. batch := new(leveldb.Batch)
  62. buf := make([]byte, 4)
  63. for _, file := range files {
  64. if file.IsDirectory() {
  65. continue
  66. }
  67. if file.IsDeleted() || file.IsInvalid() {
  68. for _, block := range file.Blocks {
  69. batch.Delete(m.blockKey(block.Hash, file.Name))
  70. }
  71. continue
  72. }
  73. for i, block := range file.Blocks {
  74. binary.BigEndian.PutUint32(buf, uint32(i))
  75. batch.Put(m.blockKey(block.Hash, file.Name), buf)
  76. }
  77. }
  78. return m.db.Write(batch, nil)
  79. }
  80. // Discard block map state, removing the given files
  81. func (m *BlockMap) Discard(files []protocol.FileInfo) error {
  82. batch := new(leveldb.Batch)
  83. for _, file := range files {
  84. for _, block := range file.Blocks {
  85. batch.Delete(m.blockKey(block.Hash, file.Name))
  86. }
  87. }
  88. return m.db.Write(batch, nil)
  89. }
  90. // Drop block map, removing all entries related to this block map from the db.
  91. func (m *BlockMap) Drop() error {
  92. batch := new(leveldb.Batch)
  93. iter := m.db.NewIterator(util.BytesPrefix(m.blockKey(nil, "")[:1+64]), nil)
  94. defer iter.Release()
  95. for iter.Next() {
  96. batch.Delete(iter.Key())
  97. }
  98. if iter.Error() != nil {
  99. return iter.Error()
  100. }
  101. return m.db.Write(batch, nil)
  102. }
  103. func (m *BlockMap) blockKey(hash []byte, file string) []byte {
  104. return toBlockKey(hash, m.folder, file)
  105. }
  106. type BlockFinder struct {
  107. db *leveldb.DB
  108. folders []string
  109. mut sync.RWMutex
  110. }
  111. func NewBlockFinder(db *leveldb.DB, cfg *config.ConfigWrapper) *BlockFinder {
  112. if blockFinder != nil {
  113. return blockFinder
  114. }
  115. f := &BlockFinder{
  116. db: db,
  117. }
  118. f.Changed(cfg.Raw())
  119. cfg.Subscribe(f)
  120. return f
  121. }
  122. // Implements config.Handler interface
  123. func (f *BlockFinder) Changed(cfg config.Configuration) error {
  124. folders := make([]string, len(cfg.Folders))
  125. for i, folder := range cfg.Folders {
  126. folders[i] = folder.ID
  127. }
  128. sort.Strings(folders)
  129. f.mut.Lock()
  130. f.folders = folders
  131. f.mut.Unlock()
  132. return nil
  133. }
  134. // An iterator function which iterates over all matching blocks for the given
  135. // hash. The iterator function has to return either true (if they are happy with
  136. // the block) or false to continue iterating for whatever reason.
  137. // The iterator finally returns the result, whether or not a satisfying block
  138. // was eventually found.
  139. func (f *BlockFinder) Iterate(hash []byte, iterFn func(string, string, uint32) 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 := binary.BigEndian.Uint32(iter.Value())
  150. if iterFn(folder, osutil.NativeFilename(file), index) {
  151. return true
  152. }
  153. }
  154. }
  155. return false
  156. }
  157. // A method for repairing incorrect blockmap entries, removes the old entry
  158. // and replaces it with a new entry for the given block
  159. func (f *BlockFinder) Fix(folder, file string, index uint32, 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. }