folder_recvonly.go 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217
  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/ignore"
  14. "github.com/syncthing/syncthing/lib/protocol"
  15. "github.com/syncthing/syncthing/lib/util"
  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, evLogger events.Logger, ioLimiter *util.Semaphore) service {
  49. sr := newSendReceiveFolder(model, fset, ignores, cfg, ver, 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(f.revert)
  55. }
  56. func (f *receiveOnlyFolder) revert() error {
  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 := db.NewFileInfoBatch(func(files []protocol.FileInfo) error {
  69. f.updateLocalsFromScanning(files)
  70. return nil
  71. })
  72. snap, err := f.dbSnapshot()
  73. if err != nil {
  74. return err
  75. }
  76. defer snap.Release()
  77. snap.WithHave(protocol.LocalDeviceID, func(intf protocol.FileIntf) bool {
  78. fi := intf.(protocol.FileInfo)
  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. handled, err := delQueue.handle(fi, snap)
  96. if err != nil {
  97. l.Infof("Revert: deleting %s: %v\n", fi.Name, err)
  98. return true // continue
  99. }
  100. if !handled {
  101. return true // continue
  102. }
  103. fi.SetDeleted(f.shortID)
  104. fi.Version = protocol.Vector{} // if this file ever resurfaces anywhere we want our delete to be strictly older
  105. case gf.IsEquivalentOptional(fi, f.modTimeWindow, false, false, protocol.FlagLocalReceiveOnly):
  106. // What we have locally is equivalent to the global file.
  107. fi = gf
  108. default:
  109. // Revert means to throw away our local changes. We reset the
  110. // version to the empty vector, which is strictly older than any
  111. // other existing version. It is not in conflict with anything,
  112. // either, so we will not create a conflict copy of our local
  113. // changes.
  114. fi.Version = protocol.Vector{}
  115. }
  116. batch.Append(fi)
  117. _ = batch.FlushIfFull()
  118. return true
  119. })
  120. _ = batch.Flush()
  121. // Handle any queued directories
  122. deleted, err := delQueue.flush(snap)
  123. if err != nil {
  124. l.Infoln("Revert:", err)
  125. }
  126. now := time.Now()
  127. for _, dir := range deleted {
  128. batch.Append(protocol.FileInfo{
  129. Name: dir,
  130. Type: protocol.FileInfoTypeDirectory,
  131. ModifiedS: now.Unix(),
  132. ModifiedBy: f.shortID,
  133. Deleted: true,
  134. Version: protocol.Vector{},
  135. })
  136. }
  137. _ = batch.Flush()
  138. // We will likely have changed our local index, but that won't trigger a
  139. // pull by itself. Make sure we schedule one so that we start
  140. // downloading files.
  141. f.SchedulePull()
  142. return nil
  143. }
  144. // deleteQueue handles deletes by delegating to a handler and queuing
  145. // directories for last.
  146. type deleteQueue struct {
  147. handler interface {
  148. deleteItemOnDisk(item protocol.FileInfo, snap *db.Snapshot, scanChan chan<- string) error
  149. deleteDirOnDisk(dir string, snap *db.Snapshot, scanChan chan<- string) error
  150. }
  151. ignores *ignore.Matcher
  152. dirs []string
  153. scanChan chan<- string
  154. }
  155. func (q *deleteQueue) handle(fi protocol.FileInfo, snap *db.Snapshot) (bool, error) {
  156. // Things that are ignored but not marked deletable are not processed.
  157. ign := q.ignores.Match(fi.Name)
  158. if ign.IsIgnored() && !ign.IsDeletable() {
  159. return false, nil
  160. }
  161. // Directories are queued for later processing.
  162. if fi.IsDirectory() {
  163. q.dirs = append(q.dirs, fi.Name)
  164. return false, nil
  165. }
  166. // Kill it.
  167. err := q.handler.deleteItemOnDisk(fi, snap, q.scanChan)
  168. return true, err
  169. }
  170. func (q *deleteQueue) flush(snap *db.Snapshot) ([]string, error) {
  171. // Process directories from the leaves inward.
  172. sort.Sort(sort.Reverse(sort.StringSlice(q.dirs)))
  173. var firstError error
  174. var deleted []string
  175. for _, dir := range q.dirs {
  176. if err := q.handler.deleteDirOnDisk(dir, snap, q.scanChan); err == nil {
  177. deleted = append(deleted, dir)
  178. } else if err != nil && firstError == nil {
  179. firstError = err
  180. }
  181. }
  182. return deleted, firstError
  183. }