rwfolder.go 45 KB

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