chunker.go 15 KB

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