set.go 15 KB

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