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.

789 lines
22 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: seed mode refactoring (#3011) ListOfKnownAddresses is removed panic if addrbook size is less than zero CrawlPeers does not attempt to connect to existing or peers we're currently dialing various perf. fixes improved tests (though not complete) move IsDialingOrExistingAddress check into DialPeerWithAddress (Fixes #2716) * addrbook: preallocate memory when saving addrbook to file * addrbook: remove oldestFirst struct and check for ID * oldestFirst replaced with sort.Slice * ID is now mandatory, so no need to check * addrbook: remove ListOfKnownAddresses GetSelection is used instead in seed mode. * addrbook: panic if size is less than 0 * rewrite addrbook#saveToFile to not use a counter * test AttemptDisconnects func * move IsDialingOrExistingAddress check into DialPeerWithAddress * save and cleanup crawl peer data * get rid of DefaultSeedDisconnectWaitPeriod * make linter happy * fix TestPEXReactorSeedMode * fix comment * add a changelog entry * Apply suggestions from code review Co-Authored-By: melekes <anton.kalyaev@gmail.com> * rename ErrDialingOrExistingAddress to ErrCurrentlyDialingOrExistingAddress * lowercase errors * do not persist seed data pros: - no extra files - less IO cons: - if the node crashes, seed might crawl a peer too soon * fixes after Ethan's review * add a changelog entry * we should only consult Switch about peers checking addrbook size does not make sense since only PEX reactor uses it for dialing peers! https://github.com/tendermint/tendermint/pull/3011#discussion_r270948875
6 years ago
p2p: seed mode refactoring (#3011) ListOfKnownAddresses is removed panic if addrbook size is less than zero CrawlPeers does not attempt to connect to existing or peers we're currently dialing various perf. fixes improved tests (though not complete) move IsDialingOrExistingAddress check into DialPeerWithAddress (Fixes #2716) * addrbook: preallocate memory when saving addrbook to file * addrbook: remove oldestFirst struct and check for ID * oldestFirst replaced with sort.Slice * ID is now mandatory, so no need to check * addrbook: remove ListOfKnownAddresses GetSelection is used instead in seed mode. * addrbook: panic if size is less than 0 * rewrite addrbook#saveToFile to not use a counter * test AttemptDisconnects func * move IsDialingOrExistingAddress check into DialPeerWithAddress * save and cleanup crawl peer data * get rid of DefaultSeedDisconnectWaitPeriod * make linter happy * fix TestPEXReactorSeedMode * fix comment * add a changelog entry * Apply suggestions from code review Co-Authored-By: melekes <anton.kalyaev@gmail.com> * rename ErrDialingOrExistingAddress to ErrCurrentlyDialingOrExistingAddress * lowercase errors * do not persist seed data pros: - no extra files - less IO cons: - if the node crashes, seed might crawl a peer too soon * fixes after Ethan's review * add a changelog entry * we should only consult Switch about peers checking addrbook size does not make sense since only PEX reactor uses it for dialing peers! https://github.com/tendermint/tendermint/pull/3011#discussion_r270948875
6 years ago
p2p: seed mode refactoring (#3011) ListOfKnownAddresses is removed panic if addrbook size is less than zero CrawlPeers does not attempt to connect to existing or peers we're currently dialing various perf. fixes improved tests (though not complete) move IsDialingOrExistingAddress check into DialPeerWithAddress (Fixes #2716) * addrbook: preallocate memory when saving addrbook to file * addrbook: remove oldestFirst struct and check for ID * oldestFirst replaced with sort.Slice * ID is now mandatory, so no need to check * addrbook: remove ListOfKnownAddresses GetSelection is used instead in seed mode. * addrbook: panic if size is less than 0 * rewrite addrbook#saveToFile to not use a counter * test AttemptDisconnects func * move IsDialingOrExistingAddress check into DialPeerWithAddress * save and cleanup crawl peer data * get rid of DefaultSeedDisconnectWaitPeriod * make linter happy * fix TestPEXReactorSeedMode * fix comment * add a changelog entry * Apply suggestions from code review Co-Authored-By: melekes <anton.kalyaev@gmail.com> * rename ErrDialingOrExistingAddress to ErrCurrentlyDialingOrExistingAddress * lowercase errors * do not persist seed data pros: - no extra files - less IO cons: - if the node crashes, seed might crawl a peer too soon * fixes after Ethan's review * add a changelog entry * we should only consult Switch about peers checking addrbook size does not make sense since only PEX reactor uses it for dialing peers! https://github.com/tendermint/tendermint/pull/3011#discussion_r270948875
6 years ago
p2p: seed mode refactoring (#3011) ListOfKnownAddresses is removed panic if addrbook size is less than zero CrawlPeers does not attempt to connect to existing or peers we're currently dialing various perf. fixes improved tests (though not complete) move IsDialingOrExistingAddress check into DialPeerWithAddress (Fixes #2716) * addrbook: preallocate memory when saving addrbook to file * addrbook: remove oldestFirst struct and check for ID * oldestFirst replaced with sort.Slice * ID is now mandatory, so no need to check * addrbook: remove ListOfKnownAddresses GetSelection is used instead in seed mode. * addrbook: panic if size is less than 0 * rewrite addrbook#saveToFile to not use a counter * test AttemptDisconnects func * move IsDialingOrExistingAddress check into DialPeerWithAddress * save and cleanup crawl peer data * get rid of DefaultSeedDisconnectWaitPeriod * make linter happy * fix TestPEXReactorSeedMode * fix comment * add a changelog entry * Apply suggestions from code review Co-Authored-By: melekes <anton.kalyaev@gmail.com> * rename ErrDialingOrExistingAddress to ErrCurrentlyDialingOrExistingAddress * lowercase errors * do not persist seed data pros: - no extra files - less IO cons: - if the node crashes, seed might crawl a peer too soon * fixes after Ethan's review * add a changelog entry * we should only consult Switch about peers checking addrbook size does not make sense since only PEX reactor uses it for dialing peers! https://github.com/tendermint/tendermint/pull/3011#discussion_r270948875
6 years ago
p2p: seed mode refactoring (#3011) ListOfKnownAddresses is removed panic if addrbook size is less than zero CrawlPeers does not attempt to connect to existing or peers we're currently dialing various perf. fixes improved tests (though not complete) move IsDialingOrExistingAddress check into DialPeerWithAddress (Fixes #2716) * addrbook: preallocate memory when saving addrbook to file * addrbook: remove oldestFirst struct and check for ID * oldestFirst replaced with sort.Slice * ID is now mandatory, so no need to check * addrbook: remove ListOfKnownAddresses GetSelection is used instead in seed mode. * addrbook: panic if size is less than 0 * rewrite addrbook#saveToFile to not use a counter * test AttemptDisconnects func * move IsDialingOrExistingAddress check into DialPeerWithAddress * save and cleanup crawl peer data * get rid of DefaultSeedDisconnectWaitPeriod * make linter happy * fix TestPEXReactorSeedMode * fix comment * add a changelog entry * Apply suggestions from code review Co-Authored-By: melekes <anton.kalyaev@gmail.com> * rename ErrDialingOrExistingAddress to ErrCurrentlyDialingOrExistingAddress * lowercase errors * do not persist seed data pros: - no extra files - less IO cons: - if the node crashes, seed might crawl a peer too soon * fixes after Ethan's review * add a changelog entry * we should only consult Switch about peers checking addrbook size does not make sense since only PEX reactor uses it for dialing peers! https://github.com/tendermint/tendermint/pull/3011#discussion_r270948875
6 years ago
p2p: seed mode refactoring (#3011) ListOfKnownAddresses is removed panic if addrbook size is less than zero CrawlPeers does not attempt to connect to existing or peers we're currently dialing various perf. fixes improved tests (though not complete) move IsDialingOrExistingAddress check into DialPeerWithAddress (Fixes #2716) * addrbook: preallocate memory when saving addrbook to file * addrbook: remove oldestFirst struct and check for ID * oldestFirst replaced with sort.Slice * ID is now mandatory, so no need to check * addrbook: remove ListOfKnownAddresses GetSelection is used instead in seed mode. * addrbook: panic if size is less than 0 * rewrite addrbook#saveToFile to not use a counter * test AttemptDisconnects func * move IsDialingOrExistingAddress check into DialPeerWithAddress * save and cleanup crawl peer data * get rid of DefaultSeedDisconnectWaitPeriod * make linter happy * fix TestPEXReactorSeedMode * fix comment * add a changelog entry * Apply suggestions from code review Co-Authored-By: melekes <anton.kalyaev@gmail.com> * rename ErrDialingOrExistingAddress to ErrCurrentlyDialingOrExistingAddress * lowercase errors * do not persist seed data pros: - no extra files - less IO cons: - if the node crashes, seed might crawl a peer too soon * fixes after Ethan's review * add a changelog entry * we should only consult Switch about peers checking addrbook size does not make sense since only PEX reactor uses it for dialing peers! https://github.com/tendermint/tendermint/pull/3011#discussion_r270948875
6 years ago
p2p: seed mode refactoring (#3011) ListOfKnownAddresses is removed panic if addrbook size is less than zero CrawlPeers does not attempt to connect to existing or peers we're currently dialing various perf. fixes improved tests (though not complete) move IsDialingOrExistingAddress check into DialPeerWithAddress (Fixes #2716) * addrbook: preallocate memory when saving addrbook to file * addrbook: remove oldestFirst struct and check for ID * oldestFirst replaced with sort.Slice * ID is now mandatory, so no need to check * addrbook: remove ListOfKnownAddresses GetSelection is used instead in seed mode. * addrbook: panic if size is less than 0 * rewrite addrbook#saveToFile to not use a counter * test AttemptDisconnects func * move IsDialingOrExistingAddress check into DialPeerWithAddress * save and cleanup crawl peer data * get rid of DefaultSeedDisconnectWaitPeriod * make linter happy * fix TestPEXReactorSeedMode * fix comment * add a changelog entry * Apply suggestions from code review Co-Authored-By: melekes <anton.kalyaev@gmail.com> * rename ErrDialingOrExistingAddress to ErrCurrentlyDialingOrExistingAddress * lowercase errors * do not persist seed data pros: - no extra files - less IO cons: - if the node crashes, seed might crawl a peer too soon * fixes after Ethan's review * add a changelog entry * we should only consult Switch about peers checking addrbook size does not make sense since only PEX reactor uses it for dialing peers! https://github.com/tendermint/tendermint/pull/3011#discussion_r270948875
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
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. "fmt"
  4. "math"
  5. "sync"
  6. "time"
  7. "github.com/pkg/errors"
  8. "github.com/tendermint/tendermint/config"
  9. cmn "github.com/tendermint/tendermint/libs/common"
  10. "github.com/tendermint/tendermint/p2p/conn"
  11. )
  12. const (
  13. // wait a random amount of time from this interval
  14. // before dialing peers or reconnecting to help prevent DoS
  15. dialRandomizerIntervalMilliseconds = 3000
  16. // repeatedly try to reconnect for a few minutes
  17. // ie. 5 * 20 = 100s
  18. reconnectAttempts = 20
  19. reconnectInterval = 5 * time.Second
  20. // then move into exponential backoff mode for ~1day
  21. // ie. 3**10 = 16hrs
  22. reconnectBackOffAttempts = 10
  23. reconnectBackOffBaseSeconds = 3
  24. )
  25. // MConnConfig returns an MConnConfig with fields updated
  26. // from the P2PConfig.
  27. func MConnConfig(cfg *config.P2PConfig) conn.MConnConfig {
  28. mConfig := conn.DefaultMConnConfig()
  29. mConfig.FlushThrottle = cfg.FlushThrottleTimeout
  30. mConfig.SendRate = cfg.SendRate
  31. mConfig.RecvRate = cfg.RecvRate
  32. mConfig.MaxPacketMsgPayloadSize = cfg.MaxPacketMsgPayloadSize
  33. return mConfig
  34. }
  35. //-----------------------------------------------------------------------------
  36. // An AddrBook represents an address book from the pex package, which is used
  37. // to store peer addresses.
  38. type AddrBook interface {
  39. AddAddress(addr *NetAddress, src *NetAddress) error
  40. AddOurAddress(*NetAddress)
  41. OurAddress(*NetAddress) bool
  42. MarkGood(ID)
  43. RemoveAddress(*NetAddress)
  44. HasAddress(*NetAddress) bool
  45. Save()
  46. }
  47. // PeerFilterFunc to be implemented by filter hooks after a new Peer has been
  48. // fully setup.
  49. type PeerFilterFunc func(IPeerSet, Peer) error
  50. //-----------------------------------------------------------------------------
  51. // Switch handles peer connections and exposes an API to receive incoming messages
  52. // on `Reactors`. Each `Reactor` is responsible for handling incoming messages of one
  53. // or more `Channels`. So while sending outgoing messages is typically performed on the peer,
  54. // incoming messages are received on the reactor.
  55. type Switch struct {
  56. cmn.BaseService
  57. config *config.P2PConfig
  58. reactors map[string]Reactor
  59. chDescs []*conn.ChannelDescriptor
  60. reactorsByCh map[byte]Reactor
  61. peers *PeerSet
  62. dialing *cmn.CMap
  63. reconnecting *cmn.CMap
  64. nodeInfo NodeInfo // our node info
  65. nodeKey *NodeKey // our node privkey
  66. addrBook AddrBook
  67. // peers addresses with whom we'll maintain constant connection
  68. persistentPeersAddrs []*NetAddress
  69. transport Transport
  70. filterTimeout time.Duration
  71. peerFilters []PeerFilterFunc
  72. rng *cmn.Rand // seed for randomizing dial times and orders
  73. metrics *Metrics
  74. }
  75. // NetAddress returns the address the switch is listening on.
  76. func (sw *Switch) NetAddress() *NetAddress {
  77. addr := sw.transport.NetAddress()
  78. return &addr
  79. }
  80. // SwitchOption sets an optional parameter on the Switch.
  81. type SwitchOption func(*Switch)
  82. // NewSwitch creates a new Switch with the given config.
  83. func NewSwitch(
  84. cfg *config.P2PConfig,
  85. transport Transport,
  86. options ...SwitchOption,
  87. ) *Switch {
  88. sw := &Switch{
  89. config: cfg,
  90. reactors: make(map[string]Reactor),
  91. chDescs: make([]*conn.ChannelDescriptor, 0),
  92. reactorsByCh: make(map[byte]Reactor),
  93. peers: NewPeerSet(),
  94. dialing: cmn.NewCMap(),
  95. reconnecting: cmn.NewCMap(),
  96. metrics: NopMetrics(),
  97. transport: transport,
  98. filterTimeout: defaultFilterTimeout,
  99. persistentPeersAddrs: make([]*NetAddress, 0),
  100. }
  101. // Ensure we have a completely undeterministic PRNG.
  102. sw.rng = cmn.NewRand()
  103. sw.BaseService = *cmn.NewBaseService(nil, "P2P Switch", sw)
  104. for _, option := range options {
  105. option(sw)
  106. }
  107. return sw
  108. }
  109. // SwitchFilterTimeout sets the timeout used for peer filters.
  110. func SwitchFilterTimeout(timeout time.Duration) SwitchOption {
  111. return func(sw *Switch) { sw.filterTimeout = timeout }
  112. }
  113. // SwitchPeerFilters sets the filters for rejection of new peers.
  114. func SwitchPeerFilters(filters ...PeerFilterFunc) SwitchOption {
  115. return func(sw *Switch) { sw.peerFilters = filters }
  116. }
  117. // WithMetrics sets the metrics.
  118. func WithMetrics(metrics *Metrics) SwitchOption {
  119. return func(sw *Switch) { sw.metrics = metrics }
  120. }
  121. //---------------------------------------------------------------------
  122. // Switch setup
  123. // AddReactor adds the given reactor to the switch.
  124. // NOTE: Not goroutine safe.
  125. func (sw *Switch) AddReactor(name string, reactor Reactor) Reactor {
  126. for _, chDesc := range reactor.GetChannels() {
  127. chID := chDesc.ID
  128. // No two reactors can share the same channel.
  129. if sw.reactorsByCh[chID] != nil {
  130. panic(fmt.Sprintf("Channel %X has multiple reactors %v & %v", chID, sw.reactorsByCh[chID], reactor))
  131. }
  132. sw.chDescs = append(sw.chDescs, chDesc)
  133. sw.reactorsByCh[chID] = reactor
  134. }
  135. sw.reactors[name] = reactor
  136. reactor.SetSwitch(sw)
  137. return reactor
  138. }
  139. // RemoveReactor removes the given Reactor from the Switch.
  140. // NOTE: Not goroutine safe.
  141. func (sw *Switch) RemoveReactor(name string, reactor Reactor) {
  142. for _, chDesc := range reactor.GetChannels() {
  143. // remove channel description
  144. for i := 0; i < len(sw.chDescs); i++ {
  145. if chDesc.ID == sw.chDescs[i].ID {
  146. sw.chDescs = append(sw.chDescs[:i], sw.chDescs[i+1:]...)
  147. break
  148. }
  149. }
  150. delete(sw.reactorsByCh, chDesc.ID)
  151. }
  152. delete(sw.reactors, name)
  153. reactor.SetSwitch(nil)
  154. }
  155. // Reactors returns a map of reactors registered on the switch.
  156. // NOTE: Not goroutine safe.
  157. func (sw *Switch) Reactors() map[string]Reactor {
  158. return sw.reactors
  159. }
  160. // Reactor returns the reactor with the given name.
  161. // NOTE: Not goroutine safe.
  162. func (sw *Switch) Reactor(name string) Reactor {
  163. return sw.reactors[name]
  164. }
  165. // SetNodeInfo sets the switch's NodeInfo for checking compatibility and handshaking with other nodes.
  166. // NOTE: Not goroutine safe.
  167. func (sw *Switch) SetNodeInfo(nodeInfo NodeInfo) {
  168. sw.nodeInfo = nodeInfo
  169. }
  170. // NodeInfo returns the switch's NodeInfo.
  171. // NOTE: Not goroutine safe.
  172. func (sw *Switch) NodeInfo() NodeInfo {
  173. return sw.nodeInfo
  174. }
  175. // SetNodeKey sets the switch's private key for authenticated encryption.
  176. // NOTE: Not goroutine safe.
  177. func (sw *Switch) SetNodeKey(nodeKey *NodeKey) {
  178. sw.nodeKey = nodeKey
  179. }
  180. //---------------------------------------------------------------------
  181. // Service start/stop
  182. // OnStart implements BaseService. It starts all the reactors and peers.
  183. func (sw *Switch) OnStart() error {
  184. // Start reactors
  185. for _, reactor := range sw.reactors {
  186. err := reactor.Start()
  187. if err != nil {
  188. return errors.Wrapf(err, "failed to start %v", reactor)
  189. }
  190. }
  191. // Start accepting Peers.
  192. go sw.acceptRoutine()
  193. return nil
  194. }
  195. // OnStop implements BaseService. It stops all peers and reactors.
  196. func (sw *Switch) OnStop() {
  197. // Stop peers
  198. for _, p := range sw.peers.List() {
  199. sw.stopAndRemovePeer(p, nil)
  200. }
  201. // Stop reactors
  202. sw.Logger.Debug("Switch: Stopping reactors")
  203. for _, reactor := range sw.reactors {
  204. reactor.Stop()
  205. }
  206. }
  207. //---------------------------------------------------------------------
  208. // Peers
  209. // Broadcast runs a go routine for each attempted send, which will block trying
  210. // to send for defaultSendTimeoutSeconds. Returns a channel which receives
  211. // success values for each attempted send (false if times out). Channel will be
  212. // closed once msg bytes are sent to all peers (or time out).
  213. //
  214. // NOTE: Broadcast uses goroutines, so order of broadcast may not be preserved.
  215. func (sw *Switch) Broadcast(chID byte, msgBytes []byte) chan bool {
  216. sw.Logger.Debug("Broadcast", "channel", chID, "msgBytes", fmt.Sprintf("%X", msgBytes))
  217. peers := sw.peers.List()
  218. var wg sync.WaitGroup
  219. wg.Add(len(peers))
  220. successChan := make(chan bool, len(peers))
  221. for _, peer := range peers {
  222. go func(p Peer) {
  223. defer wg.Done()
  224. success := p.Send(chID, msgBytes)
  225. successChan <- success
  226. }(peer)
  227. }
  228. go func() {
  229. wg.Wait()
  230. close(successChan)
  231. }()
  232. return successChan
  233. }
  234. // NumPeers returns the count of outbound/inbound and outbound-dialing peers.
  235. func (sw *Switch) NumPeers() (outbound, inbound, dialing int) {
  236. peers := sw.peers.List()
  237. for _, peer := range peers {
  238. if peer.IsOutbound() {
  239. outbound++
  240. } else {
  241. inbound++
  242. }
  243. }
  244. dialing = sw.dialing.Size()
  245. return
  246. }
  247. // MaxNumOutboundPeers returns a maximum number of outbound peers.
  248. func (sw *Switch) MaxNumOutboundPeers() int {
  249. return sw.config.MaxNumOutboundPeers
  250. }
  251. // Peers returns the set of peers that are connected to the switch.
  252. func (sw *Switch) Peers() IPeerSet {
  253. return sw.peers
  254. }
  255. // StopPeerForError disconnects from a peer due to external error.
  256. // If the peer is persistent, it will attempt to reconnect.
  257. // TODO: make record depending on reason.
  258. func (sw *Switch) StopPeerForError(peer Peer, reason interface{}) {
  259. sw.Logger.Error("Stopping peer for error", "peer", peer, "err", reason)
  260. sw.stopAndRemovePeer(peer, reason)
  261. if peer.IsPersistent() {
  262. var addr *NetAddress
  263. if peer.IsOutbound() { // socket address for outbound peers
  264. addr = peer.SocketAddr()
  265. } else { // self-reported address for inbound peers
  266. var err error
  267. addr, err = peer.NodeInfo().NetAddress()
  268. if err != nil {
  269. sw.Logger.Error("Wanted to reconnect to inbound peer, but self-reported address is wrong",
  270. "peer", peer, "err", err)
  271. return
  272. }
  273. }
  274. go sw.reconnectToPeer(addr)
  275. }
  276. }
  277. // StopPeerGracefully disconnects from a peer gracefully.
  278. // TODO: handle graceful disconnects.
  279. func (sw *Switch) StopPeerGracefully(peer Peer) {
  280. sw.Logger.Info("Stopping peer gracefully")
  281. sw.stopAndRemovePeer(peer, nil)
  282. }
  283. func (sw *Switch) stopAndRemovePeer(peer Peer, reason interface{}) {
  284. sw.transport.Cleanup(peer)
  285. peer.Stop()
  286. for _, reactor := range sw.reactors {
  287. reactor.RemovePeer(peer, reason)
  288. }
  289. // Removing a peer should go last to avoid a situation where a peer
  290. // reconnect to our node and the switch calls InitPeer before
  291. // RemovePeer is finished.
  292. // https://github.com/tendermint/tendermint/issues/3338
  293. if sw.peers.Remove(peer) {
  294. sw.metrics.Peers.Add(float64(-1))
  295. }
  296. }
  297. // reconnectToPeer tries to reconnect to the addr, first repeatedly
  298. // with a fixed interval, then with exponential backoff.
  299. // If no success after all that, it stops trying, and leaves it
  300. // to the PEX/Addrbook to find the peer with the addr again
  301. // NOTE: this will keep trying even if the handshake or auth fails.
  302. // TODO: be more explicit with error types so we only retry on certain failures
  303. // - ie. if we're getting ErrDuplicatePeer we can stop
  304. // because the addrbook got us the peer back already
  305. func (sw *Switch) reconnectToPeer(addr *NetAddress) {
  306. if sw.reconnecting.Has(string(addr.ID)) {
  307. return
  308. }
  309. sw.reconnecting.Set(string(addr.ID), addr)
  310. defer sw.reconnecting.Delete(string(addr.ID))
  311. start := time.Now()
  312. sw.Logger.Info("Reconnecting to peer", "addr", addr)
  313. for i := 0; i < reconnectAttempts; i++ {
  314. if !sw.IsRunning() {
  315. return
  316. }
  317. err := sw.DialPeerWithAddress(addr)
  318. if err == nil {
  319. return // success
  320. } else if _, ok := err.(ErrCurrentlyDialingOrExistingAddress); ok {
  321. return
  322. }
  323. sw.Logger.Info("Error reconnecting to peer. Trying again", "tries", i, "err", err, "addr", addr)
  324. // sleep a set amount
  325. sw.randomSleep(reconnectInterval)
  326. continue
  327. }
  328. sw.Logger.Error("Failed to reconnect to peer. Beginning exponential backoff",
  329. "addr", addr, "elapsed", time.Since(start))
  330. for i := 0; i < reconnectBackOffAttempts; i++ {
  331. if !sw.IsRunning() {
  332. return
  333. }
  334. // sleep an exponentially increasing amount
  335. sleepIntervalSeconds := math.Pow(reconnectBackOffBaseSeconds, float64(i))
  336. sw.randomSleep(time.Duration(sleepIntervalSeconds) * time.Second)
  337. err := sw.DialPeerWithAddress(addr)
  338. if err == nil {
  339. return // success
  340. } else if _, ok := err.(ErrCurrentlyDialingOrExistingAddress); ok {
  341. return
  342. }
  343. sw.Logger.Info("Error reconnecting to peer. Trying again", "tries", i, "err", err, "addr", addr)
  344. }
  345. sw.Logger.Error("Failed to reconnect to peer. Giving up", "addr", addr, "elapsed", time.Since(start))
  346. }
  347. // SetAddrBook allows to set address book on Switch.
  348. func (sw *Switch) SetAddrBook(addrBook AddrBook) {
  349. sw.addrBook = addrBook
  350. }
  351. // MarkPeerAsGood marks the given peer as good when it did something useful
  352. // like contributed to consensus.
  353. func (sw *Switch) MarkPeerAsGood(peer Peer) {
  354. if sw.addrBook != nil {
  355. sw.addrBook.MarkGood(peer.ID())
  356. }
  357. }
  358. //---------------------------------------------------------------------
  359. // Dialing
  360. type privateAddr interface {
  361. PrivateAddr() bool
  362. }
  363. func isPrivateAddr(err error) bool {
  364. te, ok := errors.Cause(err).(privateAddr)
  365. return ok && te.PrivateAddr()
  366. }
  367. // DialPeersAsync dials a list of peers asynchronously in random order.
  368. // Used to dial peers from config on startup or from unsafe-RPC (trusted sources).
  369. // It ignores ErrNetAddressLookup. However, if there are other errors, first
  370. // encounter is returned.
  371. // Nop if there are no peers.
  372. func (sw *Switch) DialPeersAsync(peers []string) error {
  373. netAddrs, errs := NewNetAddressStrings(peers)
  374. // report all the errors
  375. for _, err := range errs {
  376. sw.Logger.Error("Error in peer's address", "err", err)
  377. }
  378. // return first non-ErrNetAddressLookup error
  379. for _, err := range errs {
  380. if _, ok := err.(ErrNetAddressLookup); ok {
  381. continue
  382. }
  383. return err
  384. }
  385. sw.dialPeersAsync(netAddrs)
  386. return nil
  387. }
  388. func (sw *Switch) dialPeersAsync(netAddrs []*NetAddress) {
  389. ourAddr := sw.NetAddress()
  390. // TODO: this code feels like it's in the wrong place.
  391. // The integration tests depend on the addrBook being saved
  392. // right away but maybe we can change that. Recall that
  393. // the addrBook is only written to disk every 2min
  394. if sw.addrBook != nil {
  395. // add peers to `addrBook`
  396. for _, netAddr := range netAddrs {
  397. // do not add our address or ID
  398. if !netAddr.Same(ourAddr) {
  399. if err := sw.addrBook.AddAddress(netAddr, ourAddr); err != nil {
  400. if isPrivateAddr(err) {
  401. sw.Logger.Debug("Won't add peer's address to addrbook", "err", err)
  402. } else {
  403. sw.Logger.Error("Can't add peer's address to addrbook", "err", err)
  404. }
  405. }
  406. }
  407. }
  408. // Persist some peers to disk right away.
  409. // NOTE: integration tests depend on this
  410. sw.addrBook.Save()
  411. }
  412. // permute the list, dial them in random order.
  413. perm := sw.rng.Perm(len(netAddrs))
  414. for i := 0; i < len(perm); i++ {
  415. go func(i int) {
  416. j := perm[i]
  417. addr := netAddrs[j]
  418. if addr.Same(ourAddr) {
  419. sw.Logger.Debug("Ignore attempt to connect to ourselves", "addr", addr, "ourAddr", ourAddr)
  420. return
  421. }
  422. sw.randomSleep(0)
  423. err := sw.DialPeerWithAddress(addr)
  424. if err != nil {
  425. switch err.(type) {
  426. case ErrSwitchConnectToSelf, ErrSwitchDuplicatePeerID, ErrCurrentlyDialingOrExistingAddress:
  427. sw.Logger.Debug("Error dialing peer", "err", err)
  428. default:
  429. sw.Logger.Error("Error dialing peer", "err", err)
  430. }
  431. }
  432. }(i)
  433. }
  434. }
  435. // DialPeerWithAddress dials the given peer and runs sw.addPeer if it connects
  436. // and authenticates successfully.
  437. // If we're currently dialing this address or it belongs to an existing peer,
  438. // ErrCurrentlyDialingOrExistingAddress is returned.
  439. func (sw *Switch) DialPeerWithAddress(addr *NetAddress) error {
  440. if sw.IsDialingOrExistingAddress(addr) {
  441. return ErrCurrentlyDialingOrExistingAddress{addr.String()}
  442. }
  443. sw.dialing.Set(string(addr.ID), addr)
  444. defer sw.dialing.Delete(string(addr.ID))
  445. return sw.addOutboundPeerWithConfig(addr, sw.config)
  446. }
  447. // sleep for interval plus some random amount of ms on [0, dialRandomizerIntervalMilliseconds]
  448. func (sw *Switch) randomSleep(interval time.Duration) {
  449. r := time.Duration(sw.rng.Int63n(dialRandomizerIntervalMilliseconds)) * time.Millisecond
  450. time.Sleep(r + interval)
  451. }
  452. // IsDialingOrExistingAddress returns true if switch has a peer with the given
  453. // address or dialing it at the moment.
  454. func (sw *Switch) IsDialingOrExistingAddress(addr *NetAddress) bool {
  455. return sw.dialing.Has(string(addr.ID)) ||
  456. sw.peers.Has(addr.ID) ||
  457. (!sw.config.AllowDuplicateIP && sw.peers.HasIP(addr.IP))
  458. }
  459. // AddPersistentPeers allows you to set persistent peers. It ignores
  460. // ErrNetAddressLookup. However, if there are other errors, first encounter is
  461. // returned.
  462. func (sw *Switch) AddPersistentPeers(addrs []string) error {
  463. sw.Logger.Info("Adding persistent peers", "addrs", addrs)
  464. netAddrs, errs := NewNetAddressStrings(addrs)
  465. // report all the errors
  466. for _, err := range errs {
  467. sw.Logger.Error("Error in peer's address", "err", err)
  468. }
  469. // return first non-ErrNetAddressLookup error
  470. for _, err := range errs {
  471. if _, ok := err.(ErrNetAddressLookup); ok {
  472. continue
  473. }
  474. return err
  475. }
  476. sw.persistentPeersAddrs = netAddrs
  477. return nil
  478. }
  479. func (sw *Switch) isPeerPersistentFn() func(*NetAddress) bool {
  480. return func(na *NetAddress) bool {
  481. for _, pa := range sw.persistentPeersAddrs {
  482. if pa.Equals(na) {
  483. return true
  484. }
  485. }
  486. return false
  487. }
  488. }
  489. func (sw *Switch) acceptRoutine() {
  490. for {
  491. p, err := sw.transport.Accept(peerConfig{
  492. chDescs: sw.chDescs,
  493. onPeerError: sw.StopPeerForError,
  494. reactorsByCh: sw.reactorsByCh,
  495. metrics: sw.metrics,
  496. isPersistent: sw.isPeerPersistentFn(),
  497. })
  498. if err != nil {
  499. switch err := err.(type) {
  500. case ErrRejected:
  501. if err.IsSelf() {
  502. // Remove the given address from the address book and add to our addresses
  503. // to avoid dialing in the future.
  504. addr := err.Addr()
  505. sw.addrBook.RemoveAddress(&addr)
  506. sw.addrBook.AddOurAddress(&addr)
  507. }
  508. sw.Logger.Info(
  509. "Inbound Peer rejected",
  510. "err", err,
  511. "numPeers", sw.peers.Size(),
  512. )
  513. continue
  514. case ErrFilterTimeout:
  515. sw.Logger.Error(
  516. "Peer filter timed out",
  517. "err", err,
  518. )
  519. continue
  520. case ErrTransportClosed:
  521. sw.Logger.Error(
  522. "Stopped accept routine, as transport is closed",
  523. "numPeers", sw.peers.Size(),
  524. )
  525. default:
  526. sw.Logger.Error(
  527. "Accept on transport errored",
  528. "err", err,
  529. "numPeers", sw.peers.Size(),
  530. )
  531. // We could instead have a retry loop around the acceptRoutine,
  532. // but that would need to stop and let the node shutdown eventually.
  533. // So might as well panic and let process managers restart the node.
  534. // There's no point in letting the node run without the acceptRoutine,
  535. // since it won't be able to accept new connections.
  536. panic(fmt.Errorf("accept routine exited: %v", err))
  537. }
  538. break
  539. }
  540. // Ignore connection if we already have enough peers.
  541. _, in, _ := sw.NumPeers()
  542. if in >= sw.config.MaxNumInboundPeers {
  543. sw.Logger.Info(
  544. "Ignoring inbound connection: already have enough inbound peers",
  545. "address", p.SocketAddr(),
  546. "have", in,
  547. "max", sw.config.MaxNumInboundPeers,
  548. )
  549. sw.transport.Cleanup(p)
  550. continue
  551. }
  552. if err := sw.addPeer(p); err != nil {
  553. sw.transport.Cleanup(p)
  554. if p.IsRunning() {
  555. _ = p.Stop()
  556. }
  557. sw.Logger.Info(
  558. "Ignoring inbound connection: error while adding peer",
  559. "err", err,
  560. "id", p.ID(),
  561. )
  562. }
  563. }
  564. }
  565. // dial the peer; make secret connection; authenticate against the dialed ID;
  566. // add the peer.
  567. // if dialing fails, start the reconnect loop. If handshake fails, it's over.
  568. // If peer is started successfully, reconnectLoop will start when
  569. // StopPeerForError is called.
  570. func (sw *Switch) addOutboundPeerWithConfig(
  571. addr *NetAddress,
  572. cfg *config.P2PConfig,
  573. ) error {
  574. sw.Logger.Info("Dialing peer", "address", addr)
  575. // XXX(xla): Remove the leakage of test concerns in implementation.
  576. if cfg.TestDialFail {
  577. go sw.reconnectToPeer(addr)
  578. return fmt.Errorf("dial err (peerConfig.DialFail == true)")
  579. }
  580. p, err := sw.transport.Dial(*addr, peerConfig{
  581. chDescs: sw.chDescs,
  582. onPeerError: sw.StopPeerForError,
  583. isPersistent: sw.isPeerPersistentFn(),
  584. reactorsByCh: sw.reactorsByCh,
  585. metrics: sw.metrics,
  586. })
  587. if err != nil {
  588. if e, ok := err.(ErrRejected); ok {
  589. if e.IsSelf() {
  590. // Remove the given address from the address book and add to our addresses
  591. // to avoid dialing in the future.
  592. sw.addrBook.RemoveAddress(addr)
  593. sw.addrBook.AddOurAddress(addr)
  594. return err
  595. }
  596. }
  597. // retry persistent peers after
  598. // any dial error besides IsSelf()
  599. if sw.isPeerPersistentFn()(addr) {
  600. go sw.reconnectToPeer(addr)
  601. }
  602. return err
  603. }
  604. if err := sw.addPeer(p); err != nil {
  605. sw.transport.Cleanup(p)
  606. if p.IsRunning() {
  607. _ = p.Stop()
  608. }
  609. return err
  610. }
  611. return nil
  612. }
  613. func (sw *Switch) filterPeer(p Peer) error {
  614. // Avoid duplicate
  615. if sw.peers.Has(p.ID()) {
  616. return ErrRejected{id: p.ID(), isDuplicate: true}
  617. }
  618. errc := make(chan error, len(sw.peerFilters))
  619. for _, f := range sw.peerFilters {
  620. go func(f PeerFilterFunc, p Peer, errc chan<- error) {
  621. errc <- f(sw.peers, p)
  622. }(f, p, errc)
  623. }
  624. for i := 0; i < cap(errc); i++ {
  625. select {
  626. case err := <-errc:
  627. if err != nil {
  628. return ErrRejected{id: p.ID(), err: err, isFiltered: true}
  629. }
  630. case <-time.After(sw.filterTimeout):
  631. return ErrFilterTimeout{}
  632. }
  633. }
  634. return nil
  635. }
  636. // addPeer starts up the Peer and adds it to the Switch. Error is returned if
  637. // the peer is filtered out or failed to start or can't be added.
  638. func (sw *Switch) addPeer(p Peer) error {
  639. if err := sw.filterPeer(p); err != nil {
  640. return err
  641. }
  642. p.SetLogger(sw.Logger.With("peer", p.SocketAddr()))
  643. // Handle the shut down case where the switch has stopped but we're
  644. // concurrently trying to add a peer.
  645. if !sw.IsRunning() {
  646. // XXX should this return an error or just log and terminate?
  647. sw.Logger.Error("Won't start a peer - switch is not running", "peer", p)
  648. return nil
  649. }
  650. // Add some data to the peer, which is required by reactors.
  651. for _, reactor := range sw.reactors {
  652. p = reactor.InitPeer(p)
  653. }
  654. // Start the peer's send/recv routines.
  655. // Must start it before adding it to the peer set
  656. // to prevent Start and Stop from being called concurrently.
  657. err := p.Start()
  658. if err != nil {
  659. // Should never happen
  660. sw.Logger.Error("Error starting peer", "err", err, "peer", p)
  661. return err
  662. }
  663. // Add the peer to PeerSet. Do this before starting the reactors
  664. // so that if Receive errors, we will find the peer and remove it.
  665. // Add should not err since we already checked peers.Has().
  666. if err := sw.peers.Add(p); err != nil {
  667. return err
  668. }
  669. sw.metrics.Peers.Add(float64(1))
  670. // Start all the reactor protocols on the peer.
  671. for _, reactor := range sw.reactors {
  672. reactor.AddPeer(p)
  673. }
  674. sw.Logger.Info("Added peer", "peer", p)
  675. return nil
  676. }