set.go 14 KB

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