puller.go 21 KB

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