module_node.go 9.6 KB

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