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.

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