set.go 10.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321
  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 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. "os"
  15. "time"
  16. "github.com/syncthing/syncthing/lib/fs"
  17. "github.com/syncthing/syncthing/lib/osutil"
  18. "github.com/syncthing/syncthing/lib/protocol"
  19. "github.com/syncthing/syncthing/lib/sync"
  20. )
  21. type FileSet struct {
  22. folder string
  23. fs fs.Filesystem
  24. db *Instance
  25. blockmap *BlockMap
  26. meta *metadataTracker
  27. updateMutex sync.Mutex // protects database updates and the corresponding metadata changes
  28. }
  29. // FileIntf is the set of methods implemented by both protocol.FileInfo and
  30. // FileInfoTruncated.
  31. type FileIntf interface {
  32. FileSize() int64
  33. FileName() string
  34. IsDeleted() bool
  35. IsInvalid() bool
  36. IsDirectory() bool
  37. IsSymlink() bool
  38. HasPermissionBits() bool
  39. SequenceNo() int64
  40. BlockSize() int
  41. FileVersion() protocol.Vector
  42. }
  43. // The Iterator is called with either a protocol.FileInfo or a
  44. // FileInfoTruncated (depending on the method) and returns true to
  45. // continue iteration, false to stop.
  46. type Iterator func(f FileIntf) bool
  47. var databaseRecheckInterval = 30 * 24 * time.Hour
  48. func init() {
  49. if dur, err := time.ParseDuration(os.Getenv("STRECHECKDBEVERY")); err == nil {
  50. databaseRecheckInterval = dur
  51. }
  52. }
  53. func NewFileSet(folder string, fs fs.Filesystem, db *Instance) *FileSet {
  54. var s = FileSet{
  55. folder: folder,
  56. fs: fs,
  57. db: db,
  58. blockmap: NewBlockMap(db, db.folderIdx.ID([]byte(folder))),
  59. meta: newMetadataTracker(),
  60. updateMutex: sync.NewMutex(),
  61. }
  62. if err := s.meta.fromDB(db, []byte(folder)); err != nil {
  63. l.Infof("No stored folder metadata for %q: recalculating", folder)
  64. s.recalcCounts()
  65. } else if age := time.Since(s.meta.Created()); age > databaseRecheckInterval {
  66. l.Infof("Stored folder metadata for %q is %v old; recalculating", folder, age)
  67. s.recalcCounts()
  68. }
  69. return &s
  70. }
  71. func (s *FileSet) recalcCounts() {
  72. s.meta = newMetadataTracker()
  73. s.db.checkGlobals([]byte(s.folder), s.meta)
  74. var deviceID protocol.DeviceID
  75. s.db.withAllFolderTruncated([]byte(s.folder), func(device []byte, f FileInfoTruncated) bool {
  76. copy(deviceID[:], device)
  77. s.meta.addFile(deviceID, f)
  78. return true
  79. })
  80. s.meta.SetCreated()
  81. s.meta.toDB(s.db, []byte(s.folder))
  82. }
  83. func (s *FileSet) Drop(device protocol.DeviceID) {
  84. l.Debugf("%s Drop(%v)", s.folder, device)
  85. s.updateMutex.Lock()
  86. defer s.updateMutex.Unlock()
  87. s.db.dropDeviceFolder(device[:], []byte(s.folder), s.meta)
  88. if device == protocol.LocalDeviceID {
  89. s.blockmap.Drop()
  90. s.meta.resetCounts(device)
  91. // We deliberately do not reset the sequence number here. Dropping
  92. // all files for the local device ID only happens in testing - which
  93. // expects the sequence to be retained, like an old Replace() of all
  94. // files would do. However, if we ever did it "in production" we
  95. // would anyway want to retain the sequence for delta indexes to be
  96. // happy.
  97. } else {
  98. // Here, on the other hand, we want to make sure that any file
  99. // announced from the remote is newer than our current sequence
  100. // number.
  101. s.meta.resetAll(device)
  102. }
  103. s.meta.toDB(s.db, []byte(s.folder))
  104. }
  105. func (s *FileSet) Update(device protocol.DeviceID, fs []protocol.FileInfo) {
  106. l.Debugf("%s Update(%v, [%d])", s.folder, device, len(fs))
  107. // do not modify fs in place, it is still used in outer scope
  108. fs = append([]protocol.FileInfo(nil), fs...)
  109. normalizeFilenames(fs)
  110. s.updateMutex.Lock()
  111. defer s.updateMutex.Unlock()
  112. if device == protocol.LocalDeviceID {
  113. discards := make([]protocol.FileInfo, 0, len(fs))
  114. updates := make([]protocol.FileInfo, 0, len(fs))
  115. // db.UpdateFiles will sort unchanged files out -> save one db lookup
  116. // filter slice according to https://github.com/golang/go/wiki/SliceTricks#filtering-without-allocating
  117. oldFs := fs
  118. fs = fs[:0]
  119. var dk []byte
  120. folder := []byte(s.folder)
  121. for _, nf := range oldFs {
  122. dk = s.db.deviceKeyInto(dk, folder, device[:], []byte(osutil.NormalizedFilename(nf.Name)))
  123. ef, ok := s.db.getFile(dk)
  124. if ok && ef.Version.Equal(nf.Version) && ef.Invalid == nf.Invalid {
  125. continue
  126. }
  127. nf.Sequence = s.meta.nextSeq(protocol.LocalDeviceID)
  128. fs = append(fs, nf)
  129. if ok {
  130. discards = append(discards, ef)
  131. }
  132. updates = append(updates, nf)
  133. }
  134. s.blockmap.Discard(discards)
  135. s.blockmap.Update(updates)
  136. s.db.removeSequences(folder, discards)
  137. s.db.addSequences(folder, updates)
  138. }
  139. s.db.updateFiles([]byte(s.folder), device[:], fs, s.meta)
  140. s.meta.toDB(s.db, []byte(s.folder))
  141. }
  142. func (s *FileSet) WithNeed(device protocol.DeviceID, fn Iterator) {
  143. l.Debugf("%s WithNeed(%v)", s.folder, device)
  144. s.db.withNeed([]byte(s.folder), device[:], false, nativeFileIterator(fn))
  145. }
  146. func (s *FileSet) WithNeedTruncated(device protocol.DeviceID, fn Iterator) {
  147. l.Debugf("%s WithNeedTruncated(%v)", s.folder, device)
  148. s.db.withNeed([]byte(s.folder), device[:], true, nativeFileIterator(fn))
  149. }
  150. func (s *FileSet) WithHave(device protocol.DeviceID, fn Iterator) {
  151. l.Debugf("%s WithHave(%v)", s.folder, device)
  152. s.db.withHave([]byte(s.folder), device[:], nil, false, nativeFileIterator(fn))
  153. }
  154. func (s *FileSet) WithHaveTruncated(device protocol.DeviceID, fn Iterator) {
  155. l.Debugf("%s WithHaveTruncated(%v)", s.folder, device)
  156. s.db.withHave([]byte(s.folder), device[:], nil, true, nativeFileIterator(fn))
  157. }
  158. func (s *FileSet) WithHaveSequence(startSeq int64, fn Iterator) {
  159. l.Debugf("%s WithHaveSequence(%v)", s.folder, startSeq)
  160. s.db.withHaveSequence([]byte(s.folder), startSeq, nativeFileIterator(fn))
  161. }
  162. // Except for an item with a path equal to prefix, only children of prefix are iterated.
  163. // E.g. for prefix "dir", "dir/file" is iterated, but "dir.file" is not.
  164. func (s *FileSet) WithPrefixedHaveTruncated(device protocol.DeviceID, prefix string, fn Iterator) {
  165. l.Debugf(`%s WithPrefixedHaveTruncated(%v, "%v")`, s.folder, device, prefix)
  166. s.db.withHave([]byte(s.folder), device[:], []byte(osutil.NormalizedFilename(prefix)), true, nativeFileIterator(fn))
  167. }
  168. func (s *FileSet) WithGlobal(fn Iterator) {
  169. l.Debugf("%s WithGlobal()", s.folder)
  170. s.db.withGlobal([]byte(s.folder), nil, false, nativeFileIterator(fn))
  171. }
  172. func (s *FileSet) WithGlobalTruncated(fn Iterator) {
  173. l.Debugf("%s WithGlobalTruncated()", s.folder)
  174. s.db.withGlobal([]byte(s.folder), nil, true, nativeFileIterator(fn))
  175. }
  176. // Except for an item with a path equal to prefix, only children of prefix are iterated.
  177. // E.g. for prefix "dir", "dir/file" is iterated, but "dir.file" is not.
  178. func (s *FileSet) WithPrefixedGlobalTruncated(prefix string, fn Iterator) {
  179. l.Debugf(`%s WithPrefixedGlobalTruncated("%v")`, s.folder, prefix)
  180. s.db.withGlobal([]byte(s.folder), []byte(osutil.NormalizedFilename(prefix)), true, nativeFileIterator(fn))
  181. }
  182. func (s *FileSet) Get(device protocol.DeviceID, file string) (protocol.FileInfo, bool) {
  183. f, ok := s.db.getFile(s.db.deviceKey([]byte(s.folder), device[:], []byte(osutil.NormalizedFilename(file))))
  184. f.Name = osutil.NativeFilename(f.Name)
  185. return f, ok
  186. }
  187. func (s *FileSet) GetGlobal(file string) (protocol.FileInfo, bool) {
  188. fi, ok := s.db.getGlobal([]byte(s.folder), []byte(osutil.NormalizedFilename(file)), false)
  189. if !ok {
  190. return protocol.FileInfo{}, false
  191. }
  192. f := fi.(protocol.FileInfo)
  193. f.Name = osutil.NativeFilename(f.Name)
  194. return f, true
  195. }
  196. func (s *FileSet) GetGlobalTruncated(file string) (FileInfoTruncated, bool) {
  197. fi, ok := s.db.getGlobal([]byte(s.folder), []byte(osutil.NormalizedFilename(file)), true)
  198. if !ok {
  199. return FileInfoTruncated{}, false
  200. }
  201. f := fi.(FileInfoTruncated)
  202. f.Name = osutil.NativeFilename(f.Name)
  203. return f, true
  204. }
  205. func (s *FileSet) Availability(file string) []protocol.DeviceID {
  206. return s.db.availability([]byte(s.folder), []byte(osutil.NormalizedFilename(file)))
  207. }
  208. func (s *FileSet) Sequence(device protocol.DeviceID) int64 {
  209. return s.meta.Counts(device).Sequence
  210. }
  211. func (s *FileSet) LocalSize() Counts {
  212. return s.meta.Counts(protocol.LocalDeviceID)
  213. }
  214. func (s *FileSet) GlobalSize() Counts {
  215. return s.meta.Counts(globalDeviceID)
  216. }
  217. func (s *FileSet) IndexID(device protocol.DeviceID) protocol.IndexID {
  218. id := s.db.getIndexID(device[:], []byte(s.folder))
  219. if id == 0 && device == protocol.LocalDeviceID {
  220. // No index ID set yet. We create one now.
  221. id = protocol.NewIndexID()
  222. s.db.setIndexID(device[:], []byte(s.folder), id)
  223. }
  224. return id
  225. }
  226. func (s *FileSet) SetIndexID(device protocol.DeviceID, id protocol.IndexID) {
  227. if device == protocol.LocalDeviceID {
  228. panic("do not explicitly set index ID for local device")
  229. }
  230. s.db.setIndexID(device[:], []byte(s.folder), id)
  231. }
  232. func (s *FileSet) MtimeFS() *fs.MtimeFS {
  233. prefix := s.db.mtimesKey([]byte(s.folder))
  234. kv := NewNamespacedKV(s.db, string(prefix))
  235. return fs.NewMtimeFS(s.fs, kv)
  236. }
  237. func (s *FileSet) ListDevices() []protocol.DeviceID {
  238. return s.meta.devices()
  239. }
  240. // DropFolder clears out all information related to the given folder from the
  241. // database.
  242. func DropFolder(db *Instance, folder string) {
  243. db.dropFolder([]byte(folder))
  244. db.dropMtimes([]byte(folder))
  245. db.dropFolderMeta([]byte(folder))
  246. bm := &BlockMap{
  247. db: db,
  248. folder: db.folderIdx.ID([]byte(folder)),
  249. }
  250. bm.Drop()
  251. }
  252. func normalizeFilenames(fs []protocol.FileInfo) {
  253. for i := range fs {
  254. fs[i].Name = osutil.NormalizedFilename(fs[i].Name)
  255. }
  256. }
  257. func nativeFileIterator(fn Iterator) Iterator {
  258. return func(fi FileIntf) bool {
  259. switch f := fi.(type) {
  260. case protocol.FileInfo:
  261. f.Name = osutil.NativeFilename(f.Name)
  262. return fn(f)
  263. case FileInfoTruncated:
  264. f.Name = osutil.NativeFilename(f.Name)
  265. return fn(f)
  266. default:
  267. panic("unknown interface type")
  268. }
  269. }
  270. }