github.com/core-coin/go-core/v2@v2.1.9/p2p/simulations/adapters/exec.go (about)

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