folder_recvonly.go 7.0 KB

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