rwfolder.go 44 KB

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