sharedpullerstate.go 12 KB

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