blockmap.go 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205
  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 https://mozilla.org/MPL/2.0/.
  6. package db
  7. import (
  8. "encoding/binary"
  9. "fmt"
  10. "github.com/syncthing/syncthing/lib/osutil"
  11. "github.com/syncthing/syncthing/lib/protocol"
  12. "github.com/syndtr/goleveldb/leveldb"
  13. "github.com/syndtr/goleveldb/leveldb/util"
  14. )
  15. var blockFinder *BlockFinder
  16. const maxBatchSize = 1000
  17. type BlockMap struct {
  18. db *Lowlevel
  19. folder uint32
  20. }
  21. func NewBlockMap(db *Lowlevel, folder string) *BlockMap {
  22. return &BlockMap{
  23. db: db,
  24. folder: db.folderIdx.ID([]byte(folder)),
  25. }
  26. }
  27. // Add files to the block map, ignoring any deleted or invalid files.
  28. func (m *BlockMap) Add(files []protocol.FileInfo) error {
  29. batch := new(leveldb.Batch)
  30. buf := make([]byte, 4)
  31. var key []byte
  32. for _, file := range files {
  33. m.checkFlush(batch)
  34. if file.IsDirectory() || file.IsDeleted() || file.IsInvalid() {
  35. continue
  36. }
  37. for i, block := range file.Blocks {
  38. binary.BigEndian.PutUint32(buf, uint32(i))
  39. key = m.blockKeyInto(key, block.Hash, file.Name)
  40. batch.Put(key, buf)
  41. }
  42. }
  43. return m.db.Write(batch, nil)
  44. }
  45. // Update block map state, removing any deleted or invalid files.
  46. func (m *BlockMap) Update(files []protocol.FileInfo) error {
  47. batch := new(leveldb.Batch)
  48. buf := make([]byte, 4)
  49. var key []byte
  50. for _, file := range files {
  51. m.checkFlush(batch)
  52. switch {
  53. case file.IsDirectory():
  54. case file.IsDeleted() || file.IsInvalid():
  55. for _, block := range file.Blocks {
  56. key = m.blockKeyInto(key, block.Hash, file.Name)
  57. batch.Delete(key)
  58. }
  59. default:
  60. for i, block := range file.Blocks {
  61. binary.BigEndian.PutUint32(buf, uint32(i))
  62. key = m.blockKeyInto(key, block.Hash, file.Name)
  63. batch.Put(key, buf)
  64. }
  65. }
  66. }
  67. return m.db.Write(batch, nil)
  68. }
  69. // Discard block map state, removing the given files
  70. func (m *BlockMap) Discard(files []protocol.FileInfo) error {
  71. batch := new(leveldb.Batch)
  72. var key []byte
  73. for _, file := range files {
  74. m.checkFlush(batch)
  75. m.discard(file, key, batch)
  76. }
  77. return m.db.Write(batch, nil)
  78. }
  79. func (m *BlockMap) discard(file protocol.FileInfo, key []byte, batch *leveldb.Batch) {
  80. for _, block := range file.Blocks {
  81. key = m.blockKeyInto(key, block.Hash, file.Name)
  82. batch.Delete(key)
  83. }
  84. }
  85. func (m *BlockMap) checkFlush(batch *leveldb.Batch) error {
  86. if batch.Len() > maxBatchSize {
  87. if err := m.db.Write(batch, nil); err != nil {
  88. return err
  89. }
  90. batch.Reset()
  91. }
  92. return nil
  93. }
  94. // Drop block map, removing all entries related to this block map from the db.
  95. func (m *BlockMap) Drop() error {
  96. batch := new(leveldb.Batch)
  97. iter := m.db.NewIterator(util.BytesPrefix(m.blockKeyInto(nil, nil, "")[:keyPrefixLen+keyFolderLen]), nil)
  98. defer iter.Release()
  99. for iter.Next() {
  100. m.checkFlush(batch)
  101. batch.Delete(iter.Key())
  102. }
  103. if iter.Error() != nil {
  104. return iter.Error()
  105. }
  106. return m.db.Write(batch, nil)
  107. }
  108. func (m *BlockMap) blockKeyInto(o, hash []byte, file string) []byte {
  109. return blockKeyInto(o, hash, m.folder, file)
  110. }
  111. type BlockFinder struct {
  112. db *Lowlevel
  113. }
  114. func NewBlockFinder(db *Lowlevel) *BlockFinder {
  115. if blockFinder != nil {
  116. return blockFinder
  117. }
  118. f := &BlockFinder{
  119. db: db,
  120. }
  121. return f
  122. }
  123. func (f *BlockFinder) String() string {
  124. return fmt.Sprintf("BlockFinder@%p", f)
  125. }
  126. // Iterate takes an iterator function which iterates over all matching blocks
  127. // for the given hash. The iterator function has to return either true (if
  128. // they are happy with the block) or false to continue iterating for whatever
  129. // reason. The iterator finally returns the result, whether or not a
  130. // satisfying block was eventually found.
  131. func (f *BlockFinder) Iterate(folders []string, hash []byte, iterFn func(string, string, int32) bool) bool {
  132. var key []byte
  133. for _, folder := range folders {
  134. folderID := f.db.folderIdx.ID([]byte(folder))
  135. key = blockKeyInto(key, hash, folderID, "")
  136. iter := f.db.NewIterator(util.BytesPrefix(key), nil)
  137. defer iter.Release()
  138. for iter.Next() && iter.Error() == nil {
  139. file := blockKeyName(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. // m.blockKey returns a byte slice encoding the following information:
  149. // keyTypeBlock (1 byte)
  150. // folder (4 bytes)
  151. // block hash (32 bytes)
  152. // file name (variable size)
  153. func blockKeyInto(o, hash []byte, folder uint32, file string) []byte {
  154. reqLen := keyPrefixLen + keyFolderLen + keyHashLen + len(file)
  155. if cap(o) < reqLen {
  156. o = make([]byte, reqLen)
  157. } else {
  158. o = o[:reqLen]
  159. }
  160. o[0] = KeyTypeBlock
  161. binary.BigEndian.PutUint32(o[keyPrefixLen:], folder)
  162. copy(o[keyPrefixLen+keyFolderLen:], hash)
  163. copy(o[keyPrefixLen+keyFolderLen+keyHashLen:], []byte(file))
  164. return o
  165. }
  166. // blockKeyName returns the file name from the block key
  167. func blockKeyName(data []byte) string {
  168. if len(data) < keyPrefixLen+keyFolderLen+keyHashLen+1 {
  169. panic("Incorrect key length")
  170. }
  171. if data[0] != KeyTypeBlock {
  172. panic("Incorrect key type")
  173. }
  174. file := string(data[keyPrefixLen+keyFolderLen+keyHashLen:])
  175. return file
  176. }