module_node.go 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242
  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. "fmt"
  20. "math/rand"
  21. "path/filepath"
  22. "strconv"
  23. "strings"
  24. "text/template"
  25. "github.com/ethereum/go-ethereum/log"
  26. )
  27. // nodeDockerfile is the Dockerfile required to run an Ethereum node.
  28. var nodeDockerfile = `
  29. FROM ethereum/client-go:alpine-develop
  30. ADD genesis.json /genesis.json
  31. {{if .Unlock}}
  32. ADD signer.json /signer.json
  33. ADD signer.pass /signer.pass
  34. {{end}}
  35. RUN \
  36. echo '/geth init /genesis.json' > geth.sh && \{{if .Unlock}}
  37. echo 'mkdir -p /root/.ethereum/keystore/ && cp /signer.json /root/.ethereum/keystore/' >> geth.sh && \{{end}}
  38. 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
  39. ENTRYPOINT ["/bin/sh", "geth.sh"]
  40. `
  41. // nodeComposefile is the docker-compose.yml file required to deploy and maintain
  42. // an Ethereum node (bootnode or miner for now).
  43. var nodeComposefile = `
  44. version: '2'
  45. services:
  46. {{.Type}}:
  47. build: .
  48. image: {{.Network}}/{{.Type}}
  49. ports:
  50. - "{{.FullPort}}:{{.FullPort}}"
  51. - "{{.FullPort}}:{{.FullPort}}/udp"{{if .Light}}
  52. - "{{.LightPort}}:{{.LightPort}}/udp"{{end}}
  53. volumes:
  54. - {{.Datadir}}:/root/.ethereum
  55. environment:
  56. - FULL_PORT={{.FullPort}}/tcp
  57. - LIGHT_PORT={{.LightPort}}/udp
  58. - TOTAL_PEERS={{.TotalPeers}}
  59. - LIGHT_PEERS={{.LightPeers}}
  60. - STATS_NAME={{.Ethstats}}
  61. - MINER_NAME={{.Etherbase}}
  62. - GAS_TARGET={{.GasTarget}}
  63. - GAS_PRICE={{.GasPrice}}
  64. logging:
  65. driver: "json-file"
  66. options:
  67. max-size: "1m"
  68. max-file: "10"
  69. restart: always
  70. `
  71. // deployNode deploys a new Ethereum node container to a remote machine via SSH,
  72. // docker and docker-compose. If an instance with the specified network name
  73. // already exists there, it will be overwritten!
  74. func deployNode(client *sshClient, network string, bootv4, bootv5 []string, config *nodeInfos) ([]byte, error) {
  75. kind := "sealnode"
  76. if config.keyJSON == "" && config.etherbase == "" {
  77. kind = "bootnode"
  78. bootv4 = make([]string, 0)
  79. bootv5 = 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.portFull,
  92. "Peers": config.peersTotal,
  93. "LightFlag": lightFlag,
  94. "BootV4": strings.Join(bootv4, ","),
  95. "BootV5": strings.Join(bootv5, ","),
  96. "Ethstats": config.ethstats,
  97. "Etherbase": config.etherbase,
  98. "GasTarget": uint64(1000000 * config.gasTarget),
  99. "GasPrice": uint64(1000000000 * config.gasPrice),
  100. "Unlock": config.keyJSON != "",
  101. })
  102. files[filepath.Join(workdir, "Dockerfile")] = dockerfile.Bytes()
  103. composefile := new(bytes.Buffer)
  104. template.Must(template.New("").Parse(nodeComposefile)).Execute(composefile, map[string]interface{}{
  105. "Type": kind,
  106. "Datadir": config.datadir,
  107. "Network": network,
  108. "FullPort": config.portFull,
  109. "TotalPeers": config.peersTotal,
  110. "Light": config.peersLight > 0,
  111. "LightPort": config.portFull + 1,
  112. "LightPeers": config.peersLight,
  113. "Ethstats": config.ethstats[:strings.Index(config.ethstats, ":")],
  114. "Etherbase": config.etherbase,
  115. "GasTarget": config.gasTarget,
  116. "GasPrice": config.gasPrice,
  117. })
  118. files[filepath.Join(workdir, "docker-compose.yaml")] = composefile.Bytes()
  119. //genesisfile, _ := json.MarshalIndent(config.genesis, "", " ")
  120. files[filepath.Join(workdir, "genesis.json")] = []byte(config.genesis)
  121. if config.keyJSON != "" {
  122. files[filepath.Join(workdir, "signer.json")] = []byte(config.keyJSON)
  123. files[filepath.Join(workdir, "signer.pass")] = []byte(config.keyPass)
  124. }
  125. // Upload the deployment files to the remote server (and clean up afterwards)
  126. if out, err := client.Upload(files); err != nil {
  127. return out, err
  128. }
  129. defer client.Run("rm -rf " + workdir)
  130. // Build and deploy the boot or seal node service
  131. return nil, client.Stream(fmt.Sprintf("cd %s && docker-compose -p %s up -d --build", workdir, network))
  132. }
  133. // nodeInfos is returned from a boot or seal node status check to allow reporting
  134. // various configuration parameters.
  135. type nodeInfos struct {
  136. genesis []byte
  137. network int64
  138. datadir string
  139. ethstats string
  140. portFull int
  141. portLight int
  142. enodeFull string
  143. enodeLight string
  144. peersTotal int
  145. peersLight int
  146. etherbase string
  147. keyJSON string
  148. keyPass string
  149. gasTarget float64
  150. gasPrice float64
  151. }
  152. // String implements the stringer interface.
  153. func (info *nodeInfos) String() string {
  154. discv5 := ""
  155. if info.peersLight > 0 {
  156. discv5 = fmt.Sprintf(", portv5=%d", info.portLight)
  157. }
  158. return fmt.Sprintf("port=%d%s, datadir=%s, peers=%d, lights=%d, ethstats=%s, gastarget=%0.3f MGas, gasprice=%0.3f GWei",
  159. info.portFull, discv5, info.datadir, info.peersTotal, info.peersLight, info.ethstats, info.gasTarget, info.gasPrice)
  160. }
  161. // checkNode does a health-check against an boot or seal node server to verify
  162. // whether it's running, and if yes, whether it's responsive.
  163. func checkNode(client *sshClient, network string, boot bool) (*nodeInfos, error) {
  164. kind := "bootnode"
  165. if !boot {
  166. kind = "sealnode"
  167. }
  168. // Inspect a possible bootnode container on the host
  169. infos, err := inspectContainer(client, fmt.Sprintf("%s_%s_1", network, kind))
  170. if err != nil {
  171. return nil, err
  172. }
  173. if !infos.running {
  174. return nil, ErrServiceOffline
  175. }
  176. // Resolve a few types from the environmental variables
  177. totalPeers, _ := strconv.Atoi(infos.envvars["TOTAL_PEERS"])
  178. lightPeers, _ := strconv.Atoi(infos.envvars["LIGHT_PEERS"])
  179. gasTarget, _ := strconv.ParseFloat(infos.envvars["GAS_TARGET"], 64)
  180. gasPrice, _ := strconv.ParseFloat(infos.envvars["GAS_PRICE"], 64)
  181. // Container available, retrieve its node ID and its genesis json
  182. var out []byte
  183. if out, err = client.Run(fmt.Sprintf("docker exec %s_%s_1 /geth --exec admin.nodeInfo.id attach", network, kind)); err != nil {
  184. return nil, ErrServiceUnreachable
  185. }
  186. id := bytes.Trim(bytes.TrimSpace(out), "\"")
  187. if out, err = client.Run(fmt.Sprintf("docker exec %s_%s_1 cat /genesis.json", network, kind)); err != nil {
  188. return nil, ErrServiceUnreachable
  189. }
  190. genesis := bytes.TrimSpace(out)
  191. keyJSON, keyPass := "", ""
  192. if out, err = client.Run(fmt.Sprintf("docker exec %s_%s_1 cat /signer.json", network, kind)); err == nil {
  193. keyJSON = string(bytes.TrimSpace(out))
  194. }
  195. if out, err = client.Run(fmt.Sprintf("docker exec %s_%s_1 cat /signer.pass", network, kind)); err == nil {
  196. keyPass = string(bytes.TrimSpace(out))
  197. }
  198. // Run a sanity check to see if the devp2p is reachable
  199. port := infos.portmap[infos.envvars["FULL_PORT"]]
  200. if err = checkPort(client.server, port); err != nil {
  201. log.Warn(fmt.Sprintf("%s devp2p port seems unreachable", strings.Title(kind)), "server", client.server, "port", port, "err", err)
  202. }
  203. // Assemble and return the useful infos
  204. stats := &nodeInfos{
  205. genesis: genesis,
  206. datadir: infos.volumes["/root/.ethereum"],
  207. portFull: infos.portmap[infos.envvars["FULL_PORT"]],
  208. portLight: infos.portmap[infos.envvars["LIGHT_PORT"]],
  209. peersTotal: totalPeers,
  210. peersLight: lightPeers,
  211. ethstats: infos.envvars["STATS_NAME"],
  212. etherbase: infos.envvars["MINER_NAME"],
  213. keyJSON: keyJSON,
  214. keyPass: keyPass,
  215. gasTarget: gasTarget,
  216. gasPrice: gasPrice,
  217. }
  218. stats.enodeFull = fmt.Sprintf("enode://%s@%s:%d", id, client.address, stats.portFull)
  219. if stats.portLight != 0 {
  220. stats.enodeLight = fmt.Sprintf("enode://%s@%s:%d?discport=%d", id, client.address, stats.portFull, stats.portLight)
  221. }
  222. return stats, nil
  223. }