puller.go 20 KB

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