folder_recvonly.go 7.0 KB

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