module_node.go 9.26 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
// Copyright 2017 The go-ethereum Authors
// This file is part of go-ethereum.
//
// go-ethereum is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// go-ethereum is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with go-ethereum. If not, see <http://www.gnu.org/licenses/>.

package main

import (
	"bytes"
21
	"encoding/json"
22 23 24 25 26 27 28
	"fmt"
	"math/rand"
	"path/filepath"
	"strconv"
	"strings"
	"text/template"

29
	"github.com/ethereum/go-ethereum/common"
30 31 32 33 34
	"github.com/ethereum/go-ethereum/log"
)

// nodeDockerfile is the Dockerfile required to run an Ethereum node.
var nodeDockerfile = `
35
FROM ethereum/client-go:latest
36 37 38 39 40 41 42

ADD genesis.json /genesis.json
{{if .Unlock}}
	ADD signer.json /signer.json
	ADD signer.pass /signer.pass
{{end}}
RUN \
43 44
  echo 'geth --cache 512 init /genesis.json' > geth.sh && \{{if .Unlock}}
	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.gaslimit {{.GasLimit}} --miner.gasprice {{.GasPrice}}' >> geth.sh
46

47
ENTRYPOINT ["/bin/sh", "geth.sh"]
48 49 50 51 52 53 54 55 56 57
`

// nodeComposefile is the docker-compose.yml file required to deploy and maintain
// an Ethereum node (bootnode or miner for now).
var nodeComposefile = `
version: '2'
services:
  {{.Type}}:
    build: .
    image: {{.Network}}/{{.Type}}
58
    container_name: {{.Network}}_{{.Type}}_1
59
    ports:
60 61
      - "{{.Port}}:{{.Port}}"
      - "{{.Port}}:{{.Port}}/udp"
62
    volumes:
63 64
      - {{.Datadir}}:/root/.ethereum{{if .Ethashdir}}
      - {{.Ethashdir}}:/root/.ethash{{end}}
65
    environment:
66
      - PORT={{.Port}}/tcp
67 68 69 70
      - TOTAL_PEERS={{.TotalPeers}}
      - LIGHT_PEERS={{.LightPeers}}
      - STATS_NAME={{.Ethstats}}
      - MINER_NAME={{.Etherbase}}
71
      - GAS_LIMIT={{.GasLimit}}
72
      - GAS_PRICE={{.GasPrice}}
73 74 75 76 77
    logging:
      driver: "json-file"
      options:
        max-size: "1m"
        max-file: "10"
78 79 80 81 82 83
    restart: always
`

// deployNode deploys a new Ethereum node container to a remote machine via SSH,
// docker and docker-compose. If an instance with the specified network name
// already exists there, it will be overwritten!
84
func deployNode(client *sshClient, network string, bootnodes []string, config *nodeInfos, nocache bool) ([]byte, error) {
85 86 87
	kind := "sealnode"
	if config.keyJSON == "" && config.etherbase == "" {
		kind = "bootnode"
88
		bootnodes = make([]string, 0)
89 90 91 92 93 94 95
	}
	// Generate the content to upload to the server
	workdir := fmt.Sprintf("%d", rand.Int63())
	files := make(map[string][]byte)

	lightFlag := ""
	if config.peersLight > 0 {
96
		lightFlag = fmt.Sprintf("--light.maxpeers=%d --light.serve=50", config.peersLight)
97 98 99 100
	}
	dockerfile := new(bytes.Buffer)
	template.Must(template.New("").Parse(nodeDockerfile)).Execute(dockerfile, map[string]interface{}{
		"NetworkID": config.network,
101
		"Port":      config.port,
102
		"IP":        client.address,
103 104
		"Peers":     config.peersTotal,
		"LightFlag": lightFlag,
105
		"Bootnodes": strings.Join(bootnodes, ","),
106 107
		"Ethstats":  config.ethstats,
		"Etherbase": config.etherbase,
108
		"GasLimit":  uint64(1000000 * config.gasLimit),
109
		"GasPrice":  uint64(1000000000 * config.gasPrice),
110 111 112 113 114 115 116 117
		"Unlock":    config.keyJSON != "",
	})
	files[filepath.Join(workdir, "Dockerfile")] = dockerfile.Bytes()

	composefile := new(bytes.Buffer)
	template.Must(template.New("").Parse(nodeComposefile)).Execute(composefile, map[string]interface{}{
		"Type":       kind,
		"Datadir":    config.datadir,
118
		"Ethashdir":  config.ethashdir,
119
		"Network":    network,
120
		"Port":       config.port,
121 122 123
		"TotalPeers": config.peersTotal,
		"Light":      config.peersLight > 0,
		"LightPeers": config.peersLight,
124
		"Ethstats":   getEthName(config.ethstats),
125
		"Etherbase":  config.etherbase,
126
		"GasLimit":   config.gasLimit,
127
		"GasPrice":   config.gasPrice,
128 129 130
	})
	files[filepath.Join(workdir, "docker-compose.yaml")] = composefile.Bytes()

131
	files[filepath.Join(workdir, "genesis.json")] = config.genesis
132 133 134 135 136 137 138 139 140 141
	if config.keyJSON != "" {
		files[filepath.Join(workdir, "signer.json")] = []byte(config.keyJSON)
		files[filepath.Join(workdir, "signer.pass")] = []byte(config.keyPass)
	}
	// Upload the deployment files to the remote server (and clean up afterwards)
	if out, err := client.Upload(files); err != nil {
		return out, err
	}
	defer client.Run("rm -rf " + workdir)

142
	// Build and deploy the boot or seal node service
143
	if nocache {
144
		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))
145
	}
146
	return nil, client.Stream(fmt.Sprintf("cd %s && docker-compose -p %s up -d --build --force-recreate --timeout 60", workdir, network))
147 148 149 150 151 152 153 154
}

// nodeInfos is returned from a boot or seal node status check to allow reporting
// various configuration parameters.
type nodeInfos struct {
	genesis    []byte
	network    int64
	datadir    string
155
	ethashdir  string
156
	ethstats   string
157 158
	port       int
	enode      string
159 160 161 162 163
	peersTotal int
	peersLight int
	etherbase  string
	keyJSON    string
	keyPass    string
164
	gasLimit   float64
165
	gasPrice   float64
166 167
}

168
// Report converts the typed struct into a plain string->string map, containing
169 170 171
// most - but not all - fields for reporting to the user.
func (info *nodeInfos) Report() map[string]string {
	report := map[string]string{
172 173 174 175 176
		"Data directory":           info.datadir,
		"Listener port":            strconv.Itoa(info.port),
		"Peer count (all total)":   strconv.Itoa(info.peersTotal),
		"Peer count (light nodes)": strconv.Itoa(info.peersLight),
		"Ethstats username":        info.ethstats,
177
	}
178
	if info.gasLimit > 0 {
179
		// Miner or signer node
180
		report["Gas price (minimum accepted)"] = fmt.Sprintf("%0.3f GWei", info.gasPrice)
181
		report["Gas ceil  (target maximum)"] = fmt.Sprintf("%0.3f MGas", info.gasLimit)
182 183 184 185 186

		if info.etherbase != "" {
			// Ethash proof-of-work miner
			report["Ethash directory"] = info.ethashdir
			report["Miner account"] = info.etherbase
187
		}
188 189 190 191 192 193 194 195 196 197
		if info.keyJSON != "" {
			// Clique proof-of-authority signer
			var key struct {
				Address string `json:"address"`
			}
			if err := json.Unmarshal([]byte(info.keyJSON), &key); err == nil {
				report["Signer account"] = common.HexToAddress(key.Address).Hex()
			} else {
				log.Error("Failed to retrieve signer address", "err", err)
			}
198
		}
199
	}
200
	return report
201 202
}

203
// checkNode does a health-check against a boot or seal node server to verify
204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220
// whether it's running, and if yes, whether it's responsive.
func checkNode(client *sshClient, network string, boot bool) (*nodeInfos, error) {
	kind := "bootnode"
	if !boot {
		kind = "sealnode"
	}
	// Inspect a possible bootnode container on the host
	infos, err := inspectContainer(client, fmt.Sprintf("%s_%s_1", network, kind))
	if err != nil {
		return nil, err
	}
	if !infos.running {
		return nil, ErrServiceOffline
	}
	// Resolve a few types from the environmental variables
	totalPeers, _ := strconv.Atoi(infos.envvars["TOTAL_PEERS"])
	lightPeers, _ := strconv.Atoi(infos.envvars["LIGHT_PEERS"])
221
	gasLimit, _ := strconv.ParseFloat(infos.envvars["GAS_LIMIT"], 64)
222
	gasPrice, _ := strconv.ParseFloat(infos.envvars["GAS_PRICE"], 64)
223 224 225

	// Container available, retrieve its node ID and its genesis json
	var out []byte
226
	if out, err = client.Run(fmt.Sprintf("docker exec %s_%s_1 geth --exec admin.nodeInfo.enode --cache=16 attach", network, kind)); err != nil {
227 228
		return nil, ErrServiceUnreachable
	}
229
	enode := bytes.Trim(bytes.TrimSpace(out), "\"")
230 231 232 233 234 235 236 237 238 239 240 241 242 243

	if out, err = client.Run(fmt.Sprintf("docker exec %s_%s_1 cat /genesis.json", network, kind)); err != nil {
		return nil, ErrServiceUnreachable
	}
	genesis := bytes.TrimSpace(out)

	keyJSON, keyPass := "", ""
	if out, err = client.Run(fmt.Sprintf("docker exec %s_%s_1 cat /signer.json", network, kind)); err == nil {
		keyJSON = string(bytes.TrimSpace(out))
	}
	if out, err = client.Run(fmt.Sprintf("docker exec %s_%s_1 cat /signer.pass", network, kind)); err == nil {
		keyPass = string(bytes.TrimSpace(out))
	}
	// Run a sanity check to see if the devp2p is reachable
244
	port := infos.portmap[infos.envvars["PORT"]]
245 246 247 248 249 250 251
	if err = checkPort(client.server, port); err != nil {
		log.Warn(fmt.Sprintf("%s devp2p port seems unreachable", strings.Title(kind)), "server", client.server, "port", port, "err", err)
	}
	// Assemble and return the useful infos
	stats := &nodeInfos{
		genesis:    genesis,
		datadir:    infos.volumes["/root/.ethereum"],
252
		ethashdir:  infos.volumes["/root/.ethash"],
253
		port:       port,
254 255 256 257 258 259
		peersTotal: totalPeers,
		peersLight: lightPeers,
		ethstats:   infos.envvars["STATS_NAME"],
		etherbase:  infos.envvars["MINER_NAME"],
		keyJSON:    keyJSON,
		keyPass:    keyPass,
260
		gasLimit:   gasLimit,
261
		gasPrice:   gasPrice,
262
	}
263
	stats.enode = string(enode)
264

265 266
	return stats, nil
}