puller.go 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967
  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, furthermore, the file can simply be of the wrong
  292. // type if we haven't yet managed to pull it.
  293. if ok && !df.IsDeleted() && !df.IsSymlink() && !df.IsDirectory() {
  294. // Put files into buckets per first hash
  295. key := string(df.Blocks[0].Hash)
  296. buckets[key] = append(buckets[key], df)
  297. }
  298. }
  299. case file.IsDirectory() && !file.IsSymlink():
  300. // A new or changed directory
  301. if debug {
  302. l.Debugln("Creating directory", file.Name)
  303. }
  304. p.handleDir(file)
  305. default:
  306. // A new or changed file or symlink. This is the only case where we
  307. // do stuff concurrently in the background
  308. p.queue.Push(file.Name)
  309. }
  310. changed++
  311. return true
  312. })
  313. nextFile:
  314. for {
  315. fileName, ok := p.queue.Pop()
  316. if !ok {
  317. break
  318. }
  319. f, ok := p.model.CurrentGlobalFile(p.folder, fileName)
  320. if !ok {
  321. // File is no longer in the index. Mark it as done and drop it.
  322. p.queue.Done(fileName)
  323. continue
  324. }
  325. // Local file can be already deleted, but with a lower version
  326. // number, hence the deletion coming in again as part of
  327. // WithNeed, furthermore, the file can simply be of the wrong type if
  328. // the global index changed while we were processing this iteration.
  329. if !f.IsDeleted() && !f.IsSymlink() && !f.IsDirectory() {
  330. key := string(f.Blocks[0].Hash)
  331. for i, candidate := range buckets[key] {
  332. if scanner.BlocksEqual(candidate.Blocks, f.Blocks) {
  333. // Remove the candidate from the bucket
  334. lidx := len(buckets[key]) - 1
  335. buckets[key][i] = buckets[key][lidx]
  336. buckets[key] = buckets[key][:lidx]
  337. // candidate is our current state of the file, where as the
  338. // desired state with the delete bit set is in the deletion
  339. // map.
  340. desired := fileDeletions[candidate.Name]
  341. // Remove the pending deletion (as we perform it by renaming)
  342. delete(fileDeletions, candidate.Name)
  343. p.renameFile(desired, f)
  344. p.queue.Done(fileName)
  345. continue nextFile
  346. }
  347. }
  348. }
  349. // Not a rename or a symlink, deal with it.
  350. p.handleFile(f, copyChan, finisherChan)
  351. }
  352. // Signal copy and puller routines that we are done with the in data for
  353. // this iteration. Wait for them to finish.
  354. close(copyChan)
  355. copyWg.Wait()
  356. close(pullChan)
  357. pullWg.Wait()
  358. // Signal the finisher chan that there will be no more input.
  359. close(finisherChan)
  360. // Wait for the finisherChan to finish.
  361. doneWg.Wait()
  362. for _, file := range fileDeletions {
  363. if debug {
  364. l.Debugln("Deleting file", file.Name)
  365. }
  366. p.deleteFile(file)
  367. }
  368. for i := range dirDeletions {
  369. dir := dirDeletions[len(dirDeletions)-i-1]
  370. if debug {
  371. l.Debugln("Deleting dir", dir.Name)
  372. }
  373. p.deleteDir(dir)
  374. }
  375. return changed
  376. }
  377. // handleDir creates or updates the given directory
  378. func (p *Puller) handleDir(file protocol.FileInfo) {
  379. realName := filepath.Join(p.dir, file.Name)
  380. mode := os.FileMode(file.Flags & 0777)
  381. if p.ignorePerms {
  382. mode = 0755
  383. }
  384. if debug {
  385. curFile, _ := p.model.CurrentFolderFile(p.folder, file.Name)
  386. l.Debugf("need dir\n\t%v\n\t%v", file, curFile)
  387. }
  388. info, err := os.Lstat(realName)
  389. switch {
  390. // There is already something under that name, but it's a file/link.
  391. // Most likely a file/link is getting replaced with a directory.
  392. // Remove the file/link and fall through to directory creation.
  393. case err == nil && (!info.IsDir() || info.Mode()&os.ModeSymlink != 0):
  394. err = osutil.InWritableDir(os.Remove, realName)
  395. if err != nil {
  396. l.Infof("Puller (folder %q, dir %q): %v", p.folder, file.Name, err)
  397. return
  398. }
  399. fallthrough
  400. // The directory doesn't exist, so we create it with the right
  401. // mode bits from the start.
  402. case err != nil && os.IsNotExist(err):
  403. // We declare a function that acts on only the path name, so
  404. // we can pass it to InWritableDir. We use a regular Mkdir and
  405. // not MkdirAll because the parent should already exist.
  406. mkdir := func(path string) error {
  407. return os.Mkdir(path, mode)
  408. }
  409. if err = osutil.InWritableDir(mkdir, realName); err == nil {
  410. p.model.updateLocal(p.folder, file)
  411. } else {
  412. l.Infof("Puller (folder %q, dir %q): %v", p.folder, file.Name, err)
  413. }
  414. return
  415. // Weird error when stat()'ing the dir. Probably won't work to do
  416. // anything else with it if we can't even stat() it.
  417. case err != nil:
  418. l.Infof("Puller (folder %q, dir %q): %v", p.folder, file.Name, err)
  419. return
  420. }
  421. // The directory already exists, so we just correct the mode bits. (We
  422. // don't handle modification times on directories, because that sucks...)
  423. // It's OK to change mode bits on stuff within non-writable directories.
  424. if p.ignorePerms {
  425. p.model.updateLocal(p.folder, file)
  426. } else if err := os.Chmod(realName, mode); err == nil {
  427. p.model.updateLocal(p.folder, file)
  428. } else {
  429. l.Infof("Puller (folder %q, dir %q): %v", p.folder, file.Name, err)
  430. }
  431. }
  432. // deleteDir attempts to delete the given directory
  433. func (p *Puller) deleteDir(file protocol.FileInfo) {
  434. realName := filepath.Join(p.dir, file.Name)
  435. // Delete any temporary files lying around in the directory
  436. dir, _ := os.Open(realName)
  437. if dir != nil {
  438. files, _ := dir.Readdirnames(-1)
  439. for _, file := range files {
  440. if defTempNamer.IsTemporary(file) {
  441. osutil.InWritableDir(os.Remove, filepath.Join(realName, file))
  442. }
  443. }
  444. }
  445. err := osutil.InWritableDir(os.Remove, realName)
  446. if err == nil || os.IsNotExist(err) {
  447. p.model.updateLocal(p.folder, file)
  448. } else {
  449. l.Infof("Puller (folder %q, dir %q): delete: %v", p.folder, file.Name, err)
  450. }
  451. }
  452. // deleteFile attempts to delete the given file
  453. func (p *Puller) deleteFile(file protocol.FileInfo) {
  454. realName := filepath.Join(p.dir, file.Name)
  455. var err error
  456. if p.versioner != nil {
  457. err = osutil.InWritableDir(p.versioner.Archive, realName)
  458. } else {
  459. err = osutil.InWritableDir(os.Remove, realName)
  460. }
  461. if err != nil && !os.IsNotExist(err) {
  462. l.Infof("Puller (folder %q, file %q): delete: %v", p.folder, file.Name, err)
  463. } else {
  464. p.model.updateLocal(p.folder, file)
  465. }
  466. }
  467. // renameFile attempts to rename an existing file to a destination
  468. // and set the right attributes on it.
  469. func (p *Puller) renameFile(source, target protocol.FileInfo) {
  470. if debug {
  471. l.Debugln(p, "taking rename shortcut", source.Name, "->", target.Name)
  472. }
  473. from := filepath.Join(p.dir, source.Name)
  474. to := filepath.Join(p.dir, target.Name)
  475. var err error
  476. if p.versioner != nil {
  477. err = osutil.Copy(from, to)
  478. if err == nil {
  479. err = osutil.InWritableDir(p.versioner.Archive, from)
  480. }
  481. } else {
  482. err = osutil.TryRename(from, to)
  483. }
  484. if err != nil {
  485. l.Infof("Puller (folder %q, file %q): rename from %q: %v", p.folder, target.Name, source.Name, err)
  486. return
  487. }
  488. // Fix-up the metadata, and update the local index of the target file
  489. p.shortcutFile(target)
  490. // Source file already has the delete bit set.
  491. // Because we got rid of the file (by renaming it), we just need to update
  492. // the index, and we're done with it.
  493. p.model.updateLocal(p.folder, source)
  494. }
  495. // handleFile queues the copies and pulls as necessary for a single new or
  496. // changed file.
  497. func (p *Puller) handleFile(file protocol.FileInfo, copyChan chan<- copyBlocksState, finisherChan chan<- *sharedPullerState) {
  498. curFile, ok := p.model.CurrentFolderFile(p.folder, file.Name)
  499. if ok && len(curFile.Blocks) == len(file.Blocks) && scanner.BlocksEqual(curFile.Blocks, file.Blocks) {
  500. // We are supposed to copy the entire file, and then fetch nothing. We
  501. // are only updating metadata, so we don't actually *need* to make the
  502. // copy.
  503. if debug {
  504. l.Debugln(p, "taking shortcut on", file.Name)
  505. }
  506. p.queue.Done(file.Name)
  507. if file.IsSymlink() {
  508. p.shortcutSymlink(file)
  509. } else {
  510. p.shortcutFile(file)
  511. }
  512. return
  513. }
  514. scanner.PopulateOffsets(file.Blocks)
  515. // Figure out the absolute filenames we need once and for all
  516. tempName := filepath.Join(p.dir, defTempNamer.TempName(file.Name))
  517. realName := filepath.Join(p.dir, file.Name)
  518. reused := 0
  519. var blocks []protocol.BlockInfo
  520. // Check for an old temporary file which might have some blocks we could
  521. // reuse.
  522. tempBlocks, err := scanner.HashFile(tempName, protocol.BlockSize)
  523. if err == nil {
  524. // Check for any reusable blocks in the temp file
  525. tempCopyBlocks, _ := scanner.BlockDiff(tempBlocks, file.Blocks)
  526. // block.String() returns a string unique to the block
  527. existingBlocks := make(map[string]bool, len(tempCopyBlocks))
  528. for _, block := range tempCopyBlocks {
  529. existingBlocks[block.String()] = true
  530. }
  531. // Since the blocks are already there, we don't need to get them.
  532. for _, block := range file.Blocks {
  533. _, ok := existingBlocks[block.String()]
  534. if !ok {
  535. blocks = append(blocks, block)
  536. }
  537. }
  538. // The sharedpullerstate will know which flags to use when opening the
  539. // temp file depending if we are reusing any blocks or not.
  540. reused = len(file.Blocks) - len(blocks)
  541. if reused == 0 {
  542. // Otherwise, discard the file ourselves in order for the
  543. // sharedpuller not to panic when it fails to exlusively create a
  544. // file which already exists
  545. os.Remove(tempName)
  546. }
  547. } else {
  548. blocks = file.Blocks
  549. }
  550. s := sharedPullerState{
  551. file: file,
  552. folder: p.folder,
  553. tempName: tempName,
  554. realName: realName,
  555. copyTotal: len(blocks),
  556. copyNeeded: len(blocks),
  557. reused: reused,
  558. }
  559. if debug {
  560. l.Debugf("%v need file %s; copy %d, reused %v", p, file.Name, len(blocks), reused)
  561. }
  562. cs := copyBlocksState{
  563. sharedPullerState: &s,
  564. blocks: blocks,
  565. }
  566. copyChan <- cs
  567. }
  568. // shortcutFile sets file mode and modification time, when that's the only
  569. // thing that has changed.
  570. func (p *Puller) shortcutFile(file protocol.FileInfo) {
  571. realName := filepath.Join(p.dir, file.Name)
  572. if !p.ignorePerms {
  573. err := os.Chmod(realName, os.FileMode(file.Flags&0777))
  574. if err != nil {
  575. l.Infof("Puller (folder %q, file %q): shortcut: %v", p.folder, file.Name, err)
  576. return
  577. }
  578. }
  579. t := time.Unix(file.Modified, 0)
  580. err := os.Chtimes(realName, t, t)
  581. if err != nil {
  582. if p.lenientMtimes {
  583. // We accept the failure with a warning here and allow the sync to
  584. // continue. We'll sync the new mtime back to the other devices later.
  585. // If they have the same problem & setting, we might never get in
  586. // sync.
  587. l.Infof("Puller (folder %q, file %q): shortcut: %v (continuing anyway as requested)", p.folder, file.Name, err)
  588. } else {
  589. l.Infof("Puller (folder %q, file %q): shortcut: %v", p.folder, file.Name, err)
  590. return
  591. }
  592. }
  593. p.model.updateLocal(p.folder, file)
  594. }
  595. // shortcutSymlink changes the symlinks type if necessery.
  596. func (p *Puller) shortcutSymlink(file protocol.FileInfo) {
  597. err := symlinks.ChangeType(filepath.Join(p.dir, file.Name), file.Flags)
  598. if err != nil {
  599. l.Infof("Puller (folder %q, file %q): symlink shortcut: %v", p.folder, file.Name, err)
  600. return
  601. }
  602. p.model.updateLocal(p.folder, file)
  603. }
  604. // copierRoutine reads copierStates until the in channel closes and performs
  605. // the relevant copies when possible, or passes it to the puller routine.
  606. func (p *Puller) copierRoutine(in <-chan copyBlocksState, pullChan chan<- pullBlockState, out chan<- *sharedPullerState) {
  607. buf := make([]byte, protocol.BlockSize)
  608. for state := range in {
  609. if p.progressEmitter != nil {
  610. p.progressEmitter.Register(state.sharedPullerState)
  611. }
  612. dstFd, err := state.tempFile()
  613. if err != nil {
  614. // Nothing more to do for this failed file (the error was logged
  615. // when it happened)
  616. out <- state.sharedPullerState
  617. continue
  618. }
  619. folderRoots := make(map[string]string)
  620. p.model.fmut.RLock()
  621. for folder, cfg := range p.model.folderCfgs {
  622. folderRoots[folder] = cfg.Path
  623. }
  624. p.model.fmut.RUnlock()
  625. for _, block := range state.blocks {
  626. buf = buf[:int(block.Size)]
  627. found := p.model.finder.Iterate(block.Hash, func(folder, file string, index int32) bool {
  628. fd, err := os.Open(filepath.Join(folderRoots[folder], file))
  629. if err != nil {
  630. return false
  631. }
  632. _, err = fd.ReadAt(buf, protocol.BlockSize*int64(index))
  633. fd.Close()
  634. if err != nil {
  635. return false
  636. }
  637. hash, err := scanner.VerifyBuffer(buf, block)
  638. if err != nil {
  639. if hash != nil {
  640. if debug {
  641. l.Debugf("Finder block mismatch in %s:%s:%d expected %q got %q", folder, file, index, block.Hash, hash)
  642. }
  643. err = p.model.finder.Fix(folder, file, index, block.Hash, hash)
  644. if err != nil {
  645. l.Warnln("finder fix:", err)
  646. }
  647. } else if debug {
  648. l.Debugln("Finder failed to verify buffer", err)
  649. }
  650. return false
  651. }
  652. _, err = dstFd.WriteAt(buf, block.Offset)
  653. if err != nil {
  654. state.fail("dst write", err)
  655. }
  656. if file == state.file.Name {
  657. state.copiedFromOrigin()
  658. }
  659. return true
  660. })
  661. if state.failed() != nil {
  662. break
  663. }
  664. if !found {
  665. state.pullStarted()
  666. ps := pullBlockState{
  667. sharedPullerState: state.sharedPullerState,
  668. block: block,
  669. }
  670. pullChan <- ps
  671. } else {
  672. state.copyDone()
  673. }
  674. }
  675. out <- state.sharedPullerState
  676. }
  677. }
  678. func (p *Puller) pullerRoutine(in <-chan pullBlockState, out chan<- *sharedPullerState) {
  679. for state := range in {
  680. if state.failed() != nil {
  681. continue
  682. }
  683. // Get an fd to the temporary file. Tehcnically we don't need it until
  684. // after fetching the block, but if we run into an error here there is
  685. // no point in issuing the request to the network.
  686. fd, err := state.tempFile()
  687. if err != nil {
  688. continue
  689. }
  690. var lastError error
  691. potentialDevices := p.model.availability(p.folder, state.file.Name)
  692. for {
  693. // Select the least busy device to pull the block from. If we found no
  694. // feasible device at all, fail the block (and in the long run, the
  695. // file).
  696. selected := activity.leastBusy(potentialDevices)
  697. if selected == (protocol.DeviceID{}) {
  698. if lastError != nil {
  699. state.fail("pull", lastError)
  700. } else {
  701. state.fail("pull", errNoDevice)
  702. }
  703. break
  704. }
  705. potentialDevices = removeDevice(potentialDevices, selected)
  706. // Fetch the block, while marking the selected device as in use so that
  707. // leastBusy can select another device when someone else asks.
  708. activity.using(selected)
  709. buf, lastError := p.model.requestGlobal(selected, p.folder, state.file.Name, state.block.Offset, int(state.block.Size), state.block.Hash)
  710. activity.done(selected)
  711. if lastError != nil {
  712. continue
  713. }
  714. // Verify that the received block matches the desired hash, if not
  715. // try pulling it from another device.
  716. _, lastError = scanner.VerifyBuffer(buf, state.block)
  717. if lastError != nil {
  718. continue
  719. }
  720. // Save the block data we got from the cluster
  721. _, err = fd.WriteAt(buf, state.block.Offset)
  722. if err != nil {
  723. state.fail("save", err)
  724. } else {
  725. state.pullDone()
  726. }
  727. break
  728. }
  729. out <- state.sharedPullerState
  730. }
  731. }
  732. func (p *Puller) performFinish(state *sharedPullerState) {
  733. var err error
  734. // Set the correct permission bits on the new file
  735. if !p.ignorePerms {
  736. err = os.Chmod(state.tempName, os.FileMode(state.file.Flags&0777))
  737. if err != nil {
  738. l.Warnln("puller: final:", err)
  739. return
  740. }
  741. }
  742. // Set the correct timestamp on the new file
  743. t := time.Unix(state.file.Modified, 0)
  744. err = os.Chtimes(state.tempName, t, t)
  745. if err != nil {
  746. if p.lenientMtimes {
  747. // We accept the failure with a warning here and allow the sync to
  748. // continue. We'll sync the new mtime back to the other devices later.
  749. // If they have the same problem & setting, we might never get in
  750. // sync.
  751. l.Infof("Puller (folder %q, file %q): final: %v (continuing anyway as requested)", p.folder, state.file.Name, err)
  752. } else {
  753. l.Warnln("puller: final:", err)
  754. return
  755. }
  756. }
  757. // If we should use versioning, let the versioner archive the old
  758. // file before we replace it. Archiving a non-existent file is not
  759. // an error.
  760. if p.versioner != nil {
  761. err = p.versioner.Archive(state.realName)
  762. if err != nil {
  763. l.Warnln("puller: final:", err)
  764. return
  765. }
  766. }
  767. // If the target path is a symlink or a directory, we cannot copy
  768. // over it, hence remove it before proceeding.
  769. stat, err := os.Lstat(state.realName)
  770. if err == nil && (stat.IsDir() || stat.Mode()&os.ModeSymlink != 0) {
  771. osutil.InWritableDir(os.Remove, state.realName)
  772. }
  773. // Replace the original content with the new one
  774. err = osutil.Rename(state.tempName, state.realName)
  775. if err != nil {
  776. l.Warnln("puller: final:", err)
  777. return
  778. }
  779. // If it's a symlink, the target of the symlink is inside the file.
  780. if state.file.IsSymlink() {
  781. content, err := ioutil.ReadFile(state.realName)
  782. if err != nil {
  783. l.Warnln("puller: final: reading symlink:", err)
  784. return
  785. }
  786. // Remove the file, and replace it with a symlink.
  787. err = osutil.InWritableDir(func(path string) error {
  788. os.Remove(path)
  789. return symlinks.Create(path, string(content), state.file.Flags)
  790. }, state.realName)
  791. if err != nil {
  792. l.Warnln("puller: final: creating symlink:", err)
  793. return
  794. }
  795. }
  796. // Record the updated file in the index
  797. p.model.updateLocal(p.folder, state.file)
  798. }
  799. func (p *Puller) finisherRoutine(in <-chan *sharedPullerState) {
  800. for state := range in {
  801. if closed, err := state.finalClose(); closed {
  802. if debug {
  803. l.Debugln(p, "closing", state.file.Name)
  804. }
  805. if err != nil {
  806. l.Warnln("puller: final:", err)
  807. continue
  808. }
  809. p.queue.Done(state.file.Name)
  810. if state.failed() == nil {
  811. p.performFinish(state)
  812. }
  813. p.model.receivedFile(p.folder, state.file.Name)
  814. if p.progressEmitter != nil {
  815. p.progressEmitter.Deregister(state)
  816. }
  817. }
  818. }
  819. }
  820. // Moves the given filename to the front of the job queue
  821. func (p *Puller) BringToFront(filename string) {
  822. p.queue.BringToFront(filename)
  823. }
  824. func (p *Puller) Jobs() ([]string, []string) {
  825. return p.queue.Jobs()
  826. }
  827. func invalidateFolder(cfg *config.Configuration, folderID string, err error) {
  828. for i := range cfg.Folders {
  829. folder := &cfg.Folders[i]
  830. if folder.ID == folderID {
  831. folder.Invalid = err.Error()
  832. return
  833. }
  834. }
  835. }
  836. func removeDevice(devices []protocol.DeviceID, device protocol.DeviceID) []protocol.DeviceID {
  837. for i := range devices {
  838. if devices[i] == device {
  839. devices[i] = devices[len(devices)-1]
  840. return devices[:len(devices)-1]
  841. }
  842. }
  843. return devices
  844. }