rwfolder.go 31 KB

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