chunker.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500
  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. "encoding/binary"
  19. "errors"
  20. "fmt"
  21. "hash"
  22. "io"
  23. "sync"
  24. )
  25. /*
  26. The distributed storage implemented in this package requires fix sized chunks of content.
  27. Chunker is the interface to a component that is responsible for disassembling and assembling larger data.
  28. TreeChunker implements a Chunker based on a tree structure defined as follows:
  29. 1 each node in the tree including the root and other branching nodes are stored as a chunk.
  30. 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 :
  31. data_{i} := size(subtree_{i}) || key_{j} || key_{j+1} .... || key_{j+n-1}
  32. 3 Leaf nodes encode an actual subslice of the input data.
  33. 4 if data size is not more than maximum chunksize, the data is stored in a single chunk
  34. key = hash(int64(size) + data)
  35. 5 if data size is more than chunksize*branches^l, but no more than chunksize*
  36. branches^(l+1), the data vector is split into slices of chunksize*
  37. branches^l length (except the last one).
  38. key = hash(int64(size) + key(slice0) + key(slice1) + ...)
  39. The underlying hash function is configurable
  40. */
  41. const (
  42. defaultHash = "SHA3" // http://golang.org/pkg/hash/#Hash
  43. // defaultHash = "SHA256" // http://golang.org/pkg/hash/#Hash
  44. defaultBranches int64 = 128
  45. // hashSize int64 = hasherfunc.New().Size() // hasher knows about its own length in bytes
  46. // chunksize int64 = branches * hashSize // chunk is defined as this
  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. Branches int64
  56. Hash string
  57. }
  58. func NewChunkerParams() *ChunkerParams {
  59. return &ChunkerParams{
  60. Branches: defaultBranches,
  61. Hash: defaultHash,
  62. }
  63. }
  64. type TreeChunker struct {
  65. branches int64
  66. hashFunc Hasher
  67. // calculated
  68. hashSize int64 // self.hashFunc.New().Size()
  69. chunkSize int64 // hashSize* branches
  70. workerCount int
  71. }
  72. func NewTreeChunker(params *ChunkerParams) (self *TreeChunker) {
  73. self = &TreeChunker{}
  74. self.hashFunc = MakeHashFunc(params.Hash)
  75. self.branches = params.Branches
  76. self.hashSize = int64(self.hashFunc().Size())
  77. self.chunkSize = self.hashSize * self.branches
  78. self.workerCount = 1
  79. return
  80. }
  81. // func (self *TreeChunker) KeySize() int64 {
  82. // return self.hashSize
  83. // }
  84. // String() for pretty printing
  85. func (self *Chunk) String() string {
  86. return fmt.Sprintf("Key: %v TreeSize: %v Chunksize: %v", self.Key.Log(), self.Size, len(self.SData))
  87. }
  88. type hashJob struct {
  89. key Key
  90. chunk []byte
  91. size int64
  92. parentWg *sync.WaitGroup
  93. }
  94. func (self *TreeChunker) Split(data io.Reader, size int64, chunkC chan *Chunk, swg, wwg *sync.WaitGroup) (Key, error) {
  95. if self.chunkSize <= 0 {
  96. panic("chunker must be initialised")
  97. }
  98. jobC := make(chan *hashJob, 2*processors)
  99. wg := &sync.WaitGroup{}
  100. errC := make(chan error)
  101. quitC := make(chan bool)
  102. // wwg = workers waitgroup keeps track of hashworkers spawned by this split call
  103. if wwg != nil {
  104. wwg.Add(1)
  105. }
  106. go self.hashWorker(jobC, chunkC, errC, quitC, swg, wwg)
  107. depth := 0
  108. treeSize := self.chunkSize
  109. // takes lowest depth such that chunksize*HashCount^(depth+1) > size
  110. // 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.
  111. for ; treeSize < size; treeSize *= self.branches {
  112. depth++
  113. }
  114. key := make([]byte, self.hashFunc().Size())
  115. // this waitgroup member is released after the root hash is calculated
  116. wg.Add(1)
  117. //launch actual recursive function passing the waitgroups
  118. go self.split(depth, treeSize/self.branches, key, data, size, jobC, chunkC, errC, quitC, wg, swg, wwg)
  119. // closes internal error channel if all subprocesses in the workgroup finished
  120. go func() {
  121. // waiting for all threads to finish
  122. wg.Wait()
  123. // if storage waitgroup is non-nil, we wait for storage to finish too
  124. if swg != nil {
  125. swg.Wait()
  126. }
  127. close(errC)
  128. }()
  129. select {
  130. case err := <-errC:
  131. if err != nil {
  132. close(quitC)
  133. return nil, err
  134. }
  135. //TODO: add a timeout
  136. }
  137. return key, nil
  138. }
  139. func (self *TreeChunker) split(depth int, treeSize int64, key Key, data io.Reader, size int64, jobC chan *hashJob, chunkC chan *Chunk, errC chan error, quitC chan bool, parentWg, swg, wwg *sync.WaitGroup) {
  140. for depth > 0 && size < treeSize {
  141. treeSize /= self.branches
  142. depth--
  143. }
  144. if depth == 0 {
  145. // leaf nodes -> content chunks
  146. chunkData := make([]byte, size+8)
  147. binary.LittleEndian.PutUint64(chunkData[0:8], uint64(size))
  148. var readBytes int64
  149. for readBytes < size {
  150. n, err := data.Read(chunkData[8+readBytes:])
  151. readBytes += int64(n)
  152. if err != nil && !(err == io.EOF && readBytes == size) {
  153. errC <- err
  154. return
  155. }
  156. }
  157. select {
  158. case jobC <- &hashJob{key, chunkData, size, parentWg}:
  159. case <-quitC:
  160. }
  161. return
  162. }
  163. // dept > 0
  164. // intermediate chunk containing child nodes hashes
  165. branchCnt := int64((size + treeSize - 1) / treeSize)
  166. var chunk []byte = make([]byte, branchCnt*self.hashSize+8)
  167. var pos, i int64
  168. binary.LittleEndian.PutUint64(chunk[0:8], uint64(size))
  169. childrenWg := &sync.WaitGroup{}
  170. var secSize int64
  171. for i < branchCnt {
  172. // the last item can have shorter data
  173. if size-pos < treeSize {
  174. secSize = size - pos
  175. } else {
  176. secSize = treeSize
  177. }
  178. // the hash of that data
  179. subTreeKey := chunk[8+i*self.hashSize : 8+(i+1)*self.hashSize]
  180. childrenWg.Add(1)
  181. self.split(depth-1, treeSize/self.branches, subTreeKey, data, secSize, jobC, chunkC, errC, quitC, childrenWg, swg, wwg)
  182. i++
  183. pos += treeSize
  184. }
  185. // wait for all the children to complete calculating their hashes and copying them onto sections of the chunk
  186. // parentWg.Add(1)
  187. // go func() {
  188. childrenWg.Wait()
  189. if len(jobC) > self.workerCount && self.workerCount < processors {
  190. if wwg != nil {
  191. wwg.Add(1)
  192. }
  193. self.workerCount++
  194. go self.hashWorker(jobC, chunkC, errC, quitC, swg, wwg)
  195. }
  196. select {
  197. case jobC <- &hashJob{key, chunk, size, parentWg}:
  198. case <-quitC:
  199. }
  200. }
  201. func (self *TreeChunker) hashWorker(jobC chan *hashJob, chunkC chan *Chunk, errC chan error, quitC chan bool, swg, wwg *sync.WaitGroup) {
  202. hasher := self.hashFunc()
  203. if wwg != nil {
  204. defer wwg.Done()
  205. }
  206. for {
  207. select {
  208. case job, ok := <-jobC:
  209. if !ok {
  210. return
  211. }
  212. // now we got the hashes in the chunk, then hash the chunks
  213. hasher.Reset()
  214. self.hashChunk(hasher, job, chunkC, swg)
  215. case <-quitC:
  216. return
  217. }
  218. }
  219. }
  220. // The treeChunkers own Hash hashes together
  221. // - the size (of the subtree encoded in the Chunk)
  222. // - the Chunk, ie. the contents read from the input reader
  223. func (self *TreeChunker) hashChunk(hasher hash.Hash, job *hashJob, chunkC chan *Chunk, swg *sync.WaitGroup) {
  224. hasher.Write(job.chunk)
  225. h := hasher.Sum(nil)
  226. newChunk := &Chunk{
  227. Key: h,
  228. SData: job.chunk,
  229. Size: job.size,
  230. wg: swg,
  231. }
  232. // report hash of this chunk one level up (keys corresponds to the proper subslice of the parent chunk)
  233. copy(job.key, h)
  234. // send off new chunk to storage
  235. if chunkC != nil {
  236. if swg != nil {
  237. swg.Add(1)
  238. }
  239. }
  240. job.parentWg.Done()
  241. if chunkC != nil {
  242. chunkC <- newChunk
  243. }
  244. }
  245. // LazyChunkReader implements LazySectionReader
  246. type LazyChunkReader struct {
  247. key Key // root key
  248. chunkC chan *Chunk // chunk channel to send retrieve requests on
  249. chunk *Chunk // size of the entire subtree
  250. off int64 // offset
  251. chunkSize int64 // inherit from chunker
  252. branches int64 // inherit from chunker
  253. hashSize int64 // inherit from chunker
  254. }
  255. // implements the Joiner interface
  256. func (self *TreeChunker) Join(key Key, chunkC chan *Chunk) LazySectionReader {
  257. return &LazyChunkReader{
  258. key: key,
  259. chunkC: chunkC,
  260. chunkSize: self.chunkSize,
  261. branches: self.branches,
  262. hashSize: self.hashSize,
  263. }
  264. }
  265. // Size is meant to be called on the LazySectionReader
  266. func (self *LazyChunkReader) Size(quitC chan bool) (n int64, err error) {
  267. if self.chunk != nil {
  268. return self.chunk.Size, nil
  269. }
  270. chunk := retrieve(self.key, self.chunkC, quitC)
  271. if chunk == nil {
  272. select {
  273. case <-quitC:
  274. return 0, errors.New("aborted")
  275. default:
  276. return 0, fmt.Errorf("root chunk not found for %v", self.key.Hex())
  277. }
  278. }
  279. self.chunk = chunk
  280. return chunk.Size, nil
  281. }
  282. // read at can be called numerous times
  283. // concurrent reads are allowed
  284. // Size() needs to be called synchronously on the LazyChunkReader first
  285. func (self *LazyChunkReader) ReadAt(b []byte, off int64) (read int, err error) {
  286. // this is correct, a swarm doc cannot be zero length, so no EOF is expected
  287. if len(b) == 0 {
  288. return 0, nil
  289. }
  290. quitC := make(chan bool)
  291. size, err := self.Size(quitC)
  292. if err != nil {
  293. return 0, err
  294. }
  295. errC := make(chan error)
  296. // }
  297. var treeSize int64
  298. var depth int
  299. // calculate depth and max treeSize
  300. treeSize = self.chunkSize
  301. for ; treeSize < size; treeSize *= self.branches {
  302. depth++
  303. }
  304. wg := sync.WaitGroup{}
  305. wg.Add(1)
  306. go self.join(b, off, off+int64(len(b)), depth, treeSize/self.branches, self.chunk, &wg, errC, quitC)
  307. go func() {
  308. wg.Wait()
  309. close(errC)
  310. }()
  311. err = <-errC
  312. if err != nil {
  313. close(quitC)
  314. return 0, err
  315. }
  316. if off+int64(len(b)) >= size {
  317. return len(b), io.EOF
  318. }
  319. return len(b), nil
  320. }
  321. func (self *LazyChunkReader) join(b []byte, off int64, eoff int64, depth int, treeSize int64, chunk *Chunk, parentWg *sync.WaitGroup, errC chan error, quitC chan bool) {
  322. defer parentWg.Done()
  323. // return NewDPA(&LocalStore{})
  324. // chunk.Size = int64(binary.LittleEndian.Uint64(chunk.SData[0:8]))
  325. // find appropriate block level
  326. for chunk.Size < treeSize && depth > 0 {
  327. treeSize /= self.branches
  328. depth--
  329. }
  330. // leaf chunk found
  331. if depth == 0 {
  332. extra := 8 + eoff - int64(len(chunk.SData))
  333. if extra > 0 {
  334. eoff -= extra
  335. }
  336. copy(b, chunk.SData[8+off:8+eoff])
  337. return // simply give back the chunks reader for content chunks
  338. }
  339. // subtree
  340. start := off / treeSize
  341. end := (eoff + treeSize - 1) / treeSize
  342. wg := &sync.WaitGroup{}
  343. defer wg.Wait()
  344. for i := start; i < end; i++ {
  345. soff := i * treeSize
  346. roff := soff
  347. seoff := soff + treeSize
  348. if soff < off {
  349. soff = off
  350. }
  351. if seoff > eoff {
  352. seoff = eoff
  353. }
  354. if depth > 1 {
  355. wg.Wait()
  356. }
  357. wg.Add(1)
  358. go func(j int64) {
  359. childKey := chunk.SData[8+j*self.hashSize : 8+(j+1)*self.hashSize]
  360. chunk := retrieve(childKey, self.chunkC, quitC)
  361. if chunk == nil {
  362. select {
  363. case errC <- fmt.Errorf("chunk %v-%v not found", off, off+treeSize):
  364. case <-quitC:
  365. }
  366. return
  367. }
  368. if soff < off {
  369. soff = off
  370. }
  371. self.join(b[soff-off:seoff-off], soff-roff, seoff-roff, depth-1, treeSize/self.branches, chunk, wg, errC, quitC)
  372. }(i)
  373. } //for
  374. }
  375. // the helper method submits chunks for a key to a oueue (DPA) and
  376. // block until they time out or arrive
  377. // abort if quitC is readable
  378. func retrieve(key Key, chunkC chan *Chunk, quitC chan bool) *Chunk {
  379. chunk := &Chunk{
  380. Key: key,
  381. C: make(chan bool), // close channel to signal data delivery
  382. }
  383. // submit chunk for retrieval
  384. select {
  385. case chunkC <- chunk: // submit retrieval request, someone should be listening on the other side (or we will time out globally)
  386. case <-quitC:
  387. return nil
  388. }
  389. // waiting for the chunk retrieval
  390. select { // chunk.Size = int64(binary.LittleEndian.Uint64(chunk.SData[0:8]))
  391. case <-quitC:
  392. // this is how we control process leakage (quitC is closed once join is finished (after timeout))
  393. return nil
  394. case <-chunk.C: // bells are ringing, data have been delivered
  395. }
  396. if len(chunk.SData) == 0 {
  397. return nil // chunk.Size = int64(binary.LittleEndian.Uint64(chunk.SData[0:8]))
  398. }
  399. return chunk
  400. }
  401. // Read keeps a cursor so cannot be called simulateously, see ReadAt
  402. func (self *LazyChunkReader) Read(b []byte) (read int, err error) {
  403. read, err = self.ReadAt(b, self.off)
  404. self.off += int64(read)
  405. return
  406. }
  407. // completely analogous to standard SectionReader implementation
  408. var errWhence = errors.New("Seek: invalid whence")
  409. var errOffset = errors.New("Seek: invalid offset")
  410. func (s *LazyChunkReader) Seek(offset int64, whence int) (int64, error) {
  411. switch whence {
  412. default:
  413. return 0, errWhence
  414. case 0:
  415. offset += 0
  416. case 1:
  417. offset += s.off
  418. case 2:
  419. if s.chunk == nil { //seek from the end requires rootchunk for size. call Size first
  420. _, err := s.Size(nil)
  421. if err != nil {
  422. return 0, fmt.Errorf("can't get size: %v", err)
  423. }
  424. }
  425. offset += s.chunk.Size
  426. }
  427. if offset < 0 {
  428. return 0, errOffset
  429. }
  430. s.off = offset
  431. return offset, nil
  432. }