puller.go 21 KB

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