sharedpullerstate.go 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272
  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/syncthing/lib/db"
  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. 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. if os.IsNotExist(err) {
  78. // XXX: This works around a bug elsewhere, a race condition when
  79. // things are deleted while being synced. However that happens, we
  80. // end up with a directory for "foo" with the delete bit, but a
  81. // file "foo/bar" that we want to sync. We never create the
  82. // directory, and hence fail to create the file and end up looping
  83. // forever on it. This breaks that by creating the directory; on
  84. // next scan it'll be found and the delete bit on it is removed.
  85. // The user can then clean up as they like...
  86. l.Infoln("Resurrecting directory", dir)
  87. if err := os.MkdirAll(dir, 0755); err != nil {
  88. s.failLocked("resurrect dir", err)
  89. return nil, err
  90. }
  91. } else {
  92. s.failLocked("dst stat dir", err)
  93. return nil, err
  94. }
  95. } else if info.Mode()&0200 == 0 {
  96. err := os.Chmod(dir, 0755)
  97. if !s.ignorePerms && err == nil {
  98. defer func() {
  99. err := os.Chmod(dir, info.Mode().Perm())
  100. if err != nil {
  101. panic(err)
  102. }
  103. }()
  104. }
  105. }
  106. // Attempt to create the temp file
  107. flags := os.O_WRONLY
  108. if s.reused == 0 {
  109. flags |= os.O_CREATE | os.O_EXCL
  110. } else {
  111. // With sufficiently bad luck when exiting or crashing, we may have
  112. // had time to chmod the temp file to read only state but not yet
  113. // moved it to it's final name. This leaves us with a read only temp
  114. // file that we're going to try to reuse. To handle that, we need to
  115. // make sure we have write permissions on the file before opening it.
  116. err := os.Chmod(s.tempName, 0644)
  117. if !s.ignorePerms && err != nil {
  118. s.failLocked("dst create chmod", err)
  119. return nil, err
  120. }
  121. }
  122. fd, err := os.OpenFile(s.tempName, flags, 0666)
  123. if err != nil {
  124. s.failLocked("dst create", err)
  125. return nil, err
  126. }
  127. // Same fd will be used by all writers
  128. s.fd = fd
  129. return lockedWriterAt{&s.mut, s.fd}, nil
  130. }
  131. // sourceFile opens the existing source file for reading
  132. func (s *sharedPullerState) sourceFile() (*os.File, error) {
  133. s.mut.Lock()
  134. defer s.mut.Unlock()
  135. // If we've already hit an error, return early
  136. if s.err != nil {
  137. return nil, s.err
  138. }
  139. // Attempt to open the existing file
  140. fd, err := os.Open(s.realName)
  141. if err != nil {
  142. s.failLocked("src open", err)
  143. return nil, err
  144. }
  145. return fd, nil
  146. }
  147. // earlyClose prints a warning message composed of the context and
  148. // error, and marks the sharedPullerState as failed. Is a no-op when called on
  149. // an already failed state.
  150. func (s *sharedPullerState) fail(context string, err error) {
  151. s.mut.Lock()
  152. defer s.mut.Unlock()
  153. s.failLocked(context, err)
  154. }
  155. func (s *sharedPullerState) failLocked(context string, err error) {
  156. if s.err != nil {
  157. return
  158. }
  159. l.Infof("Puller (folder %q, file %q): %s: %v", s.folder, s.file.Name, context, err)
  160. s.err = err
  161. }
  162. func (s *sharedPullerState) failed() error {
  163. s.mut.Lock()
  164. defer s.mut.Unlock()
  165. return s.err
  166. }
  167. func (s *sharedPullerState) copyDone() {
  168. s.mut.Lock()
  169. s.copyNeeded--
  170. l.Debugln("sharedPullerState", s.folder, s.file.Name, "copyNeeded ->", s.copyNeeded)
  171. s.mut.Unlock()
  172. }
  173. func (s *sharedPullerState) copiedFromOrigin() {
  174. s.mut.Lock()
  175. s.copyOrigin++
  176. s.mut.Unlock()
  177. }
  178. func (s *sharedPullerState) pullStarted() {
  179. s.mut.Lock()
  180. s.copyTotal--
  181. s.copyNeeded--
  182. s.pullTotal++
  183. s.pullNeeded++
  184. l.Debugln("sharedPullerState", s.folder, s.file.Name, "pullNeeded start ->", s.pullNeeded)
  185. s.mut.Unlock()
  186. }
  187. func (s *sharedPullerState) pullDone() {
  188. s.mut.Lock()
  189. s.pullNeeded--
  190. l.Debugln("sharedPullerState", s.folder, s.file.Name, "pullNeeded done ->", s.pullNeeded)
  191. s.mut.Unlock()
  192. }
  193. // finalClose atomically closes and returns closed status of a file. A true
  194. // first return value means the file was closed and should be finished, with
  195. // the error indicating the success or failure of the close. A false first
  196. // return value indicates the file is not ready to be closed, or is already
  197. // closed and should in either case not be finished off now.
  198. func (s *sharedPullerState) finalClose() (bool, error) {
  199. s.mut.Lock()
  200. defer s.mut.Unlock()
  201. if s.closed {
  202. // Already closed
  203. return false, nil
  204. }
  205. if s.pullNeeded+s.copyNeeded != 0 && s.err == nil {
  206. // Not done yet, and not errored
  207. return false, nil
  208. }
  209. if s.fd != nil {
  210. if closeErr := s.fd.Close(); closeErr != nil && s.err == nil {
  211. // This is our error if we weren't errored before. Otherwise we
  212. // keep the earlier error.
  213. s.err = closeErr
  214. }
  215. s.fd = nil
  216. }
  217. s.closed = true
  218. return true, s.err
  219. }
  220. // Returns the momentarily progress for the puller
  221. func (s *sharedPullerState) Progress() *pullerProgress {
  222. s.mut.Lock()
  223. defer s.mut.Unlock()
  224. total := s.reused + s.copyTotal + s.pullTotal
  225. done := total - s.copyNeeded - s.pullNeeded
  226. return &pullerProgress{
  227. Total: total,
  228. Reused: s.reused,
  229. CopiedFromOrigin: s.copyOrigin,
  230. CopiedFromElsewhere: s.copyTotal - s.copyNeeded - s.copyOrigin,
  231. Pulled: s.pullTotal - s.pullNeeded,
  232. Pulling: s.pullNeeded,
  233. BytesTotal: db.BlocksToSize(total),
  234. BytesDone: db.BlocksToSize(done),
  235. }
  236. }