module_node.go 9.6 KB

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