rwfolder.go 45 KB

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