set.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536
  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) Sequence(device protocol.DeviceID) int64 {
  259. return s.meta.Counts(device, 0).Sequence
  260. }
  261. // RemoteSequence returns the change version for the given folder, as
  262. // sent by remote peers. This is guaranteed to increment if the contents of
  263. // the remote or global folder has changed.
  264. func (s *Snapshot) RemoteSequence() int64 {
  265. var ver int64
  266. for _, device := range s.meta.devices() {
  267. ver += s.Sequence(device)
  268. }
  269. return ver
  270. }
  271. func (s *Snapshot) LocalSize() Counts {
  272. local := s.meta.Counts(protocol.LocalDeviceID, 0)
  273. return local.Add(s.ReceiveOnlyChangedSize())
  274. }
  275. func (s *Snapshot) ReceiveOnlyChangedSize() Counts {
  276. return s.meta.Counts(protocol.LocalDeviceID, protocol.FlagLocalReceiveOnly)
  277. }
  278. func (s *Snapshot) GlobalSize() Counts {
  279. return s.meta.Counts(protocol.GlobalDeviceID, 0)
  280. }
  281. func (s *Snapshot) NeedSize(device protocol.DeviceID) Counts {
  282. return s.meta.Counts(device, needFlag)
  283. }
  284. // LocalChangedFiles returns a paginated list of files that were changed locally.
  285. func (s *Snapshot) LocalChangedFiles(page, perpage int) []FileInfoTruncated {
  286. if s.ReceiveOnlyChangedSize().TotalItems() == 0 {
  287. return nil
  288. }
  289. files := make([]FileInfoTruncated, 0, perpage)
  290. skip := (page - 1) * perpage
  291. get := perpage
  292. s.WithHaveTruncated(protocol.LocalDeviceID, func(f protocol.FileIntf) bool {
  293. if !f.IsReceiveOnlyChanged() {
  294. return true
  295. }
  296. if skip > 0 {
  297. skip--
  298. return true
  299. }
  300. ft := f.(FileInfoTruncated)
  301. files = append(files, ft)
  302. get--
  303. return get > 0
  304. })
  305. return files
  306. }
  307. // RemoteNeedFolderFiles returns paginated list of currently needed files in
  308. // progress, queued, and to be queued on next puller iteration, as well as the
  309. // total number of files currently needed.
  310. func (s *Snapshot) RemoteNeedFolderFiles(device protocol.DeviceID, page, perpage int) []FileInfoTruncated {
  311. files := make([]FileInfoTruncated, 0, perpage)
  312. skip := (page - 1) * perpage
  313. get := perpage
  314. s.WithNeedTruncated(device, func(f protocol.FileIntf) bool {
  315. if skip > 0 {
  316. skip--
  317. return true
  318. }
  319. files = append(files, f.(FileInfoTruncated))
  320. get--
  321. return get > 0
  322. })
  323. return files
  324. }
  325. func (s *Snapshot) WithBlocksHash(hash []byte, fn Iterator) {
  326. opStr := fmt.Sprintf(`%s WithBlocksHash("%x")`, s.folder, hash)
  327. l.Debugf(opStr)
  328. if err := s.t.withBlocksHash([]byte(s.folder), hash, nativeFileIterator(fn)); err != nil && !backend.IsClosed(err) {
  329. s.fatalError(err, opStr)
  330. }
  331. }
  332. func (s *FileSet) Sequence(device protocol.DeviceID) int64 {
  333. return s.meta.Sequence(device)
  334. }
  335. func (s *FileSet) IndexID(device protocol.DeviceID) protocol.IndexID {
  336. opStr := fmt.Sprintf("%s IndexID(%v)", s.folder, device)
  337. l.Debugf(opStr)
  338. id, err := s.db.getIndexID(device[:], []byte(s.folder))
  339. if backend.IsClosed(err) {
  340. return 0
  341. } else if err != nil {
  342. fatalError(err, opStr, s.db)
  343. }
  344. if id == 0 && device == protocol.LocalDeviceID {
  345. // No index ID set yet. We create one now.
  346. id = protocol.NewIndexID()
  347. err := s.db.setIndexID(device[:], []byte(s.folder), id)
  348. if backend.IsClosed(err) {
  349. return 0
  350. } else if err != nil {
  351. fatalError(err, opStr, s.db)
  352. }
  353. }
  354. return id
  355. }
  356. func (s *FileSet) SetIndexID(device protocol.DeviceID, id protocol.IndexID) {
  357. if device == protocol.LocalDeviceID {
  358. panic("do not explicitly set index ID for local device")
  359. }
  360. opStr := fmt.Sprintf("%s SetIndexID(%v, %v)", s.folder, device, id)
  361. l.Debugf(opStr)
  362. if err := s.db.setIndexID(device[:], []byte(s.folder), id); err != nil && !backend.IsClosed(err) {
  363. fatalError(err, opStr, s.db)
  364. }
  365. }
  366. func (s *FileSet) MtimeFS() *fs.MtimeFS {
  367. opStr := fmt.Sprintf("%s MtimeFS()", s.folder)
  368. l.Debugf(opStr)
  369. prefix, err := s.db.keyer.GenerateMtimesKey(nil, []byte(s.folder))
  370. if backend.IsClosed(err) {
  371. return nil
  372. } else if err != nil {
  373. fatalError(err, opStr, s.db)
  374. }
  375. kv := NewNamespacedKV(s.db, string(prefix))
  376. return fs.NewMtimeFS(s.fs, kv)
  377. }
  378. func (s *FileSet) ListDevices() []protocol.DeviceID {
  379. return s.meta.devices()
  380. }
  381. func (s *FileSet) RepairSequence() (int, error) {
  382. s.updateAndGCMutexLock() // Ensures consistent locking order
  383. defer s.updateMutex.Unlock()
  384. defer s.db.gcMut.RUnlock()
  385. return s.db.repairSequenceGCLocked(s.folder, s.meta)
  386. }
  387. func (s *FileSet) updateAndGCMutexLock() {
  388. s.updateMutex.Lock()
  389. s.db.gcMut.RLock()
  390. }
  391. // DropFolder clears out all information related to the given folder from the
  392. // database.
  393. func DropFolder(db *Lowlevel, folder string) {
  394. opStr := fmt.Sprintf("DropFolder(%v)", folder)
  395. l.Debugf(opStr)
  396. droppers := []func([]byte) error{
  397. db.dropFolder,
  398. db.dropMtimes,
  399. db.dropFolderMeta,
  400. db.folderIdx.Delete,
  401. }
  402. for _, drop := range droppers {
  403. if err := drop([]byte(folder)); backend.IsClosed(err) {
  404. return
  405. } else if err != nil {
  406. fatalError(err, opStr, db)
  407. }
  408. }
  409. }
  410. // DropDeltaIndexIDs removes all delta index IDs from the database.
  411. // This will cause a full index transmission on the next connection.
  412. func DropDeltaIndexIDs(db *Lowlevel) {
  413. opStr := "DropDeltaIndexIDs"
  414. l.Debugf(opStr)
  415. dbi, err := db.NewPrefixIterator([]byte{KeyTypeIndexID})
  416. if backend.IsClosed(err) {
  417. return
  418. } else if err != nil {
  419. fatalError(err, opStr, db)
  420. }
  421. defer dbi.Release()
  422. for dbi.Next() {
  423. if err := db.Delete(dbi.Key()); err != nil && !backend.IsClosed(err) {
  424. fatalError(err, opStr, db)
  425. }
  426. }
  427. if err := dbi.Error(); err != nil && !backend.IsClosed(err) {
  428. fatalError(err, opStr, db)
  429. }
  430. }
  431. func normalizeFilenamesAndDropDuplicates(fs []protocol.FileInfo) []protocol.FileInfo {
  432. positions := make(map[string]int, len(fs))
  433. for i, f := range fs {
  434. norm := osutil.NormalizedFilename(f.Name)
  435. if pos, ok := positions[norm]; ok {
  436. fs[pos] = protocol.FileInfo{}
  437. }
  438. positions[norm] = i
  439. fs[i].Name = norm
  440. }
  441. for i := 0; i < len(fs); {
  442. if fs[i].Name == "" {
  443. fs = append(fs[:i], fs[i+1:]...)
  444. continue
  445. }
  446. i++
  447. }
  448. return fs
  449. }
  450. func nativeFileIterator(fn Iterator) Iterator {
  451. return func(fi protocol.FileIntf) bool {
  452. switch f := fi.(type) {
  453. case protocol.FileInfo:
  454. f.Name = osutil.NativeFilename(f.Name)
  455. return fn(f)
  456. case FileInfoTruncated:
  457. f.Name = osutil.NativeFilename(f.Name)
  458. return fn(f)
  459. default:
  460. panic("unknown interface type")
  461. }
  462. }
  463. }
  464. func fatalError(err error, opStr string, db *Lowlevel) {
  465. if errors.Is(err, errEntryFromGlobalMissing) || errors.Is(err, errEmptyGlobal) {
  466. // Inconsistency error, mark db for repair on next start.
  467. if path := db.needsRepairPath(); path != "" {
  468. if fd, err := os.Create(path); err == nil {
  469. fd.Close()
  470. }
  471. }
  472. }
  473. l.Warnf("Fatal error: %v: %v", opStr, err)
  474. panic(err)
  475. }