set.go 15 KB

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