1
0

puller.go 21 KB

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