puller.go 21 KB

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