folder_recvonly.go 7.0 KB

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