github.com/codingfuture/orig-energi3@v0.8.4/cmd/puppeth/module_explorer.go (about)

     1  // Copyright 2018 The Energi Core Authors
     2  // Copyright 2017 The go-ethereum Authors
     3  // This file is part of Energi Core.
     4  //
     5  // Energi Core is free software: you can redistribute it and/or modify
     6  // it under the terms of the GNU General Public License as published by
     7  // the Free Software Foundation, either version 3 of the License, or
     8  // (at your option) any later version.
     9  //
    10  // Energi Core is distributed in the hope that it will be useful,
    11  // but WITHOUT ANY WARRANTY; without even the implied warranty of
    12  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
    13  // GNU General Public License for more details.
    14  //
    15  // You should have received a copy of the GNU General Public License
    16  // along with Energi Core. If not, see <http://www.gnu.org/licenses/>.
    17  
    18  package main
    19  
    20  import (
    21  	"bytes"
    22  	"fmt"
    23  	"html/template"
    24  	"math/rand"
    25  	"path/filepath"
    26  	"strconv"
    27  	"strings"
    28  
    29  	"github.com/ethereum/go-ethereum/log"
    30  )
    31  
    32  // explorerDockerfile is the Dockerfile required to run a block explorer.
    33  var explorerDockerfile = `
    34  FROM puppeth/explorer:latest
    35  
    36  ADD ethstats.json /ethstats.json
    37  ADD chain.json /chain.json
    38  
    39  RUN \
    40    echo '(cd ../eth-net-intelligence-api && pm2 start /ethstats.json)' >  explorer.sh && \
    41  	echo '(cd ../etherchain-light && npm start &)'                      >> explorer.sh && \
    42  	echo 'exec /parity/parity --chain=/chain.json --port={{.NodePort}} --tracing=on --fat-db=on --pruning=archive' >> explorer.sh
    43  
    44  ENTRYPOINT ["/bin/sh", "explorer.sh"]
    45  `
    46  
    47  // explorerEthstats is the configuration file for the ethstats javascript client.
    48  var explorerEthstats = `[
    49    {
    50      "name"              : "node-app",
    51      "script"            : "app.js",
    52      "log_date_format"   : "YYYY-MM-DD HH:mm Z",
    53      "merge_logs"        : false,
    54      "watch"             : false,
    55      "max_restarts"      : 10,
    56      "exec_interpreter"  : "node",
    57      "exec_mode"         : "fork_mode",
    58      "env":
    59      {
    60        "NODE_ENV"        : "production",
    61        "RPC_HOST"        : "localhost",
    62        "RPC_PORT"        : "39796",
    63        "LISTENING_PORT"  : "{{.Port}}",
    64        "INSTANCE_NAME"   : "{{.Name}}",
    65        "CONTACT_DETAILS" : "",
    66        "WS_SERVER"       : "{{.Host}}",
    67        "WS_SECRET"       : "{{.Secret}}",
    68        "VERBOSITY"       : 2
    69      }
    70    }
    71  ]`
    72  
    73  // explorerComposefile is the docker-compose.yml file required to deploy and
    74  // maintain a block explorer.
    75  var explorerComposefile = `
    76  version: '2'
    77  services:
    78    explorer:
    79      build: .
    80      image: {{.Network}}/explorer
    81      container_name: {{.Network}}_explorer_1
    82      ports:
    83        - "{{.NodePort}}:{{.NodePort}}"
    84        - "{{.NodePort}}:{{.NodePort}}/udp"{{if not .VHost}}
    85        - "{{.WebPort}}:3000"{{end}}
    86      volumes:
    87        - {{.Datadir}}:/root/.local/share/io.parity.ethereum
    88      environment:
    89        - NODE_PORT={{.NodePort}}/tcp
    90        - STATS={{.Ethstats}}{{if .VHost}}
    91        - VIRTUAL_HOST={{.VHost}}
    92        - VIRTUAL_PORT=3000{{end}}
    93      logging:
    94        driver: "json-file"
    95        options:
    96          max-size: "1m"
    97          max-file: "10"
    98      restart: always
    99  `
   100  
   101  // deployExplorer deploys a new block explorer container to a remote machine via
   102  // SSH, docker and docker-compose. If an instance with the specified network name
   103  // already exists there, it will be overwritten!
   104  func deployExplorer(client *sshClient, network string, chainspec []byte, config *explorerInfos, nocache bool) ([]byte, error) {
   105  	// Generate the content to upload to the server
   106  	workdir := fmt.Sprintf("%d", rand.Int63())
   107  	files := make(map[string][]byte)
   108  
   109  	dockerfile := new(bytes.Buffer)
   110  	template.Must(template.New("").Parse(explorerDockerfile)).Execute(dockerfile, map[string]interface{}{
   111  		"NodePort": config.nodePort,
   112  	})
   113  	files[filepath.Join(workdir, "Dockerfile")] = dockerfile.Bytes()
   114  
   115  	ethstats := new(bytes.Buffer)
   116  	template.Must(template.New("").Parse(explorerEthstats)).Execute(ethstats, map[string]interface{}{
   117  		"Port":   config.nodePort,
   118  		"Name":   config.ethstats[:strings.Index(config.ethstats, ":")],
   119  		"Secret": config.ethstats[strings.Index(config.ethstats, ":")+1 : strings.Index(config.ethstats, "@")],
   120  		"Host":   config.ethstats[strings.Index(config.ethstats, "@")+1:],
   121  	})
   122  	files[filepath.Join(workdir, "ethstats.json")] = ethstats.Bytes()
   123  
   124  	composefile := new(bytes.Buffer)
   125  	template.Must(template.New("").Parse(explorerComposefile)).Execute(composefile, map[string]interface{}{
   126  		"Datadir":  config.datadir,
   127  		"Network":  network,
   128  		"NodePort": config.nodePort,
   129  		"VHost":    config.webHost,
   130  		"WebPort":  config.webPort,
   131  		"Ethstats": config.ethstats[:strings.Index(config.ethstats, ":")],
   132  	})
   133  	files[filepath.Join(workdir, "docker-compose.yaml")] = composefile.Bytes()
   134  
   135  	files[filepath.Join(workdir, "chain.json")] = chainspec
   136  
   137  	// Upload the deployment files to the remote server (and clean up afterwards)
   138  	if out, err := client.Upload(files); err != nil {
   139  		return out, err
   140  	}
   141  	defer client.Run("rm -rf " + workdir)
   142  
   143  	// Build and deploy the boot or seal node service
   144  	if nocache {
   145  		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))
   146  	}
   147  	return nil, client.Stream(fmt.Sprintf("cd %s && docker-compose -p %s up -d --build --force-recreate --timeout 60", workdir, network))
   148  }
   149  
   150  // explorerInfos is returned from a block explorer status check to allow reporting
   151  // various configuration parameters.
   152  type explorerInfos struct {
   153  	datadir  string
   154  	ethstats string
   155  	nodePort int
   156  	webHost  string
   157  	webPort  int
   158  }
   159  
   160  // Report converts the typed struct into a plain string->string map, containing
   161  // most - but not all - fields for reporting to the user.
   162  func (info *explorerInfos) Report() map[string]string {
   163  	report := map[string]string{
   164  		"Data directory":         info.datadir,
   165  		"Node listener port ":    strconv.Itoa(info.nodePort),
   166  		"Ethstats username":      info.ethstats,
   167  		"Website address ":       info.webHost,
   168  		"Website listener port ": strconv.Itoa(info.webPort),
   169  	}
   170  	return report
   171  }
   172  
   173  // checkExplorer does a health-check against a block explorer server to verify
   174  // whether it's running, and if yes, whether it's responsive.
   175  func checkExplorer(client *sshClient, network string) (*explorerInfos, error) {
   176  	// Inspect a possible block explorer container on the host
   177  	infos, err := inspectContainer(client, fmt.Sprintf("%s_explorer_1", network))
   178  	if err != nil {
   179  		return nil, err
   180  	}
   181  	if !infos.running {
   182  		return nil, ErrServiceOffline
   183  	}
   184  	// Resolve the port from the host, or the reverse proxy
   185  	webPort := infos.portmap["3000/tcp"]
   186  	if webPort == 0 {
   187  		if proxy, _ := checkNginx(client, network); proxy != nil {
   188  			webPort = proxy.port
   189  		}
   190  	}
   191  	if webPort == 0 {
   192  		return nil, ErrNotExposed
   193  	}
   194  	// Resolve the host from the reverse-proxy and the config values
   195  	host := infos.envvars["VIRTUAL_HOST"]
   196  	if host == "" {
   197  		host = client.server
   198  	}
   199  	// Run a sanity check to see if the devp2p is reachable
   200  	nodePort := infos.portmap[infos.envvars["NODE_PORT"]]
   201  	if err = checkPort(client.server, nodePort); err != nil {
   202  		log.Warn(fmt.Sprintf("Explorer devp2p port seems unreachable"), "server", client.server, "port", nodePort, "err", err)
   203  	}
   204  	// Assemble and return the useful infos
   205  	stats := &explorerInfos{
   206  		datadir:  infos.volumes["/root/.local/share/io.parity.ethereum"],
   207  		nodePort: nodePort,
   208  		webHost:  host,
   209  		webPort:  webPort,
   210  		ethstats: infos.envvars["STATS"],
   211  	}
   212  	return stats, nil
   213  }