blockmap.go 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212
  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. // Discard block map state, removing the given files
  80. func (m *BlockMap) Discard(files []protocol.FileInfo) error {
  81. batch := new(leveldb.Batch)
  82. for _, file := range files {
  83. for _, block := range file.Blocks {
  84. batch.Delete(m.blockKey(block.Hash, file.Name))
  85. }
  86. }
  87. return m.db.Write(batch, nil)
  88. }
  89. // Drop block map, removing all entries related to this block map from the db.
  90. func (m *BlockMap) Drop() error {
  91. batch := new(leveldb.Batch)
  92. iter := m.db.NewIterator(util.BytesPrefix(m.blockKey(nil, "")[:1+64]), nil)
  93. defer iter.Release()
  94. for iter.Next() {
  95. batch.Delete(iter.Key())
  96. }
  97. if iter.Error() != nil {
  98. return iter.Error()
  99. }
  100. return m.db.Write(batch, nil)
  101. }
  102. func (m *BlockMap) blockKey(hash []byte, file string) []byte {
  103. return toBlockKey(hash, m.folder, file)
  104. }
  105. type BlockFinder struct {
  106. db *leveldb.DB
  107. folders []string
  108. mut sync.RWMutex
  109. }
  110. func NewBlockFinder(db *leveldb.DB, cfg *config.ConfigWrapper) *BlockFinder {
  111. if blockFinder != nil {
  112. return blockFinder
  113. }
  114. f := &BlockFinder{
  115. db: db,
  116. }
  117. f.Changed(cfg.Raw())
  118. cfg.Subscribe(f)
  119. return f
  120. }
  121. // Implements config.Handler interface
  122. func (f *BlockFinder) Changed(cfg config.Configuration) error {
  123. folders := make([]string, len(cfg.Folders))
  124. for i, folder := range cfg.Folders {
  125. folders[i] = folder.ID
  126. }
  127. sort.Strings(folders)
  128. f.mut.Lock()
  129. f.folders = folders
  130. f.mut.Unlock()
  131. return nil
  132. }
  133. // An iterator function which iterates over all matching blocks for the given
  134. // hash. The iterator function has to return either true (if they are happy with
  135. // the block) or false to continue iterating for whatever reason.
  136. // The iterator finally returns the result, whether or not a satisfying block
  137. // was eventually found.
  138. func (f *BlockFinder) Iterate(hash []byte, iterFn func(string, string, uint32) bool) bool {
  139. f.mut.RLock()
  140. folders := f.folders
  141. f.mut.RUnlock()
  142. for _, folder := range folders {
  143. key := toBlockKey(hash, folder, "")
  144. iter := f.db.NewIterator(util.BytesPrefix(key), nil)
  145. defer iter.Release()
  146. for iter.Next() && iter.Error() == nil {
  147. folder, file := fromBlockKey(iter.Key())
  148. index := binary.BigEndian.Uint32(iter.Value())
  149. if iterFn(folder, nativeFilename(file), index) {
  150. return true
  151. }
  152. }
  153. }
  154. return false
  155. }
  156. // m.blockKey returns a byte slice encoding the following information:
  157. // keyTypeBlock (1 byte)
  158. // folder (64 bytes)
  159. // block hash (32 bytes)
  160. // file name (variable size)
  161. func toBlockKey(hash []byte, folder, file string) []byte {
  162. o := make([]byte, 1+64+32+len(file))
  163. o[0] = keyTypeBlock
  164. copy(o[1:], []byte(folder))
  165. copy(o[1+64:], []byte(hash))
  166. copy(o[1+64+32:], []byte(file))
  167. return o
  168. }
  169. func fromBlockKey(data []byte) (string, string) {
  170. if len(data) < 1+64+32+1 {
  171. panic("Incorrect key length")
  172. }
  173. if data[0] != keyTypeBlock {
  174. panic("Incorrect key type")
  175. }
  176. file := string(data[1+64+32:])
  177. slice := data[1 : 1+64]
  178. izero := bytes.IndexByte(slice, 0)
  179. if izero > -1 {
  180. return string(slice[:izero]), file
  181. }
  182. return string(slice), file
  183. }