set.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366
  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. "sort"
  16. "time"
  17. "github.com/syncthing/syncthing/lib/fs"
  18. "github.com/syncthing/syncthing/lib/osutil"
  19. "github.com/syncthing/syncthing/lib/protocol"
  20. "github.com/syncthing/syncthing/lib/sync"
  21. "github.com/syndtr/goleveldb/leveldb/util"
  22. )
  23. type FileSet struct {
  24. folder string
  25. fs fs.Filesystem
  26. db *instance
  27. blockmap *BlockMap
  28. meta *metadataTracker
  29. updateMutex sync.Mutex // protects database updates and the corresponding metadata changes
  30. }
  31. // FileIntf is the set of methods implemented by both protocol.FileInfo and
  32. // FileInfoTruncated.
  33. type FileIntf interface {
  34. FileSize() int64
  35. FileName() string
  36. FileLocalFlags() uint32
  37. IsDeleted() bool
  38. IsInvalid() bool
  39. IsIgnored() bool
  40. IsUnsupported() bool
  41. MustRescan() bool
  42. IsReceiveOnlyChanged() bool
  43. IsDirectory() bool
  44. IsSymlink() bool
  45. ShouldConflict() bool
  46. HasPermissionBits() bool
  47. SequenceNo() int64
  48. BlockSize() int
  49. FileVersion() protocol.Vector
  50. }
  51. // The Iterator is called with either a protocol.FileInfo or a
  52. // FileInfoTruncated (depending on the method) and returns true to
  53. // continue iteration, false to stop.
  54. type Iterator func(f FileIntf) bool
  55. var databaseRecheckInterval = 30 * 24 * time.Hour
  56. func init() {
  57. if dur, err := time.ParseDuration(os.Getenv("STRECHECKDBEVERY")); err == nil {
  58. databaseRecheckInterval = dur
  59. }
  60. }
  61. func NewFileSet(folder string, fs fs.Filesystem, ll *Lowlevel) *FileSet {
  62. db := newInstance(ll)
  63. var s = FileSet{
  64. folder: folder,
  65. fs: fs,
  66. db: db,
  67. blockmap: NewBlockMap(ll, folder),
  68. meta: newMetadataTracker(),
  69. updateMutex: sync.NewMutex(),
  70. }
  71. if err := s.meta.fromDB(db, []byte(folder)); err != nil {
  72. l.Infof("No stored folder metadata for %q: recalculating", folder)
  73. s.recalcCounts()
  74. } else if age := time.Since(s.meta.Created()); age > databaseRecheckInterval {
  75. l.Infof("Stored folder metadata for %q is %v old; recalculating", folder, age)
  76. s.recalcCounts()
  77. }
  78. return &s
  79. }
  80. func (s *FileSet) recalcCounts() {
  81. s.meta = newMetadataTracker()
  82. s.db.checkGlobals([]byte(s.folder), s.meta)
  83. var deviceID protocol.DeviceID
  84. s.db.withAllFolderTruncated([]byte(s.folder), func(device []byte, f FileInfoTruncated) bool {
  85. copy(deviceID[:], device)
  86. s.meta.addFile(deviceID, f)
  87. return true
  88. })
  89. s.meta.SetCreated()
  90. s.meta.toDB(s.db, []byte(s.folder))
  91. }
  92. func (s *FileSet) Drop(device protocol.DeviceID) {
  93. l.Debugf("%s Drop(%v)", s.folder, device)
  94. s.updateMutex.Lock()
  95. defer s.updateMutex.Unlock()
  96. s.db.dropDeviceFolder(device[:], []byte(s.folder), s.meta)
  97. if device == protocol.LocalDeviceID {
  98. s.blockmap.Drop()
  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. // Easy case, just update the files and we're done.
  124. s.db.updateFiles([]byte(s.folder), device[:], fs, s.meta)
  125. return
  126. }
  127. // For the local device we have a bunch of metadata to track however...
  128. discards := make([]protocol.FileInfo, 0, len(fs))
  129. updates := make([]protocol.FileInfo, 0, len(fs))
  130. // db.UpdateFiles will sort unchanged files out -> save one db lookup
  131. // filter slice according to https://github.com/golang/go/wiki/SliceTricks#filtering-without-allocating
  132. oldFs := fs
  133. fs = fs[:0]
  134. folder := []byte(s.folder)
  135. for _, nf := range oldFs {
  136. ef, ok := s.db.getFileDirty(folder, device[:], []byte(osutil.NormalizedFilename(nf.Name)))
  137. if ok && unchanged(nf, ef) {
  138. continue
  139. }
  140. nf.Sequence = s.meta.nextSeq(protocol.LocalDeviceID)
  141. fs = append(fs, nf)
  142. if ok {
  143. discards = append(discards, ef)
  144. }
  145. updates = append(updates, nf)
  146. }
  147. // The ordering here is important. We first remove stuff that point to
  148. // files we are going to update, then update them, then add new index
  149. // pointers etc. In addition, we do the discards in reverse order so
  150. // that a reader traversing the sequence index will get a consistent
  151. // view up until the point they meet the writer.
  152. sort.Slice(discards, func(a, b int) bool {
  153. // n.b. "b < a" instead of the usual "a < b"
  154. return discards[b].Sequence < discards[a].Sequence
  155. })
  156. s.blockmap.Discard(discards)
  157. s.db.removeSequences(folder, discards)
  158. s.db.updateFiles([]byte(s.folder), device[:], fs, s.meta)
  159. s.db.addSequences(folder, updates)
  160. s.blockmap.Update(updates)
  161. }
  162. func (s *FileSet) WithNeed(device protocol.DeviceID, fn Iterator) {
  163. l.Debugf("%s WithNeed(%v)", s.folder, device)
  164. s.db.withNeed([]byte(s.folder), device[:], false, nativeFileIterator(fn))
  165. }
  166. func (s *FileSet) WithNeedTruncated(device protocol.DeviceID, fn Iterator) {
  167. l.Debugf("%s WithNeedTruncated(%v)", s.folder, device)
  168. s.db.withNeed([]byte(s.folder), device[:], true, nativeFileIterator(fn))
  169. }
  170. func (s *FileSet) WithHave(device protocol.DeviceID, fn Iterator) {
  171. l.Debugf("%s WithHave(%v)", s.folder, device)
  172. s.db.withHave([]byte(s.folder), device[:], nil, false, nativeFileIterator(fn))
  173. }
  174. func (s *FileSet) WithHaveTruncated(device protocol.DeviceID, fn Iterator) {
  175. l.Debugf("%s WithHaveTruncated(%v)", s.folder, device)
  176. s.db.withHave([]byte(s.folder), device[:], nil, true, nativeFileIterator(fn))
  177. }
  178. func (s *FileSet) WithHaveSequence(startSeq int64, fn Iterator) {
  179. l.Debugf("%s WithHaveSequence(%v)", s.folder, startSeq)
  180. s.db.withHaveSequence([]byte(s.folder), startSeq, nativeFileIterator(fn))
  181. }
  182. // Except for an item with a path equal to prefix, only children of prefix are iterated.
  183. // E.g. for prefix "dir", "dir/file" is iterated, but "dir.file" is not.
  184. func (s *FileSet) WithPrefixedHaveTruncated(device protocol.DeviceID, prefix string, fn Iterator) {
  185. l.Debugf(`%s WithPrefixedHaveTruncated(%v, "%v")`, s.folder, device, prefix)
  186. s.db.withHave([]byte(s.folder), device[:], []byte(osutil.NormalizedFilename(prefix)), true, nativeFileIterator(fn))
  187. }
  188. func (s *FileSet) WithGlobal(fn Iterator) {
  189. l.Debugf("%s WithGlobal()", s.folder)
  190. s.db.withGlobal([]byte(s.folder), nil, false, nativeFileIterator(fn))
  191. }
  192. func (s *FileSet) WithGlobalTruncated(fn Iterator) {
  193. l.Debugf("%s WithGlobalTruncated()", s.folder)
  194. s.db.withGlobal([]byte(s.folder), nil, true, nativeFileIterator(fn))
  195. }
  196. // Except for an item with a path equal to prefix, only children of prefix are iterated.
  197. // E.g. for prefix "dir", "dir/file" is iterated, but "dir.file" is not.
  198. func (s *FileSet) WithPrefixedGlobalTruncated(prefix string, fn Iterator) {
  199. l.Debugf(`%s WithPrefixedGlobalTruncated("%v")`, s.folder, prefix)
  200. s.db.withGlobal([]byte(s.folder), []byte(osutil.NormalizedFilename(prefix)), true, nativeFileIterator(fn))
  201. }
  202. func (s *FileSet) Get(device protocol.DeviceID, file string) (protocol.FileInfo, bool) {
  203. f, ok := s.db.getFileDirty([]byte(s.folder), device[:], []byte(osutil.NormalizedFilename(file)))
  204. f.Name = osutil.NativeFilename(f.Name)
  205. return f, ok
  206. }
  207. func (s *FileSet) GetGlobal(file string) (protocol.FileInfo, bool) {
  208. fi, ok := s.db.getGlobalDirty([]byte(s.folder), []byte(osutil.NormalizedFilename(file)), false)
  209. if !ok {
  210. return protocol.FileInfo{}, false
  211. }
  212. f := fi.(protocol.FileInfo)
  213. f.Name = osutil.NativeFilename(f.Name)
  214. return f, true
  215. }
  216. func (s *FileSet) GetGlobalTruncated(file string) (FileInfoTruncated, bool) {
  217. fi, ok := s.db.getGlobalDirty([]byte(s.folder), []byte(osutil.NormalizedFilename(file)), true)
  218. if !ok {
  219. return FileInfoTruncated{}, false
  220. }
  221. f := fi.(FileInfoTruncated)
  222. f.Name = osutil.NativeFilename(f.Name)
  223. return f, true
  224. }
  225. func (s *FileSet) Availability(file string) []protocol.DeviceID {
  226. return s.db.availability([]byte(s.folder), []byte(osutil.NormalizedFilename(file)))
  227. }
  228. func (s *FileSet) Sequence(device protocol.DeviceID) int64 {
  229. return s.meta.Sequence(device)
  230. }
  231. func (s *FileSet) LocalSize() Counts {
  232. local := s.meta.Counts(protocol.LocalDeviceID, 0)
  233. recvOnlyChanged := s.meta.Counts(protocol.LocalDeviceID, protocol.FlagLocalReceiveOnly)
  234. return local.Add(recvOnlyChanged)
  235. }
  236. func (s *FileSet) ReceiveOnlyChangedSize() Counts {
  237. return s.meta.Counts(protocol.LocalDeviceID, protocol.FlagLocalReceiveOnly)
  238. }
  239. func (s *FileSet) GlobalSize() Counts {
  240. global := s.meta.Counts(protocol.GlobalDeviceID, 0)
  241. recvOnlyChanged := s.meta.Counts(protocol.GlobalDeviceID, protocol.FlagLocalReceiveOnly)
  242. return global.Add(recvOnlyChanged)
  243. }
  244. func (s *FileSet) IndexID(device protocol.DeviceID) protocol.IndexID {
  245. id := s.db.getIndexID(device[:], []byte(s.folder))
  246. if id == 0 && device == protocol.LocalDeviceID {
  247. // No index ID set yet. We create one now.
  248. id = protocol.NewIndexID()
  249. s.db.setIndexID(device[:], []byte(s.folder), id)
  250. }
  251. return id
  252. }
  253. func (s *FileSet) SetIndexID(device protocol.DeviceID, id protocol.IndexID) {
  254. if device == protocol.LocalDeviceID {
  255. panic("do not explicitly set index ID for local device")
  256. }
  257. s.db.setIndexID(device[:], []byte(s.folder), id)
  258. }
  259. func (s *FileSet) MtimeFS() *fs.MtimeFS {
  260. prefix := s.db.keyer.GenerateMtimesKey(nil, []byte(s.folder))
  261. kv := NewNamespacedKV(s.db.Lowlevel, string(prefix))
  262. return fs.NewMtimeFS(s.fs, kv)
  263. }
  264. func (s *FileSet) ListDevices() []protocol.DeviceID {
  265. return s.meta.devices()
  266. }
  267. // DropFolder clears out all information related to the given folder from the
  268. // database.
  269. func DropFolder(ll *Lowlevel, folder string) {
  270. db := newInstance(ll)
  271. db.dropFolder([]byte(folder))
  272. db.dropMtimes([]byte(folder))
  273. db.dropFolderMeta([]byte(folder))
  274. bm := NewBlockMap(ll, folder)
  275. bm.Drop()
  276. // Also clean out the folder ID mapping.
  277. db.folderIdx.Delete([]byte(folder))
  278. }
  279. // DropDeltaIndexIDs removes all delta index IDs from the database.
  280. // This will cause a full index transmission on the next connection.
  281. func DropDeltaIndexIDs(db *Lowlevel) {
  282. dbi := db.NewIterator(util.BytesPrefix([]byte{KeyTypeIndexID}), nil)
  283. defer dbi.Release()
  284. for dbi.Next() {
  285. db.Delete(dbi.Key(), nil)
  286. }
  287. }
  288. func normalizeFilenames(fs []protocol.FileInfo) {
  289. for i := range fs {
  290. fs[i].Name = osutil.NormalizedFilename(fs[i].Name)
  291. }
  292. }
  293. func nativeFileIterator(fn Iterator) Iterator {
  294. return func(fi FileIntf) bool {
  295. switch f := fi.(type) {
  296. case protocol.FileInfo:
  297. f.Name = osutil.NativeFilename(f.Name)
  298. return fn(f)
  299. case FileInfoTruncated:
  300. f.Name = osutil.NativeFilename(f.Name)
  301. return fn(f)
  302. default:
  303. panic("unknown interface type")
  304. }
  305. }
  306. }