sharedpullerstate.go 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257
  1. // Copyright (C) 2014 The Syncthing Authors.
  2. //
  3. // This program is free software: you can redistribute it and/or modify it
  4. // under the terms of the GNU General Public License as published by the Free
  5. // Software Foundation, either version 3 of the License, or (at your option)
  6. // any later version.
  7. //
  8. // This program is distributed in the hope that it will be useful, but WITHOUT
  9. // ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  10. // FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
  11. // more details.
  12. //
  13. // You should have received a copy of the GNU General Public License along
  14. // with this program. If not, see <http://www.gnu.org/licenses/>.
  15. package model
  16. import (
  17. "io"
  18. "os"
  19. "path/filepath"
  20. "sync"
  21. "github.com/syncthing/protocol"
  22. "github.com/syncthing/syncthing/internal/db"
  23. )
  24. // A sharedPullerState is kept for each file that is being synced and is kept
  25. // updated along the way.
  26. type sharedPullerState struct {
  27. // Immutable, does not require locking
  28. file protocol.FileInfo
  29. folder string
  30. tempName string
  31. realName string
  32. reused int // Number of blocks reused from temporary file
  33. ignorePerms bool
  34. // Mutable, must be locked for access
  35. err error // The first error we hit
  36. fd *os.File // The fd of the temp file
  37. copyTotal int // Total number of copy actions for the whole job
  38. pullTotal int // Total number of pull actions for the whole job
  39. copyOrigin int // Number of blocks copied from the original file
  40. copyNeeded int // Number of copy actions still pending
  41. pullNeeded int // Number of block pulls still pending
  42. mut sync.Mutex // Protects the above
  43. }
  44. // A momentary state representing the progress of the puller
  45. type pullerProgress struct {
  46. Total int
  47. Reused int
  48. CopiedFromOrigin int
  49. CopiedFromElsewhere int
  50. Pulled int
  51. Pulling int
  52. BytesDone int64
  53. BytesTotal int64
  54. }
  55. // A lockedWriterAt synchronizes WriteAt calls with an external mutex.
  56. // WriteAt() is goroutine safe by itself, but not against for example Close().
  57. type lockedWriterAt struct {
  58. mut *sync.Mutex
  59. wr io.WriterAt
  60. }
  61. func (w lockedWriterAt) WriteAt(p []byte, off int64) (n int, err error) {
  62. w.mut.Lock()
  63. defer w.mut.Unlock()
  64. return w.wr.WriteAt(p, off)
  65. }
  66. // tempFile returns the fd for the temporary file, reusing an open fd
  67. // or creating the file as necessary.
  68. func (s *sharedPullerState) tempFile() (io.WriterAt, error) {
  69. s.mut.Lock()
  70. defer s.mut.Unlock()
  71. // If we've already hit an error, return early
  72. if s.err != nil {
  73. return nil, s.err
  74. }
  75. // If the temp file is already open, return the file descriptor
  76. if s.fd != nil {
  77. return lockedWriterAt{&s.mut, s.fd}, nil
  78. }
  79. // Ensure that the parent directory is writable. This is
  80. // osutil.InWritableDir except we need to do more stuff so we duplicate it
  81. // here.
  82. dir := filepath.Dir(s.tempName)
  83. if info, err := os.Stat(dir); err != nil {
  84. s.failLocked("dst stat dir", err)
  85. return nil, err
  86. } else if info.Mode()&0200 == 0 {
  87. err := os.Chmod(dir, 0755)
  88. if !s.ignorePerms && err == nil {
  89. defer func() {
  90. err := os.Chmod(dir, info.Mode().Perm())
  91. if err != nil {
  92. panic(err)
  93. }
  94. }()
  95. }
  96. }
  97. // Attempt to create the temp file
  98. flags := os.O_WRONLY
  99. if s.reused == 0 {
  100. flags |= os.O_CREATE | os.O_EXCL
  101. } else {
  102. // With sufficiently bad luck when exiting or crashing, we may have
  103. // had time to chmod the temp file to read only state but not yet
  104. // moved it to it's final name. This leaves us with a read only temp
  105. // file that we're going to try to reuse. To handle that, we need to
  106. // make sure we have write permissions on the file before opening it.
  107. err := os.Chmod(s.tempName, 0644)
  108. if !s.ignorePerms && err != nil {
  109. s.failLocked("dst create chmod", err)
  110. return nil, err
  111. }
  112. }
  113. fd, err := os.OpenFile(s.tempName, flags, 0644)
  114. if err != nil {
  115. s.failLocked("dst create", err)
  116. return nil, err
  117. }
  118. // Same fd will be used by all writers
  119. s.fd = fd
  120. return lockedWriterAt{&s.mut, s.fd}, nil
  121. }
  122. // sourceFile opens the existing source file for reading
  123. func (s *sharedPullerState) sourceFile() (*os.File, error) {
  124. s.mut.Lock()
  125. defer s.mut.Unlock()
  126. // If we've already hit an error, return early
  127. if s.err != nil {
  128. return nil, s.err
  129. }
  130. // Attempt to open the existing file
  131. fd, err := os.Open(s.realName)
  132. if err != nil {
  133. s.failLocked("src open", err)
  134. return nil, err
  135. }
  136. return fd, nil
  137. }
  138. // earlyClose prints a warning message composed of the context and
  139. // error, and marks the sharedPullerState as failed. Is a no-op when called on
  140. // an already failed state.
  141. func (s *sharedPullerState) fail(context string, err error) {
  142. s.mut.Lock()
  143. defer s.mut.Unlock()
  144. s.failLocked(context, err)
  145. }
  146. func (s *sharedPullerState) failLocked(context string, err error) {
  147. if s.err != nil {
  148. return
  149. }
  150. l.Infof("Puller (folder %q, file %q): %s: %v", s.folder, s.file.Name, context, err)
  151. s.err = err
  152. }
  153. func (s *sharedPullerState) failed() error {
  154. s.mut.Lock()
  155. defer s.mut.Unlock()
  156. return s.err
  157. }
  158. func (s *sharedPullerState) copyDone() {
  159. s.mut.Lock()
  160. s.copyNeeded--
  161. if debug {
  162. l.Debugln("sharedPullerState", s.folder, s.file.Name, "copyNeeded ->", s.copyNeeded)
  163. }
  164. s.mut.Unlock()
  165. }
  166. func (s *sharedPullerState) copiedFromOrigin() {
  167. s.mut.Lock()
  168. s.copyOrigin++
  169. s.mut.Unlock()
  170. }
  171. func (s *sharedPullerState) pullStarted() {
  172. s.mut.Lock()
  173. s.copyTotal--
  174. s.copyNeeded--
  175. s.pullTotal++
  176. s.pullNeeded++
  177. if debug {
  178. l.Debugln("sharedPullerState", s.folder, s.file.Name, "pullNeeded start ->", s.pullNeeded)
  179. }
  180. s.mut.Unlock()
  181. }
  182. func (s *sharedPullerState) pullDone() {
  183. s.mut.Lock()
  184. s.pullNeeded--
  185. if debug {
  186. l.Debugln("sharedPullerState", s.folder, s.file.Name, "pullNeeded done ->", s.pullNeeded)
  187. }
  188. s.mut.Unlock()
  189. }
  190. // finalClose atomically closes and returns closed status of a file. A true
  191. // first return value means the file was closed and should be finished, with
  192. // the error indicating the success or failure of the close. A false first
  193. // return value indicates the file is not ready to be closed, or is already
  194. // closed and should in either case not be finished off now.
  195. func (s *sharedPullerState) finalClose() (bool, error) {
  196. s.mut.Lock()
  197. defer s.mut.Unlock()
  198. if s.pullNeeded+s.copyNeeded != 0 && s.err == nil {
  199. // Not done yet.
  200. return false, nil
  201. }
  202. if fd := s.fd; fd != nil {
  203. s.fd = nil
  204. return true, fd.Close()
  205. }
  206. return false, nil
  207. }
  208. // Returns the momentarily progress for the puller
  209. func (s *sharedPullerState) Progress() *pullerProgress {
  210. s.mut.Lock()
  211. defer s.mut.Unlock()
  212. total := s.reused + s.copyTotal + s.pullTotal
  213. done := total - s.copyNeeded - s.pullNeeded
  214. return &pullerProgress{
  215. Total: total,
  216. Reused: s.reused,
  217. CopiedFromOrigin: s.copyOrigin,
  218. CopiedFromElsewhere: s.copyTotal - s.copyNeeded - s.copyOrigin,
  219. Pulled: s.pullTotal - s.pullNeeded,
  220. Pulling: s.pullNeeded,
  221. BytesTotal: db.BlocksToSize(total),
  222. BytesDone: db.BlocksToSize(done),
  223. }
  224. }