rwfolder.go 45 KB

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