set.go 15 KB

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