puller.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575
  1. package main
  2. import (
  3. "bytes"
  4. "errors"
  5. "os"
  6. "path/filepath"
  7. "time"
  8. "github.com/calmh/syncthing/buffers"
  9. "github.com/calmh/syncthing/cid"
  10. "github.com/calmh/syncthing/config"
  11. "github.com/calmh/syncthing/protocol"
  12. "github.com/calmh/syncthing/scanner"
  13. )
  14. type requestResult struct {
  15. node string
  16. file scanner.File
  17. filepath string // full filepath name
  18. offset int64
  19. data []byte
  20. err error
  21. }
  22. type openFile struct {
  23. filepath string // full filepath name
  24. temp string // temporary filename
  25. availability uint64 // availability bitset
  26. file *os.File
  27. err error // error when opening or writing to file, all following operations are cancelled
  28. outstanding int // number of requests we still have outstanding
  29. done bool // we have sent all requests for this file
  30. }
  31. type activityMap map[string]int
  32. func (m activityMap) leastBusyNode(availability uint64, cm *cid.Map) string {
  33. var low int = 2<<30 - 1
  34. var selected string
  35. for _, node := range cm.Names() {
  36. id := cm.Get(node)
  37. if id == cid.LocalID {
  38. continue
  39. }
  40. usage := m[node]
  41. if availability&(1<<id) != 0 {
  42. if usage < low {
  43. low = usage
  44. selected = node
  45. }
  46. }
  47. }
  48. m[selected]++
  49. return selected
  50. }
  51. func (m activityMap) decrease(node string) {
  52. m[node]--
  53. }
  54. var errNoNode = errors.New("no available source node")
  55. type puller struct {
  56. repo string
  57. dir string
  58. bq *blockQueue
  59. model *Model
  60. oustandingPerNode activityMap
  61. openFiles map[string]openFile
  62. requestSlots chan bool
  63. blocks chan bqBlock
  64. requestResults chan requestResult
  65. }
  66. func newPuller(repo, dir string, model *Model, slots int) *puller {
  67. p := &puller{
  68. repo: repo,
  69. dir: dir,
  70. bq: newBlockQueue(),
  71. model: model,
  72. oustandingPerNode: make(activityMap),
  73. openFiles: make(map[string]openFile),
  74. requestSlots: make(chan bool, slots),
  75. blocks: make(chan bqBlock),
  76. requestResults: make(chan requestResult),
  77. }
  78. if slots > 0 {
  79. // Read/write
  80. for i := 0; i < slots; i++ {
  81. p.requestSlots <- true
  82. }
  83. if debugPull {
  84. l.Debugf("starting puller; repo %q dir %q slots %d", repo, dir, slots)
  85. }
  86. go p.run()
  87. } else {
  88. // Read only
  89. if debugPull {
  90. l.Debugf("starting puller; repo %q dir %q (read only)", repo, dir)
  91. }
  92. go p.runRO()
  93. }
  94. return p
  95. }
  96. func (p *puller) run() {
  97. go func() {
  98. // fill blocks queue when there are free slots
  99. for {
  100. <-p.requestSlots
  101. b := p.bq.get()
  102. if debugPull {
  103. l.Debugf("filler: queueing %q / %q offset %d copy %d", p.repo, b.file.Name, b.block.Offset, len(b.copy))
  104. }
  105. p.blocks <- b
  106. }
  107. }()
  108. walkTicker := time.Tick(time.Duration(cfg.Options.RescanIntervalS) * time.Second)
  109. timeout := time.Tick(5 * time.Second)
  110. changed := true
  111. for {
  112. // Run the pulling loop as long as there are blocks to fetch
  113. pull:
  114. for {
  115. select {
  116. case res := <-p.requestResults:
  117. p.model.setState(p.repo, RepoSyncing)
  118. changed = true
  119. p.requestSlots <- true
  120. p.handleRequestResult(res)
  121. case b := <-p.blocks:
  122. p.model.setState(p.repo, RepoSyncing)
  123. changed = true
  124. if p.handleBlock(b) {
  125. // Block was fully handled, free up the slot
  126. p.requestSlots <- true
  127. }
  128. case <-timeout:
  129. if len(p.openFiles) == 0 && p.bq.empty() {
  130. // Nothing more to do for the moment
  131. break pull
  132. }
  133. if debugPull {
  134. l.Debugf("%q: idle but have %d open files", p.repo, len(p.openFiles))
  135. i := 5
  136. for _, f := range p.openFiles {
  137. l.Debugf(" %v", f)
  138. i--
  139. if i == 0 {
  140. break
  141. }
  142. }
  143. }
  144. }
  145. }
  146. if changed {
  147. p.model.setState(p.repo, RepoCleaning)
  148. p.fixupDirectories()
  149. changed = false
  150. }
  151. p.model.setState(p.repo, RepoIdle)
  152. // Do a rescan if it's time for it
  153. select {
  154. case <-walkTicker:
  155. if debugPull {
  156. l.Debugf("%q: time for rescan", p.repo)
  157. }
  158. err := p.model.ScanRepo(p.repo)
  159. if err != nil {
  160. invalidateRepo(cfg, p.repo, err)
  161. return
  162. }
  163. default:
  164. }
  165. // Queue more blocks to fetch, if any
  166. p.queueNeededBlocks()
  167. }
  168. }
  169. func (p *puller) runRO() {
  170. walkTicker := time.Tick(time.Duration(cfg.Options.RescanIntervalS) * time.Second)
  171. for _ = range walkTicker {
  172. if debugPull {
  173. l.Debugf("%q: time for rescan", p.repo)
  174. }
  175. err := p.model.ScanRepo(p.repo)
  176. if err != nil {
  177. invalidateRepo(cfg, p.repo, err)
  178. return
  179. }
  180. }
  181. }
  182. func (p *puller) fixupDirectories() {
  183. var deleteDirs []string
  184. filepath.Walk(p.dir, func(path string, info os.FileInfo, err error) error {
  185. if !info.IsDir() {
  186. return nil
  187. }
  188. rn, err := filepath.Rel(p.dir, path)
  189. if err != nil {
  190. return nil
  191. }
  192. if rn == "." {
  193. return nil
  194. }
  195. cur := p.model.CurrentGlobalFile(p.repo, rn)
  196. if cur.Name != rn {
  197. // No matching dir in current list; weird
  198. return nil
  199. }
  200. if cur.Flags&protocol.FlagDeleted != 0 {
  201. if debugPull {
  202. l.Debugf("queue delete dir: %v", cur)
  203. }
  204. // We queue the directories to delete since we walk the
  205. // tree in depth first order and need to remove the
  206. // directories in the opposite order.
  207. deleteDirs = append(deleteDirs, path)
  208. return nil
  209. }
  210. if cur.Flags&uint32(os.ModePerm) != uint32(info.Mode()&os.ModePerm) {
  211. os.Chmod(path, os.FileMode(cur.Flags)&os.ModePerm)
  212. if debugPull {
  213. l.Debugf("restored dir flags: %o -> %v", info.Mode()&os.ModePerm, cur)
  214. }
  215. }
  216. if cur.Modified != info.ModTime().Unix() {
  217. t := time.Unix(cur.Modified, 0)
  218. os.Chtimes(path, t, t)
  219. if debugPull {
  220. l.Debugf("restored dir modtime: %d -> %v", info.ModTime().Unix(), cur)
  221. }
  222. }
  223. return nil
  224. })
  225. // Delete any queued directories
  226. for i := len(deleteDirs) - 1; i >= 0; i-- {
  227. if debugPull {
  228. l.Debugln("delete dir:", deleteDirs[i])
  229. }
  230. err := os.Remove(deleteDirs[i])
  231. if err != nil {
  232. l.Warnln(err)
  233. }
  234. }
  235. }
  236. func (p *puller) handleRequestResult(res requestResult) {
  237. p.oustandingPerNode.decrease(res.node)
  238. f := res.file
  239. of, ok := p.openFiles[f.Name]
  240. if !ok || of.err != nil {
  241. // no entry in openFiles means there was an error and we've cancelled the operation
  242. return
  243. }
  244. _, of.err = of.file.WriteAt(res.data, res.offset)
  245. buffers.Put(res.data)
  246. of.outstanding--
  247. p.openFiles[f.Name] = of
  248. if debugPull {
  249. l.Debugf("pull: wrote %q / %q offset %d outstanding %d done %v", p.repo, f.Name, res.offset, of.outstanding, of.done)
  250. }
  251. if of.done && of.outstanding == 0 {
  252. p.closeFile(f)
  253. }
  254. }
  255. // handleBlock fulfills the block request by copying, ignoring or fetching
  256. // from the network. Returns true if the block was fully handled
  257. // synchronously, i.e. if the slot can be reused.
  258. func (p *puller) handleBlock(b bqBlock) bool {
  259. f := b.file
  260. // For directories, simply making sure they exist is enough
  261. if f.Flags&protocol.FlagDirectory != 0 {
  262. path := filepath.Join(p.dir, f.Name)
  263. _, err := os.Stat(path)
  264. if err != nil && os.IsNotExist(err) {
  265. os.MkdirAll(path, 0777)
  266. }
  267. p.model.updateLocal(p.repo, f)
  268. return true
  269. }
  270. of, ok := p.openFiles[f.Name]
  271. of.done = b.last
  272. if !ok {
  273. if debugPull {
  274. l.Debugf("pull: %q: opening file %q", p.repo, f.Name)
  275. }
  276. of.availability = uint64(p.model.repoFiles[p.repo].Availability(f.Name))
  277. of.filepath = filepath.Join(p.dir, f.Name)
  278. of.temp = filepath.Join(p.dir, defTempNamer.TempName(f.Name))
  279. dirName := filepath.Dir(of.filepath)
  280. _, err := os.Stat(dirName)
  281. if err != nil {
  282. err = os.MkdirAll(dirName, 0777)
  283. }
  284. if err != nil {
  285. l.Debugf("pull: error: %q / %q: %v", p.repo, f.Name, err)
  286. }
  287. of.file, of.err = os.Create(of.temp)
  288. if of.err != nil {
  289. if debugPull {
  290. l.Debugf("pull: error: %q / %q: %v", p.repo, f.Name, of.err)
  291. }
  292. if !b.last {
  293. p.openFiles[f.Name] = of
  294. }
  295. return true
  296. }
  297. defTempNamer.Hide(of.temp)
  298. }
  299. if of.err != nil {
  300. // We have already failed this file.
  301. if debugPull {
  302. l.Debugf("pull: error: %q / %q has already failed: %v", p.repo, f.Name, of.err)
  303. }
  304. if b.last {
  305. l.Debugf("pull: removing failed file %q / %q", p.repo, f.Name)
  306. delete(p.openFiles, f.Name)
  307. }
  308. return true
  309. }
  310. p.openFiles[f.Name] = of
  311. switch {
  312. case len(b.copy) > 0:
  313. p.handleCopyBlock(b)
  314. return true
  315. case b.block.Size > 0:
  316. return p.handleRequestBlock(b)
  317. default:
  318. p.handleEmptyBlock(b)
  319. return true
  320. }
  321. }
  322. func (p *puller) handleCopyBlock(b bqBlock) {
  323. // We have blocks to copy from the existing file
  324. f := b.file
  325. of := p.openFiles[f.Name]
  326. if debugPull {
  327. l.Debugf("pull: copying %d blocks for %q / %q", len(b.copy), p.repo, f.Name)
  328. }
  329. var exfd *os.File
  330. exfd, of.err = os.Open(of.filepath)
  331. if of.err != nil {
  332. if debugPull {
  333. l.Debugf("pull: error: %q / %q: %v", p.repo, f.Name, of.err)
  334. }
  335. of.file.Close()
  336. of.file = nil
  337. p.openFiles[f.Name] = of
  338. return
  339. }
  340. defer exfd.Close()
  341. for _, b := range b.copy {
  342. bs := buffers.Get(int(b.Size))
  343. _, of.err = exfd.ReadAt(bs, b.Offset)
  344. if of.err == nil {
  345. _, of.err = of.file.WriteAt(bs, b.Offset)
  346. }
  347. buffers.Put(bs)
  348. if of.err != nil {
  349. if debugPull {
  350. l.Debugf("pull: error: %q / %q: %v", p.repo, f.Name, of.err)
  351. }
  352. exfd.Close()
  353. of.file.Close()
  354. of.file = nil
  355. p.openFiles[f.Name] = of
  356. return
  357. }
  358. }
  359. }
  360. // handleRequestBlock tries to pull a block from the network. Returns true if
  361. // the block could _not_ be fetched (i.e. it was fully handled, matching the
  362. // return criteria of handleBlock)
  363. func (p *puller) handleRequestBlock(b bqBlock) bool {
  364. f := b.file
  365. of, ok := p.openFiles[f.Name]
  366. if !ok {
  367. panic("bug: request for non-open file")
  368. }
  369. node := p.oustandingPerNode.leastBusyNode(of.availability, p.model.cm)
  370. if len(node) == 0 {
  371. of.err = errNoNode
  372. if of.file != nil {
  373. of.file.Close()
  374. of.file = nil
  375. os.Remove(of.temp)
  376. }
  377. if b.last {
  378. delete(p.openFiles, f.Name)
  379. } else {
  380. p.openFiles[f.Name] = of
  381. }
  382. return true
  383. }
  384. of.outstanding++
  385. p.openFiles[f.Name] = of
  386. go func(node string, b bqBlock) {
  387. if debugPull {
  388. l.Debugf("pull: requesting %q / %q offset %d size %d from %q outstanding %d", p.repo, f.Name, b.block.Offset, b.block.Size, node, of.outstanding)
  389. }
  390. bs, err := p.model.requestGlobal(node, p.repo, f.Name, b.block.Offset, int(b.block.Size), nil)
  391. p.requestResults <- requestResult{
  392. node: node,
  393. file: f,
  394. filepath: of.filepath,
  395. offset: b.block.Offset,
  396. data: bs,
  397. err: err,
  398. }
  399. }(node, b)
  400. return false
  401. }
  402. func (p *puller) handleEmptyBlock(b bqBlock) {
  403. f := b.file
  404. of := p.openFiles[f.Name]
  405. if b.last {
  406. if of.err == nil {
  407. of.file.Close()
  408. }
  409. }
  410. if f.Flags&protocol.FlagDeleted != 0 {
  411. if debugPull {
  412. l.Debugf("pull: delete %q", f.Name)
  413. }
  414. os.Remove(of.temp)
  415. os.Remove(of.filepath)
  416. } else {
  417. if debugPull {
  418. l.Debugf("pull: no blocks to fetch and nothing to copy for %q / %q", p.repo, f.Name)
  419. }
  420. t := time.Unix(f.Modified, 0)
  421. os.Chtimes(of.temp, t, t)
  422. os.Chmod(of.temp, os.FileMode(f.Flags&0777))
  423. defTempNamer.Show(of.temp)
  424. Rename(of.temp, of.filepath)
  425. }
  426. delete(p.openFiles, f.Name)
  427. p.model.updateLocal(p.repo, f)
  428. }
  429. func (p *puller) queueNeededBlocks() {
  430. queued := 0
  431. for _, f := range p.model.NeedFilesRepo(p.repo) {
  432. lf := p.model.CurrentRepoFile(p.repo, f.Name)
  433. have, need := scanner.BlockDiff(lf.Blocks, f.Blocks)
  434. if debugNeed {
  435. l.Debugf("need:\n local: %v\n global: %v\n haveBlocks: %v\n needBlocks: %v", lf, f, have, need)
  436. }
  437. queued++
  438. p.bq.put(bqAdd{
  439. file: f,
  440. have: have,
  441. need: need,
  442. })
  443. }
  444. if debugPull && queued > 0 {
  445. l.Debugf("%q: queued %d blocks", p.repo, queued)
  446. }
  447. }
  448. func (p *puller) closeFile(f scanner.File) {
  449. if debugPull {
  450. l.Debugf("pull: closing %q / %q", p.repo, f.Name)
  451. }
  452. of := p.openFiles[f.Name]
  453. of.file.Close()
  454. defer os.Remove(of.temp)
  455. delete(p.openFiles, f.Name)
  456. fd, err := os.Open(of.temp)
  457. if err != nil {
  458. if debugPull {
  459. l.Debugf("pull: error: %q / %q: %v", p.repo, f.Name, err)
  460. }
  461. return
  462. }
  463. hb, _ := scanner.Blocks(fd, BlockSize)
  464. fd.Close()
  465. if l0, l1 := len(hb), len(f.Blocks); l0 != l1 {
  466. if debugPull {
  467. l.Debugf("pull: %q / %q: nblocks %d != %d", p.repo, f.Name, l0, l1)
  468. }
  469. return
  470. }
  471. for i := range hb {
  472. if bytes.Compare(hb[i].Hash, f.Blocks[i].Hash) != 0 {
  473. l.Debugf("pull: %q / %q: block %d hash mismatch", p.repo, f.Name, i)
  474. return
  475. }
  476. }
  477. t := time.Unix(f.Modified, 0)
  478. os.Chtimes(of.temp, t, t)
  479. os.Chmod(of.temp, os.FileMode(f.Flags&0777))
  480. defTempNamer.Show(of.temp)
  481. if debugPull {
  482. l.Debugf("pull: rename %q / %q: %q", p.repo, f.Name, of.filepath)
  483. }
  484. if err := Rename(of.temp, of.filepath); err == nil {
  485. p.model.updateLocal(p.repo, f)
  486. } else {
  487. l.Debugf("pull: error: %q / %q: %v", p.repo, f.Name, err)
  488. }
  489. }
  490. func invalidateRepo(cfg config.Configuration, repoID string, err error) {
  491. for i := range cfg.Repositories {
  492. repo := &cfg.Repositories[i]
  493. if repo.ID == repoID {
  494. repo.Invalid = err.Error()
  495. return
  496. }
  497. }
  498. }