set.go 16 KB

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