folder_recvonly.go 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213
  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. f.doInSync(func() error { f.revert(); return nil })
  55. }
  56. func (f *receiveOnlyFolder) revert() {
  57. l.Infof("Reverting folder %v", f.Description)
  58. f.setState(FolderScanning)
  59. defer f.setState(FolderIdle)
  60. scanChan := make(chan string)
  61. go f.pullScannerRoutine(scanChan)
  62. defer close(scanChan)
  63. delQueue := &deleteQueue{
  64. handler: f, // for the deleteItemOnDisk and deleteDirOnDisk methods
  65. ignores: f.ignores,
  66. scanChan: scanChan,
  67. }
  68. batch := make([]protocol.FileInfo, 0, maxBatchSizeFiles)
  69. batchSizeBytes := 0
  70. snap := f.fset.Snapshot()
  71. defer snap.Release()
  72. snap.WithHave(protocol.LocalDeviceID, func(intf db.FileIntf) bool {
  73. fi := intf.(protocol.FileInfo)
  74. if !fi.IsReceiveOnlyChanged() {
  75. // We're only interested in files that have changed locally in
  76. // receive only mode.
  77. return true
  78. }
  79. fi.LocalFlags &^= protocol.FlagLocalReceiveOnly
  80. if len(fi.Version.Counters) == 1 && fi.Version.Counters[0].ID == f.shortID {
  81. // We are the only device mentioned in the version vector so the
  82. // file must originate here. A revert then means to delete it.
  83. // We'll delete files directly, directories get queued and
  84. // handled below.
  85. handled, err := delQueue.handle(fi, snap)
  86. if err != nil {
  87. l.Infof("Revert: deleting %s: %v\n", fi.Name, err)
  88. return true // continue
  89. }
  90. if !handled {
  91. return true // continue
  92. }
  93. fi.SetDeleted(f.shortID)
  94. fi.Version = protocol.Vector{} // if this file ever resurfaces anywhere we want our delete to be strictly older
  95. } else {
  96. // Revert means to throw away our local changes. We reset the
  97. // version to the empty vector, which is strictly older than any
  98. // other existing version. It is not in conflict with anything,
  99. // either, so we will not create a conflict copy of our local
  100. // changes.
  101. fi.Version = protocol.Vector{}
  102. }
  103. batch = append(batch, fi)
  104. batchSizeBytes += fi.ProtoSize()
  105. if len(batch) >= maxBatchSizeFiles || batchSizeBytes >= maxBatchSizeBytes {
  106. f.updateLocalsFromScanning(batch)
  107. batch = batch[:0]
  108. batchSizeBytes = 0
  109. }
  110. return true
  111. })
  112. if len(batch) > 0 {
  113. f.updateLocalsFromScanning(batch)
  114. }
  115. batch = batch[:0]
  116. batchSizeBytes = 0
  117. // Handle any queued directories
  118. deleted, err := delQueue.flush(snap)
  119. if err != nil {
  120. l.Infoln("Revert:", err)
  121. }
  122. now := time.Now()
  123. for _, dir := range deleted {
  124. batch = append(batch, protocol.FileInfo{
  125. Name: dir,
  126. Type: protocol.FileInfoTypeDirectory,
  127. ModifiedS: now.Unix(),
  128. ModifiedBy: f.shortID,
  129. Deleted: true,
  130. Version: protocol.Vector{},
  131. })
  132. }
  133. if len(batch) > 0 {
  134. f.updateLocalsFromScanning(batch)
  135. }
  136. // We will likely have changed our local index, but that won't trigger a
  137. // pull by itself. Make sure we schedule one so that we start
  138. // downloading files.
  139. f.SchedulePull()
  140. }
  141. // deleteQueue handles deletes by delegating to a handler and queuing
  142. // directories for last.
  143. type deleteQueue struct {
  144. handler interface {
  145. deleteItemOnDisk(item protocol.FileInfo, snap *db.Snapshot, scanChan chan<- string) error
  146. deleteDirOnDisk(dir string, snap *db.Snapshot, scanChan chan<- string) error
  147. }
  148. ignores *ignore.Matcher
  149. dirs []string
  150. scanChan chan<- string
  151. }
  152. func (q *deleteQueue) handle(fi protocol.FileInfo, snap *db.Snapshot) (bool, error) {
  153. // Things that are ignored but not marked deletable are not processed.
  154. ign := q.ignores.Match(fi.Name)
  155. if ign.IsIgnored() && !ign.IsDeletable() {
  156. return false, nil
  157. }
  158. // Directories are queued for later processing.
  159. if fi.IsDirectory() {
  160. q.dirs = append(q.dirs, fi.Name)
  161. return false, nil
  162. }
  163. // Kill it.
  164. err := q.handler.deleteItemOnDisk(fi, snap, q.scanChan)
  165. return true, err
  166. }
  167. func (q *deleteQueue) flush(snap *db.Snapshot) ([]string, error) {
  168. // Process directories from the leaves inward.
  169. sort.Sort(sort.Reverse(sort.StringSlice(q.dirs)))
  170. var firstError error
  171. var deleted []string
  172. for _, dir := range q.dirs {
  173. if err := q.handler.deleteDirOnDisk(dir, snap, q.scanChan); err == nil {
  174. deleted = append(deleted, dir)
  175. } else if err != nil && firstError == nil {
  176. firstError = err
  177. }
  178. }
  179. return deleted, firstError
  180. }