sharedpullerstate.go 9.6 KB

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