set.go 9.6 KB

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