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