set.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501
  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. func (s *Snapshot) WithBlocksHash(hash []byte, fn Iterator) {
  296. opStr := fmt.Sprintf(`%s WithBlocksHash("%x")`, s.folder, hash)
  297. l.Debugf(opStr)
  298. if err := s.t.withBlocksHash([]byte(s.folder), hash, nativeFileIterator(fn)); err != nil && !backend.IsClosed(err) {
  299. s.fatalError(err, opStr)
  300. }
  301. }
  302. func (s *FileSet) Sequence(device protocol.DeviceID) int64 {
  303. return s.meta.Sequence(device)
  304. }
  305. func (s *FileSet) IndexID(device protocol.DeviceID) protocol.IndexID {
  306. opStr := fmt.Sprintf("%s IndexID(%v)", s.folder, device)
  307. l.Debugf(opStr)
  308. id, err := s.db.getIndexID(device[:], []byte(s.folder))
  309. if backend.IsClosed(err) {
  310. return 0
  311. } else if err != nil {
  312. fatalError(err, opStr, s.db)
  313. }
  314. if id == 0 && device == protocol.LocalDeviceID {
  315. // No index ID set yet. We create one now.
  316. id = protocol.NewIndexID()
  317. err := s.db.setIndexID(device[:], []byte(s.folder), id)
  318. if backend.IsClosed(err) {
  319. return 0
  320. } else if err != nil {
  321. fatalError(err, opStr, s.db)
  322. }
  323. }
  324. return id
  325. }
  326. func (s *FileSet) SetIndexID(device protocol.DeviceID, id protocol.IndexID) {
  327. if device == protocol.LocalDeviceID {
  328. panic("do not explicitly set index ID for local device")
  329. }
  330. opStr := fmt.Sprintf("%s SetIndexID(%v, %v)", s.folder, device, id)
  331. l.Debugf(opStr)
  332. if err := s.db.setIndexID(device[:], []byte(s.folder), id); err != nil && !backend.IsClosed(err) {
  333. fatalError(err, opStr, s.db)
  334. }
  335. }
  336. func (s *FileSet) MtimeFS() *fs.MtimeFS {
  337. opStr := fmt.Sprintf("%s MtimeFS()", s.folder)
  338. l.Debugf(opStr)
  339. prefix, err := s.db.keyer.GenerateMtimesKey(nil, []byte(s.folder))
  340. if backend.IsClosed(err) {
  341. return nil
  342. } else if err != nil {
  343. fatalError(err, opStr, s.db)
  344. }
  345. kv := NewNamespacedKV(s.db, string(prefix))
  346. return fs.NewMtimeFS(s.fs, kv)
  347. }
  348. func (s *FileSet) ListDevices() []protocol.DeviceID {
  349. return s.meta.devices()
  350. }
  351. func (s *FileSet) RepairSequence() (int, error) {
  352. s.updateAndGCMutexLock() // Ensures consistent locking order
  353. defer s.updateMutex.Unlock()
  354. defer s.db.gcMut.RUnlock()
  355. return s.db.repairSequenceGCLocked(s.folder, s.meta)
  356. }
  357. func (s *FileSet) updateAndGCMutexLock() {
  358. s.updateMutex.Lock()
  359. s.db.gcMut.RLock()
  360. }
  361. // DropFolder clears out all information related to the given folder from the
  362. // database.
  363. func DropFolder(db *Lowlevel, folder string) {
  364. opStr := fmt.Sprintf("DropFolder(%v)", folder)
  365. l.Debugf(opStr)
  366. droppers := []func([]byte) error{
  367. db.dropFolder,
  368. db.dropMtimes,
  369. db.dropFolderMeta,
  370. db.folderIdx.Delete,
  371. }
  372. for _, drop := range droppers {
  373. if err := drop([]byte(folder)); backend.IsClosed(err) {
  374. return
  375. } else if err != nil {
  376. fatalError(err, opStr, db)
  377. }
  378. }
  379. }
  380. // DropDeltaIndexIDs removes all delta index IDs from the database.
  381. // This will cause a full index transmission on the next connection.
  382. func DropDeltaIndexIDs(db *Lowlevel) {
  383. opStr := "DropDeltaIndexIDs"
  384. l.Debugf(opStr)
  385. dbi, err := db.NewPrefixIterator([]byte{KeyTypeIndexID})
  386. if backend.IsClosed(err) {
  387. return
  388. } else if err != nil {
  389. fatalError(err, opStr, db)
  390. }
  391. defer dbi.Release()
  392. for dbi.Next() {
  393. if err := db.Delete(dbi.Key()); err != nil && !backend.IsClosed(err) {
  394. fatalError(err, opStr, db)
  395. }
  396. }
  397. if err := dbi.Error(); err != nil && !backend.IsClosed(err) {
  398. fatalError(err, opStr, db)
  399. }
  400. }
  401. func normalizeFilenamesAndDropDuplicates(fs []protocol.FileInfo) []protocol.FileInfo {
  402. positions := make(map[string]int, len(fs))
  403. for i, f := range fs {
  404. norm := osutil.NormalizedFilename(f.Name)
  405. if pos, ok := positions[norm]; ok {
  406. fs[pos] = protocol.FileInfo{}
  407. }
  408. positions[norm] = i
  409. fs[i].Name = norm
  410. }
  411. for i := 0; i < len(fs); {
  412. if fs[i].Name == "" {
  413. fs = append(fs[:i], fs[i+1:]...)
  414. continue
  415. }
  416. i++
  417. }
  418. return fs
  419. }
  420. func nativeFileIterator(fn Iterator) Iterator {
  421. return func(fi protocol.FileIntf) bool {
  422. switch f := fi.(type) {
  423. case protocol.FileInfo:
  424. f.Name = osutil.NativeFilename(f.Name)
  425. return fn(f)
  426. case FileInfoTruncated:
  427. f.Name = osutil.NativeFilename(f.Name)
  428. return fn(f)
  429. default:
  430. panic("unknown interface type")
  431. }
  432. }
  433. }
  434. func fatalError(err error, opStr string, db *Lowlevel) {
  435. if errors.Is(err, errEntryFromGlobalMissing) || errors.Is(err, errEmptyGlobal) {
  436. // Inconsistency error, mark db for repair on next start.
  437. if path := db.needsRepairPath(); path != "" {
  438. if fd, err := os.Create(path); err == nil {
  439. fd.Close()
  440. }
  441. }
  442. }
  443. l.Warnf("Fatal error: %v: %v", opStr, err)
  444. obfuscateAndPanic(err)
  445. }