github.com/pfcoder/quorum@v2.0.3-0.20180501191142-d4a1b0958135+incompatible/node/node.go (about) 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 17 package node 18 19 import ( 20 "errors" 21 "fmt" 22 "net" 23 "os" 24 "path/filepath" 25 "reflect" 26 "strings" 27 "sync" 28 29 "github.com/ethereum/go-ethereum/accounts" 30 "github.com/ethereum/go-ethereum/ethdb" 31 "github.com/ethereum/go-ethereum/event" 32 "github.com/ethereum/go-ethereum/internal/debug" 33 "github.com/ethereum/go-ethereum/log" 34 "github.com/ethereum/go-ethereum/p2p" 35 "github.com/ethereum/go-ethereum/rpc" 36 "github.com/prometheus/prometheus/util/flock" 37 ) 38 39 // Node is a container on which services can be registered. 40 type Node struct { 41 eventmux *event.TypeMux // Event multiplexer used between the services of a stack 42 config *Config 43 accman *accounts.Manager 44 45 ephemeralKeystore string // if non-empty, the key directory that will be removed by Stop 46 instanceDirLock flock.Releaser // prevents concurrent use of instance directory 47 48 serverConfig p2p.Config 49 server *p2p.Server // Currently running P2P networking layer 50 51 serviceFuncs []ServiceConstructor // Service constructors (in dependency order) 52 services map[reflect.Type]Service // Currently running services 53 54 rpcAPIs []rpc.API // List of APIs currently provided by the node 55 inprocHandler *rpc.Server // In-process RPC request handler to process the API requests 56 57 ipcEndpoint string // IPC endpoint to listen at (empty = IPC disabled) 58 ipcListener net.Listener // IPC RPC listener socket to serve API requests 59 ipcHandler *rpc.Server // IPC RPC request handler to process the API requests 60 61 httpEndpoint string // HTTP endpoint (interface + port) to listen at (empty = HTTP disabled) 62 httpWhitelist []string // HTTP RPC modules to allow through this endpoint 63 httpListener net.Listener // HTTP RPC listener socket to server API requests 64 httpHandler *rpc.Server // HTTP RPC request handler to process the API requests 65 66 wsEndpoint string // Websocket endpoint (interface + port) to listen at (empty = websocket disabled) 67 wsListener net.Listener // Websocket RPC listener socket to server API requests 68 wsHandler *rpc.Server // Websocket RPC request handler to process the API requests 69 70 stop chan struct{} // Channel to wait for termination notifications 71 lock sync.RWMutex 72 } 73 74 // New creates a new P2P node, ready for protocol registration. 75 func New(conf *Config) (*Node, error) { 76 // Copy config and resolve the datadir so future changes to the current 77 // working directory don't affect the node. 78 confCopy := *conf 79 conf = &confCopy 80 if conf.DataDir != "" { 81 absdatadir, err := filepath.Abs(conf.DataDir) 82 if err != nil { 83 return nil, err 84 } 85 conf.DataDir = absdatadir 86 } 87 // Ensure that the instance name doesn't cause weird conflicts with 88 // other files in the data directory. 89 if strings.ContainsAny(conf.Name, `/\`) { 90 return nil, errors.New(`Config.Name must not contain '/' or '\'`) 91 } 92 if conf.Name == datadirDefaultKeyStore { 93 return nil, errors.New(`Config.Name cannot be "` + datadirDefaultKeyStore + `"`) 94 } 95 if strings.HasSuffix(conf.Name, ".ipc") { 96 return nil, errors.New(`Config.Name cannot end in ".ipc"`) 97 } 98 // Ensure that the AccountManager method works before the node has started. 99 // We rely on this in cmd/geth. 100 am, ephemeralKeystore, err := makeAccountManager(conf) 101 if err != nil { 102 return nil, err 103 } 104 // Note: any interaction with Config that would create/touch files 105 // in the data directory or instance directory is delayed until Start. 106 return &Node{ 107 accman: am, 108 ephemeralKeystore: ephemeralKeystore, 109 config: conf, 110 serviceFuncs: []ServiceConstructor{}, 111 ipcEndpoint: conf.IPCEndpoint(), 112 httpEndpoint: conf.HTTPEndpoint(), 113 wsEndpoint: conf.WSEndpoint(), 114 eventmux: new(event.TypeMux), 115 }, nil 116 } 117 118 // Register injects a new service into the node's stack. The service created by 119 // the passed constructor must be unique in its type with regard to sibling ones. 120 func (n *Node) Register(constructor ServiceConstructor) error { 121 n.lock.Lock() 122 defer n.lock.Unlock() 123 124 if n.server != nil { 125 return ErrNodeRunning 126 } 127 n.serviceFuncs = append(n.serviceFuncs, constructor) 128 return nil 129 } 130 131 // Start create a live P2P node and starts running it. 132 func (n *Node) Start() error { 133 n.lock.Lock() 134 defer n.lock.Unlock() 135 136 // Short circuit if the node's already running 137 if n.server != nil { 138 return ErrNodeRunning 139 } 140 if err := n.openDataDir(); err != nil { 141 return err 142 } 143 144 // Initialize the p2p server. This creates the node key and 145 // discovery databases. 146 n.config.P2P.PrivateKey = n.config.NodeKey() 147 n.serverConfig = n.config.P2P 148 n.serverConfig.Name = n.config.NodeName() 149 if n.serverConfig.StaticNodes == nil { 150 n.serverConfig.StaticNodes = n.config.StaticNodes() 151 } 152 if n.serverConfig.TrustedNodes == nil { 153 n.serverConfig.TrustedNodes = n.config.TrustedNodes() 154 } 155 if n.serverConfig.NodeDatabase == "" { 156 n.serverConfig.NodeDatabase = n.config.NodeDB() 157 } 158 n.serverConfig.EnableNodePermission = n.config.EnableNodePermission 159 n.serverConfig.DataDir = n.config.DataDir 160 running := &p2p.Server{Config: n.serverConfig} 161 log.Info("Starting peer-to-peer node", "instance", n.serverConfig.Name) 162 163 // Otherwise copy and specialize the P2P configuration 164 services := make(map[reflect.Type]Service) 165 for _, constructor := range n.serviceFuncs { 166 // Create a new context for the particular service 167 ctx := &ServiceContext{ 168 config: n.config, 169 services: make(map[reflect.Type]Service), 170 EventMux: n.eventmux, 171 AccountManager: n.accman, 172 } 173 for kind, s := range services { // copy needed for threaded access 174 ctx.services[kind] = s 175 } 176 // Construct and save the service 177 service, err := constructor(ctx) 178 if err != nil { 179 return err 180 } 181 kind := reflect.TypeOf(service) 182 if _, exists := services[kind]; exists { 183 return &DuplicateServiceError{Kind: kind} 184 } 185 services[kind] = service 186 } 187 // Gather the protocols and start the freshly assembled P2P server 188 for _, service := range services { 189 running.Protocols = append(running.Protocols, service.Protocols()...) 190 } 191 if err := running.Start(); err != nil { 192 return convertFileLockError(err) 193 } 194 // Start each of the services 195 started := []reflect.Type{} 196 for kind, service := range services { 197 // Start the next service, stopping all previous upon failure 198 if err := service.Start(running); err != nil { 199 for _, kind := range started { 200 services[kind].Stop() 201 } 202 running.Stop() 203 204 return err 205 } 206 // Mark the service started for potential cleanup 207 started = append(started, kind) 208 } 209 // Lastly start the configured RPC interfaces 210 if err := n.startRPC(services); err != nil { 211 for _, service := range services { 212 service.Stop() 213 } 214 running.Stop() 215 return err 216 } 217 // Finish initializing the startup 218 n.services = services 219 n.server = running 220 n.stop = make(chan struct{}) 221 222 return nil 223 } 224 225 func (n *Node) openDataDir() error { 226 if n.config.DataDir == "" { 227 return nil // ephemeral 228 } 229 230 instdir := filepath.Join(n.config.DataDir, n.config.name()) 231 if err := os.MkdirAll(instdir, 0700); err != nil { 232 return err 233 } 234 // Lock the instance directory to prevent concurrent use by another instance as well as 235 // accidental use of the instance directory as a database. 236 release, _, err := flock.New(filepath.Join(instdir, "LOCK")) 237 if err != nil { 238 return convertFileLockError(err) 239 } 240 n.instanceDirLock = release 241 return nil 242 } 243 244 // startRPC is a helper method to start all the various RPC endpoint during node 245 // startup. It's not meant to be called at any time afterwards as it makes certain 246 // assumptions about the state of the node. 247 func (n *Node) startRPC(services map[reflect.Type]Service) error { 248 // Gather all the possible APIs to surface 249 apis := n.apis() 250 for _, service := range services { 251 apis = append(apis, service.APIs()...) 252 } 253 // Start the various API endpoints, terminating all in case of errors 254 if err := n.startInProc(apis); err != nil { 255 return err 256 } 257 if err := n.startIPC(apis); err != nil { 258 n.stopInProc() 259 return err 260 } 261 if err := n.startHTTP(n.httpEndpoint, apis, n.config.HTTPModules, n.config.HTTPCors); err != nil { 262 n.stopIPC() 263 n.stopInProc() 264 return err 265 } 266 if err := n.startWS(n.wsEndpoint, apis, n.config.WSModules, n.config.WSOrigins, n.config.WSExposeAll); err != nil { 267 n.stopHTTP() 268 n.stopIPC() 269 n.stopInProc() 270 return err 271 } 272 // All API endpoints started successfully 273 n.rpcAPIs = apis 274 return nil 275 } 276 277 // startInProc initializes an in-process RPC endpoint. 278 func (n *Node) startInProc(apis []rpc.API) error { 279 // Register all the APIs exposed by the services 280 handler := rpc.NewServer() 281 for _, api := range apis { 282 if err := handler.RegisterName(api.Namespace, api.Service); err != nil { 283 return err 284 } 285 log.Debug(fmt.Sprintf("InProc registered %T under '%s'", api.Service, api.Namespace)) 286 } 287 n.inprocHandler = handler 288 return nil 289 } 290 291 // stopInProc terminates the in-process RPC endpoint. 292 func (n *Node) stopInProc() { 293 if n.inprocHandler != nil { 294 n.inprocHandler.Stop() 295 n.inprocHandler = nil 296 } 297 } 298 299 // startIPC initializes and starts the IPC RPC endpoint. 300 func (n *Node) startIPC(apis []rpc.API) error { 301 // Short circuit if the IPC endpoint isn't being exposed 302 if n.ipcEndpoint == "" { 303 return nil 304 } 305 // Register all the APIs exposed by the services 306 handler := rpc.NewServer() 307 for _, api := range apis { 308 if err := handler.RegisterName(api.Namespace, api.Service); err != nil { 309 return err 310 } 311 log.Debug(fmt.Sprintf("IPC registered %T under '%s'", api.Service, api.Namespace)) 312 } 313 // All APIs registered, start the IPC listener 314 var ( 315 listener net.Listener 316 err error 317 ) 318 if listener, err = rpc.CreateIPCListener(n.ipcEndpoint); err != nil { 319 return err 320 } 321 go func() { 322 log.Info(fmt.Sprintf("IPC endpoint opened: %s", n.ipcEndpoint)) 323 324 for { 325 conn, err := listener.Accept() 326 if err != nil { 327 // Terminate if the listener was closed 328 n.lock.RLock() 329 closed := n.ipcListener == nil 330 n.lock.RUnlock() 331 if closed { 332 return 333 } 334 // Not closed, just some error; report and continue 335 log.Error(fmt.Sprintf("IPC accept failed: %v", err)) 336 continue 337 } 338 go handler.ServeCodec(rpc.NewJSONCodec(conn), rpc.OptionMethodInvocation|rpc.OptionSubscriptions) 339 } 340 }() 341 // All listeners booted successfully 342 n.ipcListener = listener 343 n.ipcHandler = handler 344 345 return nil 346 } 347 348 // stopIPC terminates the IPC RPC endpoint. 349 func (n *Node) stopIPC() { 350 if n.ipcListener != nil { 351 n.ipcListener.Close() 352 n.ipcListener = nil 353 354 log.Info(fmt.Sprintf("IPC endpoint closed: %s", n.ipcEndpoint)) 355 } 356 if n.ipcHandler != nil { 357 n.ipcHandler.Stop() 358 n.ipcHandler = nil 359 } 360 } 361 362 // startHTTP initializes and starts the HTTP RPC endpoint. 363 func (n *Node) startHTTP(endpoint string, apis []rpc.API, modules []string, cors []string) error { 364 // Short circuit if the HTTP endpoint isn't being exposed 365 if endpoint == "" { 366 return nil 367 } 368 // Generate the whitelist based on the allowed modules 369 whitelist := make(map[string]bool) 370 for _, module := range modules { 371 whitelist[module] = true 372 } 373 // Register all the APIs exposed by the services 374 handler := rpc.NewServer() 375 for _, api := range apis { 376 if whitelist[api.Namespace] || (len(whitelist) == 0 && api.Public) { 377 if err := handler.RegisterName(api.Namespace, api.Service); err != nil { 378 return err 379 } 380 log.Debug(fmt.Sprintf("HTTP registered %T under '%s'", api.Service, api.Namespace)) 381 } 382 } 383 // All APIs registered, start the HTTP listener 384 var ( 385 listener net.Listener 386 err error 387 ) 388 if listener, err = net.Listen("tcp", endpoint); err != nil { 389 return err 390 } 391 go rpc.NewHTTPServer(cors, handler).Serve(listener) 392 log.Info(fmt.Sprintf("HTTP endpoint opened: http://%s", endpoint)) 393 394 // All listeners booted successfully 395 n.httpEndpoint = endpoint 396 n.httpListener = listener 397 n.httpHandler = handler 398 399 return nil 400 } 401 402 // stopHTTP terminates the HTTP RPC endpoint. 403 func (n *Node) stopHTTP() { 404 if n.httpListener != nil { 405 n.httpListener.Close() 406 n.httpListener = nil 407 408 log.Info(fmt.Sprintf("HTTP endpoint closed: http://%s", n.httpEndpoint)) 409 } 410 if n.httpHandler != nil { 411 n.httpHandler.Stop() 412 n.httpHandler = nil 413 } 414 } 415 416 // startWS initializes and starts the websocket RPC endpoint. 417 func (n *Node) startWS(endpoint string, apis []rpc.API, modules []string, wsOrigins []string, exposeAll bool) error { 418 // Short circuit if the WS endpoint isn't being exposed 419 if endpoint == "" { 420 return nil 421 } 422 // Generate the whitelist based on the allowed modules 423 whitelist := make(map[string]bool) 424 for _, module := range modules { 425 whitelist[module] = true 426 } 427 // Register all the APIs exposed by the services 428 handler := rpc.NewServer() 429 for _, api := range apis { 430 if exposeAll || whitelist[api.Namespace] || (len(whitelist) == 0 && api.Public) { 431 if err := handler.RegisterName(api.Namespace, api.Service); err != nil { 432 return err 433 } 434 log.Debug(fmt.Sprintf("WebSocket registered %T under '%s'", api.Service, api.Namespace)) 435 } 436 } 437 // All APIs registered, start the HTTP listener 438 var ( 439 listener net.Listener 440 err error 441 ) 442 if listener, err = net.Listen("tcp", endpoint); err != nil { 443 return err 444 } 445 go rpc.NewWSServer(wsOrigins, handler).Serve(listener) 446 log.Info(fmt.Sprintf("WebSocket endpoint opened: ws://%s", listener.Addr())) 447 448 // All listeners booted successfully 449 n.wsEndpoint = endpoint 450 n.wsListener = listener 451 n.wsHandler = handler 452 453 return nil 454 } 455 456 // stopWS terminates the websocket RPC endpoint. 457 func (n *Node) stopWS() { 458 if n.wsListener != nil { 459 n.wsListener.Close() 460 n.wsListener = nil 461 462 log.Info(fmt.Sprintf("WebSocket endpoint closed: ws://%s", n.wsEndpoint)) 463 } 464 if n.wsHandler != nil { 465 n.wsHandler.Stop() 466 n.wsHandler = nil 467 } 468 } 469 470 // Stop terminates a running node along with all it's services. In the node was 471 // not started, an error is returned. 472 func (n *Node) Stop() error { 473 n.lock.Lock() 474 defer n.lock.Unlock() 475 476 // Short circuit if the node's not running 477 if n.server == nil { 478 return ErrNodeStopped 479 } 480 481 // Terminate the API, services and the p2p server. 482 n.stopWS() 483 n.stopHTTP() 484 n.stopIPC() 485 n.rpcAPIs = nil 486 failure := &StopError{ 487 Services: make(map[reflect.Type]error), 488 } 489 for kind, service := range n.services { 490 if err := service.Stop(); err != nil { 491 failure.Services[kind] = err 492 } 493 } 494 n.server.Stop() 495 n.services = nil 496 n.server = nil 497 498 // Release instance directory lock. 499 if n.instanceDirLock != nil { 500 if err := n.instanceDirLock.Release(); err != nil { 501 log.Error("Can't release datadir lock", "err", err) 502 } 503 n.instanceDirLock = nil 504 } 505 506 // unblock n.Wait 507 close(n.stop) 508 509 // Remove the keystore if it was created ephemerally. 510 var keystoreErr error 511 if n.ephemeralKeystore != "" { 512 keystoreErr = os.RemoveAll(n.ephemeralKeystore) 513 } 514 515 if len(failure.Services) > 0 { 516 return failure 517 } 518 if keystoreErr != nil { 519 return keystoreErr 520 } 521 return nil 522 } 523 524 // Wait blocks the thread until the node is stopped. If the node is not running 525 // at the time of invocation, the method immediately returns. 526 func (n *Node) Wait() { 527 n.lock.RLock() 528 if n.server == nil { 529 n.lock.RUnlock() 530 return 531 } 532 stop := n.stop 533 n.lock.RUnlock() 534 535 <-stop 536 } 537 538 // Restart terminates a running node and boots up a new one in its place. If the 539 // node isn't running, an error is returned. 540 func (n *Node) Restart() error { 541 if err := n.Stop(); err != nil { 542 return err 543 } 544 if err := n.Start(); err != nil { 545 return err 546 } 547 return nil 548 } 549 550 // Attach creates an RPC client attached to an in-process API handler. 551 func (n *Node) Attach() (*rpc.Client, error) { 552 n.lock.RLock() 553 defer n.lock.RUnlock() 554 555 if n.server == nil { 556 return nil, ErrNodeStopped 557 } 558 return rpc.DialInProc(n.inprocHandler), nil 559 } 560 561 // RPCHandler returns the in-process RPC request handler. 562 func (n *Node) RPCHandler() (*rpc.Server, error) { 563 n.lock.RLock() 564 defer n.lock.RUnlock() 565 566 if n.inprocHandler == nil { 567 return nil, ErrNodeStopped 568 } 569 return n.inprocHandler, nil 570 } 571 572 // Server retrieves the currently running P2P network layer. This method is meant 573 // only to inspect fields of the currently running server, life cycle management 574 // should be left to this Node entity. 575 func (n *Node) Server() *p2p.Server { 576 n.lock.RLock() 577 defer n.lock.RUnlock() 578 579 return n.server 580 } 581 582 // Service retrieves a currently running service registered of a specific type. 583 func (n *Node) Service(service interface{}) error { 584 n.lock.RLock() 585 defer n.lock.RUnlock() 586 587 // Short circuit if the node's not running 588 if n.server == nil { 589 return ErrNodeStopped 590 } 591 // Otherwise try to find the service to return 592 element := reflect.ValueOf(service).Elem() 593 if running, ok := n.services[element.Type()]; ok { 594 element.Set(reflect.ValueOf(running)) 595 return nil 596 } 597 return ErrServiceUnknown 598 } 599 600 // DataDir retrieves the current datadir used by the protocol stack. 601 // Deprecated: No files should be stored in this directory, use InstanceDir instead. 602 func (n *Node) DataDir() string { 603 return n.config.DataDir 604 } 605 606 // InstanceDir retrieves the instance directory used by the protocol stack. 607 func (n *Node) InstanceDir() string { 608 return n.config.instanceDir() 609 } 610 611 // AccountManager retrieves the account manager used by the protocol stack. 612 func (n *Node) AccountManager() *accounts.Manager { 613 return n.accman 614 } 615 616 // IPCEndpoint retrieves the current IPC endpoint used by the protocol stack. 617 func (n *Node) IPCEndpoint() string { 618 return n.ipcEndpoint 619 } 620 621 // HTTPEndpoint retrieves the current HTTP endpoint used by the protocol stack. 622 func (n *Node) HTTPEndpoint() string { 623 return n.httpEndpoint 624 } 625 626 // WSEndpoint retrieves the current WS endpoint used by the protocol stack. 627 func (n *Node) WSEndpoint() string { 628 return n.wsEndpoint 629 } 630 631 // EventMux retrieves the event multiplexer used by all the network services in 632 // the current protocol stack. 633 func (n *Node) EventMux() *event.TypeMux { 634 return n.eventmux 635 } 636 637 // OpenDatabase opens an existing database with the given name (or creates one if no 638 // previous can be found) from within the node's instance directory. If the node is 639 // ephemeral, a memory database is returned. 640 func (n *Node) OpenDatabase(name string, cache, handles int) (ethdb.Database, error) { 641 if n.config.DataDir == "" { 642 return ethdb.NewMemDatabase() 643 } 644 return ethdb.NewLDBDatabase(n.config.resolvePath(name), cache, handles) 645 } 646 647 // ResolvePath returns the absolute path of a resource in the instance directory. 648 func (n *Node) ResolvePath(x string) string { 649 return n.config.resolvePath(x) 650 } 651 652 // apis returns the collection of RPC descriptors this node offers. 653 func (n *Node) apis() []rpc.API { 654 return []rpc.API{ 655 { 656 Namespace: "admin", 657 Version: "1.0", 658 Service: NewPrivateAdminAPI(n), 659 }, { 660 Namespace: "admin", 661 Version: "1.0", 662 Service: NewPublicAdminAPI(n), 663 Public: true, 664 }, { 665 Namespace: "debug", 666 Version: "1.0", 667 Service: debug.Handler, 668 }, { 669 Namespace: "debug", 670 Version: "1.0", 671 Service: NewPublicDebugAPI(n), 672 Public: true, 673 }, { 674 Namespace: "web3", 675 Version: "1.0", 676 Service: NewPublicWeb3API(n), 677 Public: true, 678 }, 679 } 680 }