set.go 17 KB

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