rwfolder.go 43 KB

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