github.com/bcskill/bcschain/v3@v3.4.9-beta2/p2p/simulations/adapters/exec.go (about)

     1  // Copyright 2017 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 adapters
    18  
    19  import (
    20  	"bufio"
    21  	"context"
    22  	"crypto/ecdsa"
    23  	"encoding/json"
    24  	"errors"
    25  	"fmt"
    26  	"io"
    27  	"net"
    28  	"os"
    29  	"os/exec"
    30  	"os/signal"
    31  	"path/filepath"
    32  	"regexp"
    33  	"strings"
    34  	"sync"
    35  	"syscall"
    36  	"time"
    37  
    38  	"github.com/docker/docker/pkg/reexec"
    39  	"github.com/bcskill/bcschain/v3/log"
    40  	"github.com/bcskill/bcschain/v3/node"
    41  	"github.com/bcskill/bcschain/v3/p2p"
    42  	"github.com/bcskill/bcschain/v3/p2p/discover"
    43  	"github.com/bcskill/bcschain/v3/rpc"
    44  	"github.com/gorilla/websocket"
    45  )
    46  
    47  // ExecAdapter is a NodeAdapter which runs simulation nodes by executing the
    48  // current binary as a child process.
    49  //
    50  // An init hook is used so that the child process executes the node services
    51  // (rather than whataver the main() function would normally do), see the
    52  // execP2PNode function for more information.
    53  type ExecAdapter struct {
    54  	// BaseDir is the directory under which the data directories for each
    55  	// simulation node are created.
    56  	BaseDir string
    57  
    58  	nodes map[discover.NodeID]*ExecNode
    59  }
    60  
    61  // NewExecAdapter returns an ExecAdapter which stores node data in
    62  // subdirectories of the given base directory
    63  func NewExecAdapter(baseDir string) *ExecAdapter {
    64  	return &ExecAdapter{
    65  		BaseDir: baseDir,
    66  		nodes:   make(map[discover.NodeID]*ExecNode),
    67  	}
    68  }
    69  
    70  // Name returns the name of the adapter for logging purposes
    71  func (e *ExecAdapter) Name() string {
    72  	return "exec-adapter"
    73  }
    74  
    75  // NewNode returns a new ExecNode using the given config
    76  func (e *ExecAdapter) NewNode(config *NodeConfig) (Node, error) {
    77  	if len(config.Services) == 0 {
    78  		return nil, errors.New("node must have at least one service")
    79  	}
    80  	for _, service := range config.Services {
    81  		if _, exists := serviceFuncs[service]; !exists {
    82  			return nil, fmt.Errorf("unknown node service %q", service)
    83  		}
    84  	}
    85  
    86  	// create the node directory using the first 12 characters of the ID
    87  	// as Unix socket paths cannot be longer than 256 characters
    88  	dir := filepath.Join(e.BaseDir, config.ID.String()[:12])
    89  	if err := os.Mkdir(dir, 0755); err != nil {
    90  		return nil, fmt.Errorf("error creating node directory: %s", err)
    91  	}
    92  
    93  	// generate the config
    94  	conf := &execNodeConfig{
    95  		Stack: node.DefaultConfig,
    96  		Node:  config,
    97  	}
    98  	conf.Stack.DataDir = filepath.Join(dir, "data")
    99  	conf.Stack.WSHost = "127.0.0.1"
   100  	conf.Stack.WSPort = 0
   101  	conf.Stack.WSOrigins = []string{"*"}
   102  	conf.Stack.WSExposeAll = true
   103  	conf.Stack.P2P.EnableMsgEvents = false
   104  	conf.Stack.P2P.NoDiscovery = true
   105  	conf.Stack.P2P.NAT = nil
   106  	conf.Stack.NoUSB = true
   107  
   108  	// listen on a random localhost port (we'll get the actual port after
   109  	// starting the node through the RPC admin.nodeInfo method)
   110  	conf.Stack.P2P.ListenAddr = "127.0.0.1:0"
   111  
   112  	node := &ExecNode{
   113  		ID:      config.ID,
   114  		Dir:     dir,
   115  		Config:  conf,
   116  		adapter: e,
   117  	}
   118  	node.newCmd = node.execCommand
   119  	e.nodes[node.ID] = node
   120  	return node, nil
   121  }
   122  
   123  // ExecNode starts a simulation node by exec'ing the current binary and
   124  // running the configured services
   125  type ExecNode struct {
   126  	ID     discover.NodeID
   127  	Dir    string
   128  	Config *execNodeConfig
   129  	Cmd    *exec.Cmd
   130  	Info   *p2p.NodeInfo
   131  
   132  	adapter *ExecAdapter
   133  	client  *rpc.Client
   134  	wsAddr  string
   135  	newCmd  func() *exec.Cmd
   136  	key     *ecdsa.PrivateKey
   137  }
   138  
   139  // Addr returns the node's enode URL
   140  func (n *ExecNode) Addr() []byte {
   141  	if n.Info == nil {
   142  		return nil
   143  	}
   144  	return []byte(n.Info.Enode)
   145  }
   146  
   147  // Client returns an rpc.Client which can be used to communicate with the
   148  // underlying services (it is set once the node has started)
   149  func (n *ExecNode) Client() (*rpc.Client, error) {
   150  	return n.client, nil
   151  }
   152  
   153  // wsAddrPattern is a regex used to read the WebSocket address from the node's
   154  // log
   155  var wsAddrPattern = regexp.MustCompile(`ws://[\d.:]+`)
   156  
   157  // Start exec's the node passing the ID and service as command line arguments
   158  // and the node config encoded as JSON in the _P2P_NODE_CONFIG environment
   159  // variable
   160  func (n *ExecNode) Start(snapshots map[string][]byte) (err error) {
   161  	if n.Cmd != nil {
   162  		return errors.New("already started")
   163  	}
   164  	defer func() {
   165  		if err != nil {
   166  			log.Error("node failed to start", "err", err)
   167  			n.Stop()
   168  		}
   169  	}()
   170  
   171  	// encode a copy of the config containing the snapshot
   172  	confCopy := *n.Config
   173  	confCopy.Snapshots = snapshots
   174  	confCopy.PeerAddrs = make(map[string]string)
   175  	for id, node := range n.adapter.nodes {
   176  		confCopy.PeerAddrs[id.String()] = node.wsAddr
   177  	}
   178  	confData, err := json.Marshal(confCopy)
   179  	if err != nil {
   180  		return fmt.Errorf("error generating node config: %s", err)
   181  	}
   182  
   183  	// use a pipe for stderr so we can both copy the node's stderr to
   184  	// os.Stderr and read the WebSocket address from the logs
   185  	stderrR, stderrW := io.Pipe()
   186  	stderr := io.MultiWriter(os.Stderr, stderrW)
   187  
   188  	// start the node
   189  	cmd := n.newCmd()
   190  	cmd.Stdout = os.Stdout
   191  	cmd.Stderr = stderr
   192  	cmd.Env = append(os.Environ(), fmt.Sprintf("_P2P_NODE_CONFIG=%s", confData))
   193  	if err := cmd.Start(); err != nil {
   194  		return fmt.Errorf("error starting node: %s", err)
   195  	}
   196  	n.Cmd = cmd
   197  
   198  	// read the WebSocket address from the stderr logs
   199  	var wsAddr string
   200  	wsAddrC := make(chan string)
   201  	go func() {
   202  		s := bufio.NewScanner(stderrR)
   203  		for s.Scan() {
   204  			if strings.Contains(s.Text(), "WebSocket endpoint opened:") {
   205  				wsAddrC <- wsAddrPattern.FindString(s.Text())
   206  			}
   207  		}
   208  	}()
   209  	select {
   210  	case wsAddr = <-wsAddrC:
   211  		if wsAddr == "" {
   212  			return errors.New("failed to read WebSocket address from stderr")
   213  		}
   214  	case <-time.After(10 * time.Second):
   215  		return errors.New("timed out waiting for WebSocket address on stderr")
   216  	}
   217  
   218  	// create the RPC client and load the node info
   219  	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
   220  	defer cancel()
   221  	client, err := rpc.DialWebsocket(ctx, wsAddr, "")
   222  	if err != nil {
   223  		return fmt.Errorf("error dialing rpc websocket: %s", err)
   224  	}
   225  	var info p2p.NodeInfo
   226  	if err := client.CallContext(ctx, &info, "admin_nodeInfo"); err != nil {
   227  		return fmt.Errorf("error getting node info: %s", err)
   228  	}
   229  	n.client = client
   230  	n.wsAddr = wsAddr
   231  	n.Info = &info
   232  
   233  	return nil
   234  }
   235  
   236  // execCommand returns a command which runs the node locally by exec'ing
   237  // the current binary but setting argv[0] to "p2p-node" so that the child
   238  // runs execP2PNode
   239  func (n *ExecNode) execCommand() *exec.Cmd {
   240  	return &exec.Cmd{
   241  		Path: reexec.Self(),
   242  		Args: []string{"p2p-node", strings.Join(n.Config.Node.Services, ","), n.ID.String()},
   243  	}
   244  }
   245  
   246  // Stop stops the node by first sending SIGTERM and then SIGKILL if the node
   247  // doesn't stop within 5s
   248  func (n *ExecNode) Stop() error {
   249  	if n.Cmd == nil {
   250  		return nil
   251  	}
   252  	defer func() {
   253  		n.Cmd = nil
   254  	}()
   255  
   256  	if n.client != nil {
   257  		n.client.Close()
   258  		n.client = nil
   259  		n.wsAddr = ""
   260  		n.Info = nil
   261  	}
   262  
   263  	if err := n.Cmd.Process.Signal(syscall.SIGTERM); err != nil {
   264  		return n.Cmd.Process.Kill()
   265  	}
   266  	waitErr := make(chan error)
   267  	go func() {
   268  		waitErr <- n.Cmd.Wait()
   269  	}()
   270  	select {
   271  	case err := <-waitErr:
   272  		return err
   273  	case <-time.After(5 * time.Second):
   274  		return n.Cmd.Process.Kill()
   275  	}
   276  }
   277  
   278  // NodeInfo returns information about the node
   279  func (n *ExecNode) NodeInfo() *p2p.NodeInfo {
   280  	info := &p2p.NodeInfo{
   281  		ID: n.ID.String(),
   282  	}
   283  	if n.client != nil {
   284  		n.client.Call(&info, "admin_nodeInfo")
   285  	}
   286  	return info
   287  }
   288  
   289  // ServeRPC serves RPC requests over the given connection by dialling the
   290  // node's WebSocket address and joining the two connections
   291  func (n *ExecNode) ServeRPC(clientConn *websocket.Conn) error {
   292  	conn, _, err := websocket.DefaultDialer.Dial(n.wsAddr, nil)
   293  	if err != nil {
   294  		return err
   295  	}
   296  	var wg sync.WaitGroup
   297  	wg.Add(2)
   298  	go wsCopy(&wg, conn, clientConn)
   299  	go wsCopy(&wg, clientConn, conn)
   300  	wg.Wait()
   301  	conn.Close()
   302  	return nil
   303  }
   304  
   305  func wsCopy(wg *sync.WaitGroup, src, dst *websocket.Conn) {
   306  	defer wg.Done()
   307  	for {
   308  		msgType, r, err := src.NextReader()
   309  		if err != nil {
   310  			return
   311  		}
   312  		w, err := dst.NextWriter(msgType)
   313  		if err != nil {
   314  			return
   315  		}
   316  		if _, err = io.Copy(w, r); err != nil {
   317  			return
   318  		}
   319  	}
   320  }
   321  
   322  // Snapshots creates snapshots of the services by calling the
   323  // simulation_snapshot RPC method
   324  func (n *ExecNode) Snapshots() (map[string][]byte, error) {
   325  	if n.client == nil {
   326  		return nil, errors.New("RPC not started")
   327  	}
   328  	var snapshots map[string][]byte
   329  	return snapshots, n.client.Call(&snapshots, "simulation_snapshot")
   330  }
   331  
   332  func init() {
   333  	// register a reexec function to start a devp2p node when the current
   334  	// binary is executed as "p2p-node"
   335  	reexec.Register("p2p-node", execP2PNode)
   336  }
   337  
   338  // execNodeConfig is used to serialize the node configuration so it can be
   339  // passed to the child process as a JSON encoded environment variable
   340  type execNodeConfig struct {
   341  	Stack     node.Config       `json:"stack"`
   342  	Node      *NodeConfig       `json:"node"`
   343  	Snapshots map[string][]byte `json:"snapshots,omitempty"`
   344  	PeerAddrs map[string]string `json:"peer_addrs,omitempty"`
   345  }
   346  
   347  // execP2PNode starts a devp2p node when the current binary is executed with
   348  // argv[0] being "p2p-node", reading the service / ID from argv[1] / argv[2]
   349  // and the node config from the _P2P_NODE_CONFIG environment variable
   350  func execP2PNode() {
   351  	glogger := log.NewGlogHandler(log.StreamHandler(os.Stderr, log.LogfmtFormat()))
   352  	glogger.Verbosity(log.LvlInfo)
   353  	log.Root().SetHandler(glogger)
   354  
   355  	// read the services from argv
   356  	serviceNames := strings.Split(os.Args[1], ",")
   357  
   358  	// decode the config
   359  	confEnv := os.Getenv("_P2P_NODE_CONFIG")
   360  	if confEnv == "" {
   361  		log.Crit("missing _P2P_NODE_CONFIG")
   362  	}
   363  	var conf execNodeConfig
   364  	if err := json.Unmarshal([]byte(confEnv), &conf); err != nil {
   365  		log.Crit("error decoding _P2P_NODE_CONFIG", "err", err)
   366  	}
   367  	conf.Stack.P2P.PrivateKey = conf.Node.PrivateKey
   368  	conf.Stack.Logger = log.New("node.id", conf.Node.ID.String())
   369  
   370  	// use explicit IP address in ListenAddr so that Enode URL is usable
   371  	externalIP := func() string {
   372  		addrs, err := net.InterfaceAddrs()
   373  		if err != nil {
   374  			log.Crit("error getting IP address", "err", err)
   375  		}
   376  		for _, addr := range addrs {
   377  			if ip, ok := addr.(*net.IPNet); ok && !ip.IP.IsLoopback() {
   378  				return ip.IP.String()
   379  			}
   380  		}
   381  		log.Crit("unable to determine explicit IP address")
   382  		return ""
   383  	}
   384  	if strings.HasPrefix(conf.Stack.P2P.ListenAddr, ":") {
   385  		conf.Stack.P2P.ListenAddr = externalIP() + conf.Stack.P2P.ListenAddr
   386  	}
   387  	if conf.Stack.WSHost == "0.0.0.0" {
   388  		conf.Stack.WSHost = externalIP()
   389  	}
   390  
   391  	// initialize the devp2p stack
   392  	stack, err := node.New(&conf.Stack)
   393  	if err != nil {
   394  		log.Crit("error creating node stack", "err", err)
   395  	}
   396  
   397  	// register the services, collecting them into a map so we can wrap
   398  	// them in a snapshot service
   399  	services := make(map[string]node.Service, len(serviceNames))
   400  	for _, name := range serviceNames {
   401  		serviceFunc, exists := serviceFuncs[name]
   402  		if !exists {
   403  			log.Crit("unknown node service", "name", name)
   404  		}
   405  		constructor := func(nodeCtx *node.ServiceContext) (node.Service, error) {
   406  			ctx := &ServiceContext{
   407  				RPCDialer:   &wsRPCDialer{addrs: conf.PeerAddrs},
   408  				NodeContext: nodeCtx,
   409  				Config:      conf.Node,
   410  			}
   411  			if conf.Snapshots != nil {
   412  				ctx.Snapshot = conf.Snapshots[name]
   413  			}
   414  			service, err := serviceFunc(ctx)
   415  			if err != nil {
   416  				return nil, err
   417  			}
   418  			services[name] = service
   419  			return service, nil
   420  		}
   421  		if err := stack.Register(constructor); err != nil {
   422  			log.Crit("error starting service", "name", name, "err", err)
   423  		}
   424  	}
   425  
   426  	// register the snapshot service
   427  	if err := stack.Register(func(ctx *node.ServiceContext) (node.Service, error) {
   428  		return &snapshotService{services}, nil
   429  	}); err != nil {
   430  		log.Crit("error starting snapshot service", "err", err)
   431  	}
   432  
   433  	// start the stack
   434  	if err := stack.Start(); err != nil {
   435  		log.Crit("error stating node stack", "err", err)
   436  	}
   437  
   438  	// stop the stack if we get a SIGTERM signal
   439  	go func() {
   440  		sigc := make(chan os.Signal, 1)
   441  		signal.Notify(sigc, syscall.SIGTERM)
   442  		defer signal.Stop(sigc)
   443  		<-sigc
   444  		log.Info("Received SIGTERM, shutting down...")
   445  		stack.Stop()
   446  	}()
   447  
   448  	// wait for the stack to exit
   449  	stack.Wait()
   450  }
   451  
   452  // snapshotService is a node.Service which wraps a list of services and
   453  // exposes an API to generate a snapshot of those services
   454  type snapshotService struct {
   455  	services map[string]node.Service
   456  }
   457  
   458  func (s *snapshotService) APIs() []rpc.API {
   459  	return []rpc.API{{
   460  		Namespace: "simulation",
   461  		Version:   "1.0",
   462  		Service:   SnapshotAPI{s.services},
   463  	}}
   464  }
   465  
   466  func (s *snapshotService) Protocols() []p2p.Protocol {
   467  	return nil
   468  }
   469  
   470  func (s *snapshotService) Start(*p2p.Server) error {
   471  	return nil
   472  }
   473  
   474  func (s *snapshotService) Stop() error {
   475  	return nil
   476  }
   477  
   478  // SnapshotAPI provides an RPC method to create snapshots of services
   479  type SnapshotAPI struct {
   480  	services map[string]node.Service
   481  }
   482  
   483  func (api SnapshotAPI) Snapshot() (map[string][]byte, error) {
   484  	snapshots := make(map[string][]byte)
   485  	for name, service := range api.services {
   486  		if s, ok := service.(interface {
   487  			Snapshot() ([]byte, error)
   488  		}); ok {
   489  			snap, err := s.Snapshot()
   490  			if err != nil {
   491  				return nil, err
   492  			}
   493  			snapshots[name] = snap
   494  		}
   495  	}
   496  	return snapshots, nil
   497  }
   498  
   499  type wsRPCDialer struct {
   500  	addrs map[string]string
   501  }
   502  
   503  // DialRPC implements the RPCDialer interface by creating a WebSocket RPC
   504  // client of the given node
   505  func (w *wsRPCDialer) DialRPC(id discover.NodeID) (*rpc.Client, error) {
   506  	addr, ok := w.addrs[id.String()]
   507  	if !ok {
   508  		return nil, fmt.Errorf("unknown node: %s", id)
   509  	}
   510  	return rpc.DialWebsocket(context.Background(), addr, "http://localhost")
   511  }