puller.go 29 KB

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