sharedpullerstate.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349
  1. // Copyright (C) 2014 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. "io"
  9. "time"
  10. "github.com/pkg/errors"
  11. "github.com/syncthing/syncthing/lib/fs"
  12. "github.com/syncthing/syncthing/lib/protocol"
  13. "github.com/syncthing/syncthing/lib/sync"
  14. )
  15. // A sharedPullerState is kept for each file that is being synced and is kept
  16. // updated along the way.
  17. type sharedPullerState struct {
  18. // Immutable, does not require locking
  19. file protocol.FileInfo // The new file (desired end state)
  20. fs fs.Filesystem
  21. folder string
  22. tempName string
  23. realName string
  24. reused int // Number of blocks reused from temporary file
  25. ignorePerms bool
  26. hasCurFile bool // Whether curFile is set
  27. curFile protocol.FileInfo // The file as it exists now in our database
  28. sparse bool
  29. created time.Time
  30. // Mutable, must be locked for access
  31. err error // The first error we hit
  32. writer *lockedWriterAt // Wraps fd to prevent fd closing at the same time as writing
  33. copyTotal int // Total number of copy actions for the whole job
  34. pullTotal int // Total number of pull actions for the whole job
  35. copyOrigin int // Number of blocks copied from the original file
  36. copyOriginShifted int // Number of blocks copied from the original file but shifted
  37. copyNeeded int // Number of copy actions still pending
  38. pullNeeded int // Number of block pulls still pending
  39. updated time.Time // Time when any of the counters above were last updated
  40. closed bool // True if the file has been finalClosed.
  41. available []int32 // Indexes of the blocks that are available in the temporary file
  42. availableUpdated time.Time // Time when list of available blocks was last updated
  43. mut sync.RWMutex // Protects the above
  44. }
  45. // A momentary state representing the progress of the puller
  46. type pullerProgress struct {
  47. Total int `json:"total"`
  48. Reused int `json:"reused"`
  49. CopiedFromOrigin int `json:"copiedFromOrigin"`
  50. CopiedFromOriginShifted int `json:"copiedFromOriginShifted"`
  51. CopiedFromElsewhere int `json:"copiedFromElsewhere"`
  52. Pulled int `json:"pulled"`
  53. Pulling int `json:"pulling"`
  54. BytesDone int64 `json:"bytesDone"`
  55. BytesTotal int64 `json:"bytesTotal"`
  56. }
  57. // lockedWriterAt adds a lock to protect from closing the fd at the same time as writing.
  58. // WriteAt() is goroutine safe by itself, but not against for example Close().
  59. type lockedWriterAt struct {
  60. mut sync.RWMutex
  61. fd fs.File
  62. }
  63. // WriteAt itself is goroutine safe, thus just needs to acquire a read-lock to
  64. // prevent closing concurrently (see SyncClose).
  65. func (w *lockedWriterAt) WriteAt(p []byte, off int64) (n int, err error) {
  66. w.mut.RLock()
  67. defer w.mut.RUnlock()
  68. return w.fd.WriteAt(p, off)
  69. }
  70. // SyncClose ensures that no more writes are happening before going ahead and
  71. // syncing and closing the fd, thus needs to acquire a write-lock.
  72. func (w *lockedWriterAt) SyncClose() error {
  73. w.mut.Lock()
  74. defer w.mut.Unlock()
  75. if err := w.fd.Sync(); err != nil {
  76. // Sync() is nice if it works but not worth failing the
  77. // operation over if it fails.
  78. l.Debugf("fsync failed: %v", err)
  79. }
  80. return w.fd.Close()
  81. }
  82. // tempFile returns the fd for the temporary file, reusing an open fd
  83. // or creating the file as necessary.
  84. func (s *sharedPullerState) tempFile() (io.WriterAt, error) {
  85. s.mut.Lock()
  86. defer s.mut.Unlock()
  87. // If we've already hit an error, return early
  88. if s.err != nil {
  89. return nil, s.err
  90. }
  91. // If the temp file is already open, return the file descriptor
  92. if s.writer != nil {
  93. return s.writer, nil
  94. }
  95. if err := inWritableDir(s.tempFileInWritableDir, s.fs, s.tempName, s.ignorePerms); err != nil {
  96. s.failLocked(err)
  97. return nil, err
  98. }
  99. return s.writer, nil
  100. }
  101. // tempFileInWritableDir should only be called from tempFile.
  102. func (s *sharedPullerState) tempFileInWritableDir(_ string) error {
  103. // The permissions to use for the temporary file should be those of the
  104. // final file, except we need user read & write at minimum. The
  105. // permissions will be set to the final value later, but in the meantime
  106. // we don't want to have a temporary file with looser permissions than
  107. // the final outcome.
  108. mode := fs.FileMode(s.file.Permissions) | 0600
  109. if s.ignorePerms {
  110. // When ignorePerms is set we use a very permissive mode and let the
  111. // system umask filter it.
  112. mode = 0666
  113. }
  114. // Attempt to create the temp file
  115. // RDWR because of issue #2994.
  116. flags := fs.OptReadWrite
  117. if s.reused == 0 {
  118. flags |= fs.OptCreate | fs.OptExclusive
  119. } else if !s.ignorePerms {
  120. // With sufficiently bad luck when exiting or crashing, we may have
  121. // had time to chmod the temp file to read only state but not yet
  122. // moved it to its final name. This leaves us with a read only temp
  123. // file that we're going to try to reuse. To handle that, we need to
  124. // make sure we have write permissions on the file before opening it.
  125. //
  126. // When ignorePerms is set we trust that the permissions are fine
  127. // already and make no modification, as we would otherwise override
  128. // what the umask dictates.
  129. if err := s.fs.Chmod(s.tempName, mode); err != nil {
  130. return errors.Wrap(err, "setting perms on temp file")
  131. }
  132. }
  133. fd, err := s.fs.OpenFile(s.tempName, flags, mode)
  134. if err != nil {
  135. return errors.Wrap(err, "opening temp file")
  136. }
  137. // Hide the temporary file
  138. s.fs.Hide(s.tempName)
  139. // Don't truncate symlink files, as that will mean that the path will
  140. // contain a bunch of nulls.
  141. if s.sparse && !s.file.IsSymlink() {
  142. // Truncate sets the size of the file. This creates a sparse file or a
  143. // space reservation, depending on the underlying filesystem.
  144. if err := fd.Truncate(s.file.Size); err != nil {
  145. // The truncate call failed. That can happen in some cases when
  146. // space reservation isn't possible or over some network
  147. // filesystems... This generally doesn't matter.
  148. if s.reused > 0 {
  149. // ... but if we are attempting to reuse a file we have a
  150. // corner case when the old file is larger than the new one
  151. // and we can't just overwrite blocks and let the old data
  152. // linger at the end. In this case we attempt a delete of
  153. // the file and hope for better luck next time, when we
  154. // should come around with s.reused == 0.
  155. fd.Close()
  156. if remErr := s.fs.Remove(s.tempName); remErr != nil {
  157. l.Debugln("failed to remove temporary file:", remErr)
  158. }
  159. return err
  160. }
  161. }
  162. }
  163. // Same fd will be used by all writers
  164. s.writer = &lockedWriterAt{sync.NewRWMutex(), fd}
  165. return nil
  166. }
  167. // fail sets the error on the puller state compose of error, and marks the
  168. // sharedPullerState as failed. Is a no-op when called on an already failed state.
  169. func (s *sharedPullerState) fail(err error) {
  170. s.mut.Lock()
  171. defer s.mut.Unlock()
  172. s.failLocked(err)
  173. }
  174. func (s *sharedPullerState) failLocked(err error) {
  175. if s.err != nil || err == nil {
  176. return
  177. }
  178. s.err = err
  179. }
  180. func (s *sharedPullerState) failed() error {
  181. s.mut.RLock()
  182. err := s.err
  183. s.mut.RUnlock()
  184. return err
  185. }
  186. func (s *sharedPullerState) copyDone(block protocol.BlockInfo) {
  187. s.mut.Lock()
  188. s.copyNeeded--
  189. s.updated = time.Now()
  190. s.available = append(s.available, int32(block.Offset/int64(s.file.BlockSize())))
  191. s.availableUpdated = time.Now()
  192. l.Debugln("sharedPullerState", s.folder, s.file.Name, "copyNeeded ->", s.copyNeeded)
  193. s.mut.Unlock()
  194. }
  195. func (s *sharedPullerState) copiedFromOrigin() {
  196. s.mut.Lock()
  197. s.copyOrigin++
  198. s.updated = time.Now()
  199. s.mut.Unlock()
  200. }
  201. func (s *sharedPullerState) copiedFromOriginShifted() {
  202. s.mut.Lock()
  203. s.copyOrigin++
  204. s.copyOriginShifted++
  205. s.updated = time.Now()
  206. s.mut.Unlock()
  207. }
  208. func (s *sharedPullerState) pullStarted() {
  209. s.mut.Lock()
  210. s.copyTotal--
  211. s.copyNeeded--
  212. s.pullTotal++
  213. s.pullNeeded++
  214. s.updated = time.Now()
  215. l.Debugln("sharedPullerState", s.folder, s.file.Name, "pullNeeded start ->", s.pullNeeded)
  216. s.mut.Unlock()
  217. }
  218. func (s *sharedPullerState) pullDone(block protocol.BlockInfo) {
  219. s.mut.Lock()
  220. s.pullNeeded--
  221. s.updated = time.Now()
  222. s.available = append(s.available, int32(block.Offset/int64(s.file.BlockSize())))
  223. s.availableUpdated = time.Now()
  224. l.Debugln("sharedPullerState", s.folder, s.file.Name, "pullNeeded done ->", s.pullNeeded)
  225. s.mut.Unlock()
  226. }
  227. // finalClose atomically closes and returns closed status of a file. A true
  228. // first return value means the file was closed and should be finished, with
  229. // the error indicating the success or failure of the close. A false first
  230. // return value indicates the file is not ready to be closed, or is already
  231. // closed and should in either case not be finished off now.
  232. func (s *sharedPullerState) finalClose() (bool, error) {
  233. s.mut.Lock()
  234. defer s.mut.Unlock()
  235. if s.closed {
  236. // Already closed
  237. return false, nil
  238. }
  239. if s.pullNeeded+s.copyNeeded != 0 && s.err == nil {
  240. // Not done yet, and not errored
  241. return false, nil
  242. }
  243. if s.writer != nil {
  244. if err := s.writer.SyncClose(); err != nil && s.err == nil {
  245. // This is our error as we weren't errored before.
  246. s.err = err
  247. }
  248. s.writer = nil
  249. }
  250. s.closed = true
  251. // Unhide the temporary file when we close it, as it's likely to
  252. // immediately be renamed to the final name. If this is a failed temp
  253. // file we will also unhide it, but I'm fine with that as we're now
  254. // leaving it around for potentially quite a while.
  255. s.fs.Unhide(s.tempName)
  256. return true, s.err
  257. }
  258. // Progress returns the momentarily progress for the puller
  259. func (s *sharedPullerState) Progress() *pullerProgress {
  260. s.mut.RLock()
  261. defer s.mut.RUnlock()
  262. total := s.reused + s.copyTotal + s.pullTotal
  263. done := total - s.copyNeeded - s.pullNeeded
  264. return &pullerProgress{
  265. Total: total,
  266. Reused: s.reused,
  267. CopiedFromOrigin: s.copyOrigin,
  268. CopiedFromElsewhere: s.copyTotal - s.copyNeeded - s.copyOrigin,
  269. Pulled: s.pullTotal - s.pullNeeded,
  270. Pulling: s.pullNeeded,
  271. BytesTotal: blocksToSize(s.file.BlockSize(), total),
  272. BytesDone: blocksToSize(s.file.BlockSize(), done),
  273. }
  274. }
  275. // Updated returns the time when any of the progress related counters was last updated.
  276. func (s *sharedPullerState) Updated() time.Time {
  277. s.mut.RLock()
  278. t := s.updated
  279. s.mut.RUnlock()
  280. return t
  281. }
  282. // AvailableUpdated returns the time last time list of available blocks was updated
  283. func (s *sharedPullerState) AvailableUpdated() time.Time {
  284. s.mut.RLock()
  285. t := s.availableUpdated
  286. s.mut.RUnlock()
  287. return t
  288. }
  289. // Available returns blocks available in the current temporary file
  290. func (s *sharedPullerState) Available() []int32 {
  291. s.mut.RLock()
  292. blocks := s.available
  293. s.mut.RUnlock()
  294. return blocks
  295. }
  296. func blocksToSize(size int, num int) int64 {
  297. if num < 2 {
  298. return int64(size / 2)
  299. }
  300. return int64(num-1)*int64(size) + int64(size/2)
  301. }