puller.go 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950
  1. // Copyright (C) 2014 The Syncthing Authors.
  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. "io/ioutil"
  20. "math/rand"
  21. "os"
  22. "path/filepath"
  23. "sync"
  24. "time"
  25. "github.com/syncthing/protocol"
  26. "github.com/syncthing/syncthing/internal/config"
  27. "github.com/syncthing/syncthing/internal/db"
  28. "github.com/syncthing/syncthing/internal/events"
  29. "github.com/syncthing/syncthing/internal/ignore"
  30. "github.com/syncthing/syncthing/internal/osutil"
  31. "github.com/syncthing/syncthing/internal/scanner"
  32. "github.com/syncthing/syncthing/internal/symlinks"
  33. "github.com/syncthing/syncthing/internal/versioner"
  34. )
  35. // TODO: Stop on errors
  36. const (
  37. pauseIntv = 60 * time.Second
  38. nextPullIntv = 10 * time.Second
  39. checkPullIntv = 1 * time.Second
  40. )
  41. // A pullBlockState is passed to the puller routine for each block that needs
  42. // to be fetched.
  43. type pullBlockState struct {
  44. *sharedPullerState
  45. block protocol.BlockInfo
  46. }
  47. // A copyBlocksState is passed to copy routine if the file has blocks to be
  48. // copied.
  49. type copyBlocksState struct {
  50. *sharedPullerState
  51. blocks []protocol.BlockInfo
  52. }
  53. var (
  54. activity = newDeviceActivity()
  55. errNoDevice = errors.New("no available source device")
  56. )
  57. type Puller struct {
  58. folder string
  59. dir string
  60. scanIntv time.Duration
  61. model *Model
  62. stop chan struct{}
  63. versioner versioner.Versioner
  64. ignorePerms bool
  65. lenientMtimes bool
  66. progressEmitter *ProgressEmitter
  67. copiers int
  68. pullers int
  69. queue *jobQueue
  70. }
  71. // Serve will run scans and pulls. It will return when Stop()ed or on a
  72. // critical error.
  73. func (p *Puller) Serve() {
  74. if debug {
  75. l.Debugln(p, "starting")
  76. defer l.Debugln(p, "exiting")
  77. }
  78. p.stop = make(chan struct{})
  79. pullTimer := time.NewTimer(checkPullIntv)
  80. scanTimer := time.NewTimer(time.Millisecond) // The first scan should be done immediately.
  81. defer func() {
  82. pullTimer.Stop()
  83. scanTimer.Stop()
  84. // TODO: Should there be an actual FolderStopped state?
  85. p.model.setState(p.folder, FolderIdle)
  86. }()
  87. var prevVer int64
  88. var prevIgnoreHash string
  89. // We don't start pulling files until a scan has been completed.
  90. initialScanCompleted := false
  91. loop:
  92. for {
  93. select {
  94. case <-p.stop:
  95. return
  96. // TODO: We could easily add a channel here for notifications from
  97. // Index(), so that we immediately start a pull when new index
  98. // information is available. Before that though, I'd like to build a
  99. // repeatable benchmark of how long it takes to sync a change from
  100. // device A to device B, so we have something to work against.
  101. case <-pullTimer.C:
  102. if !initialScanCompleted {
  103. // How did we even get here?
  104. if debug {
  105. l.Debugln(p, "skip (initial)")
  106. }
  107. pullTimer.Reset(nextPullIntv)
  108. continue
  109. }
  110. p.model.fmut.RLock()
  111. curIgnores := p.model.folderIgnores[p.folder]
  112. p.model.fmut.RUnlock()
  113. if newHash := curIgnores.Hash(); newHash != prevIgnoreHash {
  114. // The ignore patterns have changed. We need to re-evaluate if
  115. // there are files we need now that were ignored before.
  116. if debug {
  117. l.Debugln(p, "ignore patterns have changed, resetting prevVer")
  118. }
  119. prevVer = 0
  120. prevIgnoreHash = newHash
  121. }
  122. // RemoteLocalVersion() is a fast call, doesn't touch the database.
  123. curVer := p.model.RemoteLocalVersion(p.folder)
  124. if curVer == prevVer {
  125. if debug {
  126. l.Debugln(p, "skip (curVer == prevVer)", prevVer)
  127. }
  128. pullTimer.Reset(checkPullIntv)
  129. continue
  130. }
  131. if debug {
  132. l.Debugln(p, "pulling", prevVer, curVer)
  133. }
  134. p.model.setState(p.folder, FolderSyncing)
  135. tries := 0
  136. for {
  137. tries++
  138. changed := p.pullerIteration(curIgnores)
  139. if debug {
  140. l.Debugln(p, "changed", changed)
  141. }
  142. if changed == 0 {
  143. // No files were changed by the puller, so we are in
  144. // sync. Remember the local version number and
  145. // schedule a resync a little bit into the future.
  146. if lv := p.model.RemoteLocalVersion(p.folder); lv < curVer {
  147. // There's a corner case where the device we needed
  148. // files from disconnected during the puller
  149. // iteration. The files will have been removed from
  150. // the index, so we've concluded that we don't need
  151. // them, but at the same time we have the local
  152. // version that includes those files in curVer. So we
  153. // catch the case that localVersion might have
  154. // decreased here.
  155. l.Debugln(p, "adjusting curVer", lv)
  156. curVer = lv
  157. }
  158. prevVer = curVer
  159. if debug {
  160. l.Debugln(p, "next pull in", nextPullIntv)
  161. }
  162. pullTimer.Reset(nextPullIntv)
  163. break
  164. }
  165. if tries > 10 {
  166. // We've tried a bunch of times to get in sync, but
  167. // we're not making it. Probably there are write
  168. // errors preventing us. Flag this with a warning and
  169. // wait a bit longer before retrying.
  170. l.Warnf("Folder %q isn't making progress - check logs for possible root cause. Pausing puller for %v.", p.folder, pauseIntv)
  171. if debug {
  172. l.Debugln(p, "next pull in", pauseIntv)
  173. }
  174. pullTimer.Reset(pauseIntv)
  175. break
  176. }
  177. }
  178. p.model.setState(p.folder, FolderIdle)
  179. // The reason for running the scanner from within the puller is that
  180. // this is the easiest way to make sure we are not doing both at the
  181. // same time.
  182. case <-scanTimer.C:
  183. if debug {
  184. l.Debugln(p, "rescan")
  185. }
  186. p.model.setState(p.folder, FolderScanning)
  187. if err := p.model.ScanFolder(p.folder); err != nil {
  188. p.model.cfg.InvalidateFolder(p.folder, err.Error())
  189. break loop
  190. }
  191. p.model.setState(p.folder, FolderIdle)
  192. if p.scanIntv > 0 {
  193. // Sleep a random time between 3/4 and 5/4 of the configured interval.
  194. sleepNanos := (p.scanIntv.Nanoseconds()*3 + rand.Int63n(2*p.scanIntv.Nanoseconds())) / 4
  195. intv := time.Duration(sleepNanos) * time.Nanosecond
  196. if debug {
  197. l.Debugln(p, "next rescan in", intv)
  198. }
  199. scanTimer.Reset(intv)
  200. }
  201. if !initialScanCompleted {
  202. l.Infoln("Completed initial scan (rw) of folder", p.folder)
  203. initialScanCompleted = true
  204. }
  205. }
  206. }
  207. }
  208. func (p *Puller) Stop() {
  209. close(p.stop)
  210. }
  211. func (p *Puller) String() string {
  212. return fmt.Sprintf("puller/%s@%p", p.folder, p)
  213. }
  214. // pullerIteration runs a single puller iteration for the given folder and
  215. // returns the number items that should have been synced (even those that
  216. // might have failed). One puller iteration handles all files currently
  217. // flagged as needed in the folder.
  218. func (p *Puller) pullerIteration(ignores *ignore.Matcher) int {
  219. pullChan := make(chan pullBlockState)
  220. copyChan := make(chan copyBlocksState)
  221. finisherChan := make(chan *sharedPullerState)
  222. var copyWg sync.WaitGroup
  223. var pullWg sync.WaitGroup
  224. var doneWg sync.WaitGroup
  225. if debug {
  226. l.Debugln(p, "c", p.copiers, "p", p.pullers)
  227. }
  228. for i := 0; i < p.copiers; i++ {
  229. copyWg.Add(1)
  230. go func() {
  231. // copierRoutine finishes when copyChan is closed
  232. p.copierRoutine(copyChan, pullChan, finisherChan)
  233. copyWg.Done()
  234. }()
  235. }
  236. for i := 0; i < p.pullers; i++ {
  237. pullWg.Add(1)
  238. go func() {
  239. // pullerRoutine finishes when pullChan is closed
  240. p.pullerRoutine(pullChan, finisherChan)
  241. pullWg.Done()
  242. }()
  243. }
  244. doneWg.Add(1)
  245. // finisherRoutine finishes when finisherChan is closed
  246. go func() {
  247. p.finisherRoutine(finisherChan)
  248. doneWg.Done()
  249. }()
  250. p.model.fmut.RLock()
  251. folderFiles := p.model.folderFiles[p.folder]
  252. p.model.fmut.RUnlock()
  253. // !!!
  254. // WithNeed takes a database snapshot (by necessity). By the time we've
  255. // handled a bunch of files it might have become out of date and we might
  256. // be attempting to sync with an old version of a file...
  257. // !!!
  258. changed := 0
  259. fileDeletions := map[string]protocol.FileInfo{}
  260. dirDeletions := []protocol.FileInfo{}
  261. buckets := map[string][]protocol.FileInfo{}
  262. folderFiles.WithNeed(protocol.LocalDeviceID, func(intf db.FileIntf) bool {
  263. // Needed items are delivered sorted lexicographically. This isn't
  264. // really optimal from a performance point of view - it would be
  265. // better if files were handled in random order, to spread the load
  266. // over the cluster. But it means that we can be sure that we fully
  267. // handle directories before the files that go inside them, which is
  268. // nice.
  269. file := intf.(protocol.FileInfo)
  270. if ignores.Match(file.Name) {
  271. // This is an ignored file. Skip it, continue iteration.
  272. return true
  273. }
  274. events.Default.Log(events.ItemStarted, map[string]string{
  275. "folder": p.folder,
  276. "item": file.Name,
  277. })
  278. if debug {
  279. l.Debugln(p, "handling", file.Name)
  280. }
  281. switch {
  282. case file.IsDeleted():
  283. // A deleted file, directory or symlink
  284. if file.IsDirectory() {
  285. dirDeletions = append(dirDeletions, file)
  286. } else {
  287. fileDeletions[file.Name] = file
  288. df, ok := p.model.CurrentFolderFile(p.folder, file.Name)
  289. // Local file can be already deleted, but with a lower version
  290. // number, hence the deletion coming in again as part of
  291. // WithNeed
  292. if ok && !df.IsDeleted() {
  293. // Put files into buckets per first hash
  294. key := string(df.Blocks[0].Hash)
  295. buckets[key] = append(buckets[key], df)
  296. }
  297. }
  298. case file.IsDirectory() && !file.IsSymlink():
  299. // A new or changed directory
  300. p.handleDir(file)
  301. default:
  302. // A new or changed file or symlink. This is the only case where we
  303. // do stuff concurrently in the background
  304. p.queue.Push(file.Name)
  305. }
  306. changed++
  307. return true
  308. })
  309. nextFile:
  310. for {
  311. fileName, ok := p.queue.Pop()
  312. if !ok {
  313. break
  314. }
  315. f, ok := p.model.CurrentGlobalFile(p.folder, fileName)
  316. if !ok {
  317. // File is no longer in the index. Mark it as done and drop it.
  318. p.queue.Done(fileName)
  319. continue
  320. }
  321. // Local file can be already deleted, but with a lower version
  322. // number, hence the deletion coming in again as part of
  323. // WithNeed
  324. if !f.IsSymlink() && !f.IsDeleted() {
  325. key := string(f.Blocks[0].Hash)
  326. for i, candidate := range buckets[key] {
  327. if scanner.BlocksEqual(candidate.Blocks, f.Blocks) {
  328. // Remove the candidate from the bucket
  329. l := len(buckets[key]) - 1
  330. buckets[key][i] = buckets[key][l]
  331. buckets[key] = buckets[key][:l]
  332. // Remove the pending deletion (as we perform it by renaming)
  333. delete(fileDeletions, candidate.Name)
  334. p.renameFile(candidate, f)
  335. p.queue.Done(fileName)
  336. continue nextFile
  337. }
  338. }
  339. }
  340. // Not a rename or a symlink, deal with it.
  341. p.handleFile(f, copyChan, finisherChan)
  342. }
  343. // Signal copy and puller routines that we are done with the in data for
  344. // this iteration. Wait for them to finish.
  345. close(copyChan)
  346. copyWg.Wait()
  347. close(pullChan)
  348. pullWg.Wait()
  349. // Signal the finisher chan that there will be no more input.
  350. close(finisherChan)
  351. // Wait for the finisherChan to finish.
  352. doneWg.Wait()
  353. for _, file := range fileDeletions {
  354. p.deleteFile(file)
  355. }
  356. for i := range dirDeletions {
  357. p.deleteDir(dirDeletions[len(dirDeletions)-i-1])
  358. }
  359. return changed
  360. }
  361. // handleDir creates or updates the given directory
  362. func (p *Puller) handleDir(file protocol.FileInfo) {
  363. realName := filepath.Join(p.dir, file.Name)
  364. mode := os.FileMode(file.Flags & 0777)
  365. if p.ignorePerms {
  366. mode = 0755
  367. }
  368. if debug {
  369. curFile, _ := p.model.CurrentFolderFile(p.folder, file.Name)
  370. l.Debugf("need dir\n\t%v\n\t%v", file, curFile)
  371. }
  372. info, err := os.Lstat(realName)
  373. switch {
  374. // There is already something under that name, but it's a file/link.
  375. // Most likely a file/link is getting replaced with a directory.
  376. // Remove the file/link and fall through to directory creation.
  377. case err == nil && (!info.IsDir() || info.Mode()&os.ModeSymlink != 0):
  378. err = osutil.InWritableDir(os.Remove, realName)
  379. if err != nil {
  380. l.Infof("Puller (folder %q, dir %q): %v", p.folder, file.Name, err)
  381. return
  382. }
  383. fallthrough
  384. // The directory doesn't exist, so we create it with the right
  385. // mode bits from the start.
  386. case err != nil && os.IsNotExist(err):
  387. // We declare a function that acts on only the path name, so
  388. // we can pass it to InWritableDir. We use a regular Mkdir and
  389. // not MkdirAll because the parent should already exist.
  390. mkdir := func(path string) error {
  391. return os.Mkdir(path, mode)
  392. }
  393. if err = osutil.InWritableDir(mkdir, realName); err == nil {
  394. p.model.updateLocal(p.folder, file)
  395. } else {
  396. l.Infof("Puller (folder %q, dir %q): %v", p.folder, file.Name, err)
  397. }
  398. return
  399. // Weird error when stat()'ing the dir. Probably won't work to do
  400. // anything else with it if we can't even stat() it.
  401. case err != nil:
  402. l.Infof("Puller (folder %q, dir %q): %v", p.folder, file.Name, err)
  403. return
  404. }
  405. // The directory already exists, so we just correct the mode bits. (We
  406. // don't handle modification times on directories, because that sucks...)
  407. // It's OK to change mode bits on stuff within non-writable directories.
  408. if p.ignorePerms {
  409. p.model.updateLocal(p.folder, file)
  410. } else if err := os.Chmod(realName, mode); err == nil {
  411. p.model.updateLocal(p.folder, file)
  412. } else {
  413. l.Infof("Puller (folder %q, dir %q): %v", p.folder, file.Name, err)
  414. }
  415. }
  416. // deleteDir attempts to delete the given directory
  417. func (p *Puller) deleteDir(file protocol.FileInfo) {
  418. realName := filepath.Join(p.dir, file.Name)
  419. // Delete any temporary files lying around in the directory
  420. dir, _ := os.Open(realName)
  421. if dir != nil {
  422. files, _ := dir.Readdirnames(-1)
  423. for _, file := range files {
  424. if defTempNamer.IsTemporary(file) {
  425. osutil.InWritableDir(os.Remove, filepath.Join(realName, file))
  426. }
  427. }
  428. }
  429. err := osutil.InWritableDir(os.Remove, realName)
  430. if err == nil || os.IsNotExist(err) {
  431. p.model.updateLocal(p.folder, file)
  432. } else {
  433. l.Infof("Puller (folder %q, dir %q): delete: %v", p.folder, file.Name, err)
  434. }
  435. }
  436. // deleteFile attempts to delete the given file
  437. func (p *Puller) deleteFile(file protocol.FileInfo) {
  438. realName := filepath.Join(p.dir, file.Name)
  439. var err error
  440. if p.versioner != nil {
  441. err = osutil.InWritableDir(p.versioner.Archive, realName)
  442. } else {
  443. err = osutil.InWritableDir(os.Remove, realName)
  444. }
  445. if err != nil && !os.IsNotExist(err) {
  446. l.Infof("Puller (folder %q, file %q): delete: %v", p.folder, file.Name, err)
  447. } else {
  448. p.model.updateLocal(p.folder, file)
  449. }
  450. }
  451. // renameFile attempts to rename an existing file to a destination
  452. // and set the right attributes on it.
  453. func (p *Puller) renameFile(source, target protocol.FileInfo) {
  454. if debug {
  455. l.Debugln(p, "taking rename shortcut", source.Name, "->", target.Name)
  456. }
  457. from := filepath.Join(p.dir, source.Name)
  458. to := filepath.Join(p.dir, target.Name)
  459. var err error
  460. if p.versioner != nil {
  461. err = osutil.Copy(from, to)
  462. if err == nil {
  463. err = osutil.InWritableDir(p.versioner.Archive, from)
  464. }
  465. } else {
  466. err = osutil.TryRename(from, to)
  467. }
  468. if err != nil {
  469. l.Infof("Puller (folder %q, file %q): rename from %q: %v", p.folder, target.Name, source.Name, err)
  470. return
  471. }
  472. // Fix-up the metadata, and update the local index of the target file
  473. p.shortcutFile(target)
  474. // Source file already has the delete bit set.
  475. // Because we got rid of the file (by renaming it), we just need to update
  476. // the index, and we're done with it.
  477. p.model.updateLocal(p.folder, source)
  478. }
  479. // handleFile queues the copies and pulls as necessary for a single new or
  480. // changed file.
  481. func (p *Puller) handleFile(file protocol.FileInfo, copyChan chan<- copyBlocksState, finisherChan chan<- *sharedPullerState) {
  482. curFile, ok := p.model.CurrentFolderFile(p.folder, file.Name)
  483. if ok && len(curFile.Blocks) == len(file.Blocks) && scanner.BlocksEqual(curFile.Blocks, file.Blocks) {
  484. // We are supposed to copy the entire file, and then fetch nothing. We
  485. // are only updating metadata, so we don't actually *need* to make the
  486. // copy.
  487. if debug {
  488. l.Debugln(p, "taking shortcut on", file.Name)
  489. }
  490. p.queue.Done(file.Name)
  491. if file.IsSymlink() {
  492. p.shortcutSymlink(file)
  493. } else {
  494. p.shortcutFile(file)
  495. }
  496. return
  497. }
  498. scanner.PopulateOffsets(file.Blocks)
  499. // Figure out the absolute filenames we need once and for all
  500. tempName := filepath.Join(p.dir, defTempNamer.TempName(file.Name))
  501. realName := filepath.Join(p.dir, file.Name)
  502. reused := 0
  503. var blocks []protocol.BlockInfo
  504. // Check for an old temporary file which might have some blocks we could
  505. // reuse.
  506. tempBlocks, err := scanner.HashFile(tempName, protocol.BlockSize)
  507. if err == nil {
  508. // Check for any reusable blocks in the temp file
  509. tempCopyBlocks, _ := scanner.BlockDiff(tempBlocks, file.Blocks)
  510. // block.String() returns a string unique to the block
  511. existingBlocks := make(map[string]bool, len(tempCopyBlocks))
  512. for _, block := range tempCopyBlocks {
  513. existingBlocks[block.String()] = true
  514. }
  515. // Since the blocks are already there, we don't need to get them.
  516. for _, block := range file.Blocks {
  517. _, ok := existingBlocks[block.String()]
  518. if !ok {
  519. blocks = append(blocks, block)
  520. }
  521. }
  522. // The sharedpullerstate will know which flags to use when opening the
  523. // temp file depending if we are reusing any blocks or not.
  524. reused = len(file.Blocks) - len(blocks)
  525. if reused == 0 {
  526. // Otherwise, discard the file ourselves in order for the
  527. // sharedpuller not to panic when it fails to exlusively create a
  528. // file which already exists
  529. os.Remove(tempName)
  530. }
  531. } else {
  532. blocks = file.Blocks
  533. }
  534. s := sharedPullerState{
  535. file: file,
  536. folder: p.folder,
  537. tempName: tempName,
  538. realName: realName,
  539. copyTotal: len(blocks),
  540. copyNeeded: len(blocks),
  541. reused: reused,
  542. }
  543. if debug {
  544. l.Debugf("%v need file %s; copy %d, reused %v", p, file.Name, len(blocks), reused)
  545. }
  546. cs := copyBlocksState{
  547. sharedPullerState: &s,
  548. blocks: blocks,
  549. }
  550. copyChan <- cs
  551. }
  552. // shortcutFile sets file mode and modification time, when that's the only
  553. // thing that has changed.
  554. func (p *Puller) shortcutFile(file protocol.FileInfo) {
  555. realName := filepath.Join(p.dir, file.Name)
  556. if !p.ignorePerms {
  557. err := os.Chmod(realName, os.FileMode(file.Flags&0777))
  558. if err != nil {
  559. l.Infof("Puller (folder %q, file %q): shortcut: %v", p.folder, file.Name, err)
  560. return
  561. }
  562. }
  563. t := time.Unix(file.Modified, 0)
  564. err := os.Chtimes(realName, t, t)
  565. if err != nil {
  566. if p.lenientMtimes {
  567. // We accept the failure with a warning here and allow the sync to
  568. // continue. We'll sync the new mtime back to the other devices later.
  569. // If they have the same problem & setting, we might never get in
  570. // sync.
  571. l.Infof("Puller (folder %q, file %q): shortcut: %v (continuing anyway as requested)", p.folder, file.Name, err)
  572. } else {
  573. l.Infof("Puller (folder %q, file %q): shortcut: %v", p.folder, file.Name, err)
  574. return
  575. }
  576. }
  577. p.model.updateLocal(p.folder, file)
  578. }
  579. // shortcutSymlink changes the symlinks type if necessery.
  580. func (p *Puller) shortcutSymlink(file protocol.FileInfo) {
  581. err := symlinks.ChangeType(filepath.Join(p.dir, file.Name), file.Flags)
  582. if err != nil {
  583. l.Infof("Puller (folder %q, file %q): symlink shortcut: %v", p.folder, file.Name, err)
  584. return
  585. }
  586. p.model.updateLocal(p.folder, file)
  587. }
  588. // copierRoutine reads copierStates until the in channel closes and performs
  589. // the relevant copies when possible, or passes it to the puller routine.
  590. func (p *Puller) copierRoutine(in <-chan copyBlocksState, pullChan chan<- pullBlockState, out chan<- *sharedPullerState) {
  591. buf := make([]byte, protocol.BlockSize)
  592. for state := range in {
  593. if p.progressEmitter != nil {
  594. p.progressEmitter.Register(state.sharedPullerState)
  595. }
  596. dstFd, err := state.tempFile()
  597. if err != nil {
  598. // Nothing more to do for this failed file (the error was logged
  599. // when it happened)
  600. out <- state.sharedPullerState
  601. continue
  602. }
  603. folderRoots := make(map[string]string)
  604. p.model.fmut.RLock()
  605. for folder, cfg := range p.model.folderCfgs {
  606. folderRoots[folder] = cfg.Path
  607. }
  608. p.model.fmut.RUnlock()
  609. for _, block := range state.blocks {
  610. buf = buf[:int(block.Size)]
  611. found := p.model.finder.Iterate(block.Hash, func(folder, file string, index int32) bool {
  612. fd, err := os.Open(filepath.Join(folderRoots[folder], file))
  613. if err != nil {
  614. return false
  615. }
  616. _, err = fd.ReadAt(buf, protocol.BlockSize*int64(index))
  617. fd.Close()
  618. if err != nil {
  619. return false
  620. }
  621. hash, err := scanner.VerifyBuffer(buf, block)
  622. if err != nil {
  623. if hash != nil {
  624. if debug {
  625. l.Debugf("Finder block mismatch in %s:%s:%d expected %q got %q", folder, file, index, block.Hash, hash)
  626. }
  627. err = p.model.finder.Fix(folder, file, index, block.Hash, hash)
  628. if err != nil {
  629. l.Warnln("finder fix:", err)
  630. }
  631. } else if debug {
  632. l.Debugln("Finder failed to verify buffer", err)
  633. }
  634. return false
  635. }
  636. _, err = dstFd.WriteAt(buf, block.Offset)
  637. if err != nil {
  638. state.fail("dst write", err)
  639. }
  640. if file == state.file.Name {
  641. state.copiedFromOrigin()
  642. }
  643. return true
  644. })
  645. if state.failed() != nil {
  646. break
  647. }
  648. if !found {
  649. state.pullStarted()
  650. ps := pullBlockState{
  651. sharedPullerState: state.sharedPullerState,
  652. block: block,
  653. }
  654. pullChan <- ps
  655. } else {
  656. state.copyDone()
  657. }
  658. }
  659. out <- state.sharedPullerState
  660. }
  661. }
  662. func (p *Puller) pullerRoutine(in <-chan pullBlockState, out chan<- *sharedPullerState) {
  663. for state := range in {
  664. if state.failed() != nil {
  665. continue
  666. }
  667. // Get an fd to the temporary file. Tehcnically we don't need it until
  668. // after fetching the block, but if we run into an error here there is
  669. // no point in issuing the request to the network.
  670. fd, err := state.tempFile()
  671. if err != nil {
  672. continue
  673. }
  674. var lastError error
  675. potentialDevices := p.model.availability(p.folder, state.file.Name)
  676. for {
  677. // Select the least busy device to pull the block from. If we found no
  678. // feasible device at all, fail the block (and in the long run, the
  679. // file).
  680. selected := activity.leastBusy(potentialDevices)
  681. if selected == (protocol.DeviceID{}) {
  682. if lastError != nil {
  683. state.fail("pull", lastError)
  684. } else {
  685. state.fail("pull", errNoDevice)
  686. }
  687. break
  688. }
  689. potentialDevices = removeDevice(potentialDevices, selected)
  690. // Fetch the block, while marking the selected device as in use so that
  691. // leastBusy can select another device when someone else asks.
  692. activity.using(selected)
  693. buf, lastError := p.model.requestGlobal(selected, p.folder, state.file.Name, state.block.Offset, int(state.block.Size), state.block.Hash)
  694. activity.done(selected)
  695. if lastError != nil {
  696. continue
  697. }
  698. // Verify that the received block matches the desired hash, if not
  699. // try pulling it from another device.
  700. _, lastError = scanner.VerifyBuffer(buf, state.block)
  701. if lastError != nil {
  702. continue
  703. }
  704. // Save the block data we got from the cluster
  705. _, err = fd.WriteAt(buf, state.block.Offset)
  706. if err != nil {
  707. state.fail("save", err)
  708. } else {
  709. state.pullDone()
  710. }
  711. break
  712. }
  713. out <- state.sharedPullerState
  714. }
  715. }
  716. func (p *Puller) performFinish(state *sharedPullerState) {
  717. var err error
  718. // Set the correct permission bits on the new file
  719. if !p.ignorePerms {
  720. err = os.Chmod(state.tempName, os.FileMode(state.file.Flags&0777))
  721. if err != nil {
  722. l.Warnln("puller: final:", err)
  723. return
  724. }
  725. }
  726. // Set the correct timestamp on the new file
  727. t := time.Unix(state.file.Modified, 0)
  728. err = os.Chtimes(state.tempName, t, t)
  729. if err != nil {
  730. if p.lenientMtimes {
  731. // We accept the failure with a warning here and allow the sync to
  732. // continue. We'll sync the new mtime back to the other devices later.
  733. // If they have the same problem & setting, we might never get in
  734. // sync.
  735. l.Infof("Puller (folder %q, file %q): final: %v (continuing anyway as requested)", p.folder, state.file.Name, err)
  736. } else {
  737. l.Warnln("puller: final:", err)
  738. return
  739. }
  740. }
  741. // If we should use versioning, let the versioner archive the old
  742. // file before we replace it. Archiving a non-existent file is not
  743. // an error.
  744. if p.versioner != nil {
  745. err = p.versioner.Archive(state.realName)
  746. if err != nil {
  747. l.Warnln("puller: final:", err)
  748. return
  749. }
  750. }
  751. // If the target path is a symlink or a directory, we cannot copy
  752. // over it, hence remove it before proceeding.
  753. stat, err := os.Lstat(state.realName)
  754. if err == nil && (stat.IsDir() || stat.Mode()&os.ModeSymlink != 0) {
  755. osutil.InWritableDir(os.Remove, state.realName)
  756. }
  757. // Replace the original content with the new one
  758. err = osutil.Rename(state.tempName, state.realName)
  759. if err != nil {
  760. l.Warnln("puller: final:", err)
  761. return
  762. }
  763. // If it's a symlink, the target of the symlink is inside the file.
  764. if state.file.IsSymlink() {
  765. content, err := ioutil.ReadFile(state.realName)
  766. if err != nil {
  767. l.Warnln("puller: final: reading symlink:", err)
  768. return
  769. }
  770. // Remove the file, and replace it with a symlink.
  771. err = osutil.InWritableDir(func(path string) error {
  772. os.Remove(path)
  773. return symlinks.Create(path, string(content), state.file.Flags)
  774. }, state.realName)
  775. if err != nil {
  776. l.Warnln("puller: final: creating symlink:", err)
  777. return
  778. }
  779. }
  780. // Record the updated file in the index
  781. p.model.updateLocal(p.folder, state.file)
  782. }
  783. func (p *Puller) finisherRoutine(in <-chan *sharedPullerState) {
  784. for state := range in {
  785. if closed, err := state.finalClose(); closed {
  786. if debug {
  787. l.Debugln(p, "closing", state.file.Name)
  788. }
  789. if err != nil {
  790. l.Warnln("puller: final:", err)
  791. continue
  792. }
  793. p.queue.Done(state.file.Name)
  794. if state.failed() == nil {
  795. p.performFinish(state)
  796. }
  797. p.model.receivedFile(p.folder, state.file.Name)
  798. if p.progressEmitter != nil {
  799. p.progressEmitter.Deregister(state)
  800. }
  801. }
  802. }
  803. }
  804. // Moves the given filename to the front of the job queue
  805. func (p *Puller) BringToFront(filename string) {
  806. p.queue.BringToFront(filename)
  807. }
  808. func (p *Puller) Jobs() ([]string, []string) {
  809. return p.queue.Jobs()
  810. }
  811. func invalidateFolder(cfg *config.Configuration, folderID string, err error) {
  812. for i := range cfg.Folders {
  813. folder := &cfg.Folders[i]
  814. if folder.ID == folderID {
  815. folder.Invalid = err.Error()
  816. return
  817. }
  818. }
  819. }
  820. func removeDevice(devices []protocol.DeviceID, device protocol.DeviceID) []protocol.DeviceID {
  821. for i := range devices {
  822. if devices[i] == device {
  823. devices[i] = devices[len(devices)-1]
  824. return devices[:len(devices)-1]
  825. }
  826. }
  827. return devices
  828. }