You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

552 lines
15 KiB

p2p: file descriptor leaks (#3150) * close peer's connection to avoid fd leak Fixes #2967 * rename peer#Addr to RemoteAddr * fix test * fixes after Ethan's review * bring back the check * changelog entry * write a test for switch#acceptRoutine * increase timeouts? :( * remove extra assertNPeersWithTimeout * simplify test * assert number of peers (just to be safe) * Cleanup in OnStop * run tests with verbose flag on CircleCI * spawn a reading routine to prevent connection from closing * get port from the listener random port is faster, but often results in ``` panic: listen tcp 127.0.0.1:44068: bind: address already in use [recovered] panic: listen tcp 127.0.0.1:44068: bind: address already in use goroutine 79 [running]: testing.tRunner.func1(0xc0001bd600) /usr/local/go/src/testing/testing.go:792 +0x387 panic(0x974d20, 0xc0001b0500) /usr/local/go/src/runtime/panic.go:513 +0x1b9 github.com/tendermint/tendermint/p2p.MakeSwitch(0xc0000f42a0, 0x0, 0x9fb9cc, 0x9, 0x9fc346, 0xb, 0xb42128, 0x0, 0x0, 0x0, ...) /home/vagrant/go/src/github.com/tendermint/tendermint/p2p/test_util.go:182 +0xa28 github.com/tendermint/tendermint/p2p.MakeConnectedSwitches(0xc0000f42a0, 0x2, 0xb42128, 0xb41eb8, 0x4f1205, 0xc0001bed80, 0x4f16ed) /home/vagrant/go/src/github.com/tendermint/tendermint/p2p/test_util.go:75 +0xf9 github.com/tendermint/tendermint/p2p.MakeSwitchPair(0xbb8d20, 0xc0001bd600, 0xb42128, 0x2f7, 0x4f16c0) /home/vagrant/go/src/github.com/tendermint/tendermint/p2p/switch_test.go:94 +0x4c github.com/tendermint/tendermint/p2p.TestSwitches(0xc0001bd600) /home/vagrant/go/src/github.com/tendermint/tendermint/p2p/switch_test.go:117 +0x58 testing.tRunner(0xc0001bd600, 0xb42038) /usr/local/go/src/testing/testing.go:827 +0xbf created by testing.(*T).Run /usr/local/go/src/testing/testing.go:878 +0x353 exit status 2 FAIL github.com/tendermint/tendermint/p2p 0.350s ```
6 years ago
  1. package pex
  2. import (
  3. "fmt"
  4. "io/ioutil"
  5. "net"
  6. "os"
  7. "path/filepath"
  8. "testing"
  9. "time"
  10. "github.com/stretchr/testify/assert"
  11. "github.com/stretchr/testify/require"
  12. "github.com/tendermint/tendermint/crypto"
  13. "github.com/tendermint/tendermint/crypto/ed25519"
  14. cmn "github.com/tendermint/tendermint/libs/common"
  15. "github.com/tendermint/tendermint/libs/log"
  16. "github.com/tendermint/tendermint/config"
  17. "github.com/tendermint/tendermint/p2p"
  18. "github.com/tendermint/tendermint/p2p/conn"
  19. )
  20. var (
  21. cfg *config.P2PConfig
  22. )
  23. func init() {
  24. cfg = config.DefaultP2PConfig()
  25. cfg.PexReactor = true
  26. cfg.AllowDuplicateIP = true
  27. }
  28. func TestPEXReactorBasic(t *testing.T) {
  29. r, book := createReactor(&PEXReactorConfig{})
  30. defer teardownReactor(book)
  31. assert.NotNil(t, r)
  32. assert.NotEmpty(t, r.GetChannels())
  33. }
  34. func TestPEXReactorAddRemovePeer(t *testing.T) {
  35. r, book := createReactor(&PEXReactorConfig{})
  36. defer teardownReactor(book)
  37. size := book.Size()
  38. peer := p2p.CreateRandomPeer(false)
  39. r.AddPeer(peer)
  40. assert.Equal(t, size+1, book.Size())
  41. r.RemovePeer(peer, "peer not available")
  42. outboundPeer := p2p.CreateRandomPeer(true)
  43. r.AddPeer(outboundPeer)
  44. assert.Equal(t, size+1, book.Size(), "outbound peers should not be added to the address book")
  45. r.RemovePeer(outboundPeer, "peer not available")
  46. }
  47. // --- FAIL: TestPEXReactorRunning (11.10s)
  48. // pex_reactor_test.go:411: expected all switches to be connected to at
  49. // least one peer (switches: 0 => {outbound: 1, inbound: 0}, 1 =>
  50. // {outbound: 0, inbound: 1}, 2 => {outbound: 0, inbound: 0}, )
  51. //
  52. // EXPLANATION: peers are getting rejected because in switch#addPeer we check
  53. // if any peer (who we already connected to) has the same IP. Even though local
  54. // peers have different IP addresses, they all have the same underlying remote
  55. // IP: 127.0.0.1.
  56. //
  57. func TestPEXReactorRunning(t *testing.T) {
  58. N := 3
  59. switches := make([]*p2p.Switch, N)
  60. // directory to store address books
  61. dir, err := ioutil.TempDir("", "pex_reactor")
  62. require.Nil(t, err)
  63. defer os.RemoveAll(dir) // nolint: errcheck
  64. books := make([]*addrBook, N)
  65. logger := log.TestingLogger()
  66. // create switches
  67. for i := 0; i < N; i++ {
  68. switches[i] = p2p.MakeSwitch(cfg, i, "testing", "123.123.123", func(i int, sw *p2p.Switch) *p2p.Switch {
  69. books[i] = NewAddrBook(filepath.Join(dir, fmt.Sprintf("addrbook%d.json", i)), false)
  70. books[i].SetLogger(logger.With("pex", i))
  71. sw.SetAddrBook(books[i])
  72. sw.SetLogger(logger.With("pex", i))
  73. r := NewPEXReactor(books[i], &PEXReactorConfig{})
  74. r.SetLogger(logger.With("pex", i))
  75. r.SetEnsurePeersPeriod(250 * time.Millisecond)
  76. sw.AddReactor("pex", r)
  77. return sw
  78. })
  79. }
  80. addOtherNodeAddrToAddrBook := func(switchIndex, otherSwitchIndex int) {
  81. addr := switches[otherSwitchIndex].NodeInfo().NetAddress()
  82. books[switchIndex].AddAddress(addr, addr)
  83. }
  84. addOtherNodeAddrToAddrBook(0, 1)
  85. addOtherNodeAddrToAddrBook(1, 0)
  86. addOtherNodeAddrToAddrBook(2, 1)
  87. for _, sw := range switches {
  88. err := sw.Start() // start switch and reactors
  89. require.Nil(t, err)
  90. }
  91. assertPeersWithTimeout(t, switches, 10*time.Millisecond, 10*time.Second, N-1)
  92. // stop them
  93. for _, s := range switches {
  94. s.Stop()
  95. }
  96. }
  97. func TestPEXReactorReceive(t *testing.T) {
  98. r, book := createReactor(&PEXReactorConfig{})
  99. defer teardownReactor(book)
  100. peer := p2p.CreateRandomPeer(false)
  101. // we have to send a request to receive responses
  102. r.RequestAddrs(peer)
  103. size := book.Size()
  104. addrs := []*p2p.NetAddress{peer.NodeInfo().NetAddress()}
  105. msg := cdc.MustMarshalBinaryBare(&pexAddrsMessage{Addrs: addrs})
  106. r.Receive(PexChannel, peer, msg)
  107. assert.Equal(t, size+1, book.Size())
  108. msg = cdc.MustMarshalBinaryBare(&pexRequestMessage{})
  109. r.Receive(PexChannel, peer, msg) // should not panic.
  110. }
  111. func TestPEXReactorRequestMessageAbuse(t *testing.T) {
  112. r, book := createReactor(&PEXReactorConfig{})
  113. defer teardownReactor(book)
  114. sw := createSwitchAndAddReactors(r)
  115. sw.SetAddrBook(book)
  116. peer := newMockPeer()
  117. p2p.AddPeerToSwitch(sw, peer)
  118. assert.True(t, sw.Peers().Has(peer.ID()))
  119. id := string(peer.ID())
  120. msg := cdc.MustMarshalBinaryBare(&pexRequestMessage{})
  121. // first time creates the entry
  122. r.Receive(PexChannel, peer, msg)
  123. assert.True(t, r.lastReceivedRequests.Has(id))
  124. assert.True(t, sw.Peers().Has(peer.ID()))
  125. // next time sets the last time value
  126. r.Receive(PexChannel, peer, msg)
  127. assert.True(t, r.lastReceivedRequests.Has(id))
  128. assert.True(t, sw.Peers().Has(peer.ID()))
  129. // third time is too many too soon - peer is removed
  130. r.Receive(PexChannel, peer, msg)
  131. assert.False(t, r.lastReceivedRequests.Has(id))
  132. assert.False(t, sw.Peers().Has(peer.ID()))
  133. }
  134. func TestPEXReactorAddrsMessageAbuse(t *testing.T) {
  135. r, book := createReactor(&PEXReactorConfig{})
  136. defer teardownReactor(book)
  137. sw := createSwitchAndAddReactors(r)
  138. sw.SetAddrBook(book)
  139. peer := newMockPeer()
  140. p2p.AddPeerToSwitch(sw, peer)
  141. assert.True(t, sw.Peers().Has(peer.ID()))
  142. id := string(peer.ID())
  143. // request addrs from the peer
  144. r.RequestAddrs(peer)
  145. assert.True(t, r.requestsSent.Has(id))
  146. assert.True(t, sw.Peers().Has(peer.ID()))
  147. addrs := []*p2p.NetAddress{peer.NodeInfo().NetAddress()}
  148. msg := cdc.MustMarshalBinaryBare(&pexAddrsMessage{Addrs: addrs})
  149. // receive some addrs. should clear the request
  150. r.Receive(PexChannel, peer, msg)
  151. assert.False(t, r.requestsSent.Has(id))
  152. assert.True(t, sw.Peers().Has(peer.ID()))
  153. // receiving more addrs causes a disconnect
  154. r.Receive(PexChannel, peer, msg)
  155. assert.False(t, sw.Peers().Has(peer.ID()))
  156. }
  157. func TestCheckSeeds(t *testing.T) {
  158. // directory to store address books
  159. dir, err := ioutil.TempDir("", "pex_reactor")
  160. require.Nil(t, err)
  161. defer os.RemoveAll(dir) // nolint: errcheck
  162. // 1. test creating peer with no seeds works
  163. peer := testCreateDefaultPeer(dir, 0)
  164. require.Nil(t, peer.Start())
  165. peer.Stop()
  166. // 2. create seed
  167. seed := testCreateSeed(dir, 1, []*p2p.NetAddress{}, []*p2p.NetAddress{})
  168. // 3. test create peer with online seed works
  169. peer = testCreatePeerWithSeed(dir, 2, seed)
  170. require.Nil(t, peer.Start())
  171. peer.Stop()
  172. // 4. test create peer with all seeds having unresolvable DNS fails
  173. badPeerConfig := &PEXReactorConfig{
  174. Seeds: []string{"ed3dfd27bfc4af18f67a49862f04cc100696e84d@bad.network.addr:26657",
  175. "d824b13cb5d40fa1d8a614e089357c7eff31b670@anotherbad.network.addr:26657"},
  176. }
  177. peer = testCreatePeerWithConfig(dir, 2, badPeerConfig)
  178. require.Error(t, peer.Start())
  179. peer.Stop()
  180. // 5. test create peer with one good seed address succeeds
  181. badPeerConfig = &PEXReactorConfig{
  182. Seeds: []string{"ed3dfd27bfc4af18f67a49862f04cc100696e84d@bad.network.addr:26657",
  183. "d824b13cb5d40fa1d8a614e089357c7eff31b670@anotherbad.network.addr:26657",
  184. seed.NodeInfo().NetAddress().String()},
  185. }
  186. peer = testCreatePeerWithConfig(dir, 2, badPeerConfig)
  187. require.Nil(t, peer.Start())
  188. peer.Stop()
  189. }
  190. func TestPEXReactorUsesSeedsIfNeeded(t *testing.T) {
  191. // directory to store address books
  192. dir, err := ioutil.TempDir("", "pex_reactor")
  193. require.Nil(t, err)
  194. defer os.RemoveAll(dir) // nolint: errcheck
  195. // 1. create seed
  196. seed := testCreateSeed(dir, 0, []*p2p.NetAddress{}, []*p2p.NetAddress{})
  197. require.Nil(t, seed.Start())
  198. defer seed.Stop()
  199. // 2. create usual peer with only seed configured.
  200. peer := testCreatePeerWithSeed(dir, 1, seed)
  201. require.Nil(t, peer.Start())
  202. defer peer.Stop()
  203. // 3. check that the peer connects to seed immediately
  204. assertPeersWithTimeout(t, []*p2p.Switch{peer}, 10*time.Millisecond, 3*time.Second, 1)
  205. }
  206. func TestConnectionSpeedForPeerReceivedFromSeed(t *testing.T) {
  207. // directory to store address books
  208. dir, err := ioutil.TempDir("", "pex_reactor")
  209. require.Nil(t, err)
  210. defer os.RemoveAll(dir) // nolint: errcheck
  211. // 1. create peer
  212. peer := testCreateDefaultPeer(dir, 1)
  213. require.Nil(t, peer.Start())
  214. defer peer.Stop()
  215. // 2. Create seed which knows about the peer
  216. seed := testCreateSeed(dir, 2, []*p2p.NetAddress{peer.NodeInfo().NetAddress()}, []*p2p.NetAddress{peer.NodeInfo().NetAddress()})
  217. require.Nil(t, seed.Start())
  218. defer seed.Stop()
  219. // 3. create another peer with only seed configured.
  220. secondPeer := testCreatePeerWithSeed(dir, 3, seed)
  221. require.Nil(t, secondPeer.Start())
  222. defer secondPeer.Stop()
  223. // 4. check that the second peer connects to seed immediately
  224. assertPeersWithTimeout(t, []*p2p.Switch{secondPeer}, 10*time.Millisecond, 3*time.Second, 1)
  225. // 5. check that the second peer connects to the first peer immediately
  226. assertPeersWithTimeout(t, []*p2p.Switch{secondPeer}, 10*time.Millisecond, 1*time.Second, 2)
  227. }
  228. func TestPEXReactorCrawlStatus(t *testing.T) {
  229. pexR, book := createReactor(&PEXReactorConfig{SeedMode: true})
  230. defer teardownReactor(book)
  231. // Seed/Crawler mode uses data from the Switch
  232. sw := createSwitchAndAddReactors(pexR)
  233. sw.SetAddrBook(book)
  234. // Create a peer, add it to the peer set and the addrbook.
  235. peer := p2p.CreateRandomPeer(false)
  236. p2p.AddPeerToSwitch(pexR.Switch, peer)
  237. addr1 := peer.NodeInfo().NetAddress()
  238. pexR.book.AddAddress(addr1, addr1)
  239. // Add a non-connected address to the book.
  240. _, addr2 := p2p.CreateRoutableAddr()
  241. pexR.book.AddAddress(addr2, addr1)
  242. // Get some peerInfos to crawl
  243. peerInfos := pexR.getPeersToCrawl()
  244. // Make sure it has the proper number of elements
  245. assert.Equal(t, 2, len(peerInfos))
  246. // TODO: test
  247. }
  248. func TestPEXReactorDoesNotAddPrivatePeersToAddrBook(t *testing.T) {
  249. peer := p2p.CreateRandomPeer(false)
  250. pexR, book := createReactor(&PEXReactorConfig{})
  251. book.AddPrivateIDs([]string{string(peer.NodeInfo().ID())})
  252. defer teardownReactor(book)
  253. // we have to send a request to receive responses
  254. pexR.RequestAddrs(peer)
  255. size := book.Size()
  256. addrs := []*p2p.NetAddress{peer.NodeInfo().NetAddress()}
  257. msg := cdc.MustMarshalBinaryBare(&pexAddrsMessage{Addrs: addrs})
  258. pexR.Receive(PexChannel, peer, msg)
  259. assert.Equal(t, size, book.Size())
  260. pexR.AddPeer(peer)
  261. assert.Equal(t, size, book.Size())
  262. }
  263. func TestPEXReactorDialPeer(t *testing.T) {
  264. pexR, book := createReactor(&PEXReactorConfig{})
  265. defer teardownReactor(book)
  266. sw := createSwitchAndAddReactors(pexR)
  267. sw.SetAddrBook(book)
  268. peer := newMockPeer()
  269. addr := peer.NodeInfo().NetAddress()
  270. assert.Equal(t, 0, pexR.AttemptsToDial(addr))
  271. // 1st unsuccessful attempt
  272. pexR.dialPeer(addr)
  273. assert.Equal(t, 1, pexR.AttemptsToDial(addr))
  274. // 2nd unsuccessful attempt
  275. pexR.dialPeer(addr)
  276. // must be skipped because it is too early
  277. assert.Equal(t, 1, pexR.AttemptsToDial(addr))
  278. if !testing.Short() {
  279. time.Sleep(3 * time.Second)
  280. // 3rd attempt
  281. pexR.dialPeer(addr)
  282. assert.Equal(t, 2, pexR.AttemptsToDial(addr))
  283. }
  284. }
  285. type mockPeer struct {
  286. *cmn.BaseService
  287. pubKey crypto.PubKey
  288. addr *p2p.NetAddress
  289. outbound, persistent bool
  290. }
  291. func newMockPeer() mockPeer {
  292. _, netAddr := p2p.CreateRoutableAddr()
  293. mp := mockPeer{
  294. addr: netAddr,
  295. pubKey: ed25519.GenPrivKey().PubKey(),
  296. }
  297. mp.BaseService = cmn.NewBaseService(nil, "MockPeer", mp)
  298. mp.Start()
  299. return mp
  300. }
  301. func (mp mockPeer) FlushStop() { mp.Stop() }
  302. func (mp mockPeer) ID() p2p.ID { return mp.addr.ID }
  303. func (mp mockPeer) IsOutbound() bool { return mp.outbound }
  304. func (mp mockPeer) IsPersistent() bool { return mp.persistent }
  305. func (mp mockPeer) NodeInfo() p2p.NodeInfo {
  306. return p2p.DefaultNodeInfo{
  307. ID_: mp.addr.ID,
  308. ListenAddr: mp.addr.DialString(),
  309. }
  310. }
  311. func (mockPeer) RemoteIP() net.IP { return net.ParseIP("127.0.0.1") }
  312. func (mockPeer) Status() conn.ConnectionStatus { return conn.ConnectionStatus{} }
  313. func (mockPeer) Send(byte, []byte) bool { return false }
  314. func (mockPeer) TrySend(byte, []byte) bool { return false }
  315. func (mockPeer) Set(string, interface{}) {}
  316. func (mockPeer) Get(string) interface{} { return nil }
  317. func (mockPeer) OriginalAddr() *p2p.NetAddress { return nil }
  318. func (mockPeer) RemoteAddr() net.Addr { return &net.TCPAddr{IP: net.ParseIP("127.0.0.1"), Port: 8800} }
  319. func (mockPeer) CloseConn() error { return nil }
  320. func assertPeersWithTimeout(
  321. t *testing.T,
  322. switches []*p2p.Switch,
  323. checkPeriod, timeout time.Duration,
  324. nPeers int,
  325. ) {
  326. var (
  327. ticker = time.NewTicker(checkPeriod)
  328. remaining = timeout
  329. )
  330. for {
  331. select {
  332. case <-ticker.C:
  333. // check peers are connected
  334. allGood := true
  335. for _, s := range switches {
  336. outbound, inbound, _ := s.NumPeers()
  337. if outbound+inbound < nPeers {
  338. allGood = false
  339. break
  340. }
  341. }
  342. remaining -= checkPeriod
  343. if remaining < 0 {
  344. remaining = 0
  345. }
  346. if allGood {
  347. return
  348. }
  349. case <-time.After(remaining):
  350. numPeersStr := ""
  351. for i, s := range switches {
  352. outbound, inbound, _ := s.NumPeers()
  353. numPeersStr += fmt.Sprintf("%d => {outbound: %d, inbound: %d}, ", i, outbound, inbound)
  354. }
  355. t.Errorf(
  356. "expected all switches to be connected to at least %d peer(s) (switches: %s)",
  357. nPeers, numPeersStr,
  358. )
  359. return
  360. }
  361. }
  362. }
  363. // Creates a peer with the provided config
  364. func testCreatePeerWithConfig(dir string, id int, config *PEXReactorConfig) *p2p.Switch {
  365. peer := p2p.MakeSwitch(
  366. cfg,
  367. id,
  368. "127.0.0.1",
  369. "123.123.123",
  370. func(i int, sw *p2p.Switch) *p2p.Switch {
  371. book := NewAddrBook(filepath.Join(dir, fmt.Sprintf("addrbook%d.json", id)), false)
  372. book.SetLogger(log.TestingLogger())
  373. sw.SetAddrBook(book)
  374. sw.SetLogger(log.TestingLogger())
  375. r := NewPEXReactor(
  376. book,
  377. config,
  378. )
  379. r.SetLogger(log.TestingLogger())
  380. sw.AddReactor("pex", r)
  381. return sw
  382. },
  383. )
  384. return peer
  385. }
  386. // Creates a peer with the default config
  387. func testCreateDefaultPeer(dir string, id int) *p2p.Switch {
  388. return testCreatePeerWithConfig(dir, id, &PEXReactorConfig{})
  389. }
  390. // Creates a seed which knows about the provided addresses / source address pairs.
  391. // Starting and stopping the seed is left to the caller
  392. func testCreateSeed(dir string, id int, knownAddrs, srcAddrs []*p2p.NetAddress) *p2p.Switch {
  393. seed := p2p.MakeSwitch(
  394. cfg,
  395. id,
  396. "127.0.0.1",
  397. "123.123.123",
  398. func(i int, sw *p2p.Switch) *p2p.Switch {
  399. book := NewAddrBook(filepath.Join(dir, "addrbookSeed.json"), false)
  400. book.SetLogger(log.TestingLogger())
  401. for j := 0; j < len(knownAddrs); j++ {
  402. book.AddAddress(knownAddrs[j], srcAddrs[j])
  403. book.MarkGood(knownAddrs[j])
  404. }
  405. sw.SetAddrBook(book)
  406. sw.SetLogger(log.TestingLogger())
  407. r := NewPEXReactor(book, &PEXReactorConfig{})
  408. r.SetLogger(log.TestingLogger())
  409. sw.AddReactor("pex", r)
  410. return sw
  411. },
  412. )
  413. return seed
  414. }
  415. // Creates a peer which knows about the provided seed.
  416. // Starting and stopping the peer is left to the caller
  417. func testCreatePeerWithSeed(dir string, id int, seed *p2p.Switch) *p2p.Switch {
  418. conf := &PEXReactorConfig{
  419. Seeds: []string{seed.NodeInfo().NetAddress().String()},
  420. }
  421. return testCreatePeerWithConfig(dir, id, conf)
  422. }
  423. func createReactor(conf *PEXReactorConfig) (r *PEXReactor, book *addrBook) {
  424. // directory to store address book
  425. dir, err := ioutil.TempDir("", "pex_reactor")
  426. if err != nil {
  427. panic(err)
  428. }
  429. book = NewAddrBook(filepath.Join(dir, "addrbook.json"), true)
  430. book.SetLogger(log.TestingLogger())
  431. r = NewPEXReactor(book, conf)
  432. r.SetLogger(log.TestingLogger())
  433. return
  434. }
  435. func teardownReactor(book *addrBook) {
  436. err := os.RemoveAll(filepath.Dir(book.FilePath()))
  437. if err != nil {
  438. panic(err)
  439. }
  440. }
  441. func createSwitchAndAddReactors(reactors ...p2p.Reactor) *p2p.Switch {
  442. sw := p2p.MakeSwitch(cfg, 0, "127.0.0.1", "123.123.123", func(i int, sw *p2p.Switch) *p2p.Switch { return sw })
  443. sw.SetLogger(log.TestingLogger())
  444. for _, r := range reactors {
  445. sw.AddReactor(r.String(), r)
  446. r.SetSwitch(sw)
  447. }
  448. return sw
  449. }