puller.go 29 KB

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