rwfolder.go 45 KB

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