puller.go 19 KB

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