rwfolder.go 43 KB

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