rwfolder.go 46 KB

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