puller.go 24 KB

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