set.go 15 KB

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