rwfolder.go 37 KB

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