puller.go 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816
  1. // Copyright (C) 2014 Jakob Borg and Contributors (see the CONTRIBUTORS file).
  2. // All rights reserved. Use of this source code is governed by an MIT-style
  3. // license that can be found in the LICENSE file.
  4. /*
  5. __ __ _ _
  6. \ \ / /_ _ _ __ _ __ (_)_ __ __ _| |
  7. \ \ /\ / / _` | '__| '_ \| | '_ \ / _` | |
  8. \ V V / (_| | | | | | | | | | | (_| |_|
  9. \_/\_/ \__,_|_| |_| |_|_|_| |_|\__, (_)
  10. |___/
  11. The code in this file is a piece of crap. Don't base anything on it.
  12. Refactorin ongoing in new-puller branch.
  13. __ __ _ _
  14. \ \ / /_ _ _ __ _ __ (_)_ __ __ _| |
  15. \ \ /\ / / _` | '__| '_ \| | '_ \ / _` | |
  16. \ V V / (_| | | | | | | | | | | (_| |_|
  17. \_/\_/ \__,_|_| |_| |_|_|_| |_|\__, (_)
  18. |___/
  19. */
  20. package model
  21. import (
  22. "bytes"
  23. "errors"
  24. "fmt"
  25. "math/rand"
  26. "os"
  27. "path/filepath"
  28. "time"
  29. "github.com/syncthing/syncthing/config"
  30. "github.com/syncthing/syncthing/events"
  31. "github.com/syncthing/syncthing/osutil"
  32. "github.com/syncthing/syncthing/protocol"
  33. "github.com/syncthing/syncthing/scanner"
  34. "github.com/syncthing/syncthing/versioner"
  35. )
  36. type requestResult struct {
  37. node protocol.NodeID
  38. file protocol.FileInfo
  39. filepath string // full filepath name
  40. offset int64
  41. data []byte
  42. err error
  43. }
  44. type openFile struct {
  45. filepath string // full filepath name
  46. temp string // temporary filename
  47. availability []protocol.NodeID
  48. file *os.File
  49. err error // error when opening or writing to file, all following operations are cancelled
  50. outstanding int // number of requests we still have outstanding
  51. done bool // we have sent all requests for this file
  52. }
  53. type activityMap map[protocol.NodeID]int
  54. func (m activityMap) leastBusyNode(availability []protocol.NodeID, isValid func(protocol.NodeID) bool) protocol.NodeID {
  55. var low int = 2<<30 - 1
  56. var selected protocol.NodeID
  57. for _, node := range availability {
  58. usage := m[node]
  59. if usage < low && isValid(node) {
  60. low = usage
  61. selected = node
  62. }
  63. }
  64. m[selected]++
  65. return selected
  66. }
  67. func (m activityMap) decrease(node protocol.NodeID) {
  68. m[node]--
  69. }
  70. var errNoNode = errors.New("no available source node")
  71. type puller struct {
  72. cfg *config.Configuration
  73. repoCfg config.RepositoryConfiguration
  74. bq blockQueue
  75. slots int
  76. model *Model
  77. oustandingPerNode activityMap
  78. openFiles map[string]openFile
  79. requestSlots chan bool
  80. blocks chan bqBlock
  81. requestResults chan requestResult
  82. versioner versioner.Versioner
  83. errors int
  84. }
  85. func newPuller(repoCfg config.RepositoryConfiguration, model *Model, slots int, cfg *config.Configuration) *puller {
  86. p := &puller{
  87. cfg: cfg,
  88. repoCfg: repoCfg,
  89. slots: slots,
  90. model: model,
  91. oustandingPerNode: make(activityMap),
  92. openFiles: make(map[string]openFile),
  93. requestSlots: make(chan bool, slots),
  94. blocks: make(chan bqBlock),
  95. requestResults: make(chan requestResult),
  96. }
  97. if len(repoCfg.Versioning.Type) > 0 {
  98. factory, ok := versioner.Factories[repoCfg.Versioning.Type]
  99. if !ok {
  100. l.Fatalf("Requested versioning type %q that does not exist", repoCfg.Versioning.Type)
  101. }
  102. p.versioner = factory(repoCfg.ID, repoCfg.Directory, repoCfg.Versioning.Params)
  103. }
  104. if slots > 0 {
  105. // Read/write
  106. if debug {
  107. l.Debugf("starting puller; repo %q dir %q slots %d", repoCfg.ID, repoCfg.Directory, slots)
  108. }
  109. go p.run()
  110. } else {
  111. // Read only
  112. if debug {
  113. l.Debugf("starting puller; repo %q dir %q (read only)", repoCfg.ID, repoCfg.Directory)
  114. }
  115. go p.runRO()
  116. }
  117. return p
  118. }
  119. func (p *puller) run() {
  120. changed := true
  121. scanintv := time.Duration(p.repoCfg.RescanIntervalS) * time.Second
  122. lastscan := time.Now()
  123. var prevVer uint64
  124. var queued int
  125. // Load up the request slots
  126. for i := 0; i < cap(p.requestSlots); i++ {
  127. p.requestSlots <- true
  128. }
  129. for {
  130. if sc, sl := cap(p.requestSlots), len(p.requestSlots); sl != sc {
  131. panic(fmt.Sprintf("Incorrect number of slots; %d != %d", sl, sc))
  132. }
  133. // Run the pulling loop as long as there are blocks to fetch
  134. prevVer, queued = p.queueNeededBlocks(prevVer)
  135. if queued > 0 {
  136. p.errors = 0
  137. pull:
  138. for {
  139. select {
  140. case res := <-p.requestResults:
  141. p.model.setState(p.repoCfg.ID, RepoSyncing)
  142. changed = true
  143. p.requestSlots <- true
  144. p.handleRequestResult(res)
  145. case <-p.requestSlots:
  146. b, ok := p.bq.get()
  147. if !ok {
  148. if debug {
  149. l.Debugf("%q: pulling loop needs more blocks", p.repoCfg.ID)
  150. }
  151. if p.errors > 0 && p.errors >= queued {
  152. p.requestSlots <- true
  153. break pull
  154. }
  155. prevVer, _ = p.queueNeededBlocks(prevVer)
  156. b, ok = p.bq.get()
  157. }
  158. if !ok && len(p.openFiles) == 0 {
  159. // Nothing queued, nothing outstanding
  160. if debug {
  161. l.Debugf("%q: pulling loop done", p.repoCfg.ID)
  162. }
  163. p.requestSlots <- true
  164. break pull
  165. }
  166. if !ok {
  167. // Nothing queued, but there are still open files.
  168. // Give the situation a moment to change.
  169. if debug {
  170. l.Debugf("%q: pulling loop paused", p.repoCfg.ID)
  171. }
  172. p.requestSlots <- true
  173. time.Sleep(100 * time.Millisecond)
  174. continue pull
  175. }
  176. if debug {
  177. l.Debugf("queueing %q / %q offset %d copy %d", p.repoCfg.ID, b.file.Name, b.block.Offset, len(b.copy))
  178. }
  179. p.model.setState(p.repoCfg.ID, RepoSyncing)
  180. changed = true
  181. if p.handleBlock(b) {
  182. // Block was fully handled, free up the slot
  183. p.requestSlots <- true
  184. }
  185. }
  186. }
  187. if p.errors > 0 && p.errors >= queued {
  188. l.Warnf("All remaining files failed to sync. Stopping repo %q.", p.repoCfg.ID)
  189. invalidateRepo(p.cfg, p.repoCfg.ID, errors.New("too many errors, check logs"))
  190. return
  191. }
  192. }
  193. if changed {
  194. p.model.setState(p.repoCfg.ID, RepoCleaning)
  195. p.fixupDirectories()
  196. changed = false
  197. }
  198. p.model.setState(p.repoCfg.ID, RepoIdle)
  199. // Do a rescan if it's time for it
  200. if time.Since(lastscan) > scanintv {
  201. if debug {
  202. l.Debugf("%q: time for rescan", p.repoCfg.ID)
  203. }
  204. err := p.model.ScanRepo(p.repoCfg.ID)
  205. if err != nil {
  206. invalidateRepo(p.cfg, p.repoCfg.ID, err)
  207. return
  208. }
  209. lastscan = time.Now()
  210. }
  211. time.Sleep(5 * time.Second)
  212. }
  213. }
  214. func (p *puller) runRO() {
  215. walkTicker := time.Tick(time.Duration(p.repoCfg.RescanIntervalS) * time.Second)
  216. for _ = range walkTicker {
  217. if debug {
  218. l.Debugf("%q: time for rescan", p.repoCfg.ID)
  219. }
  220. err := p.model.ScanRepo(p.repoCfg.ID)
  221. if err != nil {
  222. invalidateRepo(p.cfg, p.repoCfg.ID, err)
  223. return
  224. }
  225. }
  226. }
  227. func (p *puller) fixupDirectories() {
  228. var deleteDirs []string
  229. var changed = 0
  230. var walkFn = func(path string, info os.FileInfo, err error) error {
  231. if err != nil {
  232. return err
  233. }
  234. if !info.IsDir() {
  235. return nil
  236. }
  237. rn, err := filepath.Rel(p.repoCfg.Directory, path)
  238. if err != nil {
  239. return nil
  240. }
  241. if rn == "." {
  242. return nil
  243. }
  244. if filepath.Base(rn) == ".stversions" {
  245. return filepath.SkipDir
  246. }
  247. cur := p.model.CurrentRepoFile(p.repoCfg.ID, rn)
  248. if cur.Name != rn {
  249. // No matching dir in current list; weird
  250. if debug {
  251. l.Debugf("missing dir: %s; %v", rn, cur)
  252. }
  253. return nil
  254. }
  255. if protocol.IsDeleted(cur.Flags) {
  256. if debug {
  257. l.Debugf("queue delete dir: %v", cur)
  258. }
  259. // We queue the directories to delete since we walk the
  260. // tree in depth first order and need to remove the
  261. // directories in the opposite order.
  262. deleteDirs = append(deleteDirs, path)
  263. return nil
  264. }
  265. if !p.repoCfg.IgnorePerms && protocol.HasPermissionBits(cur.Flags) && !scanner.PermsEqual(cur.Flags, uint32(info.Mode())) {
  266. err := os.Chmod(path, os.FileMode(cur.Flags)&os.ModePerm)
  267. if err != nil {
  268. l.Warnf("Restoring folder flags: %q: %v", path, err)
  269. } else {
  270. changed++
  271. if debug {
  272. l.Debugf("restored dir flags: %o -> %v", info.Mode()&os.ModePerm, cur)
  273. }
  274. }
  275. }
  276. return nil
  277. }
  278. for {
  279. deleteDirs = nil
  280. changed = 0
  281. filepath.Walk(p.repoCfg.Directory, walkFn)
  282. var deleted = 0
  283. // Delete any queued directories
  284. for i := len(deleteDirs) - 1; i >= 0; i-- {
  285. dir := deleteDirs[i]
  286. if debug {
  287. l.Debugln("delete dir:", dir)
  288. }
  289. err := os.Remove(dir)
  290. if err == nil {
  291. deleted++
  292. } else {
  293. l.Warnln("Delete dir:", err)
  294. }
  295. }
  296. if debug {
  297. l.Debugf("changed %d, deleted %d dirs", changed, deleted)
  298. }
  299. if changed+deleted == 0 {
  300. return
  301. }
  302. }
  303. }
  304. func (p *puller) handleRequestResult(res requestResult) {
  305. p.oustandingPerNode.decrease(res.node)
  306. f := res.file
  307. of, ok := p.openFiles[f.Name]
  308. if !ok {
  309. // no entry in openFiles means there was an error and we've cancelled the operation
  310. return
  311. }
  312. if res.err != nil {
  313. // This request resulted in an error
  314. of.err = res.err
  315. if debug {
  316. l.Debugf("pull: not writing %q / %q offset %d: %v; (done=%v, outstanding=%d)", p.repoCfg.ID, f.Name, res.offset, res.err, of.done, of.outstanding)
  317. }
  318. } else if of.err == nil {
  319. // This request was sucessfull and nothing has failed previously either
  320. _, of.err = of.file.WriteAt(res.data, res.offset)
  321. if debug {
  322. l.Debugf("pull: wrote %q / %q offset %d len %d outstanding %d done %v", p.repoCfg.ID, f.Name, res.offset, len(res.data), of.outstanding, of.done)
  323. }
  324. }
  325. of.outstanding--
  326. p.openFiles[f.Name] = of
  327. if of.done && of.outstanding == 0 {
  328. p.closeFile(f)
  329. }
  330. }
  331. // handleBlock fulfills the block request by copying, ignoring or fetching
  332. // from the network. Returns true if the block was fully handled
  333. // synchronously, i.e. if the slot can be reused.
  334. func (p *puller) handleBlock(b bqBlock) bool {
  335. f := b.file
  336. // For directories, making sure they exist is enough.
  337. // Deleted directories we mark as handled and delete later.
  338. if protocol.IsDirectory(f.Flags) {
  339. if !protocol.IsDeleted(f.Flags) {
  340. path := filepath.Join(p.repoCfg.Directory, f.Name)
  341. _, err := os.Stat(path)
  342. if err != nil && os.IsNotExist(err) {
  343. if debug {
  344. l.Debugf("create dir: %v", f)
  345. }
  346. err = os.MkdirAll(path, os.FileMode(f.Flags&0777))
  347. if err != nil {
  348. p.errors++
  349. l.Infof("mkdir: error: %q: %v", path, err)
  350. }
  351. }
  352. } else if debug {
  353. l.Debugf("ignore delete dir: %v", f)
  354. }
  355. p.model.updateLocal(p.repoCfg.ID, f)
  356. return true
  357. }
  358. if len(b.copy) > 0 && len(b.copy) == len(b.file.Blocks) && b.last {
  359. // We are supposed to copy the entire file, and then fetch nothing.
  360. // We don't actually need to make the copy.
  361. if debug {
  362. l.Debugln("taking shortcut:", f)
  363. }
  364. fp := filepath.Join(p.repoCfg.Directory, f.Name)
  365. t := time.Unix(f.Modified, 0)
  366. err := os.Chtimes(fp, t, t)
  367. if err != nil {
  368. l.Infof("chtimes: error: %q / %q: %v", p.repoCfg.ID, f.Name, err)
  369. }
  370. if !p.repoCfg.IgnorePerms && protocol.HasPermissionBits(f.Flags) {
  371. err = os.Chmod(fp, os.FileMode(f.Flags&0777))
  372. if err != nil {
  373. l.Infof("chmod: error: %q / %q: %v", p.repoCfg.ID, f.Name, err)
  374. }
  375. }
  376. events.Default.Log(events.ItemStarted, map[string]string{
  377. "repo": p.repoCfg.ID,
  378. "item": f.Name,
  379. })
  380. p.model.updateLocal(p.repoCfg.ID, f)
  381. return true
  382. }
  383. of, ok := p.openFiles[f.Name]
  384. of.done = b.last
  385. if !ok {
  386. if debug {
  387. l.Debugf("pull: %q: opening file %q", p.repoCfg.ID, f.Name)
  388. }
  389. events.Default.Log(events.ItemStarted, map[string]string{
  390. "repo": p.repoCfg.ID,
  391. "item": f.Name,
  392. })
  393. of.availability = p.model.repoFiles[p.repoCfg.ID].Availability(f.Name)
  394. of.filepath = filepath.Join(p.repoCfg.Directory, f.Name)
  395. of.temp = filepath.Join(p.repoCfg.Directory, defTempNamer.TempName(f.Name))
  396. dirName := filepath.Dir(of.filepath)
  397. info, err := os.Stat(dirName)
  398. if err != nil {
  399. err = os.MkdirAll(dirName, 0777)
  400. if debug && err != nil {
  401. l.Debugf("mkdir: error: %q / %q: %v", p.repoCfg.ID, f.Name, err)
  402. }
  403. } else {
  404. // We need to make sure the directory is writeable so we can create files in it
  405. if dirName != p.repoCfg.Directory {
  406. err = os.Chmod(dirName, 0777)
  407. if debug && err != nil {
  408. l.Debugf("make writeable: error: %q / %q: %v", p.repoCfg.ID, f.Name, err)
  409. }
  410. }
  411. // Change it back after creating the file, to minimize the time window with incorrect permissions
  412. defer os.Chmod(dirName, info.Mode())
  413. }
  414. of.file, of.err = os.Create(of.temp)
  415. if of.err != nil {
  416. p.errors++
  417. l.Infof("create: error: %q / %q: %v", p.repoCfg.ID, f.Name, of.err)
  418. if !b.last {
  419. p.openFiles[f.Name] = of
  420. }
  421. return true
  422. }
  423. osutil.HideFile(of.temp)
  424. }
  425. if of.err != nil {
  426. // We have already failed this file.
  427. if debug {
  428. l.Debugf("pull: error: %q / %q has already failed: %v", p.repoCfg.ID, f.Name, of.err)
  429. }
  430. if b.last {
  431. delete(p.openFiles, f.Name)
  432. }
  433. return true
  434. }
  435. p.openFiles[f.Name] = of
  436. switch {
  437. case len(b.copy) > 0:
  438. p.handleCopyBlock(b)
  439. return true
  440. case b.block.Size > 0:
  441. return p.handleRequestBlock(b)
  442. default:
  443. p.handleEmptyBlock(b)
  444. return true
  445. }
  446. }
  447. func (p *puller) handleCopyBlock(b bqBlock) {
  448. // We have blocks to copy from the existing file
  449. f := b.file
  450. of := p.openFiles[f.Name]
  451. if debug {
  452. l.Debugf("pull: copying %d blocks for %q / %q", len(b.copy), p.repoCfg.ID, f.Name)
  453. }
  454. var exfd *os.File
  455. exfd, of.err = os.Open(of.filepath)
  456. if of.err != nil {
  457. p.errors++
  458. l.Infof("open: error: %q / %q: %v", p.repoCfg.ID, f.Name, of.err)
  459. of.file.Close()
  460. of.file = nil
  461. p.openFiles[f.Name] = of
  462. return
  463. }
  464. defer exfd.Close()
  465. for _, b := range b.copy {
  466. bs := make([]byte, b.Size)
  467. _, of.err = exfd.ReadAt(bs, b.Offset)
  468. if of.err == nil {
  469. _, of.err = of.file.WriteAt(bs, b.Offset)
  470. }
  471. if of.err != nil {
  472. p.errors++
  473. l.Infof("write: error: %q / %q: %v", p.repoCfg.ID, f.Name, of.err)
  474. exfd.Close()
  475. of.file.Close()
  476. of.file = nil
  477. p.openFiles[f.Name] = of
  478. return
  479. }
  480. }
  481. }
  482. // handleRequestBlock tries to pull a block from the network. Returns true if
  483. // the block could _not_ be fetched (i.e. it was fully handled, matching the
  484. // return criteria of handleBlock)
  485. func (p *puller) handleRequestBlock(b bqBlock) bool {
  486. f := b.file
  487. of, ok := p.openFiles[f.Name]
  488. if !ok {
  489. panic("bug: request for non-open file")
  490. }
  491. node := p.oustandingPerNode.leastBusyNode(of.availability, p.model.ConnectedTo)
  492. if node == (protocol.NodeID{}) {
  493. of.err = errNoNode
  494. if of.file != nil {
  495. of.file.Close()
  496. of.file = nil
  497. os.Remove(of.temp)
  498. if debug {
  499. l.Debugf("pull: no source for %q / %q; closed", p.repoCfg.ID, f.Name)
  500. }
  501. }
  502. if b.last {
  503. if debug {
  504. l.Debugf("pull: no source for %q / %q; deleting", p.repoCfg.ID, f.Name)
  505. }
  506. delete(p.openFiles, f.Name)
  507. } else {
  508. if debug {
  509. l.Debugf("pull: no source for %q / %q; await more blocks", p.repoCfg.ID, f.Name)
  510. }
  511. p.openFiles[f.Name] = of
  512. }
  513. return true
  514. }
  515. of.outstanding++
  516. p.openFiles[f.Name] = of
  517. go func(node protocol.NodeID, b bqBlock) {
  518. if debug {
  519. l.Debugf("pull: requesting %q / %q offset %d size %d from %q outstanding %d", p.repoCfg.ID, f.Name, b.block.Offset, b.block.Size, node, of.outstanding)
  520. }
  521. bs, err := p.model.requestGlobal(node, p.repoCfg.ID, f.Name, b.block.Offset, int(b.block.Size), nil)
  522. p.requestResults <- requestResult{
  523. node: node,
  524. file: f,
  525. filepath: of.filepath,
  526. offset: b.block.Offset,
  527. data: bs,
  528. err: err,
  529. }
  530. }(node, b)
  531. return false
  532. }
  533. func (p *puller) handleEmptyBlock(b bqBlock) {
  534. f := b.file
  535. of := p.openFiles[f.Name]
  536. if b.last {
  537. if of.err == nil {
  538. of.file.Close()
  539. }
  540. }
  541. if protocol.IsDeleted(f.Flags) {
  542. if debug {
  543. l.Debugf("pull: delete %q", f.Name)
  544. }
  545. os.Remove(of.temp)
  546. // Ensure the file and the directory it is in is writeable so we can remove the file
  547. dirName := filepath.Dir(of.filepath)
  548. err := os.Chmod(of.filepath, 0666)
  549. if debug && err != nil {
  550. l.Debugf("make writeable: error: %q: %v", of.filepath, err)
  551. }
  552. if dirName != p.repoCfg.Directory {
  553. info, err := os.Stat(dirName)
  554. if err != nil {
  555. l.Debugln("weird! can't happen?", err)
  556. }
  557. err = os.Chmod(dirName, 0777)
  558. if debug && err != nil {
  559. l.Debugf("make writeable: error: %q: %v", dirName, err)
  560. }
  561. // Change it back after deleting the file, to minimize the time window with incorrect permissions
  562. defer os.Chmod(dirName, info.Mode())
  563. }
  564. if p.versioner != nil {
  565. if debug {
  566. l.Debugln("pull: deleting with versioner")
  567. }
  568. if err := p.versioner.Archive(of.filepath); err == nil {
  569. p.model.updateLocal(p.repoCfg.ID, f)
  570. } else if debug {
  571. l.Debugln("pull: error:", err)
  572. }
  573. } else if err := os.Remove(of.filepath); err == nil || os.IsNotExist(err) {
  574. p.model.updateLocal(p.repoCfg.ID, f)
  575. }
  576. } else {
  577. if debug {
  578. l.Debugf("pull: no blocks to fetch and nothing to copy for %q / %q", p.repoCfg.ID, f.Name)
  579. }
  580. t := time.Unix(f.Modified, 0)
  581. if os.Chtimes(of.temp, t, t) != nil {
  582. delete(p.openFiles, f.Name)
  583. return
  584. }
  585. if !p.repoCfg.IgnorePerms && protocol.HasPermissionBits(f.Flags) && os.Chmod(of.temp, os.FileMode(f.Flags&0777)) != nil {
  586. delete(p.openFiles, f.Name)
  587. return
  588. }
  589. osutil.ShowFile(of.temp)
  590. if osutil.Rename(of.temp, of.filepath) == nil {
  591. p.model.updateLocal(p.repoCfg.ID, f)
  592. }
  593. }
  594. delete(p.openFiles, f.Name)
  595. }
  596. func (p *puller) queueNeededBlocks(prevVer uint64) (uint64, int) {
  597. curVer := p.model.LocalVersion(p.repoCfg.ID)
  598. if curVer == prevVer {
  599. return curVer, 0
  600. }
  601. if debug {
  602. l.Debugf("%q: checking for more needed blocks", p.repoCfg.ID)
  603. }
  604. queued := 0
  605. files := make([]protocol.FileInfo, 0, indexBatchSize)
  606. for _, f := range p.model.NeedFilesRepo(p.repoCfg.ID) {
  607. if _, ok := p.openFiles[f.Name]; ok {
  608. continue
  609. }
  610. files = append(files, f)
  611. }
  612. perm := rand.Perm(len(files))
  613. for _, idx := range perm {
  614. f := files[idx]
  615. lf := p.model.CurrentRepoFile(p.repoCfg.ID, f.Name)
  616. have, need := scanner.BlockDiff(lf.Blocks, f.Blocks)
  617. if debug {
  618. l.Debugf("need:\n local: %v\n global: %v\n haveBlocks: %v\n needBlocks: %v", lf, f, have, need)
  619. }
  620. queued++
  621. p.bq.put(bqAdd{
  622. file: f,
  623. have: have,
  624. need: need,
  625. })
  626. }
  627. if debug && queued > 0 {
  628. l.Debugf("%q: queued %d items", p.repoCfg.ID, queued)
  629. }
  630. if queued > 0 {
  631. return prevVer, queued
  632. } else {
  633. return curVer, 0
  634. }
  635. }
  636. func (p *puller) closeFile(f protocol.FileInfo) {
  637. if debug {
  638. l.Debugf("pull: closing %q / %q", p.repoCfg.ID, f.Name)
  639. }
  640. of := p.openFiles[f.Name]
  641. err := of.file.Close()
  642. if err != nil {
  643. p.errors++
  644. l.Infof("close: error: %q / %q: %v", p.repoCfg.ID, f.Name, err)
  645. }
  646. defer os.Remove(of.temp)
  647. delete(p.openFiles, f.Name)
  648. fd, err := os.Open(of.temp)
  649. if err != nil {
  650. p.errors++
  651. l.Infof("open: error: %q / %q: %v", p.repoCfg.ID, f.Name, err)
  652. return
  653. }
  654. hb, _ := scanner.Blocks(fd, scanner.StandardBlockSize, f.Size())
  655. fd.Close()
  656. if l0, l1 := len(hb), len(f.Blocks); l0 != l1 {
  657. if debug {
  658. l.Debugf("pull: %q / %q: nblocks %d != %d", p.repoCfg.ID, f.Name, l0, l1)
  659. }
  660. return
  661. }
  662. for i := range hb {
  663. if bytes.Compare(hb[i].Hash, f.Blocks[i].Hash) != 0 {
  664. if debug {
  665. l.Debugf("pull: %q / %q: block %d hash mismatch\n have: %x\n want: %x", p.repoCfg.ID, f.Name, i, hb[i].Hash, f.Blocks[i].Hash)
  666. }
  667. return
  668. }
  669. }
  670. t := time.Unix(f.Modified, 0)
  671. err = os.Chtimes(of.temp, t, t)
  672. if err != nil {
  673. l.Infof("chtimes: error: %q / %q: %v", p.repoCfg.ID, f.Name, err)
  674. }
  675. if !p.repoCfg.IgnorePerms && protocol.HasPermissionBits(f.Flags) {
  676. err = os.Chmod(of.temp, os.FileMode(f.Flags&0777))
  677. if err != nil {
  678. l.Infof("chmod: error: %q / %q: %v", p.repoCfg.ID, f.Name, err)
  679. }
  680. }
  681. osutil.ShowFile(of.temp)
  682. if p.versioner != nil {
  683. err := p.versioner.Archive(of.filepath)
  684. if err != nil {
  685. if debug {
  686. l.Debugf("pull: error: %q / %q: %v", p.repoCfg.ID, f.Name, err)
  687. }
  688. return
  689. }
  690. }
  691. if debug {
  692. l.Debugf("pull: rename %q / %q: %q", p.repoCfg.ID, f.Name, of.filepath)
  693. }
  694. if err := osutil.Rename(of.temp, of.filepath); err == nil {
  695. p.model.updateLocal(p.repoCfg.ID, f)
  696. } else {
  697. p.errors++
  698. l.Infof("rename: error: %q / %q: %v", p.repoCfg.ID, f.Name, err)
  699. }
  700. }
  701. func invalidateRepo(cfg *config.Configuration, repoID string, err error) {
  702. for i := range cfg.Repositories {
  703. repo := &cfg.Repositories[i]
  704. if repo.ID == repoID {
  705. repo.Invalid = err.Error()
  706. return
  707. }
  708. }
  709. }