rwfolder.go 30 KB

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