module_node.go 9.2 KB

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