rwfolder.go 38 KB

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