set.go 14 KB

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