set.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553
  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. "bytes"
  15. "fmt"
  16. "github.com/syncthing/syncthing/internal/gen/dbproto"
  17. "github.com/syncthing/syncthing/lib/db/backend"
  18. "github.com/syncthing/syncthing/lib/fs"
  19. "github.com/syncthing/syncthing/lib/osutil"
  20. "github.com/syncthing/syncthing/lib/protocol"
  21. "github.com/syncthing/syncthing/lib/sync"
  22. )
  23. type FileSet struct {
  24. folder string
  25. db *Lowlevel
  26. meta *metadataTracker
  27. updateMutex sync.Mutex // protects database updates and the corresponding metadata changes
  28. }
  29. // The Iterator is called with either a protocol.FileInfo or a
  30. // FileInfoTruncated (depending on the method) and returns true to
  31. // continue iteration, false to stop.
  32. type Iterator func(f protocol.FileInfo) bool
  33. func NewFileSet(folder string, db *Lowlevel) (*FileSet, error) {
  34. select {
  35. case <-db.oneFileSetCreated:
  36. default:
  37. close(db.oneFileSetCreated)
  38. }
  39. meta, err := db.loadMetadataTracker(folder)
  40. if err != nil {
  41. db.handleFailure(err)
  42. return nil, err
  43. }
  44. s := &FileSet{
  45. folder: folder,
  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. s.updateMutex.Lock()
  150. defer s.updateMutex.Unlock()
  151. t, err := s.db.newReadOnlyTransaction()
  152. if err != nil {
  153. s.db.handleFailure(err)
  154. return nil, err
  155. }
  156. return &Snapshot{
  157. folder: s.folder,
  158. t: t,
  159. meta: s.meta.Snapshot(),
  160. fatalError: func(err error, opStr string) {
  161. fatalError(err, opStr, s.db)
  162. },
  163. }, nil
  164. }
  165. func (s *Snapshot) Release() {
  166. s.t.close()
  167. }
  168. func (s *Snapshot) WithNeed(device protocol.DeviceID, fn Iterator) {
  169. opStr := fmt.Sprintf("%s WithNeed(%v)", s.folder, device)
  170. l.Debugf(opStr)
  171. if err := s.t.withNeed([]byte(s.folder), device[:], false, nativeFileIterator(fn)); err != nil && !backend.IsClosed(err) {
  172. s.fatalError(err, opStr)
  173. }
  174. }
  175. func (s *Snapshot) WithNeedTruncated(device protocol.DeviceID, fn Iterator) {
  176. opStr := fmt.Sprintf("%s WithNeedTruncated(%v)", s.folder, device)
  177. l.Debugf(opStr)
  178. if err := s.t.withNeed([]byte(s.folder), device[:], true, nativeFileIterator(fn)); err != nil && !backend.IsClosed(err) {
  179. s.fatalError(err, opStr)
  180. }
  181. }
  182. func (s *Snapshot) WithHave(device protocol.DeviceID, fn Iterator) {
  183. opStr := fmt.Sprintf("%s WithHave(%v)", s.folder, device)
  184. l.Debugf(opStr)
  185. if err := s.t.withHave([]byte(s.folder), device[:], nil, false, nativeFileIterator(fn)); err != nil && !backend.IsClosed(err) {
  186. s.fatalError(err, opStr)
  187. }
  188. }
  189. func (s *Snapshot) WithHaveTruncated(device protocol.DeviceID, fn Iterator) {
  190. opStr := fmt.Sprintf("%s WithHaveTruncated(%v)", s.folder, device)
  191. l.Debugf(opStr)
  192. if err := s.t.withHave([]byte(s.folder), device[:], nil, true, nativeFileIterator(fn)); err != nil && !backend.IsClosed(err) {
  193. s.fatalError(err, opStr)
  194. }
  195. }
  196. func (s *Snapshot) WithHaveSequence(startSeq int64, fn Iterator) {
  197. opStr := fmt.Sprintf("%s WithHaveSequence(%v)", s.folder, startSeq)
  198. l.Debugf(opStr)
  199. if err := s.t.withHaveSequence([]byte(s.folder), startSeq, nativeFileIterator(fn)); err != nil && !backend.IsClosed(err) {
  200. s.fatalError(err, opStr)
  201. }
  202. }
  203. // Except for an item with a path equal to prefix, only children of prefix are iterated.
  204. // E.g. for prefix "dir", "dir/file" is iterated, but "dir.file" is not.
  205. func (s *Snapshot) WithPrefixedHaveTruncated(device protocol.DeviceID, prefix string, fn Iterator) {
  206. opStr := fmt.Sprintf(`%s WithPrefixedHaveTruncated(%v, "%v")`, s.folder, device, prefix)
  207. l.Debugf(opStr)
  208. if err := s.t.withHave([]byte(s.folder), device[:], []byte(osutil.NormalizedFilename(prefix)), true, nativeFileIterator(fn)); err != nil && !backend.IsClosed(err) {
  209. s.fatalError(err, opStr)
  210. }
  211. }
  212. func (s *Snapshot) WithGlobal(fn Iterator) {
  213. opStr := fmt.Sprintf("%s WithGlobal()", s.folder)
  214. l.Debugf(opStr)
  215. if err := s.t.withGlobal([]byte(s.folder), nil, false, nativeFileIterator(fn)); err != nil && !backend.IsClosed(err) {
  216. s.fatalError(err, opStr)
  217. }
  218. }
  219. func (s *Snapshot) WithGlobalTruncated(fn Iterator) {
  220. opStr := fmt.Sprintf("%s WithGlobalTruncated()", s.folder)
  221. l.Debugf(opStr)
  222. if err := s.t.withGlobal([]byte(s.folder), nil, true, nativeFileIterator(fn)); err != nil && !backend.IsClosed(err) {
  223. s.fatalError(err, opStr)
  224. }
  225. }
  226. // Except for an item with a path equal to prefix, only children of prefix are iterated.
  227. // E.g. for prefix "dir", "dir/file" is iterated, but "dir.file" is not.
  228. func (s *Snapshot) WithPrefixedGlobalTruncated(prefix string, fn Iterator) {
  229. opStr := fmt.Sprintf(`%s WithPrefixedGlobalTruncated("%v")`, s.folder, prefix)
  230. l.Debugf(opStr)
  231. if err := s.t.withGlobal([]byte(s.folder), []byte(osutil.NormalizedFilename(prefix)), true, nativeFileIterator(fn)); err != nil && !backend.IsClosed(err) {
  232. s.fatalError(err, opStr)
  233. }
  234. }
  235. func (s *Snapshot) Get(device protocol.DeviceID, file string) (protocol.FileInfo, bool) {
  236. opStr := fmt.Sprintf("%s Get(%v)", s.folder, file)
  237. l.Debugf(opStr)
  238. f, ok, err := s.t.getFile([]byte(s.folder), device[:], []byte(osutil.NormalizedFilename(file)))
  239. if backend.IsClosed(err) {
  240. return protocol.FileInfo{}, false
  241. } else if err != nil {
  242. s.fatalError(err, opStr)
  243. }
  244. f.Name = osutil.NativeFilename(f.Name)
  245. return f, ok
  246. }
  247. func (s *Snapshot) GetGlobal(file string) (protocol.FileInfo, bool) {
  248. opStr := fmt.Sprintf("%s GetGlobal(%v)", s.folder, file)
  249. l.Debugf(opStr)
  250. _, fi, ok, err := s.t.getGlobal(nil, []byte(s.folder), []byte(osutil.NormalizedFilename(file)), false)
  251. if backend.IsClosed(err) {
  252. return protocol.FileInfo{}, false
  253. } else if err != nil {
  254. s.fatalError(err, opStr)
  255. }
  256. if !ok {
  257. return protocol.FileInfo{}, false
  258. }
  259. fi.Name = osutil.NativeFilename(fi.Name)
  260. return fi, true
  261. }
  262. func (s *Snapshot) GetGlobalTruncated(file string) (protocol.FileInfo, bool) {
  263. opStr := fmt.Sprintf("%s GetGlobalTruncated(%v)", s.folder, file)
  264. l.Debugf(opStr)
  265. _, fi, ok, err := s.t.getGlobal(nil, []byte(s.folder), []byte(osutil.NormalizedFilename(file)), true)
  266. if backend.IsClosed(err) {
  267. return protocol.FileInfo{}, false
  268. } else if err != nil {
  269. s.fatalError(err, opStr)
  270. }
  271. if !ok {
  272. return protocol.FileInfo{}, false
  273. }
  274. fi.Name = osutil.NativeFilename(fi.Name)
  275. return fi, 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) *DebugVersionList {
  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 nil
  294. } else if err != nil {
  295. s.fatalError(err, opStr)
  296. }
  297. return &DebugVersionList{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.FileInfo) bool {
  447. fi.Name = osutil.NativeFilename(fi.Name)
  448. return fn(fi)
  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. }
  456. // DebugFileVersion is the database-internal representation of a file
  457. // version, with a nicer string representation, used only by API debug
  458. // methods.
  459. type DebugVersionList struct {
  460. *dbproto.VersionList
  461. }
  462. func (vl DebugVersionList) String() string {
  463. var b bytes.Buffer
  464. var id protocol.DeviceID
  465. b.WriteString("[")
  466. for i, v := range vl.Versions {
  467. if i > 0 {
  468. b.WriteString(", ")
  469. }
  470. fmt.Fprintf(&b, "{Version:%v, Deleted:%v, Devices:[", protocol.VectorFromWire(v.Version), v.Deleted)
  471. for j, dev := range v.Devices {
  472. if j > 0 {
  473. b.WriteString(", ")
  474. }
  475. copy(id[:], dev)
  476. fmt.Fprint(&b, id.Short())
  477. }
  478. b.WriteString("], Invalid:[")
  479. for j, dev := range v.InvalidDevices {
  480. if j > 0 {
  481. b.WriteString(", ")
  482. }
  483. copy(id[:], dev)
  484. fmt.Fprint(&b, id.Short())
  485. }
  486. fmt.Fprint(&b, "]}")
  487. }
  488. b.WriteString("]")
  489. return b.String()
  490. }