module_node.go 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278
  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 .BootV4}}--bootnodesv4 {{.BootV4}}{{end}} {{if .BootV5}}--bootnodesv5 {{.BootV5}}{{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. - "{{.FullPort}}:{{.FullPort}}"
  53. - "{{.FullPort}}:{{.FullPort}}/udp"{{if .Light}}
  54. - "{{.LightPort}}:{{.LightPort}}/udp"{{end}}
  55. volumes:
  56. - {{.Datadir}}:/root/.ethereum{{if .Ethashdir}}
  57. - {{.Ethashdir}}:/root/.ethash{{end}}
  58. environment:
  59. - FULL_PORT={{.FullPort}}/tcp
  60. - LIGHT_PORT={{.LightPort}}/udp
  61. - TOTAL_PEERS={{.TotalPeers}}
  62. - LIGHT_PEERS={{.LightPeers}}
  63. - STATS_NAME={{.Ethstats}}
  64. - MINER_NAME={{.Etherbase}}
  65. - GAS_TARGET={{.GasTarget}}
  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, bootv4, bootv5 []string, config *nodeInfos, nocache bool) ([]byte, error) {
  78. kind := "sealnode"
  79. if config.keyJSON == "" && config.etherbase == "" {
  80. kind = "bootnode"
  81. bootv4 = make([]string, 0)
  82. bootv5 = make([]string, 0)
  83. }
  84. // Generate the content to upload to the server
  85. workdir := fmt.Sprintf("%d", rand.Int63())
  86. files := make(map[string][]byte)
  87. lightFlag := ""
  88. if config.peersLight > 0 {
  89. lightFlag = fmt.Sprintf("--lightpeers=%d --lightserv=50", config.peersLight)
  90. }
  91. dockerfile := new(bytes.Buffer)
  92. template.Must(template.New("").Parse(nodeDockerfile)).Execute(dockerfile, map[string]interface{}{
  93. "NetworkID": config.network,
  94. "Port": config.portFull,
  95. "Peers": config.peersTotal,
  96. "LightFlag": lightFlag,
  97. "BootV4": strings.Join(bootv4, ","),
  98. "BootV5": strings.Join(bootv5, ","),
  99. "Ethstats": config.ethstats,
  100. "Etherbase": config.etherbase,
  101. "GasTarget": uint64(1000000 * config.gasTarget),
  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. "FullPort": config.portFull,
  113. "TotalPeers": config.peersTotal,
  114. "Light": config.peersLight > 0,
  115. "LightPort": config.portFull + 1,
  116. "LightPeers": config.peersLight,
  117. "Ethstats": config.ethstats[:strings.Index(config.ethstats, ":")],
  118. "Etherbase": config.etherbase,
  119. "GasTarget": config.gasTarget,
  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", workdir, network, network))
  136. }
  137. return nil, client.Stream(fmt.Sprintf("cd %s && docker-compose -p %s up -d --build --force-recreate", 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. portFull int
  148. portLight int
  149. enodeFull string
  150. enodeLight string
  151. peersTotal int
  152. peersLight int
  153. etherbase string
  154. keyJSON string
  155. keyPass string
  156. gasTarget float64
  157. gasPrice float64
  158. }
  159. // Report converts the typed struct into a plain string->string map, cotnaining
  160. // most - but not all - fields for reporting to the user.
  161. func (info *nodeInfos) Report() map[string]string {
  162. report := map[string]string{
  163. "Data directory": info.datadir,
  164. "Listener port (full nodes)": strconv.Itoa(info.portFull),
  165. "Peer count (all total)": strconv.Itoa(info.peersTotal),
  166. "Peer count (light nodes)": strconv.Itoa(info.peersLight),
  167. "Ethstats username": info.ethstats,
  168. }
  169. if info.peersLight > 0 {
  170. // Light server enabled
  171. report["Listener port (light nodes)"] = strconv.Itoa(info.portLight)
  172. }
  173. if info.gasTarget > 0 {
  174. // Miner or signer node
  175. report["Gas limit (baseline target)"] = fmt.Sprintf("%0.3f MGas", info.gasTarget)
  176. report["Gas price (minimum accepted)"] = fmt.Sprintf("%0.3f GWei", info.gasPrice)
  177. if info.etherbase != "" {
  178. // Ethash proof-of-work miner
  179. report["Ethash directory"] = info.ethashdir
  180. report["Miner account"] = info.etherbase
  181. }
  182. if info.keyJSON != "" {
  183. // Clique proof-of-authority signer
  184. var key struct {
  185. Address string `json:"address"`
  186. }
  187. if err := json.Unmarshal([]byte(info.keyJSON), &key); err == nil {
  188. report["Signer account"] = common.HexToAddress(key.Address).Hex()
  189. } else {
  190. log.Error("Failed to retrieve signer address", "err", err)
  191. }
  192. }
  193. }
  194. return report
  195. }
  196. // checkNode does a health-check against an boot or seal node server to verify
  197. // whether it's running, and if yes, whether it's responsive.
  198. func checkNode(client *sshClient, network string, boot bool) (*nodeInfos, error) {
  199. kind := "bootnode"
  200. if !boot {
  201. kind = "sealnode"
  202. }
  203. // Inspect a possible bootnode container on the host
  204. infos, err := inspectContainer(client, fmt.Sprintf("%s_%s_1", network, kind))
  205. if err != nil {
  206. return nil, err
  207. }
  208. if !infos.running {
  209. return nil, ErrServiceOffline
  210. }
  211. // Resolve a few types from the environmental variables
  212. totalPeers, _ := strconv.Atoi(infos.envvars["TOTAL_PEERS"])
  213. lightPeers, _ := strconv.Atoi(infos.envvars["LIGHT_PEERS"])
  214. gasTarget, _ := strconv.ParseFloat(infos.envvars["GAS_TARGET"], 64)
  215. gasPrice, _ := strconv.ParseFloat(infos.envvars["GAS_PRICE"], 64)
  216. // Container available, retrieve its node ID and its genesis json
  217. var out []byte
  218. if out, err = client.Run(fmt.Sprintf("docker exec %s_%s_1 geth --exec admin.nodeInfo.id attach", network, kind)); err != nil {
  219. return nil, ErrServiceUnreachable
  220. }
  221. id := bytes.Trim(bytes.TrimSpace(out), "\"")
  222. if out, err = client.Run(fmt.Sprintf("docker exec %s_%s_1 cat /genesis.json", network, kind)); err != nil {
  223. return nil, ErrServiceUnreachable
  224. }
  225. genesis := bytes.TrimSpace(out)
  226. keyJSON, keyPass := "", ""
  227. if out, err = client.Run(fmt.Sprintf("docker exec %s_%s_1 cat /signer.json", network, kind)); err == nil {
  228. keyJSON = string(bytes.TrimSpace(out))
  229. }
  230. if out, err = client.Run(fmt.Sprintf("docker exec %s_%s_1 cat /signer.pass", network, kind)); err == nil {
  231. keyPass = string(bytes.TrimSpace(out))
  232. }
  233. // Run a sanity check to see if the devp2p is reachable
  234. port := infos.portmap[infos.envvars["FULL_PORT"]]
  235. if err = checkPort(client.server, port); err != nil {
  236. log.Warn(fmt.Sprintf("%s devp2p port seems unreachable", strings.Title(kind)), "server", client.server, "port", port, "err", err)
  237. }
  238. // Assemble and return the useful infos
  239. stats := &nodeInfos{
  240. genesis: genesis,
  241. datadir: infos.volumes["/root/.ethereum"],
  242. ethashdir: infos.volumes["/root/.ethash"],
  243. portFull: infos.portmap[infos.envvars["FULL_PORT"]],
  244. portLight: infos.portmap[infos.envvars["LIGHT_PORT"]],
  245. peersTotal: totalPeers,
  246. peersLight: lightPeers,
  247. ethstats: infos.envvars["STATS_NAME"],
  248. etherbase: infos.envvars["MINER_NAME"],
  249. keyJSON: keyJSON,
  250. keyPass: keyPass,
  251. gasTarget: gasTarget,
  252. gasPrice: gasPrice,
  253. }
  254. stats.enodeFull = fmt.Sprintf("enode://%s@%s:%d", id, client.address, stats.portFull)
  255. if stats.portLight != 0 {
  256. stats.enodeLight = fmt.Sprintf("enode://%s@%s:%d?discport=%d", id, client.address, stats.portFull, stats.portLight)
  257. }
  258. return stats, nil
  259. }