github.com/tuotoo/go-ethereum@v1.7.4-0.20171121184211-049797d40a24/p2p/simulations/adapters/docker.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  	"errors"
    21  	"fmt"
    22  	"io"
    23  	"io/ioutil"
    24  	"os"
    25  	"os/exec"
    26  	"path/filepath"
    27  	"runtime"
    28  	"strings"
    29  
    30  	"github.com/docker/docker/pkg/reexec"
    31  	"github.com/ethereum/go-ethereum/node"
    32  	"github.com/ethereum/go-ethereum/p2p/discover"
    33  )
    34  
    35  // DockerAdapter is a NodeAdapter which runs simulation nodes inside Docker
    36  // containers.
    37  //
    38  // A Docker image is built which contains the current binary at /bin/p2p-node
    39  // which when executed runs the underlying service (see the description
    40  // of the execP2PNode function for more details)
    41  type DockerAdapter struct {
    42  	ExecAdapter
    43  }
    44  
    45  // NewDockerAdapter builds the p2p-node Docker image containing the current
    46  // binary and returns a DockerAdapter
    47  func NewDockerAdapter() (*DockerAdapter, error) {
    48  	// Since Docker containers run on Linux and this adapter runs the
    49  	// current binary in the container, it must be compiled for Linux.
    50  	//
    51  	// It is reasonable to require this because the caller can just
    52  	// compile the current binary in a Docker container.
    53  	if runtime.GOOS != "linux" {
    54  		return nil, errors.New("DockerAdapter can only be used on Linux as it uses the current binary (which must be a Linux binary)")
    55  	}
    56  
    57  	if err := buildDockerImage(); err != nil {
    58  		return nil, err
    59  	}
    60  
    61  	return &DockerAdapter{
    62  		ExecAdapter{
    63  			nodes: make(map[discover.NodeID]*ExecNode),
    64  		},
    65  	}, nil
    66  }
    67  
    68  // Name returns the name of the adapter for logging purposes
    69  func (d *DockerAdapter) Name() string {
    70  	return "docker-adapter"
    71  }
    72  
    73  // NewNode returns a new DockerNode using the given config
    74  func (d *DockerAdapter) NewNode(config *NodeConfig) (Node, error) {
    75  	if len(config.Services) == 0 {
    76  		return nil, errors.New("node must have at least one service")
    77  	}
    78  	for _, service := range config.Services {
    79  		if _, exists := serviceFuncs[service]; !exists {
    80  			return nil, fmt.Errorf("unknown node service %q", service)
    81  		}
    82  	}
    83  
    84  	// generate the config
    85  	conf := &execNodeConfig{
    86  		Stack: node.DefaultConfig,
    87  		Node:  config,
    88  	}
    89  	conf.Stack.DataDir = "/data"
    90  	conf.Stack.WSHost = "0.0.0.0"
    91  	conf.Stack.WSOrigins = []string{"*"}
    92  	conf.Stack.WSExposeAll = true
    93  	conf.Stack.P2P.EnableMsgEvents = false
    94  	conf.Stack.P2P.NoDiscovery = true
    95  	conf.Stack.P2P.NAT = nil
    96  	conf.Stack.NoUSB = true
    97  
    98  	node := &DockerNode{
    99  		ExecNode: ExecNode{
   100  			ID:      config.ID,
   101  			Config:  conf,
   102  			adapter: &d.ExecAdapter,
   103  		},
   104  	}
   105  	node.newCmd = node.dockerCommand
   106  	d.ExecAdapter.nodes[node.ID] = &node.ExecNode
   107  	return node, nil
   108  }
   109  
   110  // DockerNode wraps an ExecNode but exec's the current binary in a docker
   111  // container rather than locally
   112  type DockerNode struct {
   113  	ExecNode
   114  }
   115  
   116  // dockerCommand returns a command which exec's the binary in a Docker
   117  // container.
   118  //
   119  // It uses a shell so that we can pass the _P2P_NODE_CONFIG environment
   120  // variable to the container using the --env flag.
   121  func (n *DockerNode) dockerCommand() *exec.Cmd {
   122  	return exec.Command(
   123  		"sh", "-c",
   124  		fmt.Sprintf(
   125  			`exec docker run --interactive --env _P2P_NODE_CONFIG="${_P2P_NODE_CONFIG}" %s p2p-node %s %s`,
   126  			dockerImage, strings.Join(n.Config.Node.Services, ","), n.ID.String(),
   127  		),
   128  	)
   129  }
   130  
   131  // dockerImage is the name of the Docker image which gets built to run the
   132  // simulation node
   133  const dockerImage = "p2p-node"
   134  
   135  // buildDockerImage builds the Docker image which is used to run the simulation
   136  // node in a Docker container.
   137  //
   138  // It adds the current binary as "p2p-node" so that it runs execP2PNode
   139  // when executed.
   140  func buildDockerImage() error {
   141  	// create a directory to use as the build context
   142  	dir, err := ioutil.TempDir("", "p2p-docker")
   143  	if err != nil {
   144  		return err
   145  	}
   146  	defer os.RemoveAll(dir)
   147  
   148  	// copy the current binary into the build context
   149  	bin, err := os.Open(reexec.Self())
   150  	if err != nil {
   151  		return err
   152  	}
   153  	defer bin.Close()
   154  	dst, err := os.OpenFile(filepath.Join(dir, "self.bin"), os.O_WRONLY|os.O_CREATE, 0755)
   155  	if err != nil {
   156  		return err
   157  	}
   158  	defer dst.Close()
   159  	if _, err := io.Copy(dst, bin); err != nil {
   160  		return err
   161  	}
   162  
   163  	// create the Dockerfile
   164  	dockerfile := []byte(`
   165  FROM ubuntu:16.04
   166  RUN mkdir /data
   167  ADD self.bin /bin/p2p-node
   168  	`)
   169  	if err := ioutil.WriteFile(filepath.Join(dir, "Dockerfile"), dockerfile, 0644); err != nil {
   170  		return err
   171  	}
   172  
   173  	// run 'docker build'
   174  	cmd := exec.Command("docker", "build", "-t", dockerImage, dir)
   175  	cmd.Stdout = os.Stdout
   176  	cmd.Stderr = os.Stderr
   177  	if err := cmd.Run(); err != nil {
   178  		return fmt.Errorf("error building docker image: %s", err)
   179  	}
   180  
   181  	return nil
   182  }