puller.go 29 KB

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