set.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524
  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. s.updateMutex.Lock()
  148. defer s.updateMutex.Unlock()
  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. // RemoteSequences returns a map of the sequence numbers seen for each
  303. // remote device sharing this folder.
  304. func (s *Snapshot) RemoteSequences() map[protocol.DeviceID]int64 {
  305. res := make(map[protocol.DeviceID]int64)
  306. for _, device := range s.meta.devices() {
  307. switch device {
  308. case protocol.EmptyDeviceID, protocol.LocalDeviceID, protocol.GlobalDeviceID:
  309. continue
  310. default:
  311. if seq := s.Sequence(device); seq > 0 {
  312. res[device] = seq
  313. }
  314. }
  315. }
  316. return res
  317. }
  318. func (s *Snapshot) LocalSize() Counts {
  319. local := s.meta.Counts(protocol.LocalDeviceID, 0)
  320. return local.Add(s.ReceiveOnlyChangedSize())
  321. }
  322. func (s *Snapshot) ReceiveOnlyChangedSize() Counts {
  323. return s.meta.Counts(protocol.LocalDeviceID, protocol.FlagLocalReceiveOnly)
  324. }
  325. func (s *Snapshot) GlobalSize() Counts {
  326. return s.meta.Counts(protocol.GlobalDeviceID, 0)
  327. }
  328. func (s *Snapshot) NeedSize(device protocol.DeviceID) Counts {
  329. return s.meta.Counts(device, needFlag)
  330. }
  331. func (s *Snapshot) WithBlocksHash(hash []byte, fn Iterator) {
  332. opStr := fmt.Sprintf(`%s WithBlocksHash("%x")`, s.folder, hash)
  333. l.Debugf(opStr)
  334. if err := s.t.withBlocksHash([]byte(s.folder), hash, nativeFileIterator(fn)); err != nil && !backend.IsClosed(err) {
  335. s.fatalError(err, opStr)
  336. }
  337. }
  338. func (s *FileSet) Sequence(device protocol.DeviceID) int64 {
  339. return s.meta.Sequence(device)
  340. }
  341. func (s *FileSet) IndexID(device protocol.DeviceID) protocol.IndexID {
  342. opStr := fmt.Sprintf("%s IndexID(%v)", s.folder, device)
  343. l.Debugf(opStr)
  344. id, err := s.db.getIndexID(device[:], []byte(s.folder))
  345. if backend.IsClosed(err) {
  346. return 0
  347. } else if err != nil {
  348. fatalError(err, opStr, s.db)
  349. }
  350. return id
  351. }
  352. func (s *FileSet) SetIndexID(device protocol.DeviceID, id protocol.IndexID) {
  353. if device == protocol.LocalDeviceID {
  354. panic("do not explicitly set index ID for local device")
  355. }
  356. opStr := fmt.Sprintf("%s SetIndexID(%v, %v)", s.folder, device, id)
  357. l.Debugf(opStr)
  358. if err := s.db.setIndexID(device[:], []byte(s.folder), id); err != nil && !backend.IsClosed(err) {
  359. fatalError(err, opStr, s.db)
  360. }
  361. }
  362. func (s *FileSet) MtimeOption() fs.Option {
  363. opStr := fmt.Sprintf("%s MtimeOption()", s.folder)
  364. l.Debugf(opStr)
  365. prefix, err := s.db.keyer.GenerateMtimesKey(nil, []byte(s.folder))
  366. if backend.IsClosed(err) {
  367. return nil
  368. } else if err != nil {
  369. fatalError(err, opStr, s.db)
  370. }
  371. kv := NewNamespacedKV(s.db, string(prefix))
  372. return fs.NewMtimeOption(kv)
  373. }
  374. func (s *FileSet) ListDevices() []protocol.DeviceID {
  375. return s.meta.devices()
  376. }
  377. func (s *FileSet) RepairSequence() (int, error) {
  378. s.updateAndGCMutexLock() // Ensures consistent locking order
  379. defer s.updateMutex.Unlock()
  380. defer s.db.gcMut.RUnlock()
  381. return s.db.repairSequenceGCLocked(s.folder, s.meta)
  382. }
  383. func (s *FileSet) updateAndGCMutexLock() {
  384. s.updateMutex.Lock()
  385. s.db.gcMut.RLock()
  386. }
  387. // DropFolder clears out all information related to the given folder from the
  388. // database.
  389. func DropFolder(db *Lowlevel, folder string) {
  390. opStr := fmt.Sprintf("DropFolder(%v)", folder)
  391. l.Debugf(opStr)
  392. droppers := []func([]byte) error{
  393. db.dropFolder,
  394. db.dropMtimes,
  395. db.dropFolderMeta,
  396. db.dropFolderIndexIDs,
  397. db.folderIdx.Delete,
  398. }
  399. for _, drop := range droppers {
  400. if err := drop([]byte(folder)); backend.IsClosed(err) {
  401. return
  402. } else if err != nil {
  403. fatalError(err, opStr, db)
  404. }
  405. }
  406. }
  407. // DropDeltaIndexIDs removes all delta index IDs from the database.
  408. // This will cause a full index transmission on the next connection.
  409. // Must be called before using FileSets, i.e. before NewFileSet is called for
  410. // the first time.
  411. func DropDeltaIndexIDs(db *Lowlevel) {
  412. select {
  413. case <-db.oneFileSetCreated:
  414. panic("DropDeltaIndexIDs must not be called after NewFileSet for the same Lowlevel")
  415. default:
  416. }
  417. opStr := "DropDeltaIndexIDs"
  418. l.Debugf(opStr)
  419. err := db.dropIndexIDs()
  420. if backend.IsClosed(err) {
  421. return
  422. } else if err != nil {
  423. fatalError(err, opStr, db)
  424. }
  425. }
  426. func normalizeFilenamesAndDropDuplicates(fs []protocol.FileInfo) []protocol.FileInfo {
  427. positions := make(map[string]int, len(fs))
  428. for i, f := range fs {
  429. norm := osutil.NormalizedFilename(f.Name)
  430. if pos, ok := positions[norm]; ok {
  431. fs[pos] = protocol.FileInfo{}
  432. }
  433. positions[norm] = i
  434. fs[i].Name = norm
  435. }
  436. for i := 0; i < len(fs); {
  437. if fs[i].Name == "" {
  438. fs = append(fs[:i], fs[i+1:]...)
  439. continue
  440. }
  441. i++
  442. }
  443. return fs
  444. }
  445. func nativeFileIterator(fn Iterator) Iterator {
  446. return func(fi protocol.FileIntf) bool {
  447. switch f := fi.(type) {
  448. case protocol.FileInfo:
  449. f.Name = osutil.NativeFilename(f.Name)
  450. return fn(f)
  451. case FileInfoTruncated:
  452. f.Name = osutil.NativeFilename(f.Name)
  453. return fn(f)
  454. default:
  455. panic("unknown interface type")
  456. }
  457. }
  458. }
  459. func fatalError(err error, opStr string, db *Lowlevel) {
  460. db.checkErrorForRepair(err)
  461. l.Warnf("Fatal error: %v: %v", opStr, err)
  462. panic(ldbPathRe.ReplaceAllString(err.Error(), "$1 x: "))
  463. }