puller.go 20 KB

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