puller.go 24 KB

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