set.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325
  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. "github.com/syndtr/goleveldb/leveldb/util"
  21. )
  22. type FileSet struct {
  23. folder string
  24. fs fs.Filesystem
  25. db *instance
  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. FileLocalFlags() uint32
  35. IsDeleted() bool
  36. IsInvalid() bool
  37. IsIgnored() bool
  38. IsUnsupported() bool
  39. MustRescan() bool
  40. IsReceiveOnlyChanged() bool
  41. IsDirectory() bool
  42. IsSymlink() bool
  43. ShouldConflict() bool
  44. HasPermissionBits() bool
  45. SequenceNo() int64
  46. BlockSize() int
  47. FileVersion() protocol.Vector
  48. FileType() protocol.FileInfoType
  49. FilePermissions() uint32
  50. FileModifiedBy() protocol.ShortID
  51. ModTime() time.Time
  52. }
  53. // The Iterator is called with either a protocol.FileInfo or a
  54. // FileInfoTruncated (depending on the method) and returns true to
  55. // continue iteration, false to stop.
  56. type Iterator func(f FileIntf) bool
  57. var databaseRecheckInterval = 30 * 24 * time.Hour
  58. func init() {
  59. if dur, err := time.ParseDuration(os.Getenv("STRECHECKDBEVERY")); err == nil {
  60. databaseRecheckInterval = dur
  61. }
  62. }
  63. func NewFileSet(folder string, fs fs.Filesystem, ll *Lowlevel) *FileSet {
  64. db := newInstance(ll)
  65. var s = FileSet{
  66. folder: folder,
  67. fs: fs,
  68. db: db,
  69. meta: newMetadataTracker(),
  70. updateMutex: sync.NewMutex(),
  71. }
  72. if err := s.meta.fromDB(db, []byte(folder)); err != nil {
  73. l.Infof("No stored folder metadata for %q: recalculating", folder)
  74. s.recalcCounts()
  75. } else if age := time.Since(s.meta.Created()); age > databaseRecheckInterval {
  76. l.Infof("Stored folder metadata for %q is %v old; recalculating", folder, age)
  77. s.recalcCounts()
  78. }
  79. return &s
  80. }
  81. func (s *FileSet) recalcCounts() {
  82. s.meta = newMetadataTracker()
  83. s.db.checkGlobals([]byte(s.folder), s.meta)
  84. var deviceID protocol.DeviceID
  85. s.db.withAllFolderTruncated([]byte(s.folder), func(device []byte, f FileInfoTruncated) bool {
  86. copy(deviceID[:], device)
  87. s.meta.addFile(deviceID, f)
  88. return true
  89. })
  90. s.meta.SetCreated()
  91. s.meta.toDB(s.db, []byte(s.folder))
  92. }
  93. func (s *FileSet) Drop(device protocol.DeviceID) {
  94. l.Debugf("%s Drop(%v)", s.folder, device)
  95. s.updateMutex.Lock()
  96. defer s.updateMutex.Unlock()
  97. s.db.dropDeviceFolder(device[:], []byte(s.folder), s.meta)
  98. if device == protocol.LocalDeviceID {
  99. s.meta.resetCounts(device)
  100. // We deliberately do not reset the sequence number here. Dropping
  101. // all files for the local device ID only happens in testing - which
  102. // expects the sequence to be retained, like an old Replace() of all
  103. // files would do. However, if we ever did it "in production" we
  104. // would anyway want to retain the sequence for delta indexes to be
  105. // happy.
  106. } else {
  107. // Here, on the other hand, we want to make sure that any file
  108. // announced from the remote is newer than our current sequence
  109. // number.
  110. s.meta.resetAll(device)
  111. }
  112. s.meta.toDB(s.db, []byte(s.folder))
  113. }
  114. func (s *FileSet) Update(device protocol.DeviceID, fs []protocol.FileInfo) {
  115. l.Debugf("%s Update(%v, [%d])", s.folder, device, len(fs))
  116. // do not modify fs in place, it is still used in outer scope
  117. fs = append([]protocol.FileInfo(nil), fs...)
  118. normalizeFilenames(fs)
  119. s.updateMutex.Lock()
  120. defer s.updateMutex.Unlock()
  121. defer s.meta.toDB(s.db, []byte(s.folder))
  122. if device == protocol.LocalDeviceID {
  123. // For the local device we have a bunch of metadata to track.
  124. s.db.updateLocalFiles([]byte(s.folder), fs, s.meta)
  125. return
  126. }
  127. // Easy case, just update the files and we're done.
  128. s.db.updateRemoteFiles([]byte(s.folder), device[:], fs, s.meta)
  129. }
  130. func (s *FileSet) WithNeed(device protocol.DeviceID, fn Iterator) {
  131. l.Debugf("%s WithNeed(%v)", s.folder, device)
  132. s.db.withNeed([]byte(s.folder), device[:], false, nativeFileIterator(fn))
  133. }
  134. func (s *FileSet) WithNeedTruncated(device protocol.DeviceID, fn Iterator) {
  135. l.Debugf("%s WithNeedTruncated(%v)", s.folder, device)
  136. s.db.withNeed([]byte(s.folder), device[:], true, nativeFileIterator(fn))
  137. }
  138. func (s *FileSet) WithHave(device protocol.DeviceID, fn Iterator) {
  139. l.Debugf("%s WithHave(%v)", s.folder, device)
  140. s.db.withHave([]byte(s.folder), device[:], nil, false, nativeFileIterator(fn))
  141. }
  142. func (s *FileSet) WithHaveTruncated(device protocol.DeviceID, fn Iterator) {
  143. l.Debugf("%s WithHaveTruncated(%v)", s.folder, device)
  144. s.db.withHave([]byte(s.folder), device[:], nil, true, nativeFileIterator(fn))
  145. }
  146. func (s *FileSet) WithHaveSequence(startSeq int64, fn Iterator) {
  147. l.Debugf("%s WithHaveSequence(%v)", s.folder, startSeq)
  148. s.db.withHaveSequence([]byte(s.folder), startSeq, nativeFileIterator(fn))
  149. }
  150. // Except for an item with a path equal to prefix, only children of prefix are iterated.
  151. // E.g. for prefix "dir", "dir/file" is iterated, but "dir.file" is not.
  152. func (s *FileSet) WithPrefixedHaveTruncated(device protocol.DeviceID, prefix string, fn Iterator) {
  153. l.Debugf(`%s WithPrefixedHaveTruncated(%v, "%v")`, s.folder, device, prefix)
  154. s.db.withHave([]byte(s.folder), device[:], []byte(osutil.NormalizedFilename(prefix)), true, nativeFileIterator(fn))
  155. }
  156. func (s *FileSet) WithGlobal(fn Iterator) {
  157. l.Debugf("%s WithGlobal()", s.folder)
  158. s.db.withGlobal([]byte(s.folder), nil, false, nativeFileIterator(fn))
  159. }
  160. func (s *FileSet) WithGlobalTruncated(fn Iterator) {
  161. l.Debugf("%s WithGlobalTruncated()", s.folder)
  162. s.db.withGlobal([]byte(s.folder), nil, true, nativeFileIterator(fn))
  163. }
  164. // Except for an item with a path equal to prefix, only children of prefix are iterated.
  165. // E.g. for prefix "dir", "dir/file" is iterated, but "dir.file" is not.
  166. func (s *FileSet) WithPrefixedGlobalTruncated(prefix string, fn Iterator) {
  167. l.Debugf(`%s WithPrefixedGlobalTruncated("%v")`, s.folder, prefix)
  168. s.db.withGlobal([]byte(s.folder), []byte(osutil.NormalizedFilename(prefix)), true, nativeFileIterator(fn))
  169. }
  170. func (s *FileSet) Get(device protocol.DeviceID, file string) (protocol.FileInfo, bool) {
  171. f, ok := s.db.getFileDirty([]byte(s.folder), device[:], []byte(osutil.NormalizedFilename(file)))
  172. f.Name = osutil.NativeFilename(f.Name)
  173. return f, ok
  174. }
  175. func (s *FileSet) GetGlobal(file string) (protocol.FileInfo, bool) {
  176. fi, ok := s.db.getGlobalDirty([]byte(s.folder), []byte(osutil.NormalizedFilename(file)), false)
  177. if !ok {
  178. return protocol.FileInfo{}, false
  179. }
  180. f := fi.(protocol.FileInfo)
  181. f.Name = osutil.NativeFilename(f.Name)
  182. return f, true
  183. }
  184. func (s *FileSet) GetGlobalTruncated(file string) (FileInfoTruncated, bool) {
  185. fi, ok := s.db.getGlobalDirty([]byte(s.folder), []byte(osutil.NormalizedFilename(file)), true)
  186. if !ok {
  187. return FileInfoTruncated{}, false
  188. }
  189. f := fi.(FileInfoTruncated)
  190. f.Name = osutil.NativeFilename(f.Name)
  191. return f, true
  192. }
  193. func (s *FileSet) Availability(file string) []protocol.DeviceID {
  194. return s.db.availability([]byte(s.folder), []byte(osutil.NormalizedFilename(file)))
  195. }
  196. func (s *FileSet) Sequence(device protocol.DeviceID) int64 {
  197. return s.meta.Sequence(device)
  198. }
  199. func (s *FileSet) LocalSize() Counts {
  200. local := s.meta.Counts(protocol.LocalDeviceID, 0)
  201. recvOnlyChanged := s.meta.Counts(protocol.LocalDeviceID, protocol.FlagLocalReceiveOnly)
  202. return local.Add(recvOnlyChanged)
  203. }
  204. func (s *FileSet) ReceiveOnlyChangedSize() Counts {
  205. return s.meta.Counts(protocol.LocalDeviceID, protocol.FlagLocalReceiveOnly)
  206. }
  207. func (s *FileSet) GlobalSize() Counts {
  208. global := s.meta.Counts(protocol.GlobalDeviceID, 0)
  209. recvOnlyChanged := s.meta.Counts(protocol.GlobalDeviceID, protocol.FlagLocalReceiveOnly)
  210. return global.Add(recvOnlyChanged)
  211. }
  212. func (s *FileSet) IndexID(device protocol.DeviceID) protocol.IndexID {
  213. id := s.db.getIndexID(device[:], []byte(s.folder))
  214. if id == 0 && device == protocol.LocalDeviceID {
  215. // No index ID set yet. We create one now.
  216. id = protocol.NewIndexID()
  217. s.db.setIndexID(device[:], []byte(s.folder), id)
  218. }
  219. return id
  220. }
  221. func (s *FileSet) SetIndexID(device protocol.DeviceID, id protocol.IndexID) {
  222. if device == protocol.LocalDeviceID {
  223. panic("do not explicitly set index ID for local device")
  224. }
  225. s.db.setIndexID(device[:], []byte(s.folder), id)
  226. }
  227. func (s *FileSet) MtimeFS() *fs.MtimeFS {
  228. prefix := s.db.keyer.GenerateMtimesKey(nil, []byte(s.folder))
  229. kv := NewNamespacedKV(s.db.Lowlevel, string(prefix))
  230. return fs.NewMtimeFS(s.fs, kv)
  231. }
  232. func (s *FileSet) ListDevices() []protocol.DeviceID {
  233. return s.meta.devices()
  234. }
  235. // DropFolder clears out all information related to the given folder from the
  236. // database.
  237. func DropFolder(ll *Lowlevel, folder string) {
  238. db := newInstance(ll)
  239. db.dropFolder([]byte(folder))
  240. db.dropMtimes([]byte(folder))
  241. db.dropFolderMeta([]byte(folder))
  242. // Also clean out the folder ID mapping.
  243. db.folderIdx.Delete([]byte(folder))
  244. }
  245. // DropDeltaIndexIDs removes all delta index IDs from the database.
  246. // This will cause a full index transmission on the next connection.
  247. func DropDeltaIndexIDs(db *Lowlevel) {
  248. dbi := db.NewIterator(util.BytesPrefix([]byte{KeyTypeIndexID}), nil)
  249. defer dbi.Release()
  250. for dbi.Next() {
  251. db.Delete(dbi.Key(), nil)
  252. }
  253. }
  254. func normalizeFilenames(fs []protocol.FileInfo) {
  255. for i := range fs {
  256. fs[i].Name = osutil.NormalizedFilename(fs[i].Name)
  257. }
  258. }
  259. func nativeFileIterator(fn Iterator) Iterator {
  260. return func(fi FileIntf) bool {
  261. switch f := fi.(type) {
  262. case protocol.FileInfo:
  263. f.Name = osutil.NativeFilename(f.Name)
  264. return fn(f)
  265. case FileInfoTruncated:
  266. f.Name = osutil.NativeFilename(f.Name)
  267. return fn(f)
  268. default:
  269. panic("unknown interface type")
  270. }
  271. }
  272. }