rwfolder.go 32 KB

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