chunker.go 17 KB

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