set.go 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306
  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. for _, nf := range oldFs {
  119. ef, ok := s.db.getFile([]byte(s.folder), device[:], []byte(nf.Name))
  120. if ok && ef.Version.Equal(nf.Version) && ef.Invalid == nf.Invalid {
  121. continue
  122. }
  123. nf.Sequence = s.meta.nextSeq(protocol.LocalDeviceID)
  124. fs = append(fs, nf)
  125. if ok {
  126. discards = append(discards, ef)
  127. }
  128. updates = append(updates, nf)
  129. }
  130. s.blockmap.Discard(discards)
  131. s.blockmap.Update(updates)
  132. }
  133. s.db.updateFiles([]byte(s.folder), device[:], fs, s.meta)
  134. s.meta.toDB(s.db, []byte(s.folder))
  135. }
  136. func (s *FileSet) WithNeed(device protocol.DeviceID, fn Iterator) {
  137. l.Debugf("%s WithNeed(%v)", s.folder, device)
  138. s.db.withNeed([]byte(s.folder), device[:], false, nativeFileIterator(fn))
  139. }
  140. func (s *FileSet) WithNeedTruncated(device protocol.DeviceID, fn Iterator) {
  141. l.Debugf("%s WithNeedTruncated(%v)", s.folder, device)
  142. s.db.withNeed([]byte(s.folder), device[:], true, nativeFileIterator(fn))
  143. }
  144. func (s *FileSet) WithHave(device protocol.DeviceID, fn Iterator) {
  145. l.Debugf("%s WithHave(%v)", s.folder, device)
  146. s.db.withHave([]byte(s.folder), device[:], nil, false, nativeFileIterator(fn))
  147. }
  148. func (s *FileSet) WithHaveTruncated(device protocol.DeviceID, fn Iterator) {
  149. l.Debugf("%s WithHaveTruncated(%v)", s.folder, device)
  150. s.db.withHave([]byte(s.folder), device[:], nil, true, nativeFileIterator(fn))
  151. }
  152. func (s *FileSet) WithPrefixedHaveTruncated(device protocol.DeviceID, prefix string, fn Iterator) {
  153. l.Debugf("%s WithPrefixedHaveTruncated(%v)", s.folder, device)
  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. func (s *FileSet) WithPrefixedGlobalTruncated(prefix string, fn Iterator) {
  165. l.Debugf("%s WithPrefixedGlobalTruncated()", s.folder, prefix)
  166. s.db.withGlobal([]byte(s.folder), []byte(osutil.NormalizedFilename(prefix)), true, nativeFileIterator(fn))
  167. }
  168. func (s *FileSet) Get(device protocol.DeviceID, file string) (protocol.FileInfo, bool) {
  169. f, ok := s.db.getFile([]byte(s.folder), device[:], []byte(osutil.NormalizedFilename(file)))
  170. f.Name = osutil.NativeFilename(f.Name)
  171. return f, ok
  172. }
  173. func (s *FileSet) GetGlobal(file string) (protocol.FileInfo, bool) {
  174. fi, ok := s.db.getGlobal([]byte(s.folder), []byte(osutil.NormalizedFilename(file)), false)
  175. if !ok {
  176. return protocol.FileInfo{}, false
  177. }
  178. f := fi.(protocol.FileInfo)
  179. f.Name = osutil.NativeFilename(f.Name)
  180. return f, true
  181. }
  182. func (s *FileSet) GetGlobalTruncated(file string) (FileInfoTruncated, bool) {
  183. fi, ok := s.db.getGlobal([]byte(s.folder), []byte(osutil.NormalizedFilename(file)), true)
  184. if !ok {
  185. return FileInfoTruncated{}, false
  186. }
  187. f := fi.(FileInfoTruncated)
  188. f.Name = osutil.NativeFilename(f.Name)
  189. return f, true
  190. }
  191. func (s *FileSet) Availability(file string) []protocol.DeviceID {
  192. return s.db.availability([]byte(s.folder), []byte(osutil.NormalizedFilename(file)))
  193. }
  194. func (s *FileSet) Sequence(device protocol.DeviceID) int64 {
  195. return s.meta.Counts(device).Sequence
  196. }
  197. func (s *FileSet) LocalSize() Counts {
  198. return s.meta.Counts(protocol.LocalDeviceID)
  199. }
  200. func (s *FileSet) GlobalSize() Counts {
  201. return s.meta.Counts(globalDeviceID)
  202. }
  203. func (s *FileSet) IndexID(device protocol.DeviceID) protocol.IndexID {
  204. id := s.db.getIndexID(device[:], []byte(s.folder))
  205. if id == 0 && device == protocol.LocalDeviceID {
  206. // No index ID set yet. We create one now.
  207. id = protocol.NewIndexID()
  208. s.db.setIndexID(device[:], []byte(s.folder), id)
  209. }
  210. return id
  211. }
  212. func (s *FileSet) SetIndexID(device protocol.DeviceID, id protocol.IndexID) {
  213. if device == protocol.LocalDeviceID {
  214. panic("do not explicitly set index ID for local device")
  215. }
  216. s.db.setIndexID(device[:], []byte(s.folder), id)
  217. }
  218. func (s *FileSet) MtimeFS() *fs.MtimeFS {
  219. prefix := s.db.mtimesKey([]byte(s.folder))
  220. kv := NewNamespacedKV(s.db, string(prefix))
  221. return fs.NewMtimeFS(s.fs, kv)
  222. }
  223. func (s *FileSet) ListDevices() []protocol.DeviceID {
  224. return s.meta.devices()
  225. }
  226. // DropFolder clears out all information related to the given folder from the
  227. // database.
  228. func DropFolder(db *Instance, folder string) {
  229. db.dropFolder([]byte(folder))
  230. db.dropMtimes([]byte(folder))
  231. db.dropFolderMeta([]byte(folder))
  232. bm := &BlockMap{
  233. db: db,
  234. folder: db.folderIdx.ID([]byte(folder)),
  235. }
  236. bm.Drop()
  237. }
  238. func normalizeFilenames(fs []protocol.FileInfo) {
  239. for i := range fs {
  240. fs[i].Name = osutil.NormalizedFilename(fs[i].Name)
  241. }
  242. }
  243. func nativeFileIterator(fn Iterator) Iterator {
  244. return func(fi FileIntf) bool {
  245. switch f := fi.(type) {
  246. case protocol.FileInfo:
  247. f.Name = osutil.NativeFilename(f.Name)
  248. return fn(f)
  249. case FileInfoTruncated:
  250. f.Name = osutil.NativeFilename(f.Name)
  251. return fn(f)
  252. default:
  253. panic("unknown interface type")
  254. }
  255. }
  256. }