rwfolder.go 43 KB

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