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. "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, error) {
  135. opStr := fmt.Sprintf("%s Snapshot()", s.folder)
  136. l.Debugf(opStr)
  137. t, err := s.db.newReadOnlyTransaction()
  138. if err != nil {
  139. s.db.handleFailure(err)
  140. return nil, err
  141. }
  142. return &Snapshot{
  143. folder: s.folder,
  144. t: t,
  145. meta: s.meta.Snapshot(),
  146. fatalError: func(err error, opStr string) {
  147. fatalError(err, opStr, s.db)
  148. },
  149. }, nil
  150. }
  151. func (s *Snapshot) Release() {
  152. s.t.close()
  153. }
  154. func (s *Snapshot) WithNeed(device protocol.DeviceID, fn Iterator) {
  155. opStr := fmt.Sprintf("%s WithNeed(%v)", s.folder, device)
  156. l.Debugf(opStr)
  157. if err := s.t.withNeed([]byte(s.folder), device[:], false, nativeFileIterator(fn)); err != nil && !backend.IsClosed(err) {
  158. s.fatalError(err, opStr)
  159. }
  160. }
  161. func (s *Snapshot) WithNeedTruncated(device protocol.DeviceID, fn Iterator) {
  162. opStr := fmt.Sprintf("%s WithNeedTruncated(%v)", s.folder, device)
  163. l.Debugf(opStr)
  164. if err := s.t.withNeed([]byte(s.folder), device[:], true, nativeFileIterator(fn)); err != nil && !backend.IsClosed(err) {
  165. s.fatalError(err, opStr)
  166. }
  167. }
  168. func (s *Snapshot) WithHave(device protocol.DeviceID, fn Iterator) {
  169. opStr := fmt.Sprintf("%s WithHave(%v)", s.folder, device)
  170. l.Debugf(opStr)
  171. if err := s.t.withHave([]byte(s.folder), device[:], nil, false, nativeFileIterator(fn)); err != nil && !backend.IsClosed(err) {
  172. s.fatalError(err, opStr)
  173. }
  174. }
  175. func (s *Snapshot) WithHaveTruncated(device protocol.DeviceID, fn Iterator) {
  176. opStr := fmt.Sprintf("%s WithHaveTruncated(%v)", s.folder, device)
  177. l.Debugf(opStr)
  178. if err := s.t.withHave([]byte(s.folder), device[:], nil, true, nativeFileIterator(fn)); err != nil && !backend.IsClosed(err) {
  179. s.fatalError(err, opStr)
  180. }
  181. }
  182. func (s *Snapshot) WithHaveSequence(startSeq int64, fn Iterator) {
  183. opStr := fmt.Sprintf("%s WithHaveSequence(%v)", s.folder, startSeq)
  184. l.Debugf(opStr)
  185. if err := s.t.withHaveSequence([]byte(s.folder), startSeq, nativeFileIterator(fn)); err != nil && !backend.IsClosed(err) {
  186. s.fatalError(err, opStr)
  187. }
  188. }
  189. // Except for an item with a path equal to prefix, only children of prefix are iterated.
  190. // E.g. for prefix "dir", "dir/file" is iterated, but "dir.file" is not.
  191. func (s *Snapshot) WithPrefixedHaveTruncated(device protocol.DeviceID, prefix string, fn Iterator) {
  192. opStr := fmt.Sprintf(`%s WithPrefixedHaveTruncated(%v, "%v")`, s.folder, device, prefix)
  193. l.Debugf(opStr)
  194. if err := s.t.withHave([]byte(s.folder), device[:], []byte(osutil.NormalizedFilename(prefix)), true, nativeFileIterator(fn)); err != nil && !backend.IsClosed(err) {
  195. s.fatalError(err, opStr)
  196. }
  197. }
  198. func (s *Snapshot) WithGlobal(fn Iterator) {
  199. opStr := fmt.Sprintf("%s WithGlobal()", s.folder)
  200. l.Debugf(opStr)
  201. if err := s.t.withGlobal([]byte(s.folder), nil, false, nativeFileIterator(fn)); err != nil && !backend.IsClosed(err) {
  202. s.fatalError(err, opStr)
  203. }
  204. }
  205. func (s *Snapshot) WithGlobalTruncated(fn Iterator) {
  206. opStr := fmt.Sprintf("%s WithGlobalTruncated()", s.folder)
  207. l.Debugf(opStr)
  208. if err := s.t.withGlobal([]byte(s.folder), nil, true, nativeFileIterator(fn)); err != nil && !backend.IsClosed(err) {
  209. s.fatalError(err, opStr)
  210. }
  211. }
  212. // Except for an item with a path equal to prefix, only children of prefix are iterated.
  213. // E.g. for prefix "dir", "dir/file" is iterated, but "dir.file" is not.
  214. func (s *Snapshot) WithPrefixedGlobalTruncated(prefix string, fn Iterator) {
  215. opStr := fmt.Sprintf(`%s WithPrefixedGlobalTruncated("%v")`, s.folder, prefix)
  216. l.Debugf(opStr)
  217. if err := s.t.withGlobal([]byte(s.folder), []byte(osutil.NormalizedFilename(prefix)), true, nativeFileIterator(fn)); err != nil && !backend.IsClosed(err) {
  218. s.fatalError(err, opStr)
  219. }
  220. }
  221. func (s *Snapshot) Get(device protocol.DeviceID, file string) (protocol.FileInfo, bool) {
  222. opStr := fmt.Sprintf("%s Get(%v)", s.folder, file)
  223. l.Debugf(opStr)
  224. f, ok, err := s.t.getFile([]byte(s.folder), device[:], []byte(osutil.NormalizedFilename(file)))
  225. if backend.IsClosed(err) {
  226. return protocol.FileInfo{}, false
  227. } else if err != nil {
  228. s.fatalError(err, opStr)
  229. }
  230. f.Name = osutil.NativeFilename(f.Name)
  231. return f, ok
  232. }
  233. func (s *Snapshot) GetGlobal(file string) (protocol.FileInfo, bool) {
  234. opStr := fmt.Sprintf("%s GetGlobal(%v)", s.folder, file)
  235. l.Debugf(opStr)
  236. _, fi, ok, err := s.t.getGlobal(nil, []byte(s.folder), []byte(osutil.NormalizedFilename(file)), false)
  237. if backend.IsClosed(err) {
  238. return protocol.FileInfo{}, false
  239. } else if err != nil {
  240. s.fatalError(err, opStr)
  241. }
  242. if !ok {
  243. return protocol.FileInfo{}, false
  244. }
  245. f := fi.(protocol.FileInfo)
  246. f.Name = osutil.NativeFilename(f.Name)
  247. return f, true
  248. }
  249. func (s *Snapshot) GetGlobalTruncated(file string) (FileInfoTruncated, bool) {
  250. opStr := fmt.Sprintf("%s GetGlobalTruncated(%v)", s.folder, file)
  251. l.Debugf(opStr)
  252. _, fi, ok, err := s.t.getGlobal(nil, []byte(s.folder), []byte(osutil.NormalizedFilename(file)), true)
  253. if backend.IsClosed(err) {
  254. return FileInfoTruncated{}, false
  255. } else if err != nil {
  256. s.fatalError(err, opStr)
  257. }
  258. if !ok {
  259. return FileInfoTruncated{}, false
  260. }
  261. f := fi.(FileInfoTruncated)
  262. f.Name = osutil.NativeFilename(f.Name)
  263. return f, true
  264. }
  265. func (s *Snapshot) Availability(file string) []protocol.DeviceID {
  266. opStr := fmt.Sprintf("%s Availability(%v)", s.folder, file)
  267. l.Debugf(opStr)
  268. av, err := s.t.availability([]byte(s.folder), []byte(osutil.NormalizedFilename(file)))
  269. if backend.IsClosed(err) {
  270. return nil
  271. } else if err != nil {
  272. s.fatalError(err, opStr)
  273. }
  274. return av
  275. }
  276. func (s *Snapshot) DebugGlobalVersions(file string) VersionList {
  277. opStr := fmt.Sprintf("%s DebugGlobalVersions(%v)", s.folder, file)
  278. l.Debugf(opStr)
  279. vl, err := s.t.getGlobalVersions(nil, []byte(s.folder), []byte(osutil.NormalizedFilename(file)))
  280. if backend.IsClosed(err) || backend.IsNotFound(err) {
  281. return VersionList{}
  282. } else if err != nil {
  283. s.fatalError(err, opStr)
  284. }
  285. return vl
  286. }
  287. func (s *Snapshot) Sequence(device protocol.DeviceID) int64 {
  288. return s.meta.Counts(device, 0).Sequence
  289. }
  290. // RemoteSequence returns the change version for the given folder, as
  291. // sent by remote peers. This is guaranteed to increment if the contents of
  292. // the remote or global folder has changed.
  293. func (s *Snapshot) RemoteSequence() int64 {
  294. var ver int64
  295. for _, device := range s.meta.devices() {
  296. ver += s.Sequence(device)
  297. }
  298. return ver
  299. }
  300. func (s *Snapshot) LocalSize() Counts {
  301. local := s.meta.Counts(protocol.LocalDeviceID, 0)
  302. return local.Add(s.ReceiveOnlyChangedSize())
  303. }
  304. func (s *Snapshot) ReceiveOnlyChangedSize() Counts {
  305. return s.meta.Counts(protocol.LocalDeviceID, protocol.FlagLocalReceiveOnly)
  306. }
  307. func (s *Snapshot) GlobalSize() Counts {
  308. return s.meta.Counts(protocol.GlobalDeviceID, 0)
  309. }
  310. func (s *Snapshot) NeedSize(device protocol.DeviceID) Counts {
  311. return s.meta.Counts(device, needFlag)
  312. }
  313. func (s *Snapshot) WithBlocksHash(hash []byte, fn Iterator) {
  314. opStr := fmt.Sprintf(`%s WithBlocksHash("%x")`, s.folder, hash)
  315. l.Debugf(opStr)
  316. if err := s.t.withBlocksHash([]byte(s.folder), hash, nativeFileIterator(fn)); err != nil && !backend.IsClosed(err) {
  317. s.fatalError(err, opStr)
  318. }
  319. }
  320. func (s *FileSet) Sequence(device protocol.DeviceID) int64 {
  321. return s.meta.Sequence(device)
  322. }
  323. func (s *FileSet) IndexID(device protocol.DeviceID) protocol.IndexID {
  324. opStr := fmt.Sprintf("%s IndexID(%v)", s.folder, device)
  325. l.Debugf(opStr)
  326. id, err := s.db.getIndexID(device[:], []byte(s.folder))
  327. if backend.IsClosed(err) {
  328. return 0
  329. } else if err != nil {
  330. fatalError(err, opStr, s.db)
  331. }
  332. return id
  333. }
  334. func (s *FileSet) SetIndexID(device protocol.DeviceID, id protocol.IndexID) {
  335. if device == protocol.LocalDeviceID {
  336. panic("do not explicitly set index ID for local device")
  337. }
  338. opStr := fmt.Sprintf("%s SetIndexID(%v, %v)", s.folder, device, id)
  339. l.Debugf(opStr)
  340. if err := s.db.setIndexID(device[:], []byte(s.folder), id); err != nil && !backend.IsClosed(err) {
  341. fatalError(err, opStr, s.db)
  342. }
  343. }
  344. func (s *FileSet) MtimeFS() fs.Filesystem {
  345. opStr := fmt.Sprintf("%s MtimeFS()", s.folder)
  346. l.Debugf(opStr)
  347. prefix, err := s.db.keyer.GenerateMtimesKey(nil, []byte(s.folder))
  348. if backend.IsClosed(err) {
  349. return nil
  350. } else if err != nil {
  351. fatalError(err, opStr, s.db)
  352. }
  353. kv := NewNamespacedKV(s.db, string(prefix))
  354. return fs.NewMtimeFS(s.fs, kv)
  355. }
  356. func (s *FileSet) ListDevices() []protocol.DeviceID {
  357. return s.meta.devices()
  358. }
  359. func (s *FileSet) RepairSequence() (int, error) {
  360. s.updateAndGCMutexLock() // Ensures consistent locking order
  361. defer s.updateMutex.Unlock()
  362. defer s.db.gcMut.RUnlock()
  363. return s.db.repairSequenceGCLocked(s.folder, s.meta)
  364. }
  365. func (s *FileSet) updateAndGCMutexLock() {
  366. s.updateMutex.Lock()
  367. s.db.gcMut.RLock()
  368. }
  369. // DropFolder clears out all information related to the given folder from the
  370. // database.
  371. func DropFolder(db *Lowlevel, folder string) {
  372. opStr := fmt.Sprintf("DropFolder(%v)", folder)
  373. l.Debugf(opStr)
  374. droppers := []func([]byte) error{
  375. db.dropFolder,
  376. db.dropMtimes,
  377. db.dropFolderMeta,
  378. db.dropFolderIndexIDs,
  379. db.folderIdx.Delete,
  380. }
  381. for _, drop := range droppers {
  382. if err := drop([]byte(folder)); backend.IsClosed(err) {
  383. return
  384. } else if err != nil {
  385. fatalError(err, opStr, db)
  386. }
  387. }
  388. }
  389. // DropDeltaIndexIDs removes all delta index IDs from the database.
  390. // This will cause a full index transmission on the next connection.
  391. // Must be called before using FileSets, i.e. before NewFileSet is called for
  392. // the first time.
  393. func DropDeltaIndexIDs(db *Lowlevel) {
  394. select {
  395. case <-db.oneFileSetCreated:
  396. panic("DropDeltaIndexIDs must not be called after NewFileSet for the same Lowlevel")
  397. default:
  398. }
  399. opStr := "DropDeltaIndexIDs"
  400. l.Debugf(opStr)
  401. err := db.dropIndexIDs()
  402. if backend.IsClosed(err) {
  403. return
  404. } else if err != nil {
  405. fatalError(err, opStr, db)
  406. }
  407. }
  408. func normalizeFilenamesAndDropDuplicates(fs []protocol.FileInfo) []protocol.FileInfo {
  409. positions := make(map[string]int, len(fs))
  410. for i, f := range fs {
  411. norm := osutil.NormalizedFilename(f.Name)
  412. if pos, ok := positions[norm]; ok {
  413. fs[pos] = protocol.FileInfo{}
  414. }
  415. positions[norm] = i
  416. fs[i].Name = norm
  417. }
  418. for i := 0; i < len(fs); {
  419. if fs[i].Name == "" {
  420. fs = append(fs[:i], fs[i+1:]...)
  421. continue
  422. }
  423. i++
  424. }
  425. return fs
  426. }
  427. func nativeFileIterator(fn Iterator) Iterator {
  428. return func(fi protocol.FileIntf) bool {
  429. switch f := fi.(type) {
  430. case protocol.FileInfo:
  431. f.Name = osutil.NativeFilename(f.Name)
  432. return fn(f)
  433. case FileInfoTruncated:
  434. f.Name = osutil.NativeFilename(f.Name)
  435. return fn(f)
  436. default:
  437. panic("unknown interface type")
  438. }
  439. }
  440. }
  441. func fatalError(err error, opStr string, db *Lowlevel) {
  442. db.checkErrorForRepair(err)
  443. l.Warnf("Fatal error: %v: %v", opStr, err)
  444. panic(ldbPathRe.ReplaceAllString(err.Error(), "$1 x: "))
  445. }