module_node.go 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270
  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 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 .BootV4}}--bootnodesv4 {{.BootV4}}{{end}} {{if .BootV5}}--bootnodesv5 {{.BootV5}}{{end}} {{if .Etherbase}}--etherbase {{.Etherbase}} --mine{{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. - "{{.FullPort}}:{{.FullPort}}"
  53. - "{{.FullPort}}:{{.FullPort}}/udp"{{if .Light}}
  54. - "{{.LightPort}}:{{.LightPort}}/udp"{{end}}
  55. volumes:
  56. - {{.Datadir}}:/root/.ethereum
  57. environment:
  58. - FULL_PORT={{.FullPort}}/tcp
  59. - LIGHT_PORT={{.LightPort}}/udp
  60. - TOTAL_PEERS={{.TotalPeers}}
  61. - LIGHT_PEERS={{.LightPeers}}
  62. - STATS_NAME={{.Ethstats}}
  63. - MINER_NAME={{.Etherbase}}
  64. - GAS_TARGET={{.GasTarget}}
  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, bootv4, bootv5 []string, config *nodeInfos, nocache bool) ([]byte, error) {
  77. kind := "sealnode"
  78. if config.keyJSON == "" && config.etherbase == "" {
  79. kind = "bootnode"
  80. bootv4 = make([]string, 0)
  81. bootv5 = 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("--lightpeers=%d --lightserv=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.portFull,
  94. "Peers": config.peersTotal,
  95. "LightFlag": lightFlag,
  96. "BootV4": strings.Join(bootv4, ","),
  97. "BootV5": strings.Join(bootv5, ","),
  98. "Ethstats": config.ethstats,
  99. "Etherbase": config.etherbase,
  100. "GasTarget": uint64(1000000 * config.gasTarget),
  101. "GasPrice": uint64(1000000000 * config.gasPrice),
  102. "Unlock": config.keyJSON != "",
  103. })
  104. files[filepath.Join(workdir, "Dockerfile")] = dockerfile.Bytes()
  105. composefile := new(bytes.Buffer)
  106. template.Must(template.New("").Parse(nodeComposefile)).Execute(composefile, map[string]interface{}{
  107. "Type": kind,
  108. "Datadir": config.datadir,
  109. "Network": network,
  110. "FullPort": config.portFull,
  111. "TotalPeers": config.peersTotal,
  112. "Light": config.peersLight > 0,
  113. "LightPort": config.portFull + 1,
  114. "LightPeers": config.peersLight,
  115. "Ethstats": config.ethstats[:strings.Index(config.ethstats, ":")],
  116. "Etherbase": config.etherbase,
  117. "GasTarget": config.gasTarget,
  118. "GasPrice": config.gasPrice,
  119. })
  120. files[filepath.Join(workdir, "docker-compose.yaml")] = composefile.Bytes()
  121. //genesisfile, _ := json.MarshalIndent(config.genesis, "", " ")
  122. files[filepath.Join(workdir, "genesis.json")] = config.genesis
  123. if config.keyJSON != "" {
  124. files[filepath.Join(workdir, "signer.json")] = []byte(config.keyJSON)
  125. files[filepath.Join(workdir, "signer.pass")] = []byte(config.keyPass)
  126. }
  127. // Upload the deployment files to the remote server (and clean up afterwards)
  128. if out, err := client.Upload(files); err != nil {
  129. return out, err
  130. }
  131. defer client.Run("rm -rf " + workdir)
  132. // Build and deploy the boot or seal node service
  133. if nocache {
  134. 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))
  135. }
  136. return nil, client.Stream(fmt.Sprintf("cd %s && docker-compose -p %s up -d --build --force-recreate", workdir, network))
  137. }
  138. // nodeInfos is returned from a boot or seal node status check to allow reporting
  139. // various configuration parameters.
  140. type nodeInfos struct {
  141. genesis []byte
  142. network int64
  143. datadir string
  144. ethstats string
  145. portFull int
  146. portLight int
  147. enodeFull string
  148. enodeLight string
  149. peersTotal int
  150. peersLight int
  151. etherbase string
  152. keyJSON string
  153. keyPass string
  154. gasTarget float64
  155. gasPrice float64
  156. }
  157. // Report converts the typed struct into a plain string->string map, cotnaining
  158. // most - but not all - fields for reporting to the user.
  159. func (info *nodeInfos) Report() map[string]string {
  160. report := map[string]string{
  161. "Data directory": info.datadir,
  162. "Listener port (full nodes)": strconv.Itoa(info.portFull),
  163. "Peer count (all total)": strconv.Itoa(info.peersTotal),
  164. "Peer count (light nodes)": strconv.Itoa(info.peersLight),
  165. "Ethstats username": info.ethstats,
  166. }
  167. if info.peersLight > 0 {
  168. report["Listener port (light nodes)"] = strconv.Itoa(info.portLight)
  169. }
  170. if info.gasTarget > 0 {
  171. report["Gas limit (baseline target)"] = fmt.Sprintf("%0.3f MGas", info.gasTarget)
  172. report["Gas price (minimum accepted)"] = fmt.Sprintf("%0.3f GWei", info.gasPrice)
  173. }
  174. if info.etherbase != "" {
  175. report["Miner account"] = info.etherbase
  176. }
  177. if info.keyJSON != "" {
  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. return report
  188. }
  189. // checkNode does a health-check against an boot or seal node server to verify
  190. // whether it's running, and if yes, whether it's responsive.
  191. func checkNode(client *sshClient, network string, boot bool) (*nodeInfos, error) {
  192. kind := "bootnode"
  193. if !boot {
  194. kind = "sealnode"
  195. }
  196. // Inspect a possible bootnode container on the host
  197. infos, err := inspectContainer(client, fmt.Sprintf("%s_%s_1", network, kind))
  198. if err != nil {
  199. return nil, err
  200. }
  201. if !infos.running {
  202. return nil, ErrServiceOffline
  203. }
  204. // Resolve a few types from the environmental variables
  205. totalPeers, _ := strconv.Atoi(infos.envvars["TOTAL_PEERS"])
  206. lightPeers, _ := strconv.Atoi(infos.envvars["LIGHT_PEERS"])
  207. gasTarget, _ := strconv.ParseFloat(infos.envvars["GAS_TARGET"], 64)
  208. gasPrice, _ := strconv.ParseFloat(infos.envvars["GAS_PRICE"], 64)
  209. // Container available, retrieve its node ID and its genesis json
  210. var out []byte
  211. if out, err = client.Run(fmt.Sprintf("docker exec %s_%s_1 geth --exec admin.nodeInfo.id attach", network, kind)); err != nil {
  212. return nil, ErrServiceUnreachable
  213. }
  214. id := bytes.Trim(bytes.TrimSpace(out), "\"")
  215. if out, err = client.Run(fmt.Sprintf("docker exec %s_%s_1 cat /genesis.json", network, kind)); err != nil {
  216. return nil, ErrServiceUnreachable
  217. }
  218. genesis := bytes.TrimSpace(out)
  219. keyJSON, keyPass := "", ""
  220. if out, err = client.Run(fmt.Sprintf("docker exec %s_%s_1 cat /signer.json", network, kind)); err == nil {
  221. keyJSON = string(bytes.TrimSpace(out))
  222. }
  223. if out, err = client.Run(fmt.Sprintf("docker exec %s_%s_1 cat /signer.pass", network, kind)); err == nil {
  224. keyPass = string(bytes.TrimSpace(out))
  225. }
  226. // Run a sanity check to see if the devp2p is reachable
  227. port := infos.portmap[infos.envvars["FULL_PORT"]]
  228. if err = checkPort(client.server, port); err != nil {
  229. log.Warn(fmt.Sprintf("%s devp2p port seems unreachable", strings.Title(kind)), "server", client.server, "port", port, "err", err)
  230. }
  231. // Assemble and return the useful infos
  232. stats := &nodeInfos{
  233. genesis: genesis,
  234. datadir: infos.volumes["/root/.ethereum"],
  235. portFull: infos.portmap[infos.envvars["FULL_PORT"]],
  236. portLight: infos.portmap[infos.envvars["LIGHT_PORT"]],
  237. peersTotal: totalPeers,
  238. peersLight: lightPeers,
  239. ethstats: infos.envvars["STATS_NAME"],
  240. etherbase: infos.envvars["MINER_NAME"],
  241. keyJSON: keyJSON,
  242. keyPass: keyPass,
  243. gasTarget: gasTarget,
  244. gasPrice: gasPrice,
  245. }
  246. stats.enodeFull = fmt.Sprintf("enode://%s@%s:%d", id, client.address, stats.portFull)
  247. if stats.portLight != 0 {
  248. stats.enodeLight = fmt.Sprintf("enode://%s@%s:%d?discport=%d", id, client.address, stats.portFull, stats.portLight)
  249. }
  250. return stats, nil
  251. }