puller.go 30 KB

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