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