folder_recvonly.go 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209
  1. // Copyright (C) 2018 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 model
  7. import (
  8. "sort"
  9. "time"
  10. "github.com/syncthing/syncthing/lib/config"
  11. "github.com/syncthing/syncthing/lib/db"
  12. "github.com/syncthing/syncthing/lib/events"
  13. "github.com/syncthing/syncthing/lib/fs"
  14. "github.com/syncthing/syncthing/lib/ignore"
  15. "github.com/syncthing/syncthing/lib/protocol"
  16. "github.com/syncthing/syncthing/lib/versioner"
  17. )
  18. func init() {
  19. folderFactories[config.FolderTypeReceiveOnly] = newReceiveOnlyFolder
  20. }
  21. /*
  22. receiveOnlyFolder is a folder that does not propagate local changes outward.
  23. It does this by the following general mechanism (not all of which is
  24. implemted in this file):
  25. - Local changes are scanned and versioned as usual, but get the
  26. FlagLocalReceiveOnly bit set.
  27. - When changes are sent to the cluster this bit gets converted to the
  28. Invalid bit (like all other local flags, currently) and also the Version
  29. gets set to the empty version. The reason for clearing the Version is to
  30. ensure that other devices will not consider themselves out of date due to
  31. our change.
  32. - The database layer accounts sizes per flag bit, so we can know how many
  33. files have been changed locally. We use this to trigger a "Revert" option
  34. on the folder when the amount of locally changed data is nonzero.
  35. - To revert we take the files which have changed and reset their version
  36. counter down to zero. The next pull will replace our changed version with
  37. the globally latest. As this is a user-initiated operation we do not cause
  38. conflict copies when reverting.
  39. - When pulling normally (i.e., not in the revert case) with local changes,
  40. normal conflict resolution will apply. Conflict copies will be created,
  41. but not propagated outwards (because receive only, right).
  42. Implementation wise a receiveOnlyFolder is just a sendReceiveFolder that
  43. sets an extra bit on local changes and has a Revert method.
  44. */
  45. type receiveOnlyFolder struct {
  46. *sendReceiveFolder
  47. }
  48. func newReceiveOnlyFolder(model *model, fset *db.FileSet, ignores *ignore.Matcher, cfg config.FolderConfiguration, ver versioner.Versioner, fs fs.Filesystem, evLogger events.Logger, ioLimiter *byteSemaphore) service {
  49. sr := newSendReceiveFolder(model, fset, ignores, cfg, ver, fs, evLogger, ioLimiter).(*sendReceiveFolder)
  50. sr.localFlags = protocol.FlagLocalReceiveOnly // gets propagated to the scanner, and set on locally changed files
  51. return &receiveOnlyFolder{sr}
  52. }
  53. func (f *receiveOnlyFolder) Revert() {
  54. l.Infof("Reverting folder %v", f.Description)
  55. f.setState(FolderScanning)
  56. defer f.setState(FolderIdle)
  57. scanChan := make(chan string)
  58. go f.pullScannerRoutine(scanChan)
  59. defer close(scanChan)
  60. delQueue := &deleteQueue{
  61. handler: f, // for the deleteItemOnDisk and deleteDirOnDisk methods
  62. ignores: f.ignores,
  63. scanChan: scanChan,
  64. }
  65. batch := make([]protocol.FileInfo, 0, maxBatchSizeFiles)
  66. batchSizeBytes := 0
  67. snap := f.fset.Snapshot()
  68. defer snap.Release()
  69. snap.WithHave(protocol.LocalDeviceID, func(intf db.FileIntf) bool {
  70. fi := intf.(protocol.FileInfo)
  71. if !fi.IsReceiveOnlyChanged() {
  72. // We're only interested in files that have changed locally in
  73. // receive only mode.
  74. return true
  75. }
  76. fi.LocalFlags &^= protocol.FlagLocalReceiveOnly
  77. if len(fi.Version.Counters) == 1 && fi.Version.Counters[0].ID == f.shortID {
  78. // We are the only device mentioned in the version vector so the
  79. // file must originate here. A revert then means to delete it.
  80. // We'll delete files directly, directories get queued and
  81. // handled below.
  82. handled, err := delQueue.handle(fi, snap)
  83. if err != nil {
  84. l.Infof("Revert: deleting %s: %v\n", fi.Name, err)
  85. return true // continue
  86. }
  87. if !handled {
  88. return true // continue
  89. }
  90. fi.SetDeleted(f.shortID)
  91. fi.Version = protocol.Vector{} // if this file ever resurfaces anywhere we want our delete to be strictly older
  92. } else {
  93. // Revert means to throw away our local changes. We reset the
  94. // version to the empty vector, which is strictly older than any
  95. // other existing version. It is not in conflict with anything,
  96. // either, so we will not create a conflict copy of our local
  97. // changes.
  98. fi.Version = protocol.Vector{}
  99. }
  100. batch = append(batch, fi)
  101. batchSizeBytes += fi.ProtoSize()
  102. if len(batch) >= maxBatchSizeFiles || batchSizeBytes >= maxBatchSizeBytes {
  103. f.updateLocalsFromScanning(batch)
  104. batch = batch[:0]
  105. batchSizeBytes = 0
  106. }
  107. return true
  108. })
  109. if len(batch) > 0 {
  110. f.updateLocalsFromScanning(batch)
  111. }
  112. batch = batch[:0]
  113. batchSizeBytes = 0
  114. // Handle any queued directories
  115. deleted, err := delQueue.flush(snap)
  116. if err != nil {
  117. l.Infoln("Revert:", err)
  118. }
  119. now := time.Now()
  120. for _, dir := range deleted {
  121. batch = append(batch, protocol.FileInfo{
  122. Name: dir,
  123. Type: protocol.FileInfoTypeDirectory,
  124. ModifiedS: now.Unix(),
  125. ModifiedBy: f.shortID,
  126. Deleted: true,
  127. Version: protocol.Vector{},
  128. })
  129. }
  130. if len(batch) > 0 {
  131. f.updateLocalsFromScanning(batch)
  132. }
  133. // We will likely have changed our local index, but that won't trigger a
  134. // pull by itself. Make sure we schedule one so that we start
  135. // downloading files.
  136. f.SchedulePull()
  137. }
  138. // deleteQueue handles deletes by delegating to a handler and queuing
  139. // directories for last.
  140. type deleteQueue struct {
  141. handler interface {
  142. deleteItemOnDisk(item protocol.FileInfo, snap *db.Snapshot, scanChan chan<- string) error
  143. deleteDirOnDisk(dir string, snap *db.Snapshot, scanChan chan<- string) error
  144. }
  145. ignores *ignore.Matcher
  146. dirs []string
  147. scanChan chan<- string
  148. }
  149. func (q *deleteQueue) handle(fi protocol.FileInfo, snap *db.Snapshot) (bool, error) {
  150. // Things that are ignored but not marked deletable are not processed.
  151. ign := q.ignores.Match(fi.Name)
  152. if ign.IsIgnored() && !ign.IsDeletable() {
  153. return false, nil
  154. }
  155. // Directories are queued for later processing.
  156. if fi.IsDirectory() {
  157. q.dirs = append(q.dirs, fi.Name)
  158. return false, nil
  159. }
  160. // Kill it.
  161. err := q.handler.deleteItemOnDisk(fi, snap, q.scanChan)
  162. return true, err
  163. }
  164. func (q *deleteQueue) flush(snap *db.Snapshot) ([]string, error) {
  165. // Process directories from the leaves inward.
  166. sort.Sort(sort.Reverse(sort.StringSlice(q.dirs)))
  167. var firstError error
  168. var deleted []string
  169. for _, dir := range q.dirs {
  170. if err := q.handler.deleteDirOnDisk(dir, snap, q.scanChan); err == nil {
  171. deleted = append(deleted, dir)
  172. } else if err != nil && firstError == nil {
  173. firstError = err
  174. }
  175. }
  176. return deleted, firstError
  177. }