sharedpullerstate.go 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322
  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. "time"
  12. "github.com/syncthing/syncthing/lib/db"
  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. folder string
  22. tempName string
  23. realName string
  24. reused int // Number of blocks reused from temporary file
  25. ignorePerms bool
  26. version protocol.Vector // The current (old) version
  27. sparse bool
  28. // Mutable, must be locked for access
  29. err error // The first error we hit
  30. fd *os.File // The fd of the temp file
  31. copyTotal int // Total number of copy actions for the whole job
  32. pullTotal int // Total number of pull actions for the whole job
  33. copyOrigin int // Number of blocks copied from the original file
  34. copyNeeded int // Number of copy actions still pending
  35. pullNeeded int // Number of block pulls still pending
  36. updated time.Time // Time when any of the counters above were last updated
  37. closed bool // True if the file has been finalClosed.
  38. available []int32 // Indexes of the blocks that are available in the temporary file
  39. availableUpdated time.Time // Time when list of available blocks was last updated
  40. mut sync.RWMutex // Protects the above
  41. }
  42. // A momentary state representing the progress of the puller
  43. type pullerProgress struct {
  44. Total int `json:"total"`
  45. Reused int `json:"reused"`
  46. CopiedFromOrigin int `json:"copiedFromOrigin"`
  47. CopiedFromElsewhere int `json:"copiedFromElsewhere"`
  48. Pulled int `json:"pulled"`
  49. Pulling int `json:"pulling"`
  50. BytesDone int64 `json:"bytesDone"`
  51. BytesTotal int64 `json:"bytesTotal"`
  52. }
  53. // A lockedWriterAt synchronizes WriteAt calls with an external mutex.
  54. // WriteAt() is goroutine safe by itself, but not against for example Close().
  55. type lockedWriterAt struct {
  56. mut *sync.RWMutex
  57. wr io.WriterAt
  58. }
  59. func (w lockedWriterAt) WriteAt(p []byte, off int64) (n int, err error) {
  60. (*w.mut).Lock()
  61. defer (*w.mut).Unlock()
  62. return w.wr.WriteAt(p, off)
  63. }
  64. // tempFile returns the fd for the temporary file, reusing an open fd
  65. // or creating the file as necessary.
  66. func (s *sharedPullerState) tempFile() (io.WriterAt, error) {
  67. s.mut.Lock()
  68. defer s.mut.Unlock()
  69. // If we've already hit an error, return early
  70. if s.err != nil {
  71. return nil, s.err
  72. }
  73. // If the temp file is already open, return the file descriptor
  74. if s.fd != nil {
  75. return lockedWriterAt{&s.mut, s.fd}, nil
  76. }
  77. // Ensure that the parent directory is writable. This is
  78. // osutil.InWritableDir except we need to do more stuff so we duplicate it
  79. // here.
  80. dir := filepath.Dir(s.tempName)
  81. if info, err := os.Stat(dir); err != nil {
  82. if os.IsNotExist(err) {
  83. // XXX: This works around a bug elsewhere, a race condition when
  84. // things are deleted while being synced. However that happens, we
  85. // end up with a directory for "foo" with the delete bit, but a
  86. // file "foo/bar" that we want to sync. We never create the
  87. // directory, and hence fail to create the file and end up looping
  88. // forever on it. This breaks that by creating the directory; on
  89. // next scan it'll be found and the delete bit on it is removed.
  90. // The user can then clean up as they like...
  91. l.Infoln("Resurrecting directory", dir)
  92. if err := os.MkdirAll(dir, 0755); err != nil {
  93. s.failLocked("resurrect dir", err)
  94. return nil, err
  95. }
  96. } else {
  97. s.failLocked("dst stat dir", err)
  98. return nil, err
  99. }
  100. } else if info.Mode()&0200 == 0 {
  101. err := os.Chmod(dir, 0755)
  102. if !s.ignorePerms && err == nil {
  103. defer func() {
  104. err := os.Chmod(dir, info.Mode().Perm())
  105. if err != nil {
  106. panic(err)
  107. }
  108. }()
  109. }
  110. }
  111. // Attempt to create the temp file
  112. // RDWR because of issue #2994.
  113. flags := os.O_RDWR
  114. if s.reused == 0 {
  115. flags |= os.O_CREATE | os.O_EXCL
  116. } else {
  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 it's 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. err := os.Chmod(s.tempName, 0644)
  123. if !s.ignorePerms && err != nil {
  124. s.failLocked("dst create chmod", err)
  125. return nil, err
  126. }
  127. }
  128. fd, err := os.OpenFile(s.tempName, flags, 0666)
  129. if err != nil {
  130. s.failLocked("dst create", err)
  131. return nil, err
  132. }
  133. // Don't truncate symlink files, as that will mean that the path will
  134. // contain a bunch of nulls.
  135. if s.sparse && !s.file.IsSymlink() {
  136. // Truncate sets the size of the file. This creates a sparse file or a
  137. // space reservation, depending on the underlying filesystem.
  138. if err := fd.Truncate(s.file.Size()); err != nil {
  139. s.failLocked("dst truncate", err)
  140. return nil, err
  141. }
  142. }
  143. // Same fd will be used by all writers
  144. s.fd = fd
  145. return lockedWriterAt{&s.mut, s.fd}, nil
  146. }
  147. // sourceFile opens the existing source file for reading
  148. func (s *sharedPullerState) sourceFile() (*os.File, error) {
  149. s.mut.Lock()
  150. defer s.mut.Unlock()
  151. // If we've already hit an error, return early
  152. if s.err != nil {
  153. return nil, s.err
  154. }
  155. // Attempt to open the existing file
  156. fd, err := os.Open(s.realName)
  157. if err != nil {
  158. s.failLocked("src open", err)
  159. return nil, err
  160. }
  161. return fd, nil
  162. }
  163. // earlyClose prints a warning message composed of the context and
  164. // error, and marks the sharedPullerState as failed. Is a no-op when called on
  165. // an already failed state.
  166. func (s *sharedPullerState) fail(context string, err error) {
  167. s.mut.Lock()
  168. defer s.mut.Unlock()
  169. s.failLocked(context, err)
  170. }
  171. func (s *sharedPullerState) failLocked(context string, err error) {
  172. if s.err != nil {
  173. return
  174. }
  175. l.Infof("Puller (folder %q, file %q): %s: %v", s.folder, s.file.Name, context, err)
  176. s.err = err
  177. }
  178. func (s *sharedPullerState) failed() error {
  179. s.mut.RLock()
  180. err := s.err
  181. s.mut.RUnlock()
  182. return err
  183. }
  184. func (s *sharedPullerState) copyDone(block protocol.BlockInfo) {
  185. s.mut.Lock()
  186. s.copyNeeded--
  187. s.updated = time.Now()
  188. s.available = append(s.available, int32(block.Offset/protocol.BlockSize))
  189. s.availableUpdated = time.Now()
  190. l.Debugln("sharedPullerState", s.folder, s.file.Name, "copyNeeded ->", s.copyNeeded)
  191. s.mut.Unlock()
  192. }
  193. func (s *sharedPullerState) copiedFromOrigin() {
  194. s.mut.Lock()
  195. s.copyOrigin++
  196. s.updated = time.Now()
  197. s.mut.Unlock()
  198. }
  199. func (s *sharedPullerState) pullStarted() {
  200. s.mut.Lock()
  201. s.copyTotal--
  202. s.copyNeeded--
  203. s.pullTotal++
  204. s.pullNeeded++
  205. s.updated = time.Now()
  206. l.Debugln("sharedPullerState", s.folder, s.file.Name, "pullNeeded start ->", s.pullNeeded)
  207. s.mut.Unlock()
  208. }
  209. func (s *sharedPullerState) pullDone(block protocol.BlockInfo) {
  210. s.mut.Lock()
  211. s.pullNeeded--
  212. s.updated = time.Now()
  213. s.available = append(s.available, int32(block.Offset/protocol.BlockSize))
  214. s.availableUpdated = time.Now()
  215. l.Debugln("sharedPullerState", s.folder, s.file.Name, "pullNeeded done ->", s.pullNeeded)
  216. s.mut.Unlock()
  217. }
  218. // finalClose atomically closes and returns closed status of a file. A true
  219. // first return value means the file was closed and should be finished, with
  220. // the error indicating the success or failure of the close. A false first
  221. // return value indicates the file is not ready to be closed, or is already
  222. // closed and should in either case not be finished off now.
  223. func (s *sharedPullerState) finalClose() (bool, error) {
  224. s.mut.Lock()
  225. defer s.mut.Unlock()
  226. if s.closed {
  227. // Already closed
  228. return false, nil
  229. }
  230. if s.pullNeeded+s.copyNeeded != 0 && s.err == nil {
  231. // Not done yet, and not errored
  232. return false, nil
  233. }
  234. if s.fd != nil {
  235. if closeErr := s.fd.Close(); closeErr != nil && s.err == nil {
  236. // This is our error if we weren't errored before. Otherwise we
  237. // keep the earlier error.
  238. s.err = closeErr
  239. }
  240. s.fd = nil
  241. }
  242. s.closed = true
  243. return true, s.err
  244. }
  245. // Progress returns the momentarily progress for the puller
  246. func (s *sharedPullerState) Progress() *pullerProgress {
  247. s.mut.RLock()
  248. defer s.mut.RUnlock()
  249. total := s.reused + s.copyTotal + s.pullTotal
  250. done := total - s.copyNeeded - s.pullNeeded
  251. return &pullerProgress{
  252. Total: total,
  253. Reused: s.reused,
  254. CopiedFromOrigin: s.copyOrigin,
  255. CopiedFromElsewhere: s.copyTotal - s.copyNeeded - s.copyOrigin,
  256. Pulled: s.pullTotal - s.pullNeeded,
  257. Pulling: s.pullNeeded,
  258. BytesTotal: db.BlocksToSize(total),
  259. BytesDone: db.BlocksToSize(done),
  260. }
  261. }
  262. // Updated returns the time when any of the progress related counters was last updated.
  263. func (s *sharedPullerState) Updated() time.Time {
  264. s.mut.RLock()
  265. t := s.updated
  266. s.mut.RUnlock()
  267. return t
  268. }
  269. // AvailableUpdated returns the time last time list of available blocks was updated
  270. func (s *sharedPullerState) AvailableUpdated() time.Time {
  271. s.mut.RLock()
  272. t := s.availableUpdated
  273. s.mut.RUnlock()
  274. return t
  275. }
  276. // Available returns blocks available in the current temporary file
  277. func (s *sharedPullerState) Available() []int32 {
  278. s.mut.RLock()
  279. blocks := s.available
  280. s.mut.RUnlock()
  281. return blocks
  282. }