network_test.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530
  1. // Copyright 2018 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 swarm
  17. import (
  18. "context"
  19. "flag"
  20. "fmt"
  21. "io/ioutil"
  22. "math/rand"
  23. "os"
  24. "sync"
  25. "sync/atomic"
  26. "testing"
  27. "time"
  28. "github.com/ethereum/go-ethereum/crypto"
  29. "github.com/ethereum/go-ethereum/log"
  30. "github.com/ethereum/go-ethereum/node"
  31. "github.com/ethereum/go-ethereum/p2p/enode"
  32. "github.com/ethereum/go-ethereum/p2p/simulations/adapters"
  33. "github.com/ethereum/go-ethereum/swarm/api"
  34. "github.com/ethereum/go-ethereum/swarm/network/simulation"
  35. "github.com/ethereum/go-ethereum/swarm/storage"
  36. colorable "github.com/mattn/go-colorable"
  37. )
  38. var (
  39. loglevel = flag.Int("loglevel", 2, "verbosity of logs")
  40. longrunning = flag.Bool("longrunning", false, "do run long-running tests")
  41. waitKademlia = flag.Bool("waitkademlia", false, "wait for healthy kademlia before checking files availability")
  42. )
  43. func init() {
  44. rand.Seed(time.Now().UnixNano())
  45. flag.Parse()
  46. log.Root().SetHandler(log.LvlFilterHandler(log.Lvl(*loglevel), log.StreamHandler(colorable.NewColorableStderr(), log.TerminalFormat(true))))
  47. }
  48. // TestSwarmNetwork runs a series of test simulations with
  49. // static and dynamic Swarm nodes in network simulation, by
  50. // uploading files to every node and retrieving them.
  51. func TestSwarmNetwork(t *testing.T) {
  52. for _, tc := range []struct {
  53. name string
  54. steps []testSwarmNetworkStep
  55. options *testSwarmNetworkOptions
  56. disabled bool
  57. }{
  58. {
  59. name: "10_nodes",
  60. steps: []testSwarmNetworkStep{
  61. {
  62. nodeCount: 10,
  63. },
  64. },
  65. options: &testSwarmNetworkOptions{
  66. Timeout: 45 * time.Second,
  67. },
  68. },
  69. {
  70. name: "10_nodes_skip_check",
  71. steps: []testSwarmNetworkStep{
  72. {
  73. nodeCount: 10,
  74. },
  75. },
  76. options: &testSwarmNetworkOptions{
  77. Timeout: 45 * time.Second,
  78. SkipCheck: true,
  79. },
  80. },
  81. {
  82. name: "50_nodes",
  83. steps: []testSwarmNetworkStep{
  84. {
  85. nodeCount: 50,
  86. },
  87. },
  88. options: &testSwarmNetworkOptions{
  89. Timeout: 3 * time.Minute,
  90. },
  91. disabled: !*longrunning,
  92. },
  93. {
  94. name: "50_nodes_skip_check",
  95. steps: []testSwarmNetworkStep{
  96. {
  97. nodeCount: 50,
  98. },
  99. },
  100. options: &testSwarmNetworkOptions{
  101. Timeout: 3 * time.Minute,
  102. SkipCheck: true,
  103. },
  104. disabled: !*longrunning,
  105. },
  106. {
  107. name: "inc_node_count",
  108. steps: []testSwarmNetworkStep{
  109. {
  110. nodeCount: 2,
  111. },
  112. {
  113. nodeCount: 5,
  114. },
  115. {
  116. nodeCount: 10,
  117. },
  118. },
  119. options: &testSwarmNetworkOptions{
  120. Timeout: 90 * time.Second,
  121. },
  122. disabled: !*longrunning,
  123. },
  124. {
  125. name: "dec_node_count",
  126. steps: []testSwarmNetworkStep{
  127. {
  128. nodeCount: 10,
  129. },
  130. {
  131. nodeCount: 6,
  132. },
  133. {
  134. nodeCount: 3,
  135. },
  136. },
  137. options: &testSwarmNetworkOptions{
  138. Timeout: 90 * time.Second,
  139. },
  140. disabled: !*longrunning,
  141. },
  142. {
  143. name: "dec_inc_node_count",
  144. steps: []testSwarmNetworkStep{
  145. {
  146. nodeCount: 3,
  147. },
  148. {
  149. nodeCount: 1,
  150. },
  151. {
  152. nodeCount: 5,
  153. },
  154. },
  155. options: &testSwarmNetworkOptions{
  156. Timeout: 90 * time.Second,
  157. },
  158. },
  159. {
  160. name: "inc_dec_node_count",
  161. steps: []testSwarmNetworkStep{
  162. {
  163. nodeCount: 3,
  164. },
  165. {
  166. nodeCount: 5,
  167. },
  168. {
  169. nodeCount: 25,
  170. },
  171. {
  172. nodeCount: 10,
  173. },
  174. {
  175. nodeCount: 4,
  176. },
  177. },
  178. options: &testSwarmNetworkOptions{
  179. Timeout: 5 * time.Minute,
  180. },
  181. disabled: !*longrunning,
  182. },
  183. {
  184. name: "inc_dec_node_count_skip_check",
  185. steps: []testSwarmNetworkStep{
  186. {
  187. nodeCount: 3,
  188. },
  189. {
  190. nodeCount: 5,
  191. },
  192. {
  193. nodeCount: 25,
  194. },
  195. {
  196. nodeCount: 10,
  197. },
  198. {
  199. nodeCount: 4,
  200. },
  201. },
  202. options: &testSwarmNetworkOptions{
  203. Timeout: 5 * time.Minute,
  204. SkipCheck: true,
  205. },
  206. disabled: !*longrunning,
  207. },
  208. } {
  209. if tc.disabled {
  210. continue
  211. }
  212. t.Run(tc.name, func(t *testing.T) {
  213. testSwarmNetwork(t, tc.options, tc.steps...)
  214. })
  215. }
  216. }
  217. // testSwarmNetworkStep is the configuration
  218. // for the state of the simulation network.
  219. type testSwarmNetworkStep struct {
  220. // number of swarm nodes that must be in the Up state
  221. nodeCount int
  222. }
  223. // file represents the file uploaded on a particular node.
  224. type file struct {
  225. addr storage.Address
  226. data string
  227. nodeID enode.ID
  228. }
  229. // check represents a reference to a file that is retrieved
  230. // from a particular node.
  231. type check struct {
  232. key string
  233. nodeID enode.ID
  234. }
  235. // testSwarmNetworkOptions contains optional parameters for running
  236. // testSwarmNetwork.
  237. type testSwarmNetworkOptions struct {
  238. Timeout time.Duration
  239. SkipCheck bool
  240. }
  241. // testSwarmNetwork is a helper function used for testing different
  242. // static and dynamic Swarm network simulations.
  243. // It is responsible for:
  244. // - Setting up a Swarm network simulation, and updates the number of nodes within the network on every step according to steps.
  245. // - Uploading a unique file to every node on every step.
  246. // - May wait for Kademlia on every node to be healthy.
  247. // - Checking if a file is retrievable from all nodes.
  248. func testSwarmNetwork(t *testing.T, o *testSwarmNetworkOptions, steps ...testSwarmNetworkStep) {
  249. if o == nil {
  250. o = new(testSwarmNetworkOptions)
  251. }
  252. sim := simulation.New(map[string]simulation.ServiceFunc{
  253. "swarm": func(ctx *adapters.ServiceContext, bucket *sync.Map) (s node.Service, cleanup func(), err error) {
  254. config := api.NewConfig()
  255. dir, err := ioutil.TempDir("", "swarm-network-test-node")
  256. if err != nil {
  257. return nil, nil, err
  258. }
  259. cleanup = func() {
  260. err := os.RemoveAll(dir)
  261. if err != nil {
  262. log.Error("cleaning up swarm temp dir", "err", err)
  263. }
  264. }
  265. config.Path = dir
  266. privkey, err := crypto.GenerateKey()
  267. if err != nil {
  268. return nil, cleanup, err
  269. }
  270. config.Init(privkey)
  271. config.DeliverySkipCheck = o.SkipCheck
  272. config.Port = ""
  273. swarm, err := NewSwarm(config, nil)
  274. if err != nil {
  275. return nil, cleanup, err
  276. }
  277. bucket.Store(simulation.BucketKeyKademlia, swarm.bzz.Hive.Kademlia)
  278. log.Info("new swarm", "bzzKey", config.BzzKey, "baseAddr", fmt.Sprintf("%x", swarm.bzz.BaseAddr()))
  279. return swarm, cleanup, nil
  280. },
  281. })
  282. defer sim.Close()
  283. ctx := context.Background()
  284. if o.Timeout > 0 {
  285. var cancel context.CancelFunc
  286. ctx, cancel = context.WithTimeout(ctx, o.Timeout)
  287. defer cancel()
  288. }
  289. files := make([]file, 0)
  290. for i, step := range steps {
  291. log.Debug("test sync step", "n", i+1, "nodes", step.nodeCount)
  292. change := step.nodeCount - len(sim.UpNodeIDs())
  293. if change > 0 {
  294. _, err := sim.AddNodesAndConnectChain(change)
  295. if err != nil {
  296. t.Fatal(err)
  297. }
  298. } else if change < 0 {
  299. _, err := sim.StopRandomNodes(-change)
  300. if err != nil {
  301. t.Fatal(err)
  302. }
  303. } else {
  304. t.Logf("step %v: no change in nodes", i)
  305. continue
  306. }
  307. var checkStatusM sync.Map
  308. var nodeStatusM sync.Map
  309. var totalFoundCount uint64
  310. result := sim.Run(ctx, func(ctx context.Context, sim *simulation.Simulation) error {
  311. nodeIDs := sim.UpNodeIDs()
  312. shuffle(len(nodeIDs), func(i, j int) {
  313. nodeIDs[i], nodeIDs[j] = nodeIDs[j], nodeIDs[i]
  314. })
  315. for _, id := range nodeIDs {
  316. key, data, err := uploadFile(sim.Service("swarm", id).(*Swarm))
  317. if err != nil {
  318. return err
  319. }
  320. log.Trace("file uploaded", "node", id, "key", key.String())
  321. files = append(files, file{
  322. addr: key,
  323. data: data,
  324. nodeID: id,
  325. })
  326. }
  327. if *waitKademlia {
  328. if _, err := sim.WaitTillHealthy(ctx, 2); err != nil {
  329. return err
  330. }
  331. }
  332. // File retrieval check is repeated until all uploaded files are retrieved from all nodes
  333. // or until the timeout is reached.
  334. for {
  335. if retrieve(sim, files, &checkStatusM, &nodeStatusM, &totalFoundCount) == 0 {
  336. return nil
  337. }
  338. }
  339. })
  340. if result.Error != nil {
  341. t.Fatal(result.Error)
  342. }
  343. log.Debug("done: test sync step", "n", i+1, "nodes", step.nodeCount)
  344. }
  345. }
  346. // uploadFile, uploads a short file to the swarm instance
  347. // using the api.Put method.
  348. func uploadFile(swarm *Swarm) (storage.Address, string, error) {
  349. b := make([]byte, 8)
  350. _, err := rand.Read(b)
  351. if err != nil {
  352. return nil, "", err
  353. }
  354. // File data is very short, but it is ensured that its
  355. // uniqueness is very certain.
  356. data := fmt.Sprintf("test content %s %x", time.Now().Round(0), b)
  357. ctx := context.TODO()
  358. k, wait, err := swarm.api.Put(ctx, data, "text/plain", false)
  359. if err != nil {
  360. return nil, "", err
  361. }
  362. if wait != nil {
  363. err = wait(ctx)
  364. }
  365. return k, data, err
  366. }
  367. // retrieve is the function that is used for checking the availability of
  368. // uploaded files in testSwarmNetwork test helper function.
  369. func retrieve(
  370. sim *simulation.Simulation,
  371. files []file,
  372. checkStatusM *sync.Map,
  373. nodeStatusM *sync.Map,
  374. totalFoundCount *uint64,
  375. ) (missing uint64) {
  376. shuffle(len(files), func(i, j int) {
  377. files[i], files[j] = files[j], files[i]
  378. })
  379. var totalWg sync.WaitGroup
  380. errc := make(chan error)
  381. nodeIDs := sim.UpNodeIDs()
  382. totalCheckCount := len(nodeIDs) * len(files)
  383. for _, id := range nodeIDs {
  384. if _, ok := nodeStatusM.Load(id); ok {
  385. continue
  386. }
  387. start := time.Now()
  388. var checkCount uint64
  389. var foundCount uint64
  390. totalWg.Add(1)
  391. var wg sync.WaitGroup
  392. swarm := sim.Service("swarm", id).(*Swarm)
  393. for _, f := range files {
  394. checkKey := check{
  395. key: f.addr.String(),
  396. nodeID: id,
  397. }
  398. if n, ok := checkStatusM.Load(checkKey); ok && n.(int) == 0 {
  399. continue
  400. }
  401. checkCount++
  402. wg.Add(1)
  403. go func(f file, id enode.ID) {
  404. defer wg.Done()
  405. log.Debug("api get: check file", "node", id.String(), "key", f.addr.String(), "total files found", atomic.LoadUint64(totalFoundCount))
  406. r, _, _, _, err := swarm.api.Get(context.TODO(), api.NOOPDecrypt, f.addr, "/")
  407. if err != nil {
  408. errc <- fmt.Errorf("api get: node %s, key %s, kademlia %s: %v", id, f.addr, swarm.bzz.Hive, err)
  409. return
  410. }
  411. d, err := ioutil.ReadAll(r)
  412. if err != nil {
  413. errc <- fmt.Errorf("api get: read response: node %s, key %s: kademlia %s: %v", id, f.addr, swarm.bzz.Hive, err)
  414. return
  415. }
  416. data := string(d)
  417. if data != f.data {
  418. errc <- fmt.Errorf("file contend missmatch: node %s, key %s, expected %q, got %q", id, f.addr, f.data, data)
  419. return
  420. }
  421. checkStatusM.Store(checkKey, 0)
  422. atomic.AddUint64(&foundCount, 1)
  423. log.Info("api get: file found", "node", id.String(), "key", f.addr.String(), "content", data, "files found", atomic.LoadUint64(&foundCount))
  424. }(f, id)
  425. }
  426. go func(id enode.ID) {
  427. defer totalWg.Done()
  428. wg.Wait()
  429. atomic.AddUint64(totalFoundCount, foundCount)
  430. if foundCount == checkCount {
  431. log.Info("all files are found for node", "id", id.String(), "duration", time.Since(start))
  432. nodeStatusM.Store(id, 0)
  433. return
  434. }
  435. log.Debug("files missing for node", "id", id.String(), "check", checkCount, "found", foundCount)
  436. }(id)
  437. }
  438. go func() {
  439. totalWg.Wait()
  440. close(errc)
  441. }()
  442. var errCount int
  443. for err := range errc {
  444. if err != nil {
  445. errCount++
  446. }
  447. log.Warn(err.Error())
  448. }
  449. log.Info("check stats", "total check count", totalCheckCount, "total files found", atomic.LoadUint64(totalFoundCount), "total errors", errCount)
  450. return uint64(totalCheckCount) - atomic.LoadUint64(totalFoundCount)
  451. }
  452. // Backported from stdlib https://golang.org/src/math/rand/rand.go?s=11175:11215#L333
  453. //
  454. // Replace with rand.Shuffle from go 1.10 when go 1.9 support is dropped.
  455. //
  456. // shuffle pseudo-randomizes the order of elements.
  457. // n is the number of elements. Shuffle panics if n < 0.
  458. // swap swaps the elements with indexes i and j.
  459. func shuffle(n int, swap func(i, j int)) {
  460. if n < 0 {
  461. panic("invalid argument to Shuffle")
  462. }
  463. // Fisher-Yates shuffle: https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle
  464. // Shuffle really ought not be called with n that doesn't fit in 32 bits.
  465. // Not only will it take a very long time, but with 2³¹! possible permutations,
  466. // there's no way that any PRNG can have a big enough internal state to
  467. // generate even a minuscule percentage of the possible permutations.
  468. // Nevertheless, the right API signature accepts an int n, so handle it as best we can.
  469. i := n - 1
  470. for ; i > 1<<31-1-1; i-- {
  471. j := int(rand.Int63n(int64(i + 1)))
  472. swap(i, j)
  473. }
  474. for ; i > 0; i-- {
  475. j := int(rand.Int31n(int32(i + 1)))
  476. swap(i, j)
  477. }
  478. }