1
0

set.go 16 KB

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