rwfolder.go 45 KB

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