rwfolder.go 45 KB

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