chunker.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612
  1. // Copyright 2016 The go-ethereum Authors
  2. // This file is part of the go-ethereum library.
  3. //
  4. // The go-ethereum library is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU Lesser General Public License as published by
  6. // the Free Software Foundation, either version 3 of the License, or
  7. // (at your option) any later version.
  8. //
  9. // The go-ethereum library is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. // GNU Lesser General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU Lesser General Public License
  15. // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
  16. package storage
  17. import (
  18. "context"
  19. "encoding/binary"
  20. "errors"
  21. "fmt"
  22. "io"
  23. "sync"
  24. "time"
  25. "github.com/ethereum/go-ethereum/metrics"
  26. "github.com/ethereum/go-ethereum/swarm/chunk"
  27. "github.com/ethereum/go-ethereum/swarm/log"
  28. "github.com/ethereum/go-ethereum/swarm/spancontext"
  29. opentracing "github.com/opentracing/opentracing-go"
  30. olog "github.com/opentracing/opentracing-go/log"
  31. )
  32. /*
  33. The distributed storage implemented in this package requires fix sized chunks of content.
  34. Chunker is the interface to a component that is responsible for disassembling and assembling larger data.
  35. TreeChunker implements a Chunker based on a tree structure defined as follows:
  36. 1 each node in the tree including the root and other branching nodes are stored as a chunk.
  37. 2 branching nodes encode data contents that includes the size of the dataslice covered by its entire subtree under the node as well as the hash keys of all its children :
  38. data_{i} := size(subtree_{i}) || key_{j} || key_{j+1} .... || key_{j+n-1}
  39. 3 Leaf nodes encode an actual subslice of the input data.
  40. 4 if data size is not more than maximum chunksize, the data is stored in a single chunk
  41. key = hash(int64(size) + data)
  42. 5 if data size is more than chunksize*branches^l, but no more than chunksize*
  43. branches^(l+1), the data vector is split into slices of chunksize*
  44. branches^l length (except the last one).
  45. key = hash(int64(size) + key(slice0) + key(slice1) + ...)
  46. The underlying hash function is configurable
  47. */
  48. /*
  49. Tree chunker is a concrete implementation of data chunking.
  50. This chunker works in a simple way, it builds a tree out of the document so that each node either represents a chunk of real data or a chunk of data representing an branching non-leaf node of the tree. In particular each such non-leaf chunk will represent is a concatenation of the hash of its respective children. This scheme simultaneously guarantees data integrity as well as self addressing. Abstract nodes are transparent since their represented size component is strictly greater than their maximum data size, since they encode a subtree.
  51. If all is well it is possible to implement this by simply composing readers so that no extra allocation or buffering is necessary for the data splitting and joining. This means that in principle there can be direct IO between : memory, file system, network socket (bzz peers storage request is read from the socket). In practice there may be need for several stages of internal buffering.
  52. The hashing itself does use extra copies and allocation though, since it does need it.
  53. */
  54. type ChunkerParams struct {
  55. chunkSize int64
  56. hashSize int64
  57. }
  58. type SplitterParams struct {
  59. ChunkerParams
  60. reader io.Reader
  61. putter Putter
  62. addr Address
  63. }
  64. type TreeSplitterParams struct {
  65. SplitterParams
  66. size int64
  67. }
  68. type JoinerParams struct {
  69. ChunkerParams
  70. addr Address
  71. getter Getter
  72. // TODO: there is a bug, so depth can only be 0 today, see: https://github.com/ethersphere/go-ethereum/issues/344
  73. depth int
  74. ctx context.Context
  75. }
  76. type TreeChunker struct {
  77. ctx context.Context
  78. branches int64
  79. dataSize int64
  80. data io.Reader
  81. // calculated
  82. addr Address
  83. depth int
  84. hashSize int64 // self.hashFunc.New().Size()
  85. chunkSize int64 // hashSize* branches
  86. workerCount int64 // the number of worker routines used
  87. workerLock sync.RWMutex // lock for the worker count
  88. jobC chan *hashJob
  89. wg *sync.WaitGroup
  90. putter Putter
  91. getter Getter
  92. errC chan error
  93. quitC chan bool
  94. }
  95. /*
  96. Join reconstructs original content based on a root key.
  97. When joining, the caller gets returned a Lazy SectionReader, which is
  98. seekable and implements on-demand fetching of chunks as and where it is read.
  99. New chunks to retrieve are coming from the getter, which the caller provides.
  100. If an error is encountered during joining, it appears as a reader error.
  101. The SectionReader.
  102. As a result, partial reads from a document are possible even if other parts
  103. are corrupt or lost.
  104. The chunks are not meant to be validated by the chunker when joining. This
  105. is because it is left to the DPA to decide which sources are trusted.
  106. */
  107. func TreeJoin(ctx context.Context, addr Address, getter Getter, depth int) *LazyChunkReader {
  108. jp := &JoinerParams{
  109. ChunkerParams: ChunkerParams{
  110. chunkSize: chunk.DefaultSize,
  111. hashSize: int64(len(addr)),
  112. },
  113. addr: addr,
  114. getter: getter,
  115. depth: depth,
  116. ctx: ctx,
  117. }
  118. return NewTreeJoiner(jp).Join(ctx)
  119. }
  120. /*
  121. When splitting, data is given as a SectionReader, and the key is a hashSize long byte slice (Key), the root hash of the entire content will fill this once processing finishes.
  122. New chunks to store are store using the putter which the caller provides.
  123. */
  124. func TreeSplit(ctx context.Context, data io.Reader, size int64, putter Putter) (k Address, wait func(context.Context) error, err error) {
  125. tsp := &TreeSplitterParams{
  126. SplitterParams: SplitterParams{
  127. ChunkerParams: ChunkerParams{
  128. chunkSize: chunk.DefaultSize,
  129. hashSize: putter.RefSize(),
  130. },
  131. reader: data,
  132. putter: putter,
  133. },
  134. size: size,
  135. }
  136. return NewTreeSplitter(tsp).Split(ctx)
  137. }
  138. func NewTreeJoiner(params *JoinerParams) *TreeChunker {
  139. tc := &TreeChunker{}
  140. tc.hashSize = params.hashSize
  141. tc.branches = params.chunkSize / params.hashSize
  142. tc.addr = params.addr
  143. tc.getter = params.getter
  144. tc.depth = params.depth
  145. tc.chunkSize = params.chunkSize
  146. tc.workerCount = 0
  147. tc.jobC = make(chan *hashJob, 2*ChunkProcessors)
  148. tc.wg = &sync.WaitGroup{}
  149. tc.errC = make(chan error)
  150. tc.quitC = make(chan bool)
  151. tc.ctx = params.ctx
  152. return tc
  153. }
  154. func NewTreeSplitter(params *TreeSplitterParams) *TreeChunker {
  155. tc := &TreeChunker{}
  156. tc.data = params.reader
  157. tc.dataSize = params.size
  158. tc.hashSize = params.hashSize
  159. tc.branches = params.chunkSize / params.hashSize
  160. tc.addr = params.addr
  161. tc.chunkSize = params.chunkSize
  162. tc.putter = params.putter
  163. tc.workerCount = 0
  164. tc.jobC = make(chan *hashJob, 2*ChunkProcessors)
  165. tc.wg = &sync.WaitGroup{}
  166. tc.errC = make(chan error)
  167. tc.quitC = make(chan bool)
  168. return tc
  169. }
  170. type hashJob struct {
  171. key Address
  172. chunk []byte
  173. size int64
  174. parentWg *sync.WaitGroup
  175. }
  176. func (tc *TreeChunker) incrementWorkerCount() {
  177. tc.workerLock.Lock()
  178. defer tc.workerLock.Unlock()
  179. tc.workerCount += 1
  180. }
  181. func (tc *TreeChunker) getWorkerCount() int64 {
  182. tc.workerLock.RLock()
  183. defer tc.workerLock.RUnlock()
  184. return tc.workerCount
  185. }
  186. func (tc *TreeChunker) decrementWorkerCount() {
  187. tc.workerLock.Lock()
  188. defer tc.workerLock.Unlock()
  189. tc.workerCount -= 1
  190. }
  191. func (tc *TreeChunker) Split(ctx context.Context) (k Address, wait func(context.Context) error, err error) {
  192. if tc.chunkSize <= 0 {
  193. panic("chunker must be initialised")
  194. }
  195. tc.runWorker(ctx)
  196. depth := 0
  197. treeSize := tc.chunkSize
  198. // takes lowest depth such that chunksize*HashCount^(depth+1) > size
  199. // power series, will find the order of magnitude of the data size in base hashCount or numbers of levels of branching in the resulting tree.
  200. for ; treeSize < tc.dataSize; treeSize *= tc.branches {
  201. depth++
  202. }
  203. key := make([]byte, tc.hashSize)
  204. // this waitgroup member is released after the root hash is calculated
  205. tc.wg.Add(1)
  206. //launch actual recursive function passing the waitgroups
  207. go tc.split(ctx, depth, treeSize/tc.branches, key, tc.dataSize, tc.wg)
  208. // closes internal error channel if all subprocesses in the workgroup finished
  209. go func() {
  210. // waiting for all threads to finish
  211. tc.wg.Wait()
  212. close(tc.errC)
  213. }()
  214. defer close(tc.quitC)
  215. defer tc.putter.Close()
  216. select {
  217. case err := <-tc.errC:
  218. if err != nil {
  219. return nil, nil, err
  220. }
  221. case <-ctx.Done():
  222. return nil, nil, ctx.Err()
  223. }
  224. return key, tc.putter.Wait, nil
  225. }
  226. func (tc *TreeChunker) split(ctx context.Context, depth int, treeSize int64, addr Address, size int64, parentWg *sync.WaitGroup) {
  227. //
  228. for depth > 0 && size < treeSize {
  229. treeSize /= tc.branches
  230. depth--
  231. }
  232. if depth == 0 {
  233. // leaf nodes -> content chunks
  234. chunkData := make([]byte, size+8)
  235. binary.LittleEndian.PutUint64(chunkData[0:8], uint64(size))
  236. var readBytes int64
  237. for readBytes < size {
  238. n, err := tc.data.Read(chunkData[8+readBytes:])
  239. readBytes += int64(n)
  240. if err != nil && !(err == io.EOF && readBytes == size) {
  241. tc.errC <- err
  242. return
  243. }
  244. }
  245. select {
  246. case tc.jobC <- &hashJob{addr, chunkData, size, parentWg}:
  247. case <-tc.quitC:
  248. }
  249. return
  250. }
  251. // dept > 0
  252. // intermediate chunk containing child nodes hashes
  253. branchCnt := (size + treeSize - 1) / treeSize
  254. var chunk = make([]byte, branchCnt*tc.hashSize+8)
  255. var pos, i int64
  256. binary.LittleEndian.PutUint64(chunk[0:8], uint64(size))
  257. childrenWg := &sync.WaitGroup{}
  258. var secSize int64
  259. for i < branchCnt {
  260. // the last item can have shorter data
  261. if size-pos < treeSize {
  262. secSize = size - pos
  263. } else {
  264. secSize = treeSize
  265. }
  266. // the hash of that data
  267. subTreeAddress := chunk[8+i*tc.hashSize : 8+(i+1)*tc.hashSize]
  268. childrenWg.Add(1)
  269. tc.split(ctx, depth-1, treeSize/tc.branches, subTreeAddress, secSize, childrenWg)
  270. i++
  271. pos += treeSize
  272. }
  273. // wait for all the children to complete calculating their hashes and copying them onto sections of the chunk
  274. // parentWg.Add(1)
  275. // go func() {
  276. childrenWg.Wait()
  277. worker := tc.getWorkerCount()
  278. if int64(len(tc.jobC)) > worker && worker < ChunkProcessors {
  279. tc.runWorker(ctx)
  280. }
  281. select {
  282. case tc.jobC <- &hashJob{addr, chunk, size, parentWg}:
  283. case <-tc.quitC:
  284. }
  285. }
  286. func (tc *TreeChunker) runWorker(ctx context.Context) {
  287. tc.incrementWorkerCount()
  288. go func() {
  289. defer tc.decrementWorkerCount()
  290. for {
  291. select {
  292. case job, ok := <-tc.jobC:
  293. if !ok {
  294. return
  295. }
  296. h, err := tc.putter.Put(ctx, job.chunk)
  297. if err != nil {
  298. tc.errC <- err
  299. return
  300. }
  301. copy(job.key, h)
  302. job.parentWg.Done()
  303. case <-tc.quitC:
  304. return
  305. }
  306. }
  307. }()
  308. }
  309. // LazyChunkReader implements LazySectionReader
  310. type LazyChunkReader struct {
  311. ctx context.Context
  312. addr Address // root address
  313. chunkData ChunkData
  314. off int64 // offset
  315. chunkSize int64 // inherit from chunker
  316. branches int64 // inherit from chunker
  317. hashSize int64 // inherit from chunker
  318. depth int
  319. getter Getter
  320. }
  321. func (tc *TreeChunker) Join(ctx context.Context) *LazyChunkReader {
  322. return &LazyChunkReader{
  323. addr: tc.addr,
  324. chunkSize: tc.chunkSize,
  325. branches: tc.branches,
  326. hashSize: tc.hashSize,
  327. depth: tc.depth,
  328. getter: tc.getter,
  329. ctx: tc.ctx,
  330. }
  331. }
  332. func (r *LazyChunkReader) Context() context.Context {
  333. return r.ctx
  334. }
  335. // Size is meant to be called on the LazySectionReader
  336. func (r *LazyChunkReader) Size(ctx context.Context, quitC chan bool) (n int64, err error) {
  337. metrics.GetOrRegisterCounter("lazychunkreader.size", nil).Inc(1)
  338. var sp opentracing.Span
  339. var cctx context.Context
  340. cctx, sp = spancontext.StartSpan(
  341. ctx,
  342. "lcr.size")
  343. defer sp.Finish()
  344. log.Debug("lazychunkreader.size", "addr", r.addr)
  345. if r.chunkData == nil {
  346. startTime := time.Now()
  347. chunkData, err := r.getter.Get(cctx, Reference(r.addr))
  348. if err != nil {
  349. metrics.GetOrRegisterResettingTimer("lcr.getter.get.err", nil).UpdateSince(startTime)
  350. return 0, err
  351. }
  352. metrics.GetOrRegisterResettingTimer("lcr.getter.get", nil).UpdateSince(startTime)
  353. r.chunkData = chunkData
  354. }
  355. s := r.chunkData.Size()
  356. log.Debug("lazychunkreader.size", "key", r.addr, "size", s)
  357. return int64(s), nil
  358. }
  359. // read at can be called numerous times
  360. // concurrent reads are allowed
  361. // Size() needs to be called synchronously on the LazyChunkReader first
  362. func (r *LazyChunkReader) ReadAt(b []byte, off int64) (read int, err error) {
  363. metrics.GetOrRegisterCounter("lazychunkreader.readat", nil).Inc(1)
  364. var sp opentracing.Span
  365. var cctx context.Context
  366. cctx, sp = spancontext.StartSpan(
  367. r.ctx,
  368. "lcr.read")
  369. defer sp.Finish()
  370. defer func() {
  371. sp.LogFields(
  372. olog.Int("off", int(off)),
  373. olog.Int("read", read))
  374. }()
  375. // this is correct, a swarm doc cannot be zero length, so no EOF is expected
  376. if len(b) == 0 {
  377. return 0, nil
  378. }
  379. quitC := make(chan bool)
  380. size, err := r.Size(cctx, quitC)
  381. if err != nil {
  382. log.Debug("lazychunkreader.readat.size", "size", size, "err", err)
  383. return 0, err
  384. }
  385. errC := make(chan error)
  386. // }
  387. var treeSize int64
  388. var depth int
  389. // calculate depth and max treeSize
  390. treeSize = r.chunkSize
  391. for ; treeSize < size; treeSize *= r.branches {
  392. depth++
  393. }
  394. wg := sync.WaitGroup{}
  395. length := int64(len(b))
  396. for d := 0; d < r.depth; d++ {
  397. off *= r.chunkSize
  398. length *= r.chunkSize
  399. }
  400. wg.Add(1)
  401. go r.join(cctx, b, off, off+length, depth, treeSize/r.branches, r.chunkData, &wg, errC, quitC)
  402. go func() {
  403. wg.Wait()
  404. close(errC)
  405. }()
  406. err = <-errC
  407. if err != nil {
  408. log.Debug("lazychunkreader.readat.errc", "err", err)
  409. close(quitC)
  410. return 0, err
  411. }
  412. if off+int64(len(b)) >= size {
  413. log.Debug("lazychunkreader.readat.return at end", "size", size, "off", off)
  414. return int(size - off), io.EOF
  415. }
  416. log.Debug("lazychunkreader.readat.errc", "buff", len(b))
  417. return len(b), nil
  418. }
  419. func (r *LazyChunkReader) join(ctx context.Context, b []byte, off int64, eoff int64, depth int, treeSize int64, chunkData ChunkData, parentWg *sync.WaitGroup, errC chan error, quitC chan bool) {
  420. defer parentWg.Done()
  421. // find appropriate block level
  422. for chunkData.Size() < uint64(treeSize) && depth > r.depth {
  423. treeSize /= r.branches
  424. depth--
  425. }
  426. // leaf chunk found
  427. if depth == r.depth {
  428. extra := 8 + eoff - int64(len(chunkData))
  429. if extra > 0 {
  430. eoff -= extra
  431. }
  432. copy(b, chunkData[8+off:8+eoff])
  433. return // simply give back the chunks reader for content chunks
  434. }
  435. // subtree
  436. start := off / treeSize
  437. end := (eoff + treeSize - 1) / treeSize
  438. // last non-leaf chunk can be shorter than default chunk size, let's not read it further then its end
  439. currentBranches := int64(len(chunkData)-8) / r.hashSize
  440. if end > currentBranches {
  441. end = currentBranches
  442. }
  443. wg := &sync.WaitGroup{}
  444. defer wg.Wait()
  445. for i := start; i < end; i++ {
  446. soff := i * treeSize
  447. roff := soff
  448. seoff := soff + treeSize
  449. if soff < off {
  450. soff = off
  451. }
  452. if seoff > eoff {
  453. seoff = eoff
  454. }
  455. if depth > 1 {
  456. wg.Wait()
  457. }
  458. wg.Add(1)
  459. go func(j int64) {
  460. childAddress := chunkData[8+j*r.hashSize : 8+(j+1)*r.hashSize]
  461. startTime := time.Now()
  462. chunkData, err := r.getter.Get(ctx, Reference(childAddress))
  463. if err != nil {
  464. metrics.GetOrRegisterResettingTimer("lcr.getter.get.err", nil).UpdateSince(startTime)
  465. select {
  466. case errC <- fmt.Errorf("chunk %v-%v not found; key: %s", off, off+treeSize, fmt.Sprintf("%x", childAddress)):
  467. case <-quitC:
  468. }
  469. return
  470. }
  471. metrics.GetOrRegisterResettingTimer("lcr.getter.get", nil).UpdateSince(startTime)
  472. if l := len(chunkData); l < 9 {
  473. select {
  474. case errC <- fmt.Errorf("chunk %v-%v incomplete; key: %s, data length %v", off, off+treeSize, fmt.Sprintf("%x", childAddress), l):
  475. case <-quitC:
  476. }
  477. return
  478. }
  479. if soff < off {
  480. soff = off
  481. }
  482. r.join(ctx, b[soff-off:seoff-off], soff-roff, seoff-roff, depth-1, treeSize/r.branches, chunkData, wg, errC, quitC)
  483. }(i)
  484. } //for
  485. }
  486. // Read keeps a cursor so cannot be called simulateously, see ReadAt
  487. func (r *LazyChunkReader) Read(b []byte) (read int, err error) {
  488. log.Trace("lazychunkreader.read", "key", r.addr)
  489. metrics.GetOrRegisterCounter("lazychunkreader.read", nil).Inc(1)
  490. read, err = r.ReadAt(b, r.off)
  491. if err != nil && err != io.EOF {
  492. log.Trace("lazychunkreader.readat", "read", read, "err", err)
  493. metrics.GetOrRegisterCounter("lazychunkreader.read.err", nil).Inc(1)
  494. }
  495. metrics.GetOrRegisterCounter("lazychunkreader.read.bytes", nil).Inc(int64(read))
  496. r.off += int64(read)
  497. return read, err
  498. }
  499. // completely analogous to standard SectionReader implementation
  500. var errWhence = errors.New("Seek: invalid whence")
  501. var errOffset = errors.New("Seek: invalid offset")
  502. func (r *LazyChunkReader) Seek(offset int64, whence int) (int64, error) {
  503. cctx, sp := spancontext.StartSpan(
  504. r.ctx,
  505. "lcr.seek")
  506. defer sp.Finish()
  507. log.Debug("lazychunkreader.seek", "key", r.addr, "offset", offset)
  508. switch whence {
  509. default:
  510. return 0, errWhence
  511. case 0:
  512. offset += 0
  513. case 1:
  514. offset += r.off
  515. case 2:
  516. if r.chunkData == nil { //seek from the end requires rootchunk for size. call Size first
  517. _, err := r.Size(cctx, nil)
  518. if err != nil {
  519. return 0, fmt.Errorf("can't get size: %v", err)
  520. }
  521. }
  522. offset += int64(r.chunkData.Size())
  523. }
  524. if offset < 0 {
  525. return 0, errOffset
  526. }
  527. r.off = offset
  528. return offset, nil
  529. }