set.go 9.2 KB

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