rwfolder.go 42 KB

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