rwfolder.go 43 KB

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