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/discover"
  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"
  35. "github.com/ethereum/go-ethereum/swarm/network/simulation"
  36. "github.com/ethereum/go-ethereum/swarm/storage"
  37. colorable "github.com/mattn/go-colorable"
  38. )
  39. var (
  40. loglevel = flag.Int("loglevel", 2, "verbosity of logs")
  41. longrunning = flag.Bool("longrunning", false, "do run long-running tests")
  42. waitKademlia = flag.Bool("waitkademlia", false, "wait for healthy kademlia before checking files availability")
  43. )
  44. func init() {
  45. rand.Seed(time.Now().UnixNano())
  46. flag.Parse()
  47. log.Root().SetHandler(log.LvlFilterHandler(log.Lvl(*loglevel), log.StreamHandler(colorable.NewColorableStderr(), log.TerminalFormat(true))))
  48. }
  49. // TestSwarmNetwork runs a series of test simulations with
  50. // static and dynamic Swarm nodes in network simulation, by
  51. // uploading files to every node and retrieving them.
  52. func TestSwarmNetwork(t *testing.T) {
  53. for _, tc := range []struct {
  54. name string
  55. steps []testSwarmNetworkStep
  56. options *testSwarmNetworkOptions
  57. disabled bool
  58. }{
  59. {
  60. name: "10_nodes",
  61. steps: []testSwarmNetworkStep{
  62. {
  63. nodeCount: 10,
  64. },
  65. },
  66. options: &testSwarmNetworkOptions{
  67. Timeout: 45 * time.Second,
  68. },
  69. },
  70. {
  71. name: "10_nodes_skip_check",
  72. steps: []testSwarmNetworkStep{
  73. {
  74. nodeCount: 10,
  75. },
  76. },
  77. options: &testSwarmNetworkOptions{
  78. Timeout: 45 * time.Second,
  79. SkipCheck: true,
  80. },
  81. },
  82. {
  83. name: "100_nodes",
  84. steps: []testSwarmNetworkStep{
  85. {
  86. nodeCount: 100,
  87. },
  88. },
  89. options: &testSwarmNetworkOptions{
  90. Timeout: 3 * time.Minute,
  91. },
  92. disabled: !*longrunning,
  93. },
  94. {
  95. name: "100_nodes_skip_check",
  96. steps: []testSwarmNetworkStep{
  97. {
  98. nodeCount: 100,
  99. },
  100. },
  101. options: &testSwarmNetworkOptions{
  102. Timeout: 3 * time.Minute,
  103. SkipCheck: true,
  104. },
  105. disabled: !*longrunning,
  106. },
  107. {
  108. name: "inc_node_count",
  109. steps: []testSwarmNetworkStep{
  110. {
  111. nodeCount: 2,
  112. },
  113. {
  114. nodeCount: 5,
  115. },
  116. {
  117. nodeCount: 10,
  118. },
  119. },
  120. options: &testSwarmNetworkOptions{
  121. Timeout: 90 * time.Second,
  122. },
  123. disabled: !*longrunning,
  124. },
  125. {
  126. name: "dec_node_count",
  127. steps: []testSwarmNetworkStep{
  128. {
  129. nodeCount: 10,
  130. },
  131. {
  132. nodeCount: 6,
  133. },
  134. {
  135. nodeCount: 3,
  136. },
  137. },
  138. options: &testSwarmNetworkOptions{
  139. Timeout: 90 * time.Second,
  140. },
  141. disabled: !*longrunning,
  142. },
  143. {
  144. name: "dec_inc_node_count",
  145. steps: []testSwarmNetworkStep{
  146. {
  147. nodeCount: 5,
  148. },
  149. {
  150. nodeCount: 3,
  151. },
  152. {
  153. nodeCount: 10,
  154. },
  155. },
  156. options: &testSwarmNetworkOptions{
  157. Timeout: 90 * time.Second,
  158. },
  159. },
  160. {
  161. name: "inc_dec_node_count",
  162. steps: []testSwarmNetworkStep{
  163. {
  164. nodeCount: 3,
  165. },
  166. {
  167. nodeCount: 5,
  168. },
  169. {
  170. nodeCount: 25,
  171. },
  172. {
  173. nodeCount: 10,
  174. },
  175. {
  176. nodeCount: 4,
  177. },
  178. },
  179. options: &testSwarmNetworkOptions{
  180. Timeout: 5 * time.Minute,
  181. },
  182. disabled: !*longrunning,
  183. },
  184. {
  185. name: "inc_dec_node_count_skip_check",
  186. steps: []testSwarmNetworkStep{
  187. {
  188. nodeCount: 3,
  189. },
  190. {
  191. nodeCount: 5,
  192. },
  193. {
  194. nodeCount: 25,
  195. },
  196. {
  197. nodeCount: 10,
  198. },
  199. {
  200. nodeCount: 4,
  201. },
  202. },
  203. options: &testSwarmNetworkOptions{
  204. Timeout: 5 * time.Minute,
  205. SkipCheck: true,
  206. },
  207. disabled: !*longrunning,
  208. },
  209. } {
  210. if tc.disabled {
  211. continue
  212. }
  213. t.Run(tc.name, func(t *testing.T) {
  214. testSwarmNetwork(t, tc.options, tc.steps...)
  215. })
  216. }
  217. }
  218. // testSwarmNetworkStep is the configuration
  219. // for the state of the simulation network.
  220. type testSwarmNetworkStep struct {
  221. // number of swarm nodes that must be in the Up state
  222. nodeCount int
  223. }
  224. // file represents the file uploaded on a particular node.
  225. type file struct {
  226. addr storage.Address
  227. data string
  228. nodeID discover.NodeID
  229. }
  230. // check represents a reference to a file that is retrieved
  231. // from a particular node.
  232. type check struct {
  233. key string
  234. nodeID discover.NodeID
  235. }
  236. // testSwarmNetworkOptions contains optional parameters for running
  237. // testSwarmNetwork.
  238. type testSwarmNetworkOptions struct {
  239. Timeout time.Duration
  240. SkipCheck bool
  241. }
  242. // testSwarmNetwork is a helper function used for testing different
  243. // static and dynamic Swarm network simulations.
  244. // It is responsible for:
  245. // - Setting up a Swarm network simulation, and updates the number of nodes within the network on every step according to steps.
  246. // - Uploading a unique file to every node on every step.
  247. // - May wait for Kademlia on every node to be healthy.
  248. // - Checking if a file is retrievable from all nodes.
  249. func testSwarmNetwork(t *testing.T, o *testSwarmNetworkOptions, steps ...testSwarmNetworkStep) {
  250. if o == nil {
  251. o = new(testSwarmNetworkOptions)
  252. }
  253. sim := simulation.New(map[string]simulation.ServiceFunc{
  254. "swarm": func(ctx *adapters.ServiceContext, bucket *sync.Map) (s node.Service, cleanup func(), err error) {
  255. config := api.NewConfig()
  256. dir, err := ioutil.TempDir("", "swarm-network-test-node")
  257. if err != nil {
  258. return nil, nil, err
  259. }
  260. cleanup = func() {
  261. err := os.RemoveAll(dir)
  262. if err != nil {
  263. log.Error("cleaning up swarm temp dir", "err", err)
  264. }
  265. }
  266. config.Path = dir
  267. privkey, err := crypto.GenerateKey()
  268. if err != nil {
  269. return nil, cleanup, err
  270. }
  271. config.Init(privkey)
  272. config.DeliverySkipCheck = o.SkipCheck
  273. swarm, err := NewSwarm(config, nil)
  274. if err != nil {
  275. return nil, cleanup, err
  276. }
  277. bucket.Store(simulation.BucketKeyKademlia, swarm.bzz.Hive.Overlay.(*network.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 discover.NodeID) {
  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 discover.NodeID) {
  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. }