sharedpullerstate.go 11 KB

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