puller.go 25 KB

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