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.

637 lines
16 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
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
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
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
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 p2p
  2. import (
  3. "bytes"
  4. "errors"
  5. "fmt"
  6. "io"
  7. "io/ioutil"
  8. "net"
  9. "net/http"
  10. "net/http/httptest"
  11. "regexp"
  12. "strconv"
  13. "sync"
  14. "testing"
  15. "time"
  16. stdprometheus "github.com/prometheus/client_golang/prometheus"
  17. "github.com/stretchr/testify/assert"
  18. "github.com/stretchr/testify/require"
  19. "github.com/tendermint/tendermint/config"
  20. "github.com/tendermint/tendermint/crypto/ed25519"
  21. "github.com/tendermint/tendermint/libs/log"
  22. "github.com/tendermint/tendermint/p2p/conn"
  23. )
  24. var (
  25. cfg *config.P2PConfig
  26. )
  27. func init() {
  28. cfg = config.DefaultP2PConfig()
  29. cfg.PexReactor = true
  30. cfg.AllowDuplicateIP = true
  31. }
  32. type PeerMessage struct {
  33. PeerID ID
  34. Bytes []byte
  35. Counter int
  36. }
  37. type TestReactor struct {
  38. BaseReactor
  39. mtx sync.Mutex
  40. channels []*conn.ChannelDescriptor
  41. logMessages bool
  42. msgsCounter int
  43. msgsReceived map[byte][]PeerMessage
  44. }
  45. func NewTestReactor(channels []*conn.ChannelDescriptor, logMessages bool) *TestReactor {
  46. tr := &TestReactor{
  47. channels: channels,
  48. logMessages: logMessages,
  49. msgsReceived: make(map[byte][]PeerMessage),
  50. }
  51. tr.BaseReactor = *NewBaseReactor("TestReactor", tr)
  52. tr.SetLogger(log.TestingLogger())
  53. return tr
  54. }
  55. func (tr *TestReactor) GetChannels() []*conn.ChannelDescriptor {
  56. return tr.channels
  57. }
  58. func (tr *TestReactor) AddPeer(peer Peer) {}
  59. func (tr *TestReactor) RemovePeer(peer Peer, reason interface{}) {}
  60. func (tr *TestReactor) Receive(chID byte, peer Peer, msgBytes []byte) {
  61. if tr.logMessages {
  62. tr.mtx.Lock()
  63. defer tr.mtx.Unlock()
  64. //fmt.Printf("Received: %X, %X\n", chID, msgBytes)
  65. tr.msgsReceived[chID] = append(tr.msgsReceived[chID], PeerMessage{peer.ID(), msgBytes, tr.msgsCounter})
  66. tr.msgsCounter++
  67. }
  68. }
  69. func (tr *TestReactor) getMsgs(chID byte) []PeerMessage {
  70. tr.mtx.Lock()
  71. defer tr.mtx.Unlock()
  72. return tr.msgsReceived[chID]
  73. }
  74. //-----------------------------------------------------------------------------
  75. // convenience method for creating two switches connected to each other.
  76. // XXX: note this uses net.Pipe and not a proper TCP conn
  77. func MakeSwitchPair(t testing.TB, initSwitch func(int, *Switch) *Switch) (*Switch, *Switch) {
  78. // Create two switches that will be interconnected.
  79. switches := MakeConnectedSwitches(cfg, 2, initSwitch, Connect2Switches)
  80. return switches[0], switches[1]
  81. }
  82. func initSwitchFunc(i int, sw *Switch) *Switch {
  83. sw.SetAddrBook(&addrBookMock{
  84. addrs: make(map[string]struct{}),
  85. ourAddrs: make(map[string]struct{})})
  86. // Make two reactors of two channels each
  87. sw.AddReactor("foo", NewTestReactor([]*conn.ChannelDescriptor{
  88. {ID: byte(0x00), Priority: 10},
  89. {ID: byte(0x01), Priority: 10},
  90. }, true))
  91. sw.AddReactor("bar", NewTestReactor([]*conn.ChannelDescriptor{
  92. {ID: byte(0x02), Priority: 10},
  93. {ID: byte(0x03), Priority: 10},
  94. }, true))
  95. return sw
  96. }
  97. func TestSwitches(t *testing.T) {
  98. s1, s2 := MakeSwitchPair(t, initSwitchFunc)
  99. defer s1.Stop()
  100. defer s2.Stop()
  101. if s1.Peers().Size() != 1 {
  102. t.Errorf("Expected exactly 1 peer in s1, got %v", s1.Peers().Size())
  103. }
  104. if s2.Peers().Size() != 1 {
  105. t.Errorf("Expected exactly 1 peer in s2, got %v", s2.Peers().Size())
  106. }
  107. // Lets send some messages
  108. ch0Msg := []byte("channel zero")
  109. ch1Msg := []byte("channel foo")
  110. ch2Msg := []byte("channel bar")
  111. s1.Broadcast(byte(0x00), ch0Msg)
  112. s1.Broadcast(byte(0x01), ch1Msg)
  113. s1.Broadcast(byte(0x02), ch2Msg)
  114. assertMsgReceivedWithTimeout(t, ch0Msg, byte(0x00), s2.Reactor("foo").(*TestReactor), 10*time.Millisecond, 5*time.Second)
  115. assertMsgReceivedWithTimeout(t, ch1Msg, byte(0x01), s2.Reactor("foo").(*TestReactor), 10*time.Millisecond, 5*time.Second)
  116. assertMsgReceivedWithTimeout(t, ch2Msg, byte(0x02), s2.Reactor("bar").(*TestReactor), 10*time.Millisecond, 5*time.Second)
  117. }
  118. func assertMsgReceivedWithTimeout(t *testing.T, msgBytes []byte, channel byte, reactor *TestReactor, checkPeriod, timeout time.Duration) {
  119. ticker := time.NewTicker(checkPeriod)
  120. for {
  121. select {
  122. case <-ticker.C:
  123. msgs := reactor.getMsgs(channel)
  124. if len(msgs) > 0 {
  125. if !bytes.Equal(msgs[0].Bytes, msgBytes) {
  126. t.Fatalf("Unexpected message bytes. Wanted: %X, Got: %X", msgBytes, msgs[0].Bytes)
  127. }
  128. return
  129. }
  130. case <-time.After(timeout):
  131. t.Fatalf("Expected to have received 1 message in channel #%v, got zero", channel)
  132. }
  133. }
  134. }
  135. func TestSwitchFiltersOutItself(t *testing.T) {
  136. s1 := MakeSwitch(cfg, 1, "127.0.0.1", "123.123.123", initSwitchFunc)
  137. // simulate s1 having a public IP by creating a remote peer with the same ID
  138. rp := &remotePeer{PrivKey: s1.nodeKey.PrivKey, Config: cfg}
  139. rp.Start()
  140. // addr should be rejected in addPeer based on the same ID
  141. err := s1.DialPeerWithAddress(rp.Addr(), false)
  142. if assert.Error(t, err) {
  143. if err, ok := err.(ErrRejected); ok {
  144. if !err.IsSelf() {
  145. t.Errorf("expected self to be rejected")
  146. }
  147. } else {
  148. t.Errorf("expected ErrRejected")
  149. }
  150. }
  151. assert.True(t, s1.addrBook.OurAddress(rp.Addr()))
  152. assert.False(t, s1.addrBook.HasAddress(rp.Addr()))
  153. rp.Stop()
  154. assertNoPeersAfterTimeout(t, s1, 100*time.Millisecond)
  155. }
  156. func TestSwitchPeerFilter(t *testing.T) {
  157. var (
  158. filters = []PeerFilterFunc{
  159. func(_ IPeerSet, _ Peer) error { return nil },
  160. func(_ IPeerSet, _ Peer) error { return fmt.Errorf("denied!") },
  161. func(_ IPeerSet, _ Peer) error { return nil },
  162. }
  163. sw = MakeSwitch(
  164. cfg,
  165. 1,
  166. "testing",
  167. "123.123.123",
  168. initSwitchFunc,
  169. SwitchPeerFilters(filters...),
  170. )
  171. )
  172. defer sw.Stop()
  173. // simulate remote peer
  174. rp := &remotePeer{PrivKey: ed25519.GenPrivKey(), Config: cfg}
  175. rp.Start()
  176. defer rp.Stop()
  177. p, err := sw.transport.Dial(*rp.Addr(), peerConfig{
  178. chDescs: sw.chDescs,
  179. onPeerError: sw.StopPeerForError,
  180. reactorsByCh: sw.reactorsByCh,
  181. })
  182. if err != nil {
  183. t.Fatal(err)
  184. }
  185. err = sw.addPeer(p)
  186. if err, ok := err.(ErrRejected); ok {
  187. if !err.IsFiltered() {
  188. t.Errorf("expected peer to be filtered")
  189. }
  190. } else {
  191. t.Errorf("expected ErrRejected")
  192. }
  193. }
  194. func TestSwitchPeerFilterTimeout(t *testing.T) {
  195. var (
  196. filters = []PeerFilterFunc{
  197. func(_ IPeerSet, _ Peer) error {
  198. time.Sleep(10 * time.Millisecond)
  199. return nil
  200. },
  201. }
  202. sw = MakeSwitch(
  203. cfg,
  204. 1,
  205. "testing",
  206. "123.123.123",
  207. initSwitchFunc,
  208. SwitchFilterTimeout(5*time.Millisecond),
  209. SwitchPeerFilters(filters...),
  210. )
  211. )
  212. defer sw.Stop()
  213. // simulate remote peer
  214. rp := &remotePeer{PrivKey: ed25519.GenPrivKey(), Config: cfg}
  215. rp.Start()
  216. defer rp.Stop()
  217. p, err := sw.transport.Dial(*rp.Addr(), peerConfig{
  218. chDescs: sw.chDescs,
  219. onPeerError: sw.StopPeerForError,
  220. reactorsByCh: sw.reactorsByCh,
  221. })
  222. if err != nil {
  223. t.Fatal(err)
  224. }
  225. err = sw.addPeer(p)
  226. if _, ok := err.(ErrFilterTimeout); !ok {
  227. t.Errorf("expected ErrFilterTimeout")
  228. }
  229. }
  230. func TestSwitchPeerFilterDuplicate(t *testing.T) {
  231. sw := MakeSwitch(cfg, 1, "testing", "123.123.123", initSwitchFunc)
  232. sw.Start()
  233. defer sw.Stop()
  234. // simulate remote peer
  235. rp := &remotePeer{PrivKey: ed25519.GenPrivKey(), Config: cfg}
  236. rp.Start()
  237. defer rp.Stop()
  238. p, err := sw.transport.Dial(*rp.Addr(), peerConfig{
  239. chDescs: sw.chDescs,
  240. onPeerError: sw.StopPeerForError,
  241. reactorsByCh: sw.reactorsByCh,
  242. })
  243. if err != nil {
  244. t.Fatal(err)
  245. }
  246. if err := sw.addPeer(p); err != nil {
  247. t.Fatal(err)
  248. }
  249. err = sw.addPeer(p)
  250. if errRej, ok := err.(ErrRejected); ok {
  251. if !errRej.IsDuplicate() {
  252. t.Errorf("expected peer to be duplicate. got %v", errRej)
  253. }
  254. } else {
  255. t.Errorf("expected ErrRejected, got %v", err)
  256. }
  257. }
  258. func assertNoPeersAfterTimeout(t *testing.T, sw *Switch, timeout time.Duration) {
  259. time.Sleep(timeout)
  260. if sw.Peers().Size() != 0 {
  261. t.Fatalf("Expected %v to not connect to some peers, got %d", sw, sw.Peers().Size())
  262. }
  263. }
  264. func TestSwitchStopsNonPersistentPeerOnError(t *testing.T) {
  265. assert, require := assert.New(t), require.New(t)
  266. sw := MakeSwitch(cfg, 1, "testing", "123.123.123", initSwitchFunc)
  267. err := sw.Start()
  268. if err != nil {
  269. t.Error(err)
  270. }
  271. defer sw.Stop()
  272. // simulate remote peer
  273. rp := &remotePeer{PrivKey: ed25519.GenPrivKey(), Config: cfg}
  274. rp.Start()
  275. defer rp.Stop()
  276. p, err := sw.transport.Dial(*rp.Addr(), peerConfig{
  277. chDescs: sw.chDescs,
  278. onPeerError: sw.StopPeerForError,
  279. reactorsByCh: sw.reactorsByCh,
  280. })
  281. require.Nil(err)
  282. err = sw.addPeer(p)
  283. require.Nil(err)
  284. require.NotNil(sw.Peers().Get(rp.ID()))
  285. // simulate failure by closing connection
  286. p.(*peer).CloseConn()
  287. assertNoPeersAfterTimeout(t, sw, 100*time.Millisecond)
  288. assert.False(p.IsRunning())
  289. }
  290. func TestSwitchStopPeerForError(t *testing.T) {
  291. s := httptest.NewServer(stdprometheus.UninstrumentedHandler())
  292. defer s.Close()
  293. scrapeMetrics := func() string {
  294. resp, _ := http.Get(s.URL)
  295. buf, _ := ioutil.ReadAll(resp.Body)
  296. return string(buf)
  297. }
  298. namespace, subsystem, name := config.TestInstrumentationConfig().Namespace, MetricsSubsystem, "peers"
  299. re := regexp.MustCompile(namespace + `_` + subsystem + `_` + name + ` ([0-9\.]+)`)
  300. peersMetricValue := func() float64 {
  301. matches := re.FindStringSubmatch(scrapeMetrics())
  302. f, _ := strconv.ParseFloat(matches[1], 64)
  303. return f
  304. }
  305. p2pMetrics := PrometheusMetrics(namespace)
  306. // make two connected switches
  307. sw1, sw2 := MakeSwitchPair(t, func(i int, sw *Switch) *Switch {
  308. // set metrics on sw1
  309. if i == 0 {
  310. opt := WithMetrics(p2pMetrics)
  311. opt(sw)
  312. }
  313. return initSwitchFunc(i, sw)
  314. })
  315. assert.Equal(t, len(sw1.Peers().List()), 1)
  316. assert.EqualValues(t, 1, peersMetricValue())
  317. // send messages to the peer from sw1
  318. p := sw1.Peers().List()[0]
  319. p.Send(0x1, []byte("here's a message to send"))
  320. // stop sw2. this should cause the p to fail,
  321. // which results in calling StopPeerForError internally
  322. sw2.Stop()
  323. // now call StopPeerForError explicitly, eg. from a reactor
  324. sw1.StopPeerForError(p, fmt.Errorf("some err"))
  325. assert.Equal(t, len(sw1.Peers().List()), 0)
  326. assert.EqualValues(t, 0, peersMetricValue())
  327. }
  328. func TestSwitchReconnectsToPersistentPeer(t *testing.T) {
  329. assert, require := assert.New(t), require.New(t)
  330. sw := MakeSwitch(cfg, 1, "testing", "123.123.123", initSwitchFunc)
  331. err := sw.Start()
  332. if err != nil {
  333. t.Error(err)
  334. }
  335. defer sw.Stop()
  336. // simulate remote peer
  337. rp := &remotePeer{PrivKey: ed25519.GenPrivKey(), Config: cfg}
  338. rp.Start()
  339. defer rp.Stop()
  340. p, err := sw.transport.Dial(*rp.Addr(), peerConfig{
  341. chDescs: sw.chDescs,
  342. onPeerError: sw.StopPeerForError,
  343. persistent: true,
  344. reactorsByCh: sw.reactorsByCh,
  345. })
  346. require.Nil(err)
  347. require.Nil(sw.addPeer(p))
  348. require.NotNil(sw.Peers().Get(rp.ID()))
  349. // simulate failure by closing connection
  350. p.(*peer).CloseConn()
  351. // TODO: remove sleep, detect the disconnection, wait for reconnect
  352. npeers := sw.Peers().Size()
  353. for i := 0; i < 20; i++ {
  354. time.Sleep(250 * time.Millisecond)
  355. npeers = sw.Peers().Size()
  356. if npeers > 0 {
  357. break
  358. }
  359. }
  360. assert.NotZero(npeers)
  361. assert.False(p.IsRunning())
  362. // simulate another remote peer
  363. rp = &remotePeer{
  364. PrivKey: ed25519.GenPrivKey(),
  365. Config: cfg,
  366. // Use different interface to prevent duplicate IP filter, this will break
  367. // beyond two peers.
  368. listenAddr: "127.0.0.1:0",
  369. }
  370. rp.Start()
  371. defer rp.Stop()
  372. // simulate first time dial failure
  373. conf := config.DefaultP2PConfig()
  374. conf.TestDialFail = true
  375. err = sw.addOutboundPeerWithConfig(rp.Addr(), conf, true)
  376. require.NotNil(err)
  377. // DialPeerWithAddres - sw.peerConfig resets the dialer
  378. // TODO: same as above
  379. for i := 0; i < 20; i++ {
  380. time.Sleep(250 * time.Millisecond)
  381. npeers = sw.Peers().Size()
  382. if npeers > 1 {
  383. break
  384. }
  385. }
  386. assert.EqualValues(2, npeers)
  387. }
  388. func TestSwitchFullConnectivity(t *testing.T) {
  389. switches := MakeConnectedSwitches(cfg, 3, initSwitchFunc, Connect2Switches)
  390. defer func() {
  391. for _, sw := range switches {
  392. sw.Stop()
  393. }
  394. }()
  395. for i, sw := range switches {
  396. if sw.Peers().Size() != 2 {
  397. t.Fatalf("Expected each switch to be connected to 2 other, but %d switch only connected to %d", sw.Peers().Size(), i)
  398. }
  399. }
  400. }
  401. func TestSwitchAcceptRoutine(t *testing.T) {
  402. cfg.MaxNumInboundPeers = 5
  403. // make switch
  404. sw := MakeSwitch(cfg, 1, "testing", "123.123.123", initSwitchFunc)
  405. err := sw.Start()
  406. require.NoError(t, err)
  407. defer sw.Stop()
  408. remotePeers := make([]*remotePeer, 0)
  409. assert.Equal(t, 0, sw.Peers().Size())
  410. // 1. check we connect up to MaxNumInboundPeers
  411. for i := 0; i < cfg.MaxNumInboundPeers; i++ {
  412. rp := &remotePeer{PrivKey: ed25519.GenPrivKey(), Config: cfg}
  413. remotePeers = append(remotePeers, rp)
  414. rp.Start()
  415. c, err := rp.Dial(sw.NetAddress())
  416. require.NoError(t, err)
  417. // spawn a reading routine to prevent connection from closing
  418. go func(c net.Conn) {
  419. for {
  420. one := make([]byte, 1)
  421. _, err := c.Read(one)
  422. if err != nil {
  423. return
  424. }
  425. }
  426. }(c)
  427. }
  428. time.Sleep(10 * time.Millisecond)
  429. assert.Equal(t, cfg.MaxNumInboundPeers, sw.Peers().Size())
  430. // 2. check we close new connections if we already have MaxNumInboundPeers peers
  431. rp := &remotePeer{PrivKey: ed25519.GenPrivKey(), Config: cfg}
  432. rp.Start()
  433. conn, err := rp.Dial(sw.NetAddress())
  434. require.NoError(t, err)
  435. // check conn is closed
  436. one := make([]byte, 1)
  437. conn.SetReadDeadline(time.Now().Add(10 * time.Millisecond))
  438. _, err = conn.Read(one)
  439. assert.Equal(t, io.EOF, err)
  440. assert.Equal(t, cfg.MaxNumInboundPeers, sw.Peers().Size())
  441. rp.Stop()
  442. // stop remote peers
  443. for _, rp := range remotePeers {
  444. rp.Stop()
  445. }
  446. }
  447. type errorTransport struct {
  448. acceptErr error
  449. }
  450. func (et errorTransport) NetAddress() NetAddress {
  451. panic("not implemented")
  452. }
  453. func (et errorTransport) Accept(c peerConfig) (Peer, error) {
  454. return nil, et.acceptErr
  455. }
  456. func (errorTransport) Dial(NetAddress, peerConfig) (Peer, error) {
  457. panic("not implemented")
  458. }
  459. func (errorTransport) Cleanup(Peer) {
  460. panic("not implemented")
  461. }
  462. func TestSwitchAcceptRoutineErrorCases(t *testing.T) {
  463. sw := NewSwitch(cfg, errorTransport{ErrFilterTimeout{}})
  464. assert.NotPanics(t, func() {
  465. err := sw.Start()
  466. assert.NoError(t, err)
  467. sw.Stop()
  468. })
  469. sw = NewSwitch(cfg, errorTransport{ErrRejected{conn: nil, err: errors.New("filtered"), isFiltered: true}})
  470. assert.NotPanics(t, func() {
  471. err := sw.Start()
  472. assert.NoError(t, err)
  473. sw.Stop()
  474. })
  475. // TODO(melekes) check we remove our address from addrBook
  476. sw = NewSwitch(cfg, errorTransport{ErrTransportClosed{}})
  477. assert.NotPanics(t, func() {
  478. err := sw.Start()
  479. assert.NoError(t, err)
  480. sw.Stop()
  481. })
  482. }
  483. func BenchmarkSwitchBroadcast(b *testing.B) {
  484. s1, s2 := MakeSwitchPair(b, func(i int, sw *Switch) *Switch {
  485. // Make bar reactors of bar channels each
  486. sw.AddReactor("foo", NewTestReactor([]*conn.ChannelDescriptor{
  487. {ID: byte(0x00), Priority: 10},
  488. {ID: byte(0x01), Priority: 10},
  489. }, false))
  490. sw.AddReactor("bar", NewTestReactor([]*conn.ChannelDescriptor{
  491. {ID: byte(0x02), Priority: 10},
  492. {ID: byte(0x03), Priority: 10},
  493. }, false))
  494. return sw
  495. })
  496. defer s1.Stop()
  497. defer s2.Stop()
  498. // Allow time for goroutines to boot up
  499. time.Sleep(1 * time.Second)
  500. b.ResetTimer()
  501. numSuccess, numFailure := 0, 0
  502. // Send random message from foo channel to another
  503. for i := 0; i < b.N; i++ {
  504. chID := byte(i % 4)
  505. successChan := s1.Broadcast(chID, []byte("test data"))
  506. for s := range successChan {
  507. if s {
  508. numSuccess++
  509. } else {
  510. numFailure++
  511. }
  512. }
  513. }
  514. b.Logf("success: %v, failure: %v", numSuccess, numFailure)
  515. }
  516. type addrBookMock struct {
  517. addrs map[string]struct{}
  518. ourAddrs map[string]struct{}
  519. }
  520. var _ AddrBook = (*addrBookMock)(nil)
  521. func (book *addrBookMock) AddAddress(addr *NetAddress, src *NetAddress) error {
  522. book.addrs[addr.String()] = struct{}{}
  523. return nil
  524. }
  525. func (book *addrBookMock) AddOurAddress(addr *NetAddress) { book.ourAddrs[addr.String()] = struct{}{} }
  526. func (book *addrBookMock) OurAddress(addr *NetAddress) bool {
  527. _, ok := book.ourAddrs[addr.String()]
  528. return ok
  529. }
  530. func (book *addrBookMock) MarkGood(*NetAddress) {}
  531. func (book *addrBookMock) HasAddress(addr *NetAddress) bool {
  532. _, ok := book.addrs[addr.String()]
  533. return ok
  534. }
  535. func (book *addrBookMock) RemoveAddress(addr *NetAddress) {
  536. delete(book.addrs, addr.String())
  537. }
  538. func (book *addrBookMock) Save() {}