sharedpullerstate.go 6.8 KB

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