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.

779 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: 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. // Validate the reactor.
  127. // No two reactors can share the same channel.
  128. reactorChannels := reactor.GetChannels()
  129. for _, chDesc := range reactorChannels {
  130. chID := chDesc.ID
  131. if sw.reactorsByCh[chID] != nil {
  132. panic(fmt.Sprintf("Channel %X has multiple reactors %v & %v", chID, sw.reactorsByCh[chID], reactor))
  133. }
  134. sw.chDescs = append(sw.chDescs, chDesc)
  135. sw.reactorsByCh[chID] = reactor
  136. }
  137. sw.reactors[name] = reactor
  138. reactor.SetSwitch(sw)
  139. return reactor
  140. }
  141. // Reactors returns a map of reactors registered on the switch.
  142. // NOTE: Not goroutine safe.
  143. func (sw *Switch) Reactors() map[string]Reactor {
  144. return sw.reactors
  145. }
  146. // Reactor returns the reactor with the given name.
  147. // NOTE: Not goroutine safe.
  148. func (sw *Switch) Reactor(name string) Reactor {
  149. return sw.reactors[name]
  150. }
  151. // SetNodeInfo sets the switch's NodeInfo for checking compatibility and handshaking with other nodes.
  152. // NOTE: Not goroutine safe.
  153. func (sw *Switch) SetNodeInfo(nodeInfo NodeInfo) {
  154. sw.nodeInfo = nodeInfo
  155. }
  156. // NodeInfo returns the switch's NodeInfo.
  157. // NOTE: Not goroutine safe.
  158. func (sw *Switch) NodeInfo() NodeInfo {
  159. return sw.nodeInfo
  160. }
  161. // SetNodeKey sets the switch's private key for authenticated encryption.
  162. // NOTE: Not goroutine safe.
  163. func (sw *Switch) SetNodeKey(nodeKey *NodeKey) {
  164. sw.nodeKey = nodeKey
  165. }
  166. //---------------------------------------------------------------------
  167. // Service start/stop
  168. // OnStart implements BaseService. It starts all the reactors and peers.
  169. func (sw *Switch) OnStart() error {
  170. // Start reactors
  171. for _, reactor := range sw.reactors {
  172. err := reactor.Start()
  173. if err != nil {
  174. return cmn.ErrorWrap(err, "failed to start %v", reactor)
  175. }
  176. }
  177. // Start accepting Peers.
  178. go sw.acceptRoutine()
  179. return nil
  180. }
  181. // OnStop implements BaseService. It stops all peers and reactors.
  182. func (sw *Switch) OnStop() {
  183. // Stop peers
  184. for _, p := range sw.peers.List() {
  185. sw.transport.Cleanup(p)
  186. p.Stop()
  187. if sw.peers.Remove(p) {
  188. sw.metrics.Peers.Add(float64(-1))
  189. }
  190. }
  191. // Stop reactors
  192. sw.Logger.Debug("Switch: Stopping reactors")
  193. for _, reactor := range sw.reactors {
  194. reactor.Stop()
  195. }
  196. }
  197. //---------------------------------------------------------------------
  198. // Peers
  199. // Broadcast runs a go routine for each attempted send, which will block trying
  200. // to send for defaultSendTimeoutSeconds. Returns a channel which receives
  201. // success values for each attempted send (false if times out). Channel will be
  202. // closed once msg bytes are sent to all peers (or time out).
  203. //
  204. // NOTE: Broadcast uses goroutines, so order of broadcast may not be preserved.
  205. func (sw *Switch) Broadcast(chID byte, msgBytes []byte) chan bool {
  206. sw.Logger.Debug("Broadcast", "channel", chID, "msgBytes", fmt.Sprintf("%X", msgBytes))
  207. peers := sw.peers.List()
  208. var wg sync.WaitGroup
  209. wg.Add(len(peers))
  210. successChan := make(chan bool, len(peers))
  211. for _, peer := range peers {
  212. go func(p Peer) {
  213. defer wg.Done()
  214. success := p.Send(chID, msgBytes)
  215. successChan <- success
  216. }(peer)
  217. }
  218. go func() {
  219. wg.Wait()
  220. close(successChan)
  221. }()
  222. return successChan
  223. }
  224. // NumPeers returns the count of outbound/inbound and outbound-dialing peers.
  225. func (sw *Switch) NumPeers() (outbound, inbound, dialing int) {
  226. peers := sw.peers.List()
  227. for _, peer := range peers {
  228. if peer.IsOutbound() {
  229. outbound++
  230. } else {
  231. inbound++
  232. }
  233. }
  234. dialing = sw.dialing.Size()
  235. return
  236. }
  237. // MaxNumOutboundPeers returns a maximum number of outbound peers.
  238. func (sw *Switch) MaxNumOutboundPeers() int {
  239. return sw.config.MaxNumOutboundPeers
  240. }
  241. // Peers returns the set of peers that are connected to the switch.
  242. func (sw *Switch) Peers() IPeerSet {
  243. return sw.peers
  244. }
  245. // StopPeerForError disconnects from a peer due to external error.
  246. // If the peer is persistent, it will attempt to reconnect.
  247. // TODO: make record depending on reason.
  248. func (sw *Switch) StopPeerForError(peer Peer, reason interface{}) {
  249. sw.Logger.Error("Stopping peer for error", "peer", peer, "err", reason)
  250. sw.stopAndRemovePeer(peer, reason)
  251. if peer.IsPersistent() {
  252. var addr *NetAddress
  253. if peer.IsOutbound() { // socket address for outbound peers
  254. addr = peer.SocketAddr()
  255. } else { // self-reported address for inbound peers
  256. var err error
  257. addr, err = peer.NodeInfo().NetAddress()
  258. if err != nil {
  259. sw.Logger.Error("Wanted to reconnect to inbound peer, but self-reported address is wrong",
  260. "peer", peer, "err", err)
  261. return
  262. }
  263. }
  264. go sw.reconnectToPeer(addr)
  265. }
  266. }
  267. // StopPeerGracefully disconnects from a peer gracefully.
  268. // TODO: handle graceful disconnects.
  269. func (sw *Switch) StopPeerGracefully(peer Peer) {
  270. sw.Logger.Info("Stopping peer gracefully")
  271. sw.stopAndRemovePeer(peer, nil)
  272. }
  273. func (sw *Switch) stopAndRemovePeer(peer Peer, reason interface{}) {
  274. sw.transport.Cleanup(peer)
  275. peer.Stop()
  276. for _, reactor := range sw.reactors {
  277. reactor.RemovePeer(peer, reason)
  278. }
  279. // Removing a peer should go last to avoid a situation where a peer
  280. // reconnect to our node and the switch calls InitPeer before
  281. // RemovePeer is finished.
  282. // https://github.com/tendermint/tendermint/issues/3338
  283. if sw.peers.Remove(peer) {
  284. sw.metrics.Peers.Add(float64(-1))
  285. }
  286. }
  287. // reconnectToPeer tries to reconnect to the addr, first repeatedly
  288. // with a fixed interval, then with exponential backoff.
  289. // If no success after all that, it stops trying, and leaves it
  290. // to the PEX/Addrbook to find the peer with the addr again
  291. // NOTE: this will keep trying even if the handshake or auth fails.
  292. // TODO: be more explicit with error types so we only retry on certain failures
  293. // - ie. if we're getting ErrDuplicatePeer we can stop
  294. // because the addrbook got us the peer back already
  295. func (sw *Switch) reconnectToPeer(addr *NetAddress) {
  296. if sw.reconnecting.Has(string(addr.ID)) {
  297. return
  298. }
  299. sw.reconnecting.Set(string(addr.ID), addr)
  300. defer sw.reconnecting.Delete(string(addr.ID))
  301. start := time.Now()
  302. sw.Logger.Info("Reconnecting to peer", "addr", addr)
  303. for i := 0; i < reconnectAttempts; i++ {
  304. if !sw.IsRunning() {
  305. return
  306. }
  307. err := sw.DialPeerWithAddress(addr)
  308. if err == nil {
  309. return // success
  310. } else if _, ok := err.(ErrCurrentlyDialingOrExistingAddress); ok {
  311. return
  312. }
  313. sw.Logger.Info("Error reconnecting to peer. Trying again", "tries", i, "err", err, "addr", addr)
  314. // sleep a set amount
  315. sw.randomSleep(reconnectInterval)
  316. continue
  317. }
  318. sw.Logger.Error("Failed to reconnect to peer. Beginning exponential backoff",
  319. "addr", addr, "elapsed", time.Since(start))
  320. for i := 0; i < reconnectBackOffAttempts; i++ {
  321. if !sw.IsRunning() {
  322. return
  323. }
  324. // sleep an exponentially increasing amount
  325. sleepIntervalSeconds := math.Pow(reconnectBackOffBaseSeconds, float64(i))
  326. sw.randomSleep(time.Duration(sleepIntervalSeconds) * time.Second)
  327. err := sw.DialPeerWithAddress(addr)
  328. if err == nil {
  329. return // success
  330. } else if _, ok := err.(ErrCurrentlyDialingOrExistingAddress); ok {
  331. return
  332. }
  333. sw.Logger.Info("Error reconnecting to peer. Trying again", "tries", i, "err", err, "addr", addr)
  334. }
  335. sw.Logger.Error("Failed to reconnect to peer. Giving up", "addr", addr, "elapsed", time.Since(start))
  336. }
  337. // SetAddrBook allows to set address book on Switch.
  338. func (sw *Switch) SetAddrBook(addrBook AddrBook) {
  339. sw.addrBook = addrBook
  340. }
  341. // MarkPeerAsGood marks the given peer as good when it did something useful
  342. // like contributed to consensus.
  343. func (sw *Switch) MarkPeerAsGood(peer Peer) {
  344. if sw.addrBook != nil {
  345. sw.addrBook.MarkGood(peer.ID())
  346. }
  347. }
  348. //---------------------------------------------------------------------
  349. // Dialing
  350. type privateAddr interface {
  351. PrivateAddr() bool
  352. }
  353. func isPrivateAddr(err error) bool {
  354. te, ok := errors.Cause(err).(privateAddr)
  355. return ok && te.PrivateAddr()
  356. }
  357. // DialPeersAsync dials a list of peers asynchronously in random order.
  358. // Used to dial peers from config on startup or from unsafe-RPC (trusted sources).
  359. // It ignores ErrNetAddressLookup. However, if there are other errors, first
  360. // encounter is returned.
  361. // Nop if there are no peers.
  362. func (sw *Switch) DialPeersAsync(peers []string) error {
  363. netAddrs, errs := NewNetAddressStrings(peers)
  364. // report all the errors
  365. for _, err := range errs {
  366. sw.Logger.Error("Error in peer's address", "err", err)
  367. }
  368. // return first non-ErrNetAddressLookup error
  369. for _, err := range errs {
  370. if _, ok := err.(ErrNetAddressLookup); ok {
  371. continue
  372. }
  373. return err
  374. }
  375. sw.dialPeersAsync(netAddrs)
  376. return nil
  377. }
  378. func (sw *Switch) dialPeersAsync(netAddrs []*NetAddress) {
  379. ourAddr := sw.NetAddress()
  380. // TODO: this code feels like it's in the wrong place.
  381. // The integration tests depend on the addrBook being saved
  382. // right away but maybe we can change that. Recall that
  383. // the addrBook is only written to disk every 2min
  384. if sw.addrBook != nil {
  385. // add peers to `addrBook`
  386. for _, netAddr := range netAddrs {
  387. // do not add our address or ID
  388. if !netAddr.Same(ourAddr) {
  389. if err := sw.addrBook.AddAddress(netAddr, ourAddr); err != nil {
  390. if isPrivateAddr(err) {
  391. sw.Logger.Debug("Won't add peer's address to addrbook", "err", err)
  392. } else {
  393. sw.Logger.Error("Can't add peer's address to addrbook", "err", err)
  394. }
  395. }
  396. }
  397. }
  398. // Persist some peers to disk right away.
  399. // NOTE: integration tests depend on this
  400. sw.addrBook.Save()
  401. }
  402. // permute the list, dial them in random order.
  403. perm := sw.rng.Perm(len(netAddrs))
  404. for i := 0; i < len(perm); i++ {
  405. go func(i int) {
  406. j := perm[i]
  407. addr := netAddrs[j]
  408. if addr.Same(ourAddr) {
  409. sw.Logger.Debug("Ignore attempt to connect to ourselves", "addr", addr, "ourAddr", ourAddr)
  410. return
  411. }
  412. sw.randomSleep(0)
  413. err := sw.DialPeerWithAddress(addr)
  414. if err != nil {
  415. switch err.(type) {
  416. case ErrSwitchConnectToSelf, ErrSwitchDuplicatePeerID, ErrCurrentlyDialingOrExistingAddress:
  417. sw.Logger.Debug("Error dialing peer", "err", err)
  418. default:
  419. sw.Logger.Error("Error dialing peer", "err", err)
  420. }
  421. }
  422. }(i)
  423. }
  424. }
  425. // DialPeerWithAddress dials the given peer and runs sw.addPeer if it connects
  426. // and authenticates successfully.
  427. // If we're currently dialing this address or it belongs to an existing peer,
  428. // ErrCurrentlyDialingOrExistingAddress is returned.
  429. func (sw *Switch) DialPeerWithAddress(addr *NetAddress) error {
  430. if sw.IsDialingOrExistingAddress(addr) {
  431. return ErrCurrentlyDialingOrExistingAddress{addr.String()}
  432. }
  433. sw.dialing.Set(string(addr.ID), addr)
  434. defer sw.dialing.Delete(string(addr.ID))
  435. return sw.addOutboundPeerWithConfig(addr, sw.config)
  436. }
  437. // sleep for interval plus some random amount of ms on [0, dialRandomizerIntervalMilliseconds]
  438. func (sw *Switch) randomSleep(interval time.Duration) {
  439. r := time.Duration(sw.rng.Int63n(dialRandomizerIntervalMilliseconds)) * time.Millisecond
  440. time.Sleep(r + interval)
  441. }
  442. // IsDialingOrExistingAddress returns true if switch has a peer with the given
  443. // address or dialing it at the moment.
  444. func (sw *Switch) IsDialingOrExistingAddress(addr *NetAddress) bool {
  445. return sw.dialing.Has(string(addr.ID)) ||
  446. sw.peers.Has(addr.ID) ||
  447. (!sw.config.AllowDuplicateIP && sw.peers.HasIP(addr.IP))
  448. }
  449. // AddPersistentPeers allows you to set persistent peers. It ignores
  450. // ErrNetAddressLookup. However, if there are other errors, first encounter is
  451. // returned.
  452. func (sw *Switch) AddPersistentPeers(addrs []string) error {
  453. sw.Logger.Info("Adding persistent peers", "addrs", addrs)
  454. netAddrs, errs := NewNetAddressStrings(addrs)
  455. // report all the errors
  456. for _, err := range errs {
  457. sw.Logger.Error("Error in peer's address", "err", err)
  458. }
  459. // return first non-ErrNetAddressLookup error
  460. for _, err := range errs {
  461. if _, ok := err.(ErrNetAddressLookup); ok {
  462. continue
  463. }
  464. return err
  465. }
  466. sw.persistentPeersAddrs = netAddrs
  467. return nil
  468. }
  469. func (sw *Switch) isPeerPersistentFn() func(*NetAddress) bool {
  470. return func(na *NetAddress) bool {
  471. for _, pa := range sw.persistentPeersAddrs {
  472. if pa.Equals(na) {
  473. return true
  474. }
  475. }
  476. return false
  477. }
  478. }
  479. func (sw *Switch) acceptRoutine() {
  480. for {
  481. p, err := sw.transport.Accept(peerConfig{
  482. chDescs: sw.chDescs,
  483. onPeerError: sw.StopPeerForError,
  484. reactorsByCh: sw.reactorsByCh,
  485. metrics: sw.metrics,
  486. isPersistent: sw.isPeerPersistentFn(),
  487. })
  488. if err != nil {
  489. switch err := err.(type) {
  490. case ErrRejected:
  491. if err.IsSelf() {
  492. // Remove the given address from the address book and add to our addresses
  493. // to avoid dialing in the future.
  494. addr := err.Addr()
  495. sw.addrBook.RemoveAddress(&addr)
  496. sw.addrBook.AddOurAddress(&addr)
  497. }
  498. sw.Logger.Info(
  499. "Inbound Peer rejected",
  500. "err", err,
  501. "numPeers", sw.peers.Size(),
  502. )
  503. continue
  504. case ErrFilterTimeout:
  505. sw.Logger.Error(
  506. "Peer filter timed out",
  507. "err", err,
  508. )
  509. continue
  510. case ErrTransportClosed:
  511. sw.Logger.Error(
  512. "Stopped accept routine, as transport is closed",
  513. "numPeers", sw.peers.Size(),
  514. )
  515. default:
  516. sw.Logger.Error(
  517. "Accept on transport errored",
  518. "err", err,
  519. "numPeers", sw.peers.Size(),
  520. )
  521. // We could instead have a retry loop around the acceptRoutine,
  522. // but that would need to stop and let the node shutdown eventually.
  523. // So might as well panic and let process managers restart the node.
  524. // There's no point in letting the node run without the acceptRoutine,
  525. // since it won't be able to accept new connections.
  526. panic(fmt.Errorf("accept routine exited: %v", err))
  527. }
  528. break
  529. }
  530. // Ignore connection if we already have enough peers.
  531. _, in, _ := sw.NumPeers()
  532. if in >= sw.config.MaxNumInboundPeers {
  533. sw.Logger.Info(
  534. "Ignoring inbound connection: already have enough inbound peers",
  535. "address", p.SocketAddr(),
  536. "have", in,
  537. "max", sw.config.MaxNumInboundPeers,
  538. )
  539. sw.transport.Cleanup(p)
  540. continue
  541. }
  542. if err := sw.addPeer(p); err != nil {
  543. sw.transport.Cleanup(p)
  544. if p.IsRunning() {
  545. _ = p.Stop()
  546. }
  547. sw.Logger.Info(
  548. "Ignoring inbound connection: error while adding peer",
  549. "err", err,
  550. "id", p.ID(),
  551. )
  552. }
  553. }
  554. }
  555. // dial the peer; make secret connection; authenticate against the dialed ID;
  556. // add the peer.
  557. // if dialing fails, start the reconnect loop. If handshake fails, it's over.
  558. // If peer is started successfully, reconnectLoop will start when
  559. // StopPeerForError is called.
  560. func (sw *Switch) addOutboundPeerWithConfig(
  561. addr *NetAddress,
  562. cfg *config.P2PConfig,
  563. ) error {
  564. sw.Logger.Info("Dialing peer", "address", addr)
  565. // XXX(xla): Remove the leakage of test concerns in implementation.
  566. if cfg.TestDialFail {
  567. go sw.reconnectToPeer(addr)
  568. return fmt.Errorf("dial err (peerConfig.DialFail == true)")
  569. }
  570. p, err := sw.transport.Dial(*addr, peerConfig{
  571. chDescs: sw.chDescs,
  572. onPeerError: sw.StopPeerForError,
  573. isPersistent: sw.isPeerPersistentFn(),
  574. reactorsByCh: sw.reactorsByCh,
  575. metrics: sw.metrics,
  576. })
  577. if err != nil {
  578. switch e := err.(type) {
  579. case ErrRejected:
  580. if e.IsSelf() {
  581. // Remove the given address from the address book and add to our addresses
  582. // to avoid dialing in the future.
  583. sw.addrBook.RemoveAddress(addr)
  584. sw.addrBook.AddOurAddress(addr)
  585. return err
  586. }
  587. }
  588. // retry persistent peers after
  589. // any dial error besides IsSelf()
  590. if sw.isPeerPersistentFn()(addr) {
  591. go sw.reconnectToPeer(addr)
  592. }
  593. return err
  594. }
  595. if err := sw.addPeer(p); err != nil {
  596. sw.transport.Cleanup(p)
  597. if p.IsRunning() {
  598. _ = p.Stop()
  599. }
  600. return err
  601. }
  602. return nil
  603. }
  604. func (sw *Switch) filterPeer(p Peer) error {
  605. // Avoid duplicate
  606. if sw.peers.Has(p.ID()) {
  607. return ErrRejected{id: p.ID(), isDuplicate: true}
  608. }
  609. errc := make(chan error, len(sw.peerFilters))
  610. for _, f := range sw.peerFilters {
  611. go func(f PeerFilterFunc, p Peer, errc chan<- error) {
  612. errc <- f(sw.peers, p)
  613. }(f, p, errc)
  614. }
  615. for i := 0; i < cap(errc); i++ {
  616. select {
  617. case err := <-errc:
  618. if err != nil {
  619. return ErrRejected{id: p.ID(), err: err, isFiltered: true}
  620. }
  621. case <-time.After(sw.filterTimeout):
  622. return ErrFilterTimeout{}
  623. }
  624. }
  625. return nil
  626. }
  627. // addPeer starts up the Peer and adds it to the Switch. Error is returned if
  628. // the peer is filtered out or failed to start or can't be added.
  629. func (sw *Switch) addPeer(p Peer) error {
  630. if err := sw.filterPeer(p); err != nil {
  631. return err
  632. }
  633. p.SetLogger(sw.Logger.With("peer", p.SocketAddr()))
  634. // Handle the shut down case where the switch has stopped but we're
  635. // concurrently trying to add a peer.
  636. if !sw.IsRunning() {
  637. // XXX should this return an error or just log and terminate?
  638. sw.Logger.Error("Won't start a peer - switch is not running", "peer", p)
  639. return nil
  640. }
  641. // Add some data to the peer, which is required by reactors.
  642. for _, reactor := range sw.reactors {
  643. p = reactor.InitPeer(p)
  644. }
  645. // Start the peer's send/recv routines.
  646. // Must start it before adding it to the peer set
  647. // to prevent Start and Stop from being called concurrently.
  648. err := p.Start()
  649. if err != nil {
  650. // Should never happen
  651. sw.Logger.Error("Error starting peer", "err", err, "peer", p)
  652. return err
  653. }
  654. // Add the peer to PeerSet. Do this before starting the reactors
  655. // so that if Receive errors, we will find the peer and remove it.
  656. // Add should not err since we already checked peers.Has().
  657. if err := sw.peers.Add(p); err != nil {
  658. return err
  659. }
  660. sw.metrics.Peers.Add(float64(1))
  661. // Start all the reactor protocols on the peer.
  662. for _, reactor := range sw.reactors {
  663. reactor.AddPeer(p)
  664. }
  665. sw.Logger.Info("Added peer", "peer", p)
  666. return nil
  667. }