puller.go 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825
  1. // Copyright (C) 2014 Jakob Borg and Contributors (see the CONTRIBUTORS file).
  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. "bytes"
  18. "crypto/sha256"
  19. "errors"
  20. "fmt"
  21. "os"
  22. "path/filepath"
  23. "sync"
  24. "time"
  25. "github.com/AudriusButkevicius/lfu-go"
  26. "github.com/syncthing/syncthing/internal/config"
  27. "github.com/syncthing/syncthing/internal/events"
  28. "github.com/syncthing/syncthing/internal/osutil"
  29. "github.com/syncthing/syncthing/internal/protocol"
  30. "github.com/syncthing/syncthing/internal/scanner"
  31. "github.com/syncthing/syncthing/internal/versioner"
  32. )
  33. // TODO: Stop on errors
  34. const (
  35. copiersPerFolder = 1
  36. pullersPerFolder = 16
  37. finishersPerFolder = 2
  38. pauseIntv = 60 * time.Second
  39. nextPullIntv = 10 * time.Second
  40. checkPullIntv = 1 * time.Second
  41. )
  42. // A pullBlockState is passed to the puller routine for each block that needs
  43. // to be fetched.
  44. type pullBlockState struct {
  45. *sharedPullerState
  46. block protocol.BlockInfo
  47. }
  48. // A copyBlocksState is passed to copy routine if the file has blocks to be
  49. // copied.
  50. type copyBlocksState struct {
  51. *sharedPullerState
  52. blocks []protocol.BlockInfo
  53. }
  54. var (
  55. activity = newDeviceActivity()
  56. errNoDevice = errors.New("no available source device")
  57. )
  58. type Puller struct {
  59. folder string
  60. dir string
  61. scanIntv time.Duration
  62. model *Model
  63. stop chan struct{}
  64. versioner versioner.Versioner
  65. ignorePerms bool
  66. lenientMtimes bool
  67. }
  68. // Serve will run scans and pulls. It will return when Stop()ed or on a
  69. // critical error.
  70. func (p *Puller) Serve() {
  71. if debug {
  72. l.Debugln(p, "starting")
  73. defer l.Debugln(p, "exiting")
  74. }
  75. p.stop = make(chan struct{})
  76. pullTimer := time.NewTimer(checkPullIntv)
  77. scanTimer := time.NewTimer(time.Millisecond) // The first scan should be done immediately.
  78. cleanTimer := time.NewTicker(time.Hour)
  79. defer func() {
  80. pullTimer.Stop()
  81. scanTimer.Stop()
  82. cleanTimer.Stop()
  83. // TODO: Should there be an actual FolderStopped state?
  84. p.model.setState(p.folder, FolderIdle)
  85. }()
  86. var prevVer uint64
  87. // Clean out old temporaries before we start pulling
  88. p.clean()
  89. // We don't start pulling files until a scan has been completed.
  90. initialScanCompleted := false
  91. loop:
  92. for {
  93. select {
  94. case <-p.stop:
  95. return
  96. // TODO: We could easily add a channel here for notifications from
  97. // Index(), so that we immediately start a pull when new index
  98. // information is available. Before that though, I'd like to build a
  99. // repeatable benchmark of how long it takes to sync a change from
  100. // device A to device B, so we have something to work against.
  101. case <-pullTimer.C:
  102. if !initialScanCompleted {
  103. // How did we even get here?
  104. if debug {
  105. l.Debugln(p, "skip (initial)")
  106. }
  107. pullTimer.Reset(nextPullIntv)
  108. continue
  109. }
  110. // RemoteLocalVersion() is a fast call, doesn't touch the database.
  111. curVer := p.model.RemoteLocalVersion(p.folder)
  112. if curVer == prevVer {
  113. if debug {
  114. l.Debugln(p, "skip (curVer == prevVer)", prevVer)
  115. }
  116. pullTimer.Reset(checkPullIntv)
  117. continue
  118. }
  119. if debug {
  120. l.Debugln(p, "pulling", prevVer, curVer)
  121. }
  122. p.model.setState(p.folder, FolderSyncing)
  123. tries := 0
  124. checksum := false
  125. for {
  126. tries++
  127. // Last resort mode, to get around corrupt/invalid block maps.
  128. if tries == 10 {
  129. l.Infoln("Desperation mode ON")
  130. checksum = true
  131. }
  132. changed := p.pullerIteration(copiersPerFolder, pullersPerFolder, finishersPerFolder, checksum)
  133. if debug {
  134. l.Debugln(p, "changed", changed)
  135. }
  136. if changed == 0 {
  137. // No files were changed by the puller, so we are in
  138. // sync. Remember the local version number and
  139. // schedule a resync a little bit into the future.
  140. if lv := p.model.RemoteLocalVersion(p.folder); lv < curVer {
  141. // There's a corner case where the device we needed
  142. // files from disconnected during the puller
  143. // iteration. The files will have been removed from
  144. // the index, so we've concluded that we don't need
  145. // them, but at the same time we have the local
  146. // version that includes those files in curVer. So we
  147. // catch the case that localVersion might have
  148. // decresed here.
  149. l.Debugln(p, "adjusting curVer", lv)
  150. curVer = lv
  151. }
  152. prevVer = curVer
  153. if debug {
  154. l.Debugln(p, "next pull in", nextPullIntv)
  155. }
  156. pullTimer.Reset(nextPullIntv)
  157. break
  158. }
  159. if tries > 10 {
  160. // We've tried a bunch of times to get in sync, but
  161. // we're not making it. Probably there are write
  162. // errors preventing us. Flag this with a warning and
  163. // wait a bit longer before retrying.
  164. l.Warnf("Folder %q isn't making progress - check logs for possible root cause. Pausing puller for %v.", p.folder, pauseIntv)
  165. if debug {
  166. l.Debugln(p, "next pull in", pauseIntv)
  167. }
  168. pullTimer.Reset(pauseIntv)
  169. break
  170. }
  171. }
  172. p.model.setState(p.folder, FolderIdle)
  173. // The reason for running the scanner from within the puller is that
  174. // this is the easiest way to make sure we are not doing both at the
  175. // same time.
  176. case <-scanTimer.C:
  177. if debug {
  178. l.Debugln(p, "rescan")
  179. }
  180. p.model.setState(p.folder, FolderScanning)
  181. if err := p.model.ScanFolder(p.folder); err != nil {
  182. p.model.cfg.InvalidateFolder(p.folder, err.Error())
  183. break loop
  184. }
  185. p.model.setState(p.folder, FolderIdle)
  186. if p.scanIntv > 0 {
  187. if debug {
  188. l.Debugln(p, "next rescan in", p.scanIntv)
  189. }
  190. scanTimer.Reset(p.scanIntv)
  191. }
  192. if !initialScanCompleted {
  193. l.Infoln("Completed initial scan (rw) of folder", p.folder)
  194. initialScanCompleted = true
  195. }
  196. // Clean out old temporaries
  197. case <-cleanTimer.C:
  198. p.clean()
  199. }
  200. }
  201. }
  202. func (p *Puller) Stop() {
  203. close(p.stop)
  204. }
  205. func (p *Puller) String() string {
  206. return fmt.Sprintf("puller/%s@%p", p.folder, p)
  207. }
  208. // pullerIteration runs a single puller iteration for the given folder and
  209. // returns the number items that should have been synced (even those that
  210. // might have failed). One puller iteration handles all files currently
  211. // flagged as needed in the folder. The specified number of copier, puller and
  212. // finisher routines are used. It's seldom efficient to use more than one
  213. // copier routine, while multiple pullers are essential and multiple finishers
  214. // may be useful (they are primarily CPU bound due to hashing).
  215. func (p *Puller) pullerIteration(ncopiers, npullers, nfinishers int, checksum bool) int {
  216. pullChan := make(chan pullBlockState)
  217. copyChan := make(chan copyBlocksState)
  218. finisherChan := make(chan *sharedPullerState)
  219. var copyWg sync.WaitGroup
  220. var pullWg sync.WaitGroup
  221. var doneWg sync.WaitGroup
  222. for i := 0; i < ncopiers; i++ {
  223. copyWg.Add(1)
  224. go func() {
  225. // copierRoutine finishes when copyChan is closed
  226. p.copierRoutine(copyChan, pullChan, finisherChan, checksum)
  227. copyWg.Done()
  228. }()
  229. }
  230. for i := 0; i < npullers; i++ {
  231. pullWg.Add(1)
  232. go func() {
  233. // pullerRoutine finishes when pullChan is closed
  234. p.pullerRoutine(pullChan, finisherChan)
  235. pullWg.Done()
  236. }()
  237. }
  238. for i := 0; i < nfinishers; i++ {
  239. doneWg.Add(1)
  240. // finisherRoutine finishes when finisherChan is closed
  241. go func() {
  242. p.finisherRoutine(finisherChan)
  243. doneWg.Done()
  244. }()
  245. }
  246. p.model.fmut.RLock()
  247. files := p.model.folderFiles[p.folder]
  248. p.model.fmut.RUnlock()
  249. // !!!
  250. // WithNeed takes a database snapshot (by necessity). By the time we've
  251. // handled a bunch of files it might have become out of date and we might
  252. // be attempting to sync with an old version of a file...
  253. // !!!
  254. changed := 0
  255. var deletions []protocol.FileInfo
  256. files.WithNeed(protocol.LocalDeviceID, func(intf protocol.FileIntf) bool {
  257. // Needed items are delivered sorted lexicographically. This isn't
  258. // really optimal from a performance point of view - it would be
  259. // better if files were handled in random order, to spread the load
  260. // over the cluster. But it means that we can be sure that we fully
  261. // handle directories before the files that go inside them, which is
  262. // nice.
  263. file := intf.(protocol.FileInfo)
  264. events.Default.Log(events.ItemStarted, map[string]string{
  265. "folder": p.folder,
  266. "item": file.Name,
  267. })
  268. if debug {
  269. l.Debugln(p, "handling", file.Name)
  270. }
  271. switch {
  272. case protocol.IsDeleted(file.Flags):
  273. // A deleted file or directory
  274. deletions = append(deletions, file)
  275. case protocol.IsDirectory(file.Flags):
  276. // A new or changed directory
  277. p.handleDir(file)
  278. default:
  279. // A new or changed file. This is the only case where we do stuff
  280. // in the background; the other three are done synchronously.
  281. p.handleFile(file, copyChan, finisherChan)
  282. }
  283. changed++
  284. return true
  285. })
  286. // Signal copy and puller routines that we are done with the in data for
  287. // this iteration. Wait for them to finish.
  288. close(copyChan)
  289. copyWg.Wait()
  290. close(pullChan)
  291. pullWg.Wait()
  292. // Signal the finisher chan that there will be no more input.
  293. close(finisherChan)
  294. // Wait for the finisherChan to finish.
  295. doneWg.Wait()
  296. for i := range deletions {
  297. deletion := deletions[len(deletions)-i-1]
  298. if deletion.IsDirectory() {
  299. p.deleteDir(deletion)
  300. } else {
  301. p.deleteFile(deletion)
  302. }
  303. }
  304. return changed
  305. }
  306. // handleDir creates or updates the given directory
  307. func (p *Puller) handleDir(file protocol.FileInfo) {
  308. realName := filepath.Join(p.dir, file.Name)
  309. mode := os.FileMode(file.Flags & 0777)
  310. if p.ignorePerms {
  311. mode = 0755
  312. }
  313. if debug {
  314. curFile := p.model.CurrentFolderFile(p.folder, file.Name)
  315. l.Debugf("need dir\n\t%v\n\t%v", file, curFile)
  316. }
  317. info, err := os.Stat(realName)
  318. switch {
  319. // There is already something under that name, but it's a file.
  320. // Most likely a file is getting replaced with a directory.
  321. // Remove the file and fall through to directory creation.
  322. case err == nil && !info.IsDir():
  323. err = osutil.InWritableDir(os.Remove, realName)
  324. if err != nil {
  325. l.Infof("Puller (folder %q, dir %q): %v", p.folder, file.Name, err)
  326. return
  327. }
  328. fallthrough
  329. // The directory doesn't exist, so we create it with the right
  330. // mode bits from the start.
  331. case err != nil && os.IsNotExist(err):
  332. // We declare a function that acts on only the path name, so
  333. // we can pass it to InWritableDir. We use a regular Mkdir and
  334. // not MkdirAll because the parent should already exist.
  335. mkdir := func(path string) error {
  336. return os.Mkdir(path, mode)
  337. }
  338. if err = osutil.InWritableDir(mkdir, realName); err == nil {
  339. p.model.updateLocal(p.folder, file)
  340. } else {
  341. l.Infof("Puller (folder %q, dir %q): %v", p.folder, file.Name, err)
  342. }
  343. return
  344. // Weird error when stat()'ing the dir. Probably won't work to do
  345. // anything else with it if we can't even stat() it.
  346. case err != nil:
  347. l.Infof("Puller (folder %q, dir %q): %v", p.folder, file.Name, err)
  348. return
  349. }
  350. // The directory already exists, so we just correct the mode bits. (We
  351. // don't handle modification times on directories, because that sucks...)
  352. // It's OK to change mode bits on stuff within non-writable directories.
  353. if p.ignorePerms {
  354. p.model.updateLocal(p.folder, file)
  355. } else if err := os.Chmod(realName, mode); err == nil {
  356. p.model.updateLocal(p.folder, file)
  357. } else {
  358. l.Infof("Puller (folder %q, dir %q): %v", p.folder, file.Name, err)
  359. }
  360. }
  361. // deleteDir attempts to delete the given directory
  362. func (p *Puller) deleteDir(file protocol.FileInfo) {
  363. realName := filepath.Join(p.dir, file.Name)
  364. // Delete any temporary files lying around in the directory
  365. dir, _ := os.Open(realName)
  366. if dir != nil {
  367. files, _ := dir.Readdirnames(-1)
  368. for _, file := range files {
  369. if defTempNamer.IsTemporary(file) {
  370. osutil.InWritableDir(os.Remove, filepath.Join(realName, file))
  371. }
  372. }
  373. }
  374. err := osutil.InWritableDir(os.Remove, realName)
  375. if err == nil || os.IsNotExist(err) {
  376. p.model.updateLocal(p.folder, file)
  377. } else {
  378. l.Infof("Puller (folder %q, dir %q): delete: %v", p.folder, file.Name, err)
  379. }
  380. }
  381. // deleteFile attempts to delete the given file
  382. func (p *Puller) deleteFile(file protocol.FileInfo) {
  383. realName := filepath.Join(p.dir, file.Name)
  384. var err error
  385. if p.versioner != nil {
  386. err = osutil.InWritableDir(p.versioner.Archive, realName)
  387. } else {
  388. err = osutil.InWritableDir(os.Remove, realName)
  389. }
  390. if err != nil && !os.IsNotExist(err) {
  391. l.Infof("Puller (folder %q, file %q): delete: %v", p.folder, file.Name, err)
  392. } else {
  393. p.model.updateLocal(p.folder, file)
  394. }
  395. }
  396. // handleFile queues the copies and pulls as necessary for a single new or
  397. // changed file.
  398. func (p *Puller) handleFile(file protocol.FileInfo, copyChan chan<- copyBlocksState, finisherChan chan<- *sharedPullerState) {
  399. curFile := p.model.CurrentFolderFile(p.folder, file.Name)
  400. if len(curFile.Blocks) == len(file.Blocks) {
  401. for i := range file.Blocks {
  402. if !bytes.Equal(curFile.Blocks[i].Hash, file.Blocks[i].Hash) {
  403. goto FilesAreDifferent
  404. }
  405. }
  406. // We are supposed to copy the entire file, and then fetch nothing. We
  407. // are only updating metadata, so we don't actually *need* to make the
  408. // copy.
  409. if debug {
  410. l.Debugln(p, "taking shortcut on", file.Name)
  411. }
  412. p.shortcutFile(file)
  413. return
  414. }
  415. FilesAreDifferent:
  416. scanner.PopulateOffsets(file.Blocks)
  417. // Figure out the absolute filenames we need once and for all
  418. tempName := filepath.Join(p.dir, defTempNamer.TempName(file.Name))
  419. realName := filepath.Join(p.dir, file.Name)
  420. reused := 0
  421. var blocks []protocol.BlockInfo
  422. // Check for an old temporary file which might have some blocks we could
  423. // reuse.
  424. tempBlocks, err := scanner.HashFile(tempName, protocol.BlockSize)
  425. if err == nil {
  426. // Check for any reusable blocks in the temp file
  427. tempCopyBlocks, _ := scanner.BlockDiff(tempBlocks, file.Blocks)
  428. // block.String() returns a string unique to the block
  429. existingBlocks := make(map[string]bool, len(tempCopyBlocks))
  430. for _, block := range tempCopyBlocks {
  431. existingBlocks[block.String()] = true
  432. }
  433. // Since the blocks are already there, we don't need to get them.
  434. for _, block := range file.Blocks {
  435. _, ok := existingBlocks[block.String()]
  436. if !ok {
  437. blocks = append(blocks, block)
  438. }
  439. }
  440. // The sharedpullerstate will know which flags to use when opening the
  441. // temp file depending if we are reusing any blocks or not.
  442. reused = len(file.Blocks) - len(blocks)
  443. if reused == 0 {
  444. // Otherwise, discard the file ourselves in order for the
  445. // sharedpuller not to panic when it fails to exlusively create a
  446. // file which already exists
  447. os.Remove(tempName)
  448. }
  449. } else {
  450. blocks = file.Blocks
  451. }
  452. s := sharedPullerState{
  453. file: file,
  454. folder: p.folder,
  455. tempName: tempName,
  456. realName: realName,
  457. copyTotal: len(blocks),
  458. copyNeeded: len(blocks),
  459. reused: reused,
  460. }
  461. if debug {
  462. l.Debugf("%v need file %s; copy %d, reused %v", p, file.Name, len(blocks), reused)
  463. }
  464. cs := copyBlocksState{
  465. sharedPullerState: &s,
  466. blocks: blocks,
  467. }
  468. copyChan <- cs
  469. }
  470. // shortcutFile sets file mode and modification time, when that's the only
  471. // thing that has changed.
  472. func (p *Puller) shortcutFile(file protocol.FileInfo) {
  473. realName := filepath.Join(p.dir, file.Name)
  474. if !p.ignorePerms {
  475. err := os.Chmod(realName, os.FileMode(file.Flags&0777))
  476. if err != nil {
  477. l.Infof("Puller (folder %q, file %q): shortcut: %v", p.folder, file.Name, err)
  478. return
  479. }
  480. }
  481. t := time.Unix(file.Modified, 0)
  482. err := os.Chtimes(realName, t, t)
  483. if err != nil {
  484. if p.lenientMtimes {
  485. // We accept the failure with a warning here and allow the sync to
  486. // continue. We'll sync the new mtime back to the other devices later.
  487. // If they have the same problem & setting, we might never get in
  488. // sync.
  489. l.Infof("Puller (folder %q, file %q): shortcut: %v (continuing anyway as requested)", p.folder, file.Name, err)
  490. } else {
  491. l.Infof("Puller (folder %q, file %q): shortcut: %v", p.folder, file.Name, err)
  492. return
  493. }
  494. }
  495. p.model.updateLocal(p.folder, file)
  496. }
  497. // copierRoutine reads copierStates until the in channel closes and performs
  498. // the relevant copies when possible, or passes it to the puller routine.
  499. func (p *Puller) copierRoutine(in <-chan copyBlocksState, pullChan chan<- pullBlockState, out chan<- *sharedPullerState, checksum bool) {
  500. buf := make([]byte, protocol.BlockSize)
  501. nextFile:
  502. for state := range in {
  503. dstFd, err := state.tempFile()
  504. if err != nil {
  505. // Nothing more to do for this failed file (the error was logged
  506. // when it happened)
  507. continue nextFile
  508. }
  509. evictionChan := make(chan lfu.Eviction)
  510. fdCache := lfu.New()
  511. fdCache.UpperBound = 50
  512. fdCache.LowerBound = 20
  513. fdCache.EvictionChannel = evictionChan
  514. go func() {
  515. for item := range evictionChan {
  516. item.Value.(*os.File).Close()
  517. }
  518. }()
  519. folderRoots := make(map[string]string)
  520. p.model.fmut.RLock()
  521. for folder, cfg := range p.model.folderCfgs {
  522. folderRoots[folder] = cfg.Path
  523. }
  524. p.model.fmut.RUnlock()
  525. hasher := sha256.New()
  526. for _, block := range state.blocks {
  527. buf = buf[:int(block.Size)]
  528. found := p.model.finder.Iterate(block.Hash, func(folder, file string, index uint32) bool {
  529. path := filepath.Join(folderRoots[folder], file)
  530. var fd *os.File
  531. fdi := fdCache.Get(path)
  532. if fdi != nil {
  533. fd = fdi.(*os.File)
  534. } else {
  535. fd, err = os.Open(path)
  536. if err != nil {
  537. return false
  538. }
  539. fdCache.Set(path, fd)
  540. }
  541. _, err = fd.ReadAt(buf, protocol.BlockSize*int64(index))
  542. if err != nil {
  543. return false
  544. }
  545. // Only done on second to last puller attempt
  546. if checksum {
  547. hasher.Write(buf)
  548. hash := hasher.Sum(nil)
  549. hasher.Reset()
  550. if !bytes.Equal(hash, block.Hash) {
  551. if debug {
  552. l.Debugf("Finder block mismatch in %s:%s:%d expected %q got %q", folder, file, index, block.Hash, hash)
  553. }
  554. err = p.model.finder.Fix(folder, file, index, block.Hash, hash)
  555. if err != nil {
  556. l.Warnln("finder fix:", err)
  557. }
  558. return false
  559. }
  560. }
  561. _, err = dstFd.WriteAt(buf, block.Offset)
  562. if err != nil {
  563. state.earlyClose("dst write", err)
  564. }
  565. if file == state.file.Name {
  566. state.copiedFromOrigin()
  567. }
  568. return true
  569. })
  570. if state.failed() != nil {
  571. break
  572. }
  573. if !found {
  574. state.pullStarted()
  575. ps := pullBlockState{
  576. sharedPullerState: state.sharedPullerState,
  577. block: block,
  578. }
  579. pullChan <- ps
  580. } else {
  581. state.copyDone()
  582. }
  583. }
  584. fdCache.Evict(fdCache.Len())
  585. close(evictionChan)
  586. out <- state.sharedPullerState
  587. }
  588. }
  589. func (p *Puller) pullerRoutine(in <-chan pullBlockState, out chan<- *sharedPullerState) {
  590. nextBlock:
  591. for state := range in {
  592. if state.failed() != nil {
  593. continue nextBlock
  594. }
  595. // Select the least busy device to pull the block from. If we found no
  596. // feasible device at all, fail the block (and in the long run, the
  597. // file).
  598. potentialDevices := p.model.availability(p.folder, state.file.Name)
  599. selected := activity.leastBusy(potentialDevices)
  600. if selected == (protocol.DeviceID{}) {
  601. state.earlyClose("pull", errNoDevice)
  602. continue nextBlock
  603. }
  604. // Get an fd to the temporary file. Tehcnically we don't need it until
  605. // after fetching the block, but if we run into an error here there is
  606. // no point in issuing the request to the network.
  607. fd, err := state.tempFile()
  608. if err != nil {
  609. continue nextBlock
  610. }
  611. // Fetch the block, while marking the selected device as in use so that
  612. // leastBusy can select another device when someone else asks.
  613. activity.using(selected)
  614. buf, err := p.model.requestGlobal(selected, p.folder, state.file.Name, state.block.Offset, int(state.block.Size), state.block.Hash)
  615. activity.done(selected)
  616. if err != nil {
  617. state.earlyClose("pull", err)
  618. continue nextBlock
  619. }
  620. // Save the block data we got from the cluster
  621. _, err = fd.WriteAt(buf, state.block.Offset)
  622. if err != nil {
  623. state.earlyClose("save", err)
  624. continue nextBlock
  625. }
  626. state.pullDone()
  627. out <- state.sharedPullerState
  628. }
  629. }
  630. func (p *Puller) finisherRoutine(in <-chan *sharedPullerState) {
  631. for state := range in {
  632. if closed, err := state.finalClose(); closed {
  633. if debug {
  634. l.Debugln(p, "closing", state.file.Name)
  635. }
  636. if err != nil {
  637. l.Warnln("puller: final:", err)
  638. continue
  639. }
  640. // Verify the file against expected hashes
  641. fd, err := os.Open(state.tempName)
  642. if err != nil {
  643. l.Warnln("puller: final:", err)
  644. continue
  645. }
  646. err = scanner.Verify(fd, protocol.BlockSize, state.file.Blocks)
  647. fd.Close()
  648. if err != nil {
  649. l.Infoln("puller:", state.file.Name, err, "(file changed during pull?)")
  650. continue
  651. }
  652. // Set the correct permission bits on the new file
  653. if !p.ignorePerms {
  654. err = os.Chmod(state.tempName, os.FileMode(state.file.Flags&0777))
  655. if err != nil {
  656. l.Warnln("puller: final:", err)
  657. continue
  658. }
  659. }
  660. // Set the correct timestamp on the new file
  661. t := time.Unix(state.file.Modified, 0)
  662. err = os.Chtimes(state.tempName, t, t)
  663. if err != nil {
  664. if p.lenientMtimes {
  665. // We accept the failure with a warning here and allow the sync to
  666. // continue. We'll sync the new mtime back to the other devices later.
  667. // If they have the same problem & setting, we might never get in
  668. // sync.
  669. l.Infof("Puller (folder %q, file %q): final: %v (continuing anyway as requested)", p.folder, state.file.Name, err)
  670. } else {
  671. l.Warnln("puller: final:", err)
  672. continue
  673. }
  674. }
  675. // If we should use versioning, let the versioner archive the old
  676. // file before we replace it. Archiving a non-existent file is not
  677. // an error.
  678. if p.versioner != nil {
  679. err = p.versioner.Archive(state.realName)
  680. if err != nil {
  681. l.Warnln("puller: final:", err)
  682. continue
  683. }
  684. }
  685. // Replace the original file with the new one
  686. err = osutil.Rename(state.tempName, state.realName)
  687. if err != nil {
  688. l.Warnln("puller: final:", err)
  689. continue
  690. }
  691. // Record the updated file in the index
  692. p.model.updateLocal(p.folder, state.file)
  693. }
  694. }
  695. }
  696. // clean deletes orphaned temporary files
  697. func (p *Puller) clean() {
  698. keep := time.Duration(p.model.cfg.Options().KeepTemporariesH) * time.Hour
  699. now := time.Now()
  700. filepath.Walk(p.dir, func(path string, info os.FileInfo, err error) error {
  701. if err != nil {
  702. return err
  703. }
  704. if info.Mode().IsRegular() && defTempNamer.IsTemporary(path) && info.ModTime().Add(keep).Before(now) {
  705. os.Remove(path)
  706. }
  707. return nil
  708. })
  709. }
  710. func invalidateFolder(cfg *config.Configuration, folderID string, err error) {
  711. for i := range cfg.Folders {
  712. folder := &cfg.Folders[i]
  713. if folder.ID == folderID {
  714. folder.Invalid = err.Error()
  715. return
  716. }
  717. }
  718. }