sharedpullerstate.go 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262
  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 http://mozilla.org/MPL/2.0/.
  6. package model
  7. import (
  8. "io"
  9. "os"
  10. "path/filepath"
  11. "github.com/syncthing/protocol"
  12. "github.com/syncthing/syncthing/lib/db"
  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. folder string
  21. tempName string
  22. realName string
  23. reused int // Number of blocks reused from temporary file
  24. ignorePerms bool
  25. version protocol.Vector // The current (old) version
  26. // Mutable, must be locked for access
  27. err error // The first error we hit
  28. fd *os.File // The fd of the temp file
  29. copyTotal int // Total number of copy actions for the whole job
  30. pullTotal int // Total number of pull actions for the whole job
  31. copyOrigin int // Number of blocks copied from the original file
  32. copyNeeded int // Number of copy actions still pending
  33. pullNeeded int // Number of block pulls still pending
  34. closed bool // True if the file has been finalClosed.
  35. mut sync.Mutex // Protects the above
  36. }
  37. // A momentary state representing the progress of the puller
  38. type pullerProgress struct {
  39. Total int `json:"total"`
  40. Reused int `json:"reused"`
  41. CopiedFromOrigin int `json:"copiedFromOrigin"`
  42. CopiedFromElsewhere int `json:"copiedFromElsewhere"`
  43. Pulled int `json:"pulled"`
  44. Pulling int `json:"pulling"`
  45. BytesDone int64 `json:"bytesDone"`
  46. BytesTotal int64 `json:"bytesTotal"`
  47. }
  48. // A lockedWriterAt synchronizes WriteAt calls with an external mutex.
  49. // WriteAt() is goroutine safe by itself, but not against for example Close().
  50. type lockedWriterAt struct {
  51. mut *sync.Mutex
  52. wr io.WriterAt
  53. }
  54. func (w lockedWriterAt) WriteAt(p []byte, off int64) (n int, err error) {
  55. (*w.mut).Lock()
  56. defer (*w.mut).Unlock()
  57. return w.wr.WriteAt(p, off)
  58. }
  59. // tempFile returns the fd for the temporary file, reusing an open fd
  60. // or creating the file as necessary.
  61. func (s *sharedPullerState) tempFile() (io.WriterAt, error) {
  62. s.mut.Lock()
  63. defer s.mut.Unlock()
  64. // If we've already hit an error, return early
  65. if s.err != nil {
  66. return nil, s.err
  67. }
  68. // If the temp file is already open, return the file descriptor
  69. if s.fd != nil {
  70. return lockedWriterAt{&s.mut, s.fd}, nil
  71. }
  72. // Ensure that the parent directory is writable. This is
  73. // osutil.InWritableDir except we need to do more stuff so we duplicate it
  74. // here.
  75. dir := filepath.Dir(s.tempName)
  76. if info, err := os.Stat(dir); err != nil {
  77. s.failLocked("dst stat dir", err)
  78. return nil, err
  79. } else if info.Mode()&0200 == 0 {
  80. err := os.Chmod(dir, 0755)
  81. if !s.ignorePerms && err == nil {
  82. defer func() {
  83. err := os.Chmod(dir, info.Mode().Perm())
  84. if err != nil {
  85. panic(err)
  86. }
  87. }()
  88. }
  89. }
  90. // Attempt to create the temp file
  91. flags := os.O_WRONLY
  92. if s.reused == 0 {
  93. flags |= os.O_CREATE | os.O_EXCL
  94. } else {
  95. // With sufficiently bad luck when exiting or crashing, we may have
  96. // had time to chmod the temp file to read only state but not yet
  97. // moved it to it's final name. This leaves us with a read only temp
  98. // file that we're going to try to reuse. To handle that, we need to
  99. // make sure we have write permissions on the file before opening it.
  100. err := os.Chmod(s.tempName, 0644)
  101. if !s.ignorePerms && err != nil {
  102. s.failLocked("dst create chmod", err)
  103. return nil, err
  104. }
  105. }
  106. fd, err := os.OpenFile(s.tempName, flags, 0666)
  107. if err != nil {
  108. s.failLocked("dst create", err)
  109. return nil, err
  110. }
  111. // Same fd will be used by all writers
  112. s.fd = fd
  113. return lockedWriterAt{&s.mut, s.fd}, nil
  114. }
  115. // sourceFile opens the existing source file for reading
  116. func (s *sharedPullerState) sourceFile() (*os.File, error) {
  117. s.mut.Lock()
  118. defer s.mut.Unlock()
  119. // If we've already hit an error, return early
  120. if s.err != nil {
  121. return nil, s.err
  122. }
  123. // Attempt to open the existing file
  124. fd, err := os.Open(s.realName)
  125. if err != nil {
  126. s.failLocked("src open", err)
  127. return nil, err
  128. }
  129. return fd, nil
  130. }
  131. // earlyClose prints a warning message composed of the context and
  132. // error, and marks the sharedPullerState as failed. Is a no-op when called on
  133. // an already failed state.
  134. func (s *sharedPullerState) fail(context string, err error) {
  135. s.mut.Lock()
  136. defer s.mut.Unlock()
  137. s.failLocked(context, err)
  138. }
  139. func (s *sharedPullerState) failLocked(context string, err error) {
  140. if s.err != nil {
  141. return
  142. }
  143. l.Infof("Puller (folder %q, file %q): %s: %v", s.folder, s.file.Name, context, err)
  144. s.err = err
  145. }
  146. func (s *sharedPullerState) failed() error {
  147. s.mut.Lock()
  148. defer s.mut.Unlock()
  149. return s.err
  150. }
  151. func (s *sharedPullerState) copyDone() {
  152. s.mut.Lock()
  153. s.copyNeeded--
  154. if debug {
  155. l.Debugln("sharedPullerState", s.folder, s.file.Name, "copyNeeded ->", s.copyNeeded)
  156. }
  157. s.mut.Unlock()
  158. }
  159. func (s *sharedPullerState) copiedFromOrigin() {
  160. s.mut.Lock()
  161. s.copyOrigin++
  162. s.mut.Unlock()
  163. }
  164. func (s *sharedPullerState) pullStarted() {
  165. s.mut.Lock()
  166. s.copyTotal--
  167. s.copyNeeded--
  168. s.pullTotal++
  169. s.pullNeeded++
  170. if debug {
  171. l.Debugln("sharedPullerState", s.folder, s.file.Name, "pullNeeded start ->", s.pullNeeded)
  172. }
  173. s.mut.Unlock()
  174. }
  175. func (s *sharedPullerState) pullDone() {
  176. s.mut.Lock()
  177. s.pullNeeded--
  178. if debug {
  179. l.Debugln("sharedPullerState", s.folder, s.file.Name, "pullNeeded done ->", s.pullNeeded)
  180. }
  181. s.mut.Unlock()
  182. }
  183. // finalClose atomically closes and returns closed status of a file. A true
  184. // first return value means the file was closed and should be finished, with
  185. // the error indicating the success or failure of the close. A false first
  186. // return value indicates the file is not ready to be closed, or is already
  187. // closed and should in either case not be finished off now.
  188. func (s *sharedPullerState) finalClose() (bool, error) {
  189. s.mut.Lock()
  190. defer s.mut.Unlock()
  191. if s.closed {
  192. // Already closed
  193. return false, nil
  194. }
  195. if s.pullNeeded+s.copyNeeded != 0 && s.err == nil {
  196. // Not done yet, and not errored
  197. return false, nil
  198. }
  199. if s.fd != nil {
  200. if closeErr := s.fd.Close(); closeErr != nil && s.err == nil {
  201. // This is our error if we weren't errored before. Otherwise we
  202. // keep the earlier error.
  203. s.err = closeErr
  204. }
  205. s.fd = nil
  206. }
  207. s.closed = true
  208. return true, s.err
  209. }
  210. // Returns the momentarily progress for the puller
  211. func (s *sharedPullerState) Progress() *pullerProgress {
  212. s.mut.Lock()
  213. defer s.mut.Unlock()
  214. total := s.reused + s.copyTotal + s.pullTotal
  215. done := total - s.copyNeeded - s.pullNeeded
  216. return &pullerProgress{
  217. Total: total,
  218. Reused: s.reused,
  219. CopiedFromOrigin: s.copyOrigin,
  220. CopiedFromElsewhere: s.copyTotal - s.copyNeeded - s.copyOrigin,
  221. Pulled: s.pullTotal - s.pullNeeded,
  222. Pulling: s.pullNeeded,
  223. BytesTotal: db.BlocksToSize(total),
  224. BytesDone: db.BlocksToSize(done),
  225. }
  226. }