common_test.go 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277
  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. "bytes"
  19. "context"
  20. "flag"
  21. "fmt"
  22. "io"
  23. "io/ioutil"
  24. "os"
  25. "sync"
  26. "testing"
  27. "time"
  28. "github.com/ethereum/go-ethereum/log"
  29. ch "github.com/ethereum/go-ethereum/swarm/chunk"
  30. "github.com/mattn/go-colorable"
  31. )
  32. var (
  33. loglevel = flag.Int("loglevel", 3, "verbosity of logs")
  34. getTimeout = 30 * time.Second
  35. )
  36. func init() {
  37. flag.Parse()
  38. log.PrintOrigins(true)
  39. log.Root().SetHandler(log.LvlFilterHandler(log.Lvl(*loglevel), log.StreamHandler(colorable.NewColorableStderr(), log.TerminalFormat(true))))
  40. }
  41. type brokenLimitedReader struct {
  42. lr io.Reader
  43. errAt int
  44. off int
  45. size int
  46. }
  47. func brokenLimitReader(data io.Reader, size int, errAt int) *brokenLimitedReader {
  48. return &brokenLimitedReader{
  49. lr: data,
  50. errAt: errAt,
  51. size: size,
  52. }
  53. }
  54. func newLDBStore(t *testing.T) (*LDBStore, func()) {
  55. dir, err := ioutil.TempDir("", "bzz-storage-test")
  56. if err != nil {
  57. t.Fatal(err)
  58. }
  59. log.Trace("memstore.tempdir", "dir", dir)
  60. ldbparams := NewLDBStoreParams(NewDefaultStoreParams(), dir)
  61. db, err := NewLDBStore(ldbparams)
  62. if err != nil {
  63. t.Fatal(err)
  64. }
  65. cleanup := func() {
  66. db.Close()
  67. err := os.RemoveAll(dir)
  68. if err != nil {
  69. t.Fatal(err)
  70. }
  71. }
  72. return db, cleanup
  73. }
  74. func mputRandomChunks(store ChunkStore, n int, chunksize int64) ([]Chunk, error) {
  75. return mput(store, n, GenerateRandomChunk)
  76. }
  77. func mput(store ChunkStore, n int, f func(i int64) Chunk) (hs []Chunk, err error) {
  78. // put to localstore and wait for stored channel
  79. // does not check delivery error state
  80. errc := make(chan error)
  81. ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
  82. defer cancel()
  83. for i := int64(0); i < int64(n); i++ {
  84. chunk := f(ch.DefaultSize)
  85. go func() {
  86. select {
  87. case errc <- store.Put(ctx, chunk):
  88. case <-ctx.Done():
  89. }
  90. }()
  91. hs = append(hs, chunk)
  92. }
  93. // wait for all chunks to be stored
  94. for i := 0; i < n; i++ {
  95. err := <-errc
  96. if err != nil {
  97. return nil, err
  98. }
  99. }
  100. return hs, nil
  101. }
  102. func mget(store ChunkStore, hs []Address, f func(h Address, chunk Chunk) error) error {
  103. wg := sync.WaitGroup{}
  104. wg.Add(len(hs))
  105. errc := make(chan error)
  106. for _, k := range hs {
  107. go func(h Address) {
  108. defer wg.Done()
  109. // TODO: write timeout with context
  110. chunk, err := store.Get(context.TODO(), h)
  111. if err != nil {
  112. errc <- err
  113. return
  114. }
  115. if f != nil {
  116. err = f(h, chunk)
  117. if err != nil {
  118. errc <- err
  119. return
  120. }
  121. }
  122. }(k)
  123. }
  124. go func() {
  125. wg.Wait()
  126. close(errc)
  127. }()
  128. var err error
  129. select {
  130. case err = <-errc:
  131. case <-time.NewTimer(5 * time.Second).C:
  132. err = fmt.Errorf("timed out after 5 seconds")
  133. }
  134. return err
  135. }
  136. func (r *brokenLimitedReader) Read(buf []byte) (int, error) {
  137. if r.off+len(buf) > r.errAt {
  138. return 0, fmt.Errorf("Broken reader")
  139. }
  140. r.off += len(buf)
  141. return r.lr.Read(buf)
  142. }
  143. func testStoreRandom(m ChunkStore, n int, chunksize int64, t *testing.T) {
  144. chunks, err := mputRandomChunks(m, n, chunksize)
  145. if err != nil {
  146. t.Fatalf("expected no error, got %v", err)
  147. }
  148. err = mget(m, chunkAddresses(chunks), nil)
  149. if err != nil {
  150. t.Fatalf("testStore failed: %v", err)
  151. }
  152. }
  153. func testStoreCorrect(m ChunkStore, n int, chunksize int64, t *testing.T) {
  154. chunks, err := mputRandomChunks(m, n, chunksize)
  155. if err != nil {
  156. t.Fatalf("expected no error, got %v", err)
  157. }
  158. f := func(h Address, chunk Chunk) error {
  159. if !bytes.Equal(h, chunk.Address()) {
  160. return fmt.Errorf("key does not match retrieved chunk Address")
  161. }
  162. hasher := MakeHashFunc(DefaultHash)()
  163. hasher.ResetWithLength(chunk.SpanBytes())
  164. hasher.Write(chunk.Payload())
  165. exp := hasher.Sum(nil)
  166. if !bytes.Equal(h, exp) {
  167. return fmt.Errorf("key is not hash of chunk data")
  168. }
  169. return nil
  170. }
  171. err = mget(m, chunkAddresses(chunks), f)
  172. if err != nil {
  173. t.Fatalf("testStore failed: %v", err)
  174. }
  175. }
  176. func benchmarkStorePut(store ChunkStore, n int, chunksize int64, b *testing.B) {
  177. chunks := make([]Chunk, n)
  178. i := 0
  179. f := func(dataSize int64) Chunk {
  180. chunk := GenerateRandomChunk(dataSize)
  181. chunks[i] = chunk
  182. i++
  183. return chunk
  184. }
  185. mput(store, n, f)
  186. f = func(dataSize int64) Chunk {
  187. chunk := chunks[i]
  188. i++
  189. return chunk
  190. }
  191. b.ReportAllocs()
  192. b.ResetTimer()
  193. for j := 0; j < b.N; j++ {
  194. i = 0
  195. mput(store, n, f)
  196. }
  197. }
  198. func benchmarkStoreGet(store ChunkStore, n int, chunksize int64, b *testing.B) {
  199. chunks, err := mputRandomChunks(store, n, chunksize)
  200. if err != nil {
  201. b.Fatalf("expected no error, got %v", err)
  202. }
  203. b.ReportAllocs()
  204. b.ResetTimer()
  205. addrs := chunkAddresses(chunks)
  206. for i := 0; i < b.N; i++ {
  207. err := mget(store, addrs, nil)
  208. if err != nil {
  209. b.Fatalf("mget failed: %v", err)
  210. }
  211. }
  212. }
  213. // MapChunkStore is a very simple ChunkStore implementation to store chunks in a map in memory.
  214. type MapChunkStore struct {
  215. chunks map[string]Chunk
  216. mu sync.RWMutex
  217. }
  218. func NewMapChunkStore() *MapChunkStore {
  219. return &MapChunkStore{
  220. chunks: make(map[string]Chunk),
  221. }
  222. }
  223. func (m *MapChunkStore) Put(_ context.Context, ch Chunk) error {
  224. m.mu.Lock()
  225. defer m.mu.Unlock()
  226. m.chunks[ch.Address().Hex()] = ch
  227. return nil
  228. }
  229. func (m *MapChunkStore) Get(_ context.Context, ref Address) (Chunk, error) {
  230. m.mu.RLock()
  231. defer m.mu.RUnlock()
  232. chunk := m.chunks[ref.Hex()]
  233. if chunk == nil {
  234. return nil, ErrChunkNotFound
  235. }
  236. return chunk, nil
  237. }
  238. func (m *MapChunkStore) Close() {
  239. }
  240. func chunkAddresses(chunks []Chunk) []Address {
  241. addrs := make([]Address, len(chunks))
  242. for i, ch := range chunks {
  243. addrs[i] = ch.Address()
  244. }
  245. return addrs
  246. }