node_test.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492
  1. // Copyright 2015 The go-ethereum Authors
  2. // This file is part of the go-ethereum library.
  3. //
  4. // The go-ethereum library is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU Lesser General Public License as published by
  6. // the Free Software Foundation, either version 3 of the License, or
  7. // (at your option) any later version.
  8. //
  9. // The go-ethereum library is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. // GNU Lesser General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU Lesser General Public License
  15. // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
  16. package node
  17. import (
  18. "errors"
  19. "io/ioutil"
  20. "os"
  21. "testing"
  22. "github.com/ethereum/go-ethereum/crypto"
  23. "github.com/ethereum/go-ethereum/p2p"
  24. )
  25. var (
  26. testNodeKey, _ = crypto.GenerateKey()
  27. testNodeConfig = &Config{
  28. PrivateKey: testNodeKey,
  29. Name: "test node",
  30. }
  31. )
  32. // Tests that an empty protocol stack can be started, restarted and stopped.
  33. func TestNodeLifeCycle(t *testing.T) {
  34. stack, err := New(testNodeConfig)
  35. if err != nil {
  36. t.Fatalf("failed to create protocol stack: %v", err)
  37. }
  38. // Ensure that a stopped node can be stopped again
  39. for i := 0; i < 3; i++ {
  40. if err := stack.Stop(); err != ErrNodeStopped {
  41. t.Fatalf("iter %d: stop failure mismatch: have %v, want %v", i, err, ErrNodeStopped)
  42. }
  43. }
  44. // Ensure that a node can be successfully started, but only once
  45. if err := stack.Start(); err != nil {
  46. t.Fatalf("failed to start node: %v", err)
  47. }
  48. if err := stack.Start(); err != ErrNodeRunning {
  49. t.Fatalf("start failure mismatch: have %v, want %v ", err, ErrNodeRunning)
  50. }
  51. // Ensure that a node can be restarted arbitrarily many times
  52. for i := 0; i < 3; i++ {
  53. if err := stack.Restart(); err != nil {
  54. t.Fatalf("iter %d: failed to restart node: %v", i, err)
  55. }
  56. }
  57. // Ensure that a node can be stopped, but only once
  58. if err := stack.Stop(); err != nil {
  59. t.Fatalf("failed to stop node: %v", err)
  60. }
  61. if err := stack.Stop(); err != ErrNodeStopped {
  62. t.Fatalf("stop failure mismatch: have %v, want %v ", err, ErrNodeStopped)
  63. }
  64. }
  65. // Tests that if the data dir is already in use, an appropriate error is returned.
  66. func TestNodeUsedDataDir(t *testing.T) {
  67. // Create a temporary folder to use as the data directory
  68. dir, err := ioutil.TempDir("", "")
  69. if err != nil {
  70. t.Fatalf("failed to create temporary data directory: %v", err)
  71. }
  72. defer os.RemoveAll(dir)
  73. // Create a new node based on the data directory
  74. original, err := New(&Config{DataDir: dir})
  75. if err != nil {
  76. t.Fatalf("failed to create original protocol stack: %v", err)
  77. }
  78. if err := original.Start(); err != nil {
  79. t.Fatalf("failed to start original protocol stack: %v", err)
  80. }
  81. defer original.Stop()
  82. // Create a second node based on the same data directory and ensure failure
  83. duplicate, err := New(&Config{DataDir: dir})
  84. if err != nil {
  85. t.Fatalf("failed to create duplicate protocol stack: %v", err)
  86. }
  87. if err := duplicate.Start(); err != ErrDatadirUsed {
  88. t.Fatalf("duplicate datadir failure mismatch: have %v, want %v", err, ErrDatadirUsed)
  89. }
  90. }
  91. // NoopService is a trivial implementation of the Service interface.
  92. type NoopService struct{}
  93. func (s *NoopService) Protocols() []p2p.Protocol { return nil }
  94. func (s *NoopService) Start() error { return nil }
  95. func (s *NoopService) Stop() error { return nil }
  96. func NewNoopService(*ServiceContext) (Service, error) { return new(NoopService), nil }
  97. // Tests whether services can be registered and unregistered.
  98. func TestServiceRegistry(t *testing.T) {
  99. stack, err := New(testNodeConfig)
  100. if err != nil {
  101. t.Fatalf("failed to create protocol stack: %v", err)
  102. }
  103. // Create a batch of dummy services and ensure they don't exist
  104. ids := []string{"A", "B", "C"}
  105. for i, id := range ids {
  106. if err := stack.Unregister(id); err != ErrServiceUnknown {
  107. t.Fatalf("service %d: pre-unregistration failure mismatch: have %v, want %v", i, err, ErrServiceUnknown)
  108. }
  109. }
  110. // Register the services, checking that the operation succeeds only once
  111. for i, id := range ids {
  112. if err := stack.Register(id, NewNoopService); err != nil {
  113. t.Fatalf("service %d: registration failed: %v", i, err)
  114. }
  115. if err := stack.Register(id, NewNoopService); err != ErrServiceRegistered {
  116. t.Fatalf("service %d: registration failure mismatch: have %v, want %v", i, err, ErrServiceRegistered)
  117. }
  118. }
  119. // Unregister the services, checking that the operation succeeds only once
  120. for i, id := range ids {
  121. if err := stack.Unregister(id); err != nil {
  122. t.Fatalf("service %d: unregistration failed: %v", i, err)
  123. }
  124. if err := stack.Unregister(id); err != ErrServiceUnknown {
  125. t.Fatalf("service %d: unregistration failure mismatch: have %v, want %v", i, err, ErrServiceUnknown)
  126. }
  127. }
  128. }
  129. // InstrumentedService is an implementation of Service for which all interface
  130. // methods can be instrumented both return value as well as event hook wise.
  131. type InstrumentedService struct {
  132. protocols []p2p.Protocol
  133. start error
  134. stop error
  135. protocolsHook func()
  136. startHook func()
  137. stopHook func()
  138. }
  139. func (s *InstrumentedService) Protocols() []p2p.Protocol {
  140. if s.protocolsHook != nil {
  141. s.protocolsHook()
  142. }
  143. return s.protocols
  144. }
  145. func (s *InstrumentedService) Start() error {
  146. if s.startHook != nil {
  147. s.startHook()
  148. }
  149. return s.start
  150. }
  151. func (s *InstrumentedService) Stop() error {
  152. if s.stopHook != nil {
  153. s.stopHook()
  154. }
  155. return s.stop
  156. }
  157. // Tests that registered services get started and stopped correctly.
  158. func TestServiceLifeCycle(t *testing.T) {
  159. stack, err := New(testNodeConfig)
  160. if err != nil {
  161. t.Fatalf("failed to create protocol stack: %v", err)
  162. }
  163. // Register a batch of life-cycle instrumented services
  164. ids := []string{"A", "B", "C"}
  165. started := make(map[string]bool)
  166. stopped := make(map[string]bool)
  167. for i, id := range ids {
  168. id := id // Closure for the constructor
  169. constructor := func(*ServiceContext) (Service, error) {
  170. return &InstrumentedService{
  171. startHook: func() { started[id] = true },
  172. stopHook: func() { stopped[id] = true },
  173. }, nil
  174. }
  175. if err := stack.Register(id, constructor); err != nil {
  176. t.Fatalf("service %d: registration failed: %v", i, err)
  177. }
  178. }
  179. // Start the node and check that all services are running
  180. if err := stack.Start(); err != nil {
  181. t.Fatalf("failed to start protocol stack: %v", err)
  182. }
  183. for i, id := range ids {
  184. if !started[id] {
  185. t.Fatalf("service %d: freshly started service not running", i)
  186. }
  187. if stopped[id] {
  188. t.Fatalf("service %d: freshly started service already stopped", i)
  189. }
  190. if stack.Service(id) == nil {
  191. t.Fatalf("service %d: freshly started service unaccessible", i)
  192. }
  193. }
  194. // Stop the node and check that all services have been stopped
  195. if err := stack.Stop(); err != nil {
  196. t.Fatalf("failed to stop protocol stack: %v", err)
  197. }
  198. for i, id := range ids {
  199. if !stopped[id] {
  200. t.Fatalf("service %d: freshly terminated service still running", i)
  201. }
  202. if service := stack.Service(id); service != nil {
  203. t.Fatalf("service %d: freshly terminated service still accessible: %v", i, service)
  204. }
  205. }
  206. }
  207. // Tests that services are restarted cleanly as new instances.
  208. func TestServiceRestarts(t *testing.T) {
  209. stack, err := New(testNodeConfig)
  210. if err != nil {
  211. t.Fatalf("failed to create protocol stack: %v", err)
  212. }
  213. // Define a service that does not support restarts
  214. var (
  215. running bool
  216. started int
  217. )
  218. constructor := func(*ServiceContext) (Service, error) {
  219. running = false
  220. return &InstrumentedService{
  221. startHook: func() {
  222. if running {
  223. panic("already running")
  224. }
  225. running = true
  226. started++
  227. },
  228. }, nil
  229. }
  230. // Register the service and start the protocol stack
  231. if err := stack.Register("service", constructor); err != nil {
  232. t.Fatalf("failed to register the service: %v", err)
  233. }
  234. if err := stack.Start(); err != nil {
  235. t.Fatalf("failed to start protocol stack: %v", err)
  236. }
  237. defer stack.Stop()
  238. if running != true || started != 1 {
  239. t.Fatalf("running/started mismatch: have %v/%d, want true/1", running, started)
  240. }
  241. // Restart the stack a few times and check successful service restarts
  242. for i := 0; i < 3; i++ {
  243. if err := stack.Restart(); err != nil {
  244. t.Fatalf("iter %d: failed to restart stack: %v", i, err)
  245. }
  246. }
  247. if running != true || started != 4 {
  248. t.Fatalf("running/started mismatch: have %v/%d, want true/4", running, started)
  249. }
  250. }
  251. // Tests that if a service fails to initialize itself, none of the other services
  252. // will be allowed to even start.
  253. func TestServiceConstructionAbortion(t *testing.T) {
  254. stack, err := New(testNodeConfig)
  255. if err != nil {
  256. t.Fatalf("failed to create protocol stack: %v", err)
  257. }
  258. // Define a batch of good services
  259. ids := []string{"A", "B", "C", "D", "E", "F"}
  260. started := make(map[string]bool)
  261. for i, id := range ids {
  262. id := id // Closure for the constructor
  263. constructor := func(*ServiceContext) (Service, error) {
  264. return &InstrumentedService{
  265. startHook: func() { started[id] = true },
  266. }, nil
  267. }
  268. if err := stack.Register(id, constructor); err != nil {
  269. t.Fatalf("service %d: registration failed: %v", i, err)
  270. }
  271. }
  272. // Register a service that fails to construct itself
  273. failure := errors.New("fail")
  274. failer := func(*ServiceContext) (Service, error) {
  275. return nil, failure
  276. }
  277. if err := stack.Register("failer", failer); err != nil {
  278. t.Fatalf("failer registration failed: %v", err)
  279. }
  280. // Start the protocol stack and ensure none of the services get started
  281. for i := 0; i < 100; i++ {
  282. if err := stack.Start(); err != failure {
  283. t.Fatalf("iter %d: stack startup failure mismatch: have %v, want %v", i, err, failure)
  284. }
  285. for i, id := range ids {
  286. if started[id] {
  287. t.Fatalf("service %d: started should not have", i)
  288. }
  289. delete(started, id)
  290. }
  291. }
  292. }
  293. // Tests that if a service fails to start, all others started before it will be
  294. // shut down.
  295. func TestServiceStartupAbortion(t *testing.T) {
  296. stack, err := New(testNodeConfig)
  297. if err != nil {
  298. t.Fatalf("failed to create protocol stack: %v", err)
  299. }
  300. // Register a batch of good services
  301. ids := []string{"A", "B", "C", "D", "E", "F"}
  302. started := make(map[string]bool)
  303. stopped := make(map[string]bool)
  304. for i, id := range ids {
  305. id := id // Closure for the constructor
  306. constructor := func(*ServiceContext) (Service, error) {
  307. return &InstrumentedService{
  308. startHook: func() { started[id] = true },
  309. stopHook: func() { stopped[id] = true },
  310. }, nil
  311. }
  312. if err := stack.Register(id, constructor); err != nil {
  313. t.Fatalf("service %d: registration failed: %v", i, err)
  314. }
  315. }
  316. // Register a service that fails to start
  317. failure := errors.New("fail")
  318. failer := func(*ServiceContext) (Service, error) {
  319. return &InstrumentedService{
  320. start: failure,
  321. }, nil
  322. }
  323. if err := stack.Register("failer", failer); err != nil {
  324. t.Fatalf("failer registration failed: %v", err)
  325. }
  326. // Start the protocol stack and ensure all started services stop
  327. for i := 0; i < 100; i++ {
  328. if err := stack.Start(); err != failure {
  329. t.Fatalf("iter %d: stack startup failure mismatch: have %v, want %v", i, err, failure)
  330. }
  331. for i, id := range ids {
  332. if started[id] && !stopped[id] {
  333. t.Fatalf("service %d: started but not stopped", i)
  334. }
  335. delete(started, id)
  336. delete(stopped, id)
  337. }
  338. }
  339. }
  340. // Tests that even if a registered service fails to shut down cleanly, it does
  341. // not influece the rest of the shutdown invocations.
  342. func TestServiceTerminationGuarantee(t *testing.T) {
  343. stack, err := New(testNodeConfig)
  344. if err != nil {
  345. t.Fatalf("failed to create protocol stack: %v", err)
  346. }
  347. // Register a batch of good services
  348. ids := []string{"A", "B", "C", "D", "E", "F"}
  349. started := make(map[string]bool)
  350. stopped := make(map[string]bool)
  351. for i, id := range ids {
  352. id := id // Closure for the constructor
  353. constructor := func(*ServiceContext) (Service, error) {
  354. return &InstrumentedService{
  355. startHook: func() { started[id] = true },
  356. stopHook: func() { stopped[id] = true },
  357. }, nil
  358. }
  359. if err := stack.Register(id, constructor); err != nil {
  360. t.Fatalf("service %d: registration failed: %v", i, err)
  361. }
  362. }
  363. // Register a service that fails to shot down cleanly
  364. failure := errors.New("fail")
  365. failer := func(*ServiceContext) (Service, error) {
  366. return &InstrumentedService{
  367. stop: failure,
  368. }, nil
  369. }
  370. if err := stack.Register("failer", failer); err != nil {
  371. t.Fatalf("failer registration failed: %v", err)
  372. }
  373. // Start the protocol stack, and ensure that a failing shut down terminates all
  374. for i := 0; i < 100; i++ {
  375. // Start the stack and make sure all is online
  376. if err := stack.Start(); err != nil {
  377. t.Fatalf("iter %d: failed to start protocol stack: %v", i, err)
  378. }
  379. for j, id := range ids {
  380. if !started[id] {
  381. t.Fatalf("iter %d, service %d: service not running", i, j)
  382. }
  383. if stopped[id] {
  384. t.Fatalf("iter %d, service %d: service already stopped", i, j)
  385. }
  386. }
  387. // Stop the stack, verify failure and check all terminations
  388. err := stack.Stop()
  389. if err, ok := err.(*StopError); !ok {
  390. t.Fatalf("iter %d: termination failure mismatch: have %v, want StopError", i, err)
  391. } else {
  392. if err.Services["failer"] != failure {
  393. t.Fatalf("iter %d: failer termination failure mismatch: have %v, want %v", i, err.Services["failer"], failure)
  394. }
  395. if len(err.Services) != 1 {
  396. t.Fatalf("iter %d: failure count mismatch: have %d, want %d", i, len(err.Services), 1)
  397. }
  398. }
  399. for j, id := range ids {
  400. if !stopped[id] {
  401. t.Fatalf("iter %d, service %d: service not terminated", i, j)
  402. }
  403. delete(started, id)
  404. delete(stopped, id)
  405. }
  406. }
  407. }
  408. // Tests that all protocols defined by individual services get launched.
  409. func TestProtocolGather(t *testing.T) {
  410. stack, err := New(testNodeConfig)
  411. if err != nil {
  412. t.Fatalf("failed to create protocol stack: %v", err)
  413. }
  414. // Register a batch of services with some configured number of protocols
  415. services := map[string]int{
  416. "Zero Protocols": 0,
  417. "Single Protocol": 1,
  418. "Many Protocols": 25,
  419. }
  420. for id, count := range services {
  421. protocols := make([]p2p.Protocol, count)
  422. for i := 0; i < len(protocols); i++ {
  423. protocols[i].Name = id
  424. protocols[i].Version = uint(i)
  425. }
  426. constructor := func(*ServiceContext) (Service, error) {
  427. return &InstrumentedService{
  428. protocols: protocols,
  429. }, nil
  430. }
  431. if err := stack.Register(id, constructor); err != nil {
  432. t.Fatalf("service %s: registration failed: %v", id, err)
  433. }
  434. }
  435. // Start the services and ensure all protocols start successfully
  436. if err := stack.Start(); err != nil {
  437. t.Fatalf("failed to start protocol stack: %v", err)
  438. }
  439. defer stack.Stop()
  440. protocols := stack.Server().Protocols
  441. if len(protocols) != 26 {
  442. t.Fatalf("mismatching number of protocols launched: have %d, want %d", len(protocols), 26)
  443. }
  444. for id, count := range services {
  445. for ver := 0; ver < count; ver++ {
  446. launched := false
  447. for i := 0; i < len(protocols); i++ {
  448. if protocols[i].Name == id && protocols[i].Version == uint(ver) {
  449. launched = true
  450. break
  451. }
  452. }
  453. if !launched {
  454. t.Errorf("configured protocol not launched: %s v%d", id, ver)
  455. }
  456. }
  457. }
  458. }