puller.go 21 KB

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