sharedpullerstate.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352
  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. "path/filepath"
  10. "time"
  11. "github.com/pkg/errors"
  12. "github.com/syncthing/syncthing/lib/fs"
  13. "github.com/syncthing/syncthing/lib/protocol"
  14. "github.com/syncthing/syncthing/lib/sync"
  15. )
  16. // A sharedPullerState is kept for each file that is being synced and is kept
  17. // updated along the way.
  18. type sharedPullerState struct {
  19. // Immutable, does not require locking
  20. file protocol.FileInfo // The new file (desired end state)
  21. fs fs.Filesystem
  22. folder string
  23. tempName string
  24. realName string
  25. reused int // Number of blocks reused from temporary file
  26. ignorePerms bool
  27. hasCurFile bool // Whether curFile is set
  28. curFile protocol.FileInfo // The file as it exists now in our database
  29. sparse bool
  30. created time.Time
  31. // Mutable, must be locked for access
  32. err error // The first error we hit
  33. fd fs.File // The fd of the temp file
  34. copyTotal int // Total number of copy actions for the whole job
  35. pullTotal int // Total number of pull actions for the whole job
  36. copyOrigin int // Number of blocks copied from the original file
  37. copyOriginShifted int // Number of blocks copied from the original file but shifted
  38. copyNeeded int // Number of copy actions still pending
  39. pullNeeded int // Number of block pulls still pending
  40. updated time.Time // Time when any of the counters above were last updated
  41. closed bool // True if the file has been finalClosed.
  42. available []int32 // Indexes of the blocks that are available in the temporary file
  43. availableUpdated time.Time // Time when list of available blocks was last updated
  44. mut sync.RWMutex // Protects the above
  45. }
  46. // A momentary state representing the progress of the puller
  47. type pullerProgress struct {
  48. Total int `json:"total"`
  49. Reused int `json:"reused"`
  50. CopiedFromOrigin int `json:"copiedFromOrigin"`
  51. CopiedFromOriginShifted int `json:"copiedFromOriginShifted"`
  52. CopiedFromElsewhere int `json:"copiedFromElsewhere"`
  53. Pulled int `json:"pulled"`
  54. Pulling int `json:"pulling"`
  55. BytesDone int64 `json:"bytesDone"`
  56. BytesTotal int64 `json:"bytesTotal"`
  57. }
  58. // A lockedWriterAt synchronizes WriteAt calls with an external mutex.
  59. // WriteAt() is goroutine safe by itself, but not against for example Close().
  60. type lockedWriterAt struct {
  61. mut *sync.RWMutex
  62. wr io.WriterAt
  63. }
  64. func (w lockedWriterAt) WriteAt(p []byte, off int64) (n int, err error) {
  65. (*w.mut).Lock()
  66. defer (*w.mut).Unlock()
  67. return w.wr.WriteAt(p, off)
  68. }
  69. // tempFile returns the fd for the temporary file, reusing an open fd
  70. // or creating the file as necessary.
  71. func (s *sharedPullerState) tempFile() (io.WriterAt, error) {
  72. s.mut.Lock()
  73. defer s.mut.Unlock()
  74. // If we've already hit an error, return early
  75. if s.err != nil {
  76. return nil, s.err
  77. }
  78. // If the temp file is already open, return the file descriptor
  79. if s.fd != nil {
  80. return lockedWriterAt{&s.mut, s.fd}, nil
  81. }
  82. // Ensure that the parent directory is writable. This is
  83. // osutil.InWritableDir except we need to do more stuff so we duplicate it
  84. // here.
  85. dir := filepath.Dir(s.tempName)
  86. if info, err := s.fs.Stat(dir); err != nil {
  87. s.failLocked(errors.Wrap(err, "ensuring parent dir is writeable"))
  88. return nil, err
  89. } else if info.Mode()&0200 == 0 {
  90. err := s.fs.Chmod(dir, 0755)
  91. if !s.ignorePerms && err == nil {
  92. defer func() {
  93. err := s.fs.Chmod(dir, info.Mode()&fs.ModePerm)
  94. if err != nil {
  95. panic(err)
  96. }
  97. }()
  98. }
  99. }
  100. // The permissions to use for the temporary file should be those of the
  101. // final file, except we need user read & write at minimum. The
  102. // permissions will be set to the final value later, but in the meantime
  103. // we don't want to have a temporary file with looser permissions than
  104. // the final outcome.
  105. mode := fs.FileMode(s.file.Permissions) | 0600
  106. if s.ignorePerms {
  107. // When ignorePerms is set we use a very permissive mode and let the
  108. // system umask filter it.
  109. mode = 0666
  110. }
  111. // Attempt to create the temp file
  112. // RDWR because of issue #2994.
  113. flags := fs.OptReadWrite
  114. if s.reused == 0 {
  115. flags |= fs.OptCreate | fs.OptExclusive
  116. } else if !s.ignorePerms {
  117. // With sufficiently bad luck when exiting or crashing, we may have
  118. // had time to chmod the temp file to read only state but not yet
  119. // moved it to its final name. This leaves us with a read only temp
  120. // file that we're going to try to reuse. To handle that, we need to
  121. // make sure we have write permissions on the file before opening it.
  122. //
  123. // When ignorePerms is set we trust that the permissions are fine
  124. // already and make no modification, as we would otherwise override
  125. // what the umask dictates.
  126. if err := s.fs.Chmod(s.tempName, mode); err != nil {
  127. s.failLocked(errors.Wrap(err, "setting perms on temp file"))
  128. return nil, err
  129. }
  130. }
  131. fd, err := s.fs.OpenFile(s.tempName, flags, mode)
  132. if err != nil {
  133. s.failLocked(errors.Wrap(err, "opening temp file"))
  134. return nil, err
  135. }
  136. // Hide the temporary file
  137. s.fs.Hide(s.tempName)
  138. // Don't truncate symlink files, as that will mean that the path will
  139. // contain a bunch of nulls.
  140. if s.sparse && !s.file.IsSymlink() {
  141. // Truncate sets the size of the file. This creates a sparse file or a
  142. // space reservation, depending on the underlying filesystem.
  143. if err := fd.Truncate(s.file.Size); err != nil {
  144. // The truncate call failed. That can happen in some cases when
  145. // space reservation isn't possible or over some network
  146. // filesystems... This generally doesn't matter.
  147. if s.reused > 0 {
  148. // ... but if we are attempting to reuse a file we have a
  149. // corner case when the old file is larger than the new one
  150. // and we can't just overwrite blocks and let the old data
  151. // linger at the end. In this case we attempt a delete of
  152. // the file and hope for better luck next time, when we
  153. // should come around with s.reused == 0.
  154. fd.Close()
  155. if remErr := s.fs.Remove(s.tempName); remErr != nil {
  156. l.Debugln("failed to remove temporary file:", remErr)
  157. }
  158. s.failLocked(err)
  159. return nil, err
  160. }
  161. }
  162. }
  163. // Same fd will be used by all writers
  164. s.fd = fd
  165. return lockedWriterAt{&s.mut, s.fd}, 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.fd != nil {
  244. // This is our error if we weren't errored before. Otherwise we
  245. // keep the earlier error.
  246. if fsyncErr := s.fd.Sync(); fsyncErr != nil && s.err == nil {
  247. s.err = fsyncErr
  248. }
  249. if closeErr := s.fd.Close(); closeErr != nil && s.err == nil {
  250. s.err = closeErr
  251. }
  252. s.fd = nil
  253. }
  254. s.closed = true
  255. // Unhide the temporary file when we close it, as it's likely to
  256. // immediately be renamed to the final name. If this is a failed temp
  257. // file we will also unhide it, but I'm fine with that as we're now
  258. // leaving it around for potentially quite a while.
  259. s.fs.Unhide(s.tempName)
  260. return true, s.err
  261. }
  262. // Progress returns the momentarily progress for the puller
  263. func (s *sharedPullerState) Progress() *pullerProgress {
  264. s.mut.RLock()
  265. defer s.mut.RUnlock()
  266. total := s.reused + s.copyTotal + s.pullTotal
  267. done := total - s.copyNeeded - s.pullNeeded
  268. return &pullerProgress{
  269. Total: total,
  270. Reused: s.reused,
  271. CopiedFromOrigin: s.copyOrigin,
  272. CopiedFromElsewhere: s.copyTotal - s.copyNeeded - s.copyOrigin,
  273. Pulled: s.pullTotal - s.pullNeeded,
  274. Pulling: s.pullNeeded,
  275. BytesTotal: blocksToSize(s.file.BlockSize(), total),
  276. BytesDone: blocksToSize(s.file.BlockSize(), done),
  277. }
  278. }
  279. // Updated returns the time when any of the progress related counters was last updated.
  280. func (s *sharedPullerState) Updated() time.Time {
  281. s.mut.RLock()
  282. t := s.updated
  283. s.mut.RUnlock()
  284. return t
  285. }
  286. // AvailableUpdated returns the time last time list of available blocks was updated
  287. func (s *sharedPullerState) AvailableUpdated() time.Time {
  288. s.mut.RLock()
  289. t := s.availableUpdated
  290. s.mut.RUnlock()
  291. return t
  292. }
  293. // Available returns blocks available in the current temporary file
  294. func (s *sharedPullerState) Available() []int32 {
  295. s.mut.RLock()
  296. blocks := s.available
  297. s.mut.RUnlock()
  298. return blocks
  299. }
  300. func blocksToSize(size int, num int) int64 {
  301. if num < 2 {
  302. return int64(size / 2)
  303. }
  304. return int64(num-1)*int64(size) + int64(size/2)
  305. }