1
0

puller.go 24 KB

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