set.go 11 KB

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