common_test.go 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288
  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) ([]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(), 1*time.Minute)
  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. timeout := 20 * time.Second
  130. select {
  131. case err = <-errc:
  132. case <-time.NewTimer(timeout).C:
  133. err = fmt.Errorf("timed out after %v", timeout)
  134. }
  135. return err
  136. }
  137. func (r *brokenLimitedReader) Read(buf []byte) (int, error) {
  138. if r.off+len(buf) > r.errAt {
  139. return 0, fmt.Errorf("Broken reader")
  140. }
  141. r.off += len(buf)
  142. return r.lr.Read(buf)
  143. }
  144. func testStoreRandom(m ChunkStore, n int, t *testing.T) {
  145. chunks, err := mputRandomChunks(m, n)
  146. if err != nil {
  147. t.Fatalf("expected no error, got %v", err)
  148. }
  149. err = mget(m, chunkAddresses(chunks), nil)
  150. if err != nil {
  151. t.Fatalf("testStore failed: %v", err)
  152. }
  153. }
  154. func testStoreCorrect(m ChunkStore, n int, t *testing.T) {
  155. chunks, err := mputRandomChunks(m, n)
  156. if err != nil {
  157. t.Fatalf("expected no error, got %v", err)
  158. }
  159. f := func(h Address, chunk Chunk) error {
  160. if !bytes.Equal(h, chunk.Address()) {
  161. return fmt.Errorf("key does not match retrieved chunk Address")
  162. }
  163. hasher := MakeHashFunc(DefaultHash)()
  164. data := chunk.Data()
  165. hasher.ResetWithLength(data[:8])
  166. hasher.Write(data[8:])
  167. exp := hasher.Sum(nil)
  168. if !bytes.Equal(h, exp) {
  169. return fmt.Errorf("key is not hash of chunk data")
  170. }
  171. return nil
  172. }
  173. err = mget(m, chunkAddresses(chunks), f)
  174. if err != nil {
  175. t.Fatalf("testStore failed: %v", err)
  176. }
  177. }
  178. func benchmarkStorePut(store ChunkStore, n int, b *testing.B) {
  179. chunks := make([]Chunk, n)
  180. i := 0
  181. f := func(dataSize int64) Chunk {
  182. chunk := GenerateRandomChunk(dataSize)
  183. chunks[i] = chunk
  184. i++
  185. return chunk
  186. }
  187. mput(store, n, f)
  188. f = func(dataSize int64) Chunk {
  189. chunk := chunks[i]
  190. i++
  191. return chunk
  192. }
  193. b.ReportAllocs()
  194. b.ResetTimer()
  195. for j := 0; j < b.N; j++ {
  196. i = 0
  197. mput(store, n, f)
  198. }
  199. }
  200. func benchmarkStoreGet(store ChunkStore, n int, b *testing.B) {
  201. chunks, err := mputRandomChunks(store, n)
  202. if err != nil {
  203. b.Fatalf("expected no error, got %v", err)
  204. }
  205. b.ReportAllocs()
  206. b.ResetTimer()
  207. addrs := chunkAddresses(chunks)
  208. for i := 0; i < b.N; i++ {
  209. err := mget(store, addrs, nil)
  210. if err != nil {
  211. b.Fatalf("mget failed: %v", err)
  212. }
  213. }
  214. }
  215. // MapChunkStore is a very simple ChunkStore implementation to store chunks in a map in memory.
  216. type MapChunkStore struct {
  217. chunks map[string]Chunk
  218. mu sync.RWMutex
  219. }
  220. func NewMapChunkStore() *MapChunkStore {
  221. return &MapChunkStore{
  222. chunks: make(map[string]Chunk),
  223. }
  224. }
  225. func (m *MapChunkStore) Put(_ context.Context, ch Chunk) error {
  226. m.mu.Lock()
  227. defer m.mu.Unlock()
  228. m.chunks[ch.Address().Hex()] = ch
  229. return nil
  230. }
  231. func (m *MapChunkStore) Get(_ context.Context, ref Address) (Chunk, error) {
  232. m.mu.RLock()
  233. defer m.mu.RUnlock()
  234. chunk := m.chunks[ref.Hex()]
  235. if chunk == nil {
  236. return nil, ErrChunkNotFound
  237. }
  238. return chunk, nil
  239. }
  240. // Need to implement Has from SyncChunkStore
  241. func (m *MapChunkStore) Has(ctx context.Context, ref Address) bool {
  242. m.mu.RLock()
  243. defer m.mu.RUnlock()
  244. _, has := m.chunks[ref.Hex()]
  245. return has
  246. }
  247. func (m *MapChunkStore) Close() {
  248. }
  249. func chunkAddresses(chunks []Chunk) []Address {
  250. addrs := make([]Address, len(chunks))
  251. for i, ch := range chunks {
  252. addrs[i] = ch.Address()
  253. }
  254. return addrs
  255. }