chunker.go 15 KB

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