set.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511
  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/db/backend"
  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 *Lowlevel
  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. FileLocalFlags() uint32
  35. IsDeleted() bool
  36. IsInvalid() bool
  37. IsIgnored() bool
  38. IsUnsupported() bool
  39. MustRescan() bool
  40. IsReceiveOnlyChanged() bool
  41. IsDirectory() bool
  42. IsSymlink() bool
  43. ShouldConflict() bool
  44. HasPermissionBits() bool
  45. SequenceNo() int64
  46. BlockSize() int
  47. FileVersion() protocol.Vector
  48. FileType() protocol.FileInfoType
  49. FilePermissions() uint32
  50. FileModifiedBy() protocol.ShortID
  51. ModTime() time.Time
  52. }
  53. // The Iterator is called with either a protocol.FileInfo or a
  54. // FileInfoTruncated (depending on the method) and returns true to
  55. // continue iteration, false to stop.
  56. type Iterator func(f FileIntf) bool
  57. var databaseRecheckInterval = 30 * 24 * time.Hour
  58. func init() {
  59. if dur, err := time.ParseDuration(os.Getenv("STRECHECKDBEVERY")); err == nil {
  60. databaseRecheckInterval = dur
  61. }
  62. }
  63. func NewFileSet(folder string, fs fs.Filesystem, db *Lowlevel) *FileSet {
  64. return &FileSet{
  65. folder: folder,
  66. fs: fs,
  67. db: db,
  68. meta: db.loadMetadataTracker(folder),
  69. updateMutex: sync.NewMutex(),
  70. }
  71. }
  72. func (s *FileSet) Drop(device protocol.DeviceID) {
  73. l.Debugf("%s Drop(%v)", s.folder, device)
  74. s.updateMutex.Lock()
  75. defer s.updateMutex.Unlock()
  76. if err := s.db.dropDeviceFolder(device[:], []byte(s.folder), s.meta); backend.IsClosed(err) {
  77. return
  78. } else if err != nil {
  79. panic(err)
  80. }
  81. if device == protocol.LocalDeviceID {
  82. s.meta.resetCounts(device)
  83. // We deliberately do not reset the sequence number here. Dropping
  84. // all files for the local device ID only happens in testing - which
  85. // expects the sequence to be retained, like an old Replace() of all
  86. // files would do. However, if we ever did it "in production" we
  87. // would anyway want to retain the sequence for delta indexes to be
  88. // happy.
  89. } else {
  90. // Here, on the other hand, we want to make sure that any file
  91. // announced from the remote is newer than our current sequence
  92. // number.
  93. s.meta.resetAll(device)
  94. }
  95. t, err := s.db.newReadWriteTransaction()
  96. if backend.IsClosed(err) {
  97. return
  98. } else if err != nil {
  99. panic(err)
  100. }
  101. defer t.close()
  102. if err := s.meta.toDB(t, []byte(s.folder)); backend.IsClosed(err) {
  103. return
  104. } else if err != nil {
  105. panic(err)
  106. }
  107. if err := t.Commit(); backend.IsClosed(err) {
  108. return
  109. } else if err != nil {
  110. panic(err)
  111. }
  112. }
  113. func (s *FileSet) Update(device protocol.DeviceID, fs []protocol.FileInfo) {
  114. l.Debugf("%s Update(%v, [%d])", s.folder, device, len(fs))
  115. // do not modify fs in place, it is still used in outer scope
  116. fs = append([]protocol.FileInfo(nil), fs...)
  117. normalizeFilenames(fs)
  118. s.updateMutex.Lock()
  119. defer s.updateMutex.Unlock()
  120. if device == protocol.LocalDeviceID {
  121. // For the local device we have a bunch of metadata to track.
  122. if err := s.db.updateLocalFiles([]byte(s.folder), fs, s.meta); err != nil && !backend.IsClosed(err) {
  123. panic(err)
  124. }
  125. return
  126. }
  127. // Easy case, just update the files and we're done.
  128. if err := s.db.updateRemoteFiles([]byte(s.folder), device[:], fs, s.meta); err != nil && !backend.IsClosed(err) {
  129. panic(err)
  130. }
  131. }
  132. type Snapshot struct {
  133. folder string
  134. t readOnlyTransaction
  135. meta *countsMap
  136. }
  137. func (s *FileSet) Snapshot() *Snapshot {
  138. t, err := s.db.newReadOnlyTransaction()
  139. if err != nil {
  140. panic(err)
  141. }
  142. return &Snapshot{
  143. folder: s.folder,
  144. t: t,
  145. meta: s.meta.Snapshot(),
  146. }
  147. }
  148. func (s *Snapshot) Release() {
  149. s.t.close()
  150. }
  151. func (s *Snapshot) WithNeed(device protocol.DeviceID, fn Iterator) {
  152. l.Debugf("%s WithNeed(%v)", s.folder, device)
  153. if err := s.t.withNeed([]byte(s.folder), device[:], false, nativeFileIterator(fn)); err != nil && !backend.IsClosed(err) {
  154. panic(err)
  155. }
  156. }
  157. func (s *Snapshot) WithNeedTruncated(device protocol.DeviceID, fn Iterator) {
  158. l.Debugf("%s WithNeedTruncated(%v)", s.folder, device)
  159. if err := s.t.withNeed([]byte(s.folder), device[:], true, nativeFileIterator(fn)); err != nil && !backend.IsClosed(err) {
  160. panic(err)
  161. }
  162. }
  163. func (s *Snapshot) WithHave(device protocol.DeviceID, fn Iterator) {
  164. l.Debugf("%s WithHave(%v)", s.folder, device)
  165. if err := s.t.withHave([]byte(s.folder), device[:], nil, false, nativeFileIterator(fn)); err != nil && !backend.IsClosed(err) {
  166. panic(err)
  167. }
  168. }
  169. func (s *Snapshot) WithHaveTruncated(device protocol.DeviceID, fn Iterator) {
  170. l.Debugf("%s WithHaveTruncated(%v)", s.folder, device)
  171. if err := s.t.withHave([]byte(s.folder), device[:], nil, true, nativeFileIterator(fn)); err != nil && !backend.IsClosed(err) {
  172. panic(err)
  173. }
  174. }
  175. func (s *Snapshot) WithHaveSequence(startSeq int64, fn Iterator) {
  176. l.Debugf("%s WithHaveSequence(%v)", s.folder, startSeq)
  177. if err := s.t.withHaveSequence([]byte(s.folder), startSeq, nativeFileIterator(fn)); err != nil && !backend.IsClosed(err) {
  178. panic(err)
  179. }
  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 *Snapshot) WithPrefixedHaveTruncated(device protocol.DeviceID, prefix string, fn Iterator) {
  184. l.Debugf(`%s WithPrefixedHaveTruncated(%v, "%v")`, s.folder, device, prefix)
  185. if err := s.t.withHave([]byte(s.folder), device[:], []byte(osutil.NormalizedFilename(prefix)), true, nativeFileIterator(fn)); err != nil && !backend.IsClosed(err) {
  186. panic(err)
  187. }
  188. }
  189. func (s *Snapshot) WithGlobal(fn Iterator) {
  190. l.Debugf("%s WithGlobal()", s.folder)
  191. if err := s.t.withGlobal([]byte(s.folder), nil, false, nativeFileIterator(fn)); err != nil && !backend.IsClosed(err) {
  192. panic(err)
  193. }
  194. }
  195. func (s *Snapshot) WithGlobalTruncated(fn Iterator) {
  196. l.Debugf("%s WithGlobalTruncated()", s.folder)
  197. if err := s.t.withGlobal([]byte(s.folder), nil, true, nativeFileIterator(fn)); err != nil && !backend.IsClosed(err) {
  198. panic(err)
  199. }
  200. }
  201. // Except for an item with a path equal to prefix, only children of prefix are iterated.
  202. // E.g. for prefix "dir", "dir/file" is iterated, but "dir.file" is not.
  203. func (s *Snapshot) WithPrefixedGlobalTruncated(prefix string, fn Iterator) {
  204. l.Debugf(`%s WithPrefixedGlobalTruncated("%v")`, s.folder, prefix)
  205. if err := s.t.withGlobal([]byte(s.folder), []byte(osutil.NormalizedFilename(prefix)), true, nativeFileIterator(fn)); err != nil && !backend.IsClosed(err) {
  206. panic(err)
  207. }
  208. }
  209. func (s *Snapshot) Get(device protocol.DeviceID, file string) (protocol.FileInfo, bool) {
  210. f, ok, err := s.t.getFile([]byte(s.folder), device[:], []byte(osutil.NormalizedFilename(file)))
  211. if backend.IsClosed(err) {
  212. return protocol.FileInfo{}, false
  213. } else if err != nil {
  214. panic(err)
  215. }
  216. f.Name = osutil.NativeFilename(f.Name)
  217. return f, ok
  218. }
  219. func (s *Snapshot) GetGlobal(file string) (protocol.FileInfo, bool) {
  220. _, fi, ok, err := s.t.getGlobal(nil, []byte(s.folder), []byte(osutil.NormalizedFilename(file)), false)
  221. if backend.IsClosed(err) {
  222. return protocol.FileInfo{}, false
  223. } else if err != nil {
  224. panic(err)
  225. }
  226. if !ok {
  227. return protocol.FileInfo{}, false
  228. }
  229. f := fi.(protocol.FileInfo)
  230. f.Name = osutil.NativeFilename(f.Name)
  231. return f, true
  232. }
  233. func (s *Snapshot) GetGlobalTruncated(file string) (FileInfoTruncated, bool) {
  234. _, fi, ok, err := s.t.getGlobal(nil, []byte(s.folder), []byte(osutil.NormalizedFilename(file)), true)
  235. if backend.IsClosed(err) {
  236. return FileInfoTruncated{}, false
  237. } else if err != nil {
  238. panic(err)
  239. }
  240. if !ok {
  241. return FileInfoTruncated{}, false
  242. }
  243. f := fi.(FileInfoTruncated)
  244. f.Name = osutil.NativeFilename(f.Name)
  245. return f, true
  246. }
  247. func (s *Snapshot) Availability(file string) []protocol.DeviceID {
  248. av, err := s.t.availability([]byte(s.folder), []byte(osutil.NormalizedFilename(file)))
  249. if backend.IsClosed(err) {
  250. return nil
  251. } else if err != nil {
  252. panic(err)
  253. }
  254. return av
  255. }
  256. func (s *Snapshot) Sequence(device protocol.DeviceID) int64 {
  257. return s.meta.Counts(device, 0).Sequence
  258. }
  259. // RemoteSequence returns the change version for the given folder, as
  260. // sent by remote peers. This is guaranteed to increment if the contents of
  261. // the remote or global folder has changed.
  262. func (s *Snapshot) RemoteSequence() int64 {
  263. var ver int64
  264. for _, device := range s.meta.devices() {
  265. ver += s.Sequence(device)
  266. }
  267. return ver
  268. }
  269. func (s *Snapshot) LocalSize() Counts {
  270. local := s.meta.Counts(protocol.LocalDeviceID, 0)
  271. return local.Add(s.ReceiveOnlyChangedSize())
  272. }
  273. func (s *Snapshot) ReceiveOnlyChangedSize() Counts {
  274. return s.meta.Counts(protocol.LocalDeviceID, protocol.FlagLocalReceiveOnly)
  275. }
  276. func (s *Snapshot) GlobalSize() Counts {
  277. global := s.meta.Counts(protocol.GlobalDeviceID, 0)
  278. recvOnlyChanged := s.meta.Counts(protocol.GlobalDeviceID, protocol.FlagLocalReceiveOnly)
  279. return global.Add(recvOnlyChanged)
  280. }
  281. func (s *Snapshot) NeedSize() Counts {
  282. var result Counts
  283. s.WithNeedTruncated(protocol.LocalDeviceID, func(f FileIntf) bool {
  284. switch {
  285. case f.IsDeleted():
  286. result.Deleted++
  287. case f.IsDirectory():
  288. result.Directories++
  289. case f.IsSymlink():
  290. result.Symlinks++
  291. default:
  292. result.Files++
  293. result.Bytes += f.FileSize()
  294. }
  295. return true
  296. })
  297. return result
  298. }
  299. // LocalChangedFiles returns a paginated list of currently needed files in
  300. // progress, queued, and to be queued on next puller iteration, as well as the
  301. // total number of files currently needed.
  302. func (s *Snapshot) LocalChangedFiles(page, perpage int) []FileInfoTruncated {
  303. if s.ReceiveOnlyChangedSize().TotalItems() == 0 {
  304. return nil
  305. }
  306. files := make([]FileInfoTruncated, 0, perpage)
  307. skip := (page - 1) * perpage
  308. get := perpage
  309. s.WithHaveTruncated(protocol.LocalDeviceID, func(f FileIntf) bool {
  310. if !f.IsReceiveOnlyChanged() {
  311. return true
  312. }
  313. if skip > 0 {
  314. skip--
  315. return true
  316. }
  317. ft := f.(FileInfoTruncated)
  318. files = append(files, ft)
  319. get--
  320. return get > 0
  321. })
  322. return files
  323. }
  324. // RemoteNeedFolderFiles returns paginated list of currently needed files in
  325. // progress, queued, and to be queued on next puller iteration, as well as the
  326. // total number of files currently needed.
  327. func (s *Snapshot) RemoteNeedFolderFiles(device protocol.DeviceID, page, perpage int) []FileInfoTruncated {
  328. files := make([]FileInfoTruncated, 0, perpage)
  329. skip := (page - 1) * perpage
  330. get := perpage
  331. s.WithNeedTruncated(device, func(f FileIntf) bool {
  332. if skip > 0 {
  333. skip--
  334. return true
  335. }
  336. files = append(files, f.(FileInfoTruncated))
  337. get--
  338. return get > 0
  339. })
  340. return files
  341. }
  342. func (s *FileSet) Sequence(device protocol.DeviceID) int64 {
  343. return s.meta.Sequence(device)
  344. }
  345. func (s *FileSet) IndexID(device protocol.DeviceID) protocol.IndexID {
  346. id, err := s.db.getIndexID(device[:], []byte(s.folder))
  347. if backend.IsClosed(err) {
  348. return 0
  349. } else if err != nil {
  350. panic(err)
  351. }
  352. if id == 0 && device == protocol.LocalDeviceID {
  353. // No index ID set yet. We create one now.
  354. id = protocol.NewIndexID()
  355. err := s.db.setIndexID(device[:], []byte(s.folder), id)
  356. if backend.IsClosed(err) {
  357. return 0
  358. } else if err != nil {
  359. panic(err)
  360. }
  361. }
  362. return id
  363. }
  364. func (s *FileSet) SetIndexID(device protocol.DeviceID, id protocol.IndexID) {
  365. if device == protocol.LocalDeviceID {
  366. panic("do not explicitly set index ID for local device")
  367. }
  368. if err := s.db.setIndexID(device[:], []byte(s.folder), id); err != nil && !backend.IsClosed(err) {
  369. panic(err)
  370. }
  371. }
  372. func (s *FileSet) MtimeFS() *fs.MtimeFS {
  373. prefix, err := s.db.keyer.GenerateMtimesKey(nil, []byte(s.folder))
  374. if backend.IsClosed(err) {
  375. return nil
  376. } else if err != nil {
  377. panic(err)
  378. }
  379. kv := NewNamespacedKV(s.db, string(prefix))
  380. return fs.NewMtimeFS(s.fs, kv)
  381. }
  382. func (s *FileSet) ListDevices() []protocol.DeviceID {
  383. return s.meta.devices()
  384. }
  385. func (s *FileSet) RepairSequence() (int, error) {
  386. s.updateAndGCMutexLock() // Ensures consistent locking order
  387. defer s.updateMutex.Unlock()
  388. defer s.db.gcMut.RUnlock()
  389. return s.db.repairSequenceGCLocked(s.folder, s.meta)
  390. }
  391. func (s *FileSet) updateAndGCMutexLock() {
  392. s.updateMutex.Lock()
  393. s.db.gcMut.RLock()
  394. }
  395. // DropFolder clears out all information related to the given folder from the
  396. // database.
  397. func DropFolder(db *Lowlevel, folder string) {
  398. droppers := []func([]byte) error{
  399. db.dropFolder,
  400. db.dropMtimes,
  401. db.dropFolderMeta,
  402. db.folderIdx.Delete,
  403. }
  404. for _, drop := range droppers {
  405. if err := drop([]byte(folder)); backend.IsClosed(err) {
  406. return
  407. } else if err != nil {
  408. panic(err)
  409. }
  410. }
  411. }
  412. // DropDeltaIndexIDs removes all delta index IDs from the database.
  413. // This will cause a full index transmission on the next connection.
  414. func DropDeltaIndexIDs(db *Lowlevel) {
  415. dbi, err := db.NewPrefixIterator([]byte{KeyTypeIndexID})
  416. if backend.IsClosed(err) {
  417. return
  418. } else if err != nil {
  419. panic(err)
  420. }
  421. defer dbi.Release()
  422. for dbi.Next() {
  423. if err := db.Delete(dbi.Key()); err != nil && !backend.IsClosed(err) {
  424. panic(err)
  425. }
  426. }
  427. if err := dbi.Error(); err != nil && !backend.IsClosed(err) {
  428. panic(err)
  429. }
  430. }
  431. func normalizeFilenames(fs []protocol.FileInfo) {
  432. for i := range fs {
  433. fs[i].Name = osutil.NormalizedFilename(fs[i].Name)
  434. }
  435. }
  436. func nativeFileIterator(fn Iterator) Iterator {
  437. return func(fi FileIntf) bool {
  438. switch f := fi.(type) {
  439. case protocol.FileInfo:
  440. f.Name = osutil.NativeFilename(f.Name)
  441. return fn(f)
  442. case FileInfoTruncated:
  443. f.Name = osutil.NativeFilename(f.Name)
  444. return fn(f)
  445. default:
  446. panic("unknown interface type")
  447. }
  448. }
  449. }