github.com/oskarth/go-ethereum@v1.6.8-0.20191013093314-dac24a9d3494/cmd/puppeth/module_node.go (about)

     1  // Copyright 2017 The go-ethereum Authors
     2  // This file is part of go-ethereum.
     3  //
     4  // go-ethereum is free software: you can redistribute it and/or modify
     5  // it under the terms of the GNU 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  // go-ethereum 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 General Public License for more details.
    13  //
    14  // You should have received a copy of the GNU General Public License
    15  // along with go-ethereum. If not, see <http://www.gnu.org/licenses/>.
    16  
    17  package main
    18  
    19  import (
    20  	"bytes"
    21  	"encoding/json"
    22  	"fmt"
    23  	"math/rand"
    24  	"path/filepath"
    25  	"strconv"
    26  	"strings"
    27  	"text/template"
    28  
    29  	"github.com/ethereum/go-ethereum/common"
    30  	"github.com/ethereum/go-ethereum/log"
    31  )
    32  
    33  // nodeDockerfile is the Dockerfile required to run an Ethereum node.
    34  var nodeDockerfile = `
    35  FROM ethereum/client-go:latest
    36  
    37  ADD genesis.json /genesis.json
    38  {{if .Unlock}}
    39  	ADD signer.json /signer.json
    40  	ADD signer.pass /signer.pass
    41  {{end}}
    42  RUN \
    43    echo 'geth --cache 512 init /genesis.json' > geth.sh && \{{if .Unlock}}
    44  	echo 'mkdir -p /root/.ethereum/keystore/ && cp /signer.json /root/.ethereum/keystore/' >> geth.sh && \{{end}}
    45  	echo $'exec geth --networkid {{.NetworkID}} --cache 512 --port {{.Port}} --nat extip:{{.IP}} --maxpeers {{.Peers}} {{.LightFlag}} --ethstats \'{{.Ethstats}}\' {{if .Bootnodes}}--bootnodes {{.Bootnodes}}{{end}} {{if .Etherbase}}--miner.etherbase {{.Etherbase}} --mine --miner.threads 1{{end}} {{if .Unlock}}--unlock 0 --password /signer.pass --mine{{end}} --miner.gastarget {{.GasTarget}} --miner.gaslimit {{.GasLimit}} --miner.gasprice {{.GasPrice}}' >> geth.sh
    46  
    47  ENTRYPOINT ["/bin/sh", "geth.sh"]
    48  `
    49  
    50  // nodeComposefile is the docker-compose.yml file required to deploy and maintain
    51  // an Ethereum node (bootnode or miner for now).
    52  var nodeComposefile = `
    53  version: '2'
    54  services:
    55    {{.Type}}:
    56      build: .
    57      image: {{.Network}}/{{.Type}}
    58      ports:
    59        - "{{.Port}}:{{.Port}}"
    60        - "{{.Port}}:{{.Port}}/udp"
    61      volumes:
    62        - {{.Datadir}}:/root/.ethereum{{if .Ethashdir}}
    63        - {{.Ethashdir}}:/root/.ethash{{end}}
    64      environment:
    65        - PORT={{.Port}}/tcp
    66        - TOTAL_PEERS={{.TotalPeers}}
    67        - LIGHT_PEERS={{.LightPeers}}
    68        - STATS_NAME={{.Ethstats}}
    69        - MINER_NAME={{.Etherbase}}
    70        - GAS_TARGET={{.GasTarget}}
    71        - GAS_LIMIT={{.GasLimit}}
    72        - GAS_PRICE={{.GasPrice}}
    73      logging:
    74        driver: "json-file"
    75        options:
    76          max-size: "1m"
    77          max-file: "10"
    78      restart: always
    79  `
    80  
    81  // deployNode deploys a new Ethereum node container to a remote machine via SSH,
    82  // docker and docker-compose. If an instance with the specified network name
    83  // already exists there, it will be overwritten!
    84  func deployNode(client *sshClient, network string, bootnodes []string, config *nodeInfos, nocache bool) ([]byte, error) {
    85  	kind := "sealnode"
    86  	if config.keyJSON == "" && config.etherbase == "" {
    87  		kind = "bootnode"
    88  		bootnodes = make([]string, 0)
    89  	}
    90  	// Generate the content to upload to the server
    91  	workdir := fmt.Sprintf("%d", rand.Int63())
    92  	files := make(map[string][]byte)
    93  
    94  	lightFlag := ""
    95  	if config.peersLight > 0 {
    96  		lightFlag = fmt.Sprintf("--lightpeers=%d --lightserv=50", config.peersLight)
    97  	}
    98  	dockerfile := new(bytes.Buffer)
    99  	template.Must(template.New("").Parse(nodeDockerfile)).Execute(dockerfile, map[string]interface{}{
   100  		"NetworkID": config.network,
   101  		"Port":      config.port,
   102  		"IP":        client.address,
   103  		"Peers":     config.peersTotal,
   104  		"LightFlag": lightFlag,
   105  		"Bootnodes": strings.Join(bootnodes, ","),
   106  		"Ethstats":  config.ethstats,
   107  		"Etherbase": config.etherbase,
   108  		"GasTarget": uint64(1000000 * config.gasTarget),
   109  		"GasLimit":  uint64(1000000 * config.gasLimit),
   110  		"GasPrice":  uint64(1000000000 * config.gasPrice),
   111  		"Unlock":    config.keyJSON != "",
   112  	})
   113  	files[filepath.Join(workdir, "Dockerfile")] = dockerfile.Bytes()
   114  
   115  	composefile := new(bytes.Buffer)
   116  	template.Must(template.New("").Parse(nodeComposefile)).Execute(composefile, map[string]interface{}{
   117  		"Type":       kind,
   118  		"Datadir":    config.datadir,
   119  		"Ethashdir":  config.ethashdir,
   120  		"Network":    network,
   121  		"Port":       config.port,
   122  		"TotalPeers": config.peersTotal,
   123  		"Light":      config.peersLight > 0,
   124  		"LightPeers": config.peersLight,
   125  		"Ethstats":   config.ethstats[:strings.Index(config.ethstats, ":")],
   126  		"Etherbase":  config.etherbase,
   127  		"GasTarget":  config.gasTarget,
   128  		"GasLimit":   config.gasLimit,
   129  		"GasPrice":   config.gasPrice,
   130  	})
   131  	files[filepath.Join(workdir, "docker-compose.yaml")] = composefile.Bytes()
   132  
   133  	files[filepath.Join(workdir, "genesis.json")] = config.genesis
   134  	if config.keyJSON != "" {
   135  		files[filepath.Join(workdir, "signer.json")] = []byte(config.keyJSON)
   136  		files[filepath.Join(workdir, "signer.pass")] = []byte(config.keyPass)
   137  	}
   138  	// Upload the deployment files to the remote server (and clean up afterwards)
   139  	if out, err := client.Upload(files); err != nil {
   140  		return out, err
   141  	}
   142  	defer client.Run("rm -rf " + workdir)
   143  
   144  	// Build and deploy the boot or seal node service
   145  	if nocache {
   146  		return nil, client.Stream(fmt.Sprintf("cd %s && docker-compose -p %s build --pull --no-cache && docker-compose -p %s up -d --force-recreate --timeout 60", workdir, network, network))
   147  	}
   148  	return nil, client.Stream(fmt.Sprintf("cd %s && docker-compose -p %s up -d --build --force-recreate --timeout 60", workdir, network))
   149  }
   150  
   151  // nodeInfos is returned from a boot or seal node status check to allow reporting
   152  // various configuration parameters.
   153  type nodeInfos struct {
   154  	genesis    []byte
   155  	network    int64
   156  	datadir    string
   157  	ethashdir  string
   158  	ethstats   string
   159  	port       int
   160  	enode      string
   161  	peersTotal int
   162  	peersLight int
   163  	etherbase  string
   164  	keyJSON    string
   165  	keyPass    string
   166  	gasTarget  float64
   167  	gasLimit   float64
   168  	gasPrice   float64
   169  }
   170  
   171  // Report converts the typed struct into a plain string->string map, containing
   172  // most - but not all - fields for reporting to the user.
   173  func (info *nodeInfos) Report() map[string]string {
   174  	report := map[string]string{
   175  		"Data directory":           info.datadir,
   176  		"Listener port":            strconv.Itoa(info.port),
   177  		"Peer count (all total)":   strconv.Itoa(info.peersTotal),
   178  		"Peer count (light nodes)": strconv.Itoa(info.peersLight),
   179  		"Ethstats username":        info.ethstats,
   180  	}
   181  	if info.gasTarget > 0 {
   182  		// Miner or signer node
   183  		report["Gas price (minimum accepted)"] = fmt.Sprintf("%0.3f GWei", info.gasPrice)
   184  		report["Gas floor (baseline target)"] = fmt.Sprintf("%0.3f MGas", info.gasTarget)
   185  		report["Gas ceil  (target maximum)"] = fmt.Sprintf("%0.3f MGas", info.gasLimit)
   186  
   187  		if info.etherbase != "" {
   188  			// Ethash proof-of-work miner
   189  			report["Ethash directory"] = info.ethashdir
   190  			report["Miner account"] = info.etherbase
   191  		}
   192  		if info.keyJSON != "" {
   193  			// Clique proof-of-authority signer
   194  			var key struct {
   195  				Address string `json:"address"`
   196  			}
   197  			if err := json.Unmarshal([]byte(info.keyJSON), &key); err == nil {
   198  				report["Signer account"] = common.HexToAddress(key.Address).Hex()
   199  			} else {
   200  				log.Error("Failed to retrieve signer address", "err", err)
   201  			}
   202  		}
   203  	}
   204  	return report
   205  }
   206  
   207  // checkNode does a health-check against a boot or seal node server to verify
   208  // whether it's running, and if yes, whether it's responsive.
   209  func checkNode(client *sshClient, network string, boot bool) (*nodeInfos, error) {
   210  	kind := "bootnode"
   211  	if !boot {
   212  		kind = "sealnode"
   213  	}
   214  	// Inspect a possible bootnode container on the host
   215  	infos, err := inspectContainer(client, fmt.Sprintf("%s_%s_1", network, kind))
   216  	if err != nil {
   217  		return nil, err
   218  	}
   219  	if !infos.running {
   220  		return nil, ErrServiceOffline
   221  	}
   222  	// Resolve a few types from the environmental variables
   223  	totalPeers, _ := strconv.Atoi(infos.envvars["TOTAL_PEERS"])
   224  	lightPeers, _ := strconv.Atoi(infos.envvars["LIGHT_PEERS"])
   225  	gasTarget, _ := strconv.ParseFloat(infos.envvars["GAS_TARGET"], 64)
   226  	gasLimit, _ := strconv.ParseFloat(infos.envvars["GAS_LIMIT"], 64)
   227  	gasPrice, _ := strconv.ParseFloat(infos.envvars["GAS_PRICE"], 64)
   228  
   229  	// Container available, retrieve its node ID and its genesis json
   230  	var out []byte
   231  	if out, err = client.Run(fmt.Sprintf("docker exec %s_%s_1 geth --exec admin.nodeInfo.enode --cache=16 attach", network, kind)); err != nil {
   232  		return nil, ErrServiceUnreachable
   233  	}
   234  	enode := bytes.Trim(bytes.TrimSpace(out), "\"")
   235  
   236  	if out, err = client.Run(fmt.Sprintf("docker exec %s_%s_1 cat /genesis.json", network, kind)); err != nil {
   237  		return nil, ErrServiceUnreachable
   238  	}
   239  	genesis := bytes.TrimSpace(out)
   240  
   241  	keyJSON, keyPass := "", ""
   242  	if out, err = client.Run(fmt.Sprintf("docker exec %s_%s_1 cat /signer.json", network, kind)); err == nil {
   243  		keyJSON = string(bytes.TrimSpace(out))
   244  	}
   245  	if out, err = client.Run(fmt.Sprintf("docker exec %s_%s_1 cat /signer.pass", network, kind)); err == nil {
   246  		keyPass = string(bytes.TrimSpace(out))
   247  	}
   248  	// Run a sanity check to see if the devp2p is reachable
   249  	port := infos.portmap[infos.envvars["PORT"]]
   250  	if err = checkPort(client.server, port); err != nil {
   251  		log.Warn(fmt.Sprintf("%s devp2p port seems unreachable", strings.Title(kind)), "server", client.server, "port", port, "err", err)
   252  	}
   253  	// Assemble and return the useful infos
   254  	stats := &nodeInfos{
   255  		genesis:    genesis,
   256  		datadir:    infos.volumes["/root/.ethereum"],
   257  		ethashdir:  infos.volumes["/root/.ethash"],
   258  		port:       port,
   259  		peersTotal: totalPeers,
   260  		peersLight: lightPeers,
   261  		ethstats:   infos.envvars["STATS_NAME"],
   262  		etherbase:  infos.envvars["MINER_NAME"],
   263  		keyJSON:    keyJSON,
   264  		keyPass:    keyPass,
   265  		gasTarget:  gasTarget,
   266  		gasLimit:   gasLimit,
   267  		gasPrice:   gasPrice,
   268  	}
   269  	stats.enode = string(enode)
   270  
   271  	return stats, nil
   272  }