github.com/waltonchain/waltonchain_gwtc_src@v1.1.4-0.20201225072101-8a298c95a819/cmd/puppeth/module_faucet.go (about)

     1  // Copyright 2017 The go-ethereum Authors
     2  // This file is part of go-wtc.
     3  //
     4  // go-wtc 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-wtc 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-wtc. If not, see <http://www.gnu.org/licenses/>.
    16  
    17  package main
    18  
    19  import (
    20  	"bytes"
    21  	"fmt"
    22  	"html/template"
    23  	"math/rand"
    24  	"path/filepath"
    25  	"strconv"
    26  	"strings"
    27  
    28  	"github.com/wtc/go-wtc/log"
    29  )
    30  
    31  // faucetDockerfile is the Dockerfile required to build an faucet container to
    32  // grant crypto tokens based on GitHub authentications.
    33  var faucetDockerfile = `
    34  FROM alpine:latest
    35  
    36  RUN mkdir /go
    37  ENV GOPATH /go
    38  
    39  RUN \
    40    apk add --update git go make gcc musl-dev ca-certificates linux-headers                             && \
    41  	mkdir -p $GOPATH/src/github.com/wtc                                                            && \
    42  	(cd $GOPATH/src/github.com/wtc && git clone --depth=1 https://github.com/wtc/go-wtc) && \
    43    go build -v github.com/wtc/go-wtc/cmd/faucet                                              && \
    44    apk del git go make gcc musl-dev linux-headers                                                      && \
    45    rm -rf $GOPATH && rm -rf /var/cache/apk/*
    46  
    47  ADD genesis.json /genesis.json
    48  ADD account.json /account.json
    49  ADD account.pass /account.pass
    50  
    51  EXPOSE 8080
    52  
    53  CMD [ \
    54  	"/faucet", "--genesis", "/genesis.json", "--network", "{{.NetworkID}}", "--bootnodes", "{{.Bootnodes}}", "--ethstats", "{{.Ethstats}}", "--ethport", "{{.EthPort}}", \
    55  	"--faucet.name", "{{.FaucetName}}", "--faucet.amount", "{{.FaucetAmount}}", "--faucet.minutes", "{{.FaucetMinutes}}", "--faucet.tiers", "{{.FaucetTiers}}",          \
    56  	"--github.user", "{{.GitHubUser}}", "--github.token", "{{.GitHubToken}}", "--account.json", "/account.json", "--account.pass", "/account.pass"                       \
    57  	{{if .CaptchaToken}}, "--captcha.token", "{{.CaptchaToken}}", "--captcha.secret", "{{.CaptchaSecret}}"{{end}}                                                        \
    58  ]`
    59  
    60  // faucetComposefile is the docker-compose.yml file required to deploy and maintain
    61  // a crypto faucet.
    62  var faucetComposefile = `
    63  version: '2'
    64  services:
    65    faucet:
    66      build: .
    67      image: {{.Network}}/faucet
    68      ports:
    69        - "{{.EthPort}}:{{.EthPort}}"{{if not .VHost}}
    70        - "{{.ApiPort}}:8080"{{end}}
    71      volumes:
    72        - {{.Datadir}}:/root/.faucet
    73      environment:
    74        - ETH_PORT={{.EthPort}}
    75        - ETH_NAME={{.EthName}}
    76        - FAUCET_AMOUNT={{.FaucetAmount}}
    77        - FAUCET_MINUTES={{.FaucetMinutes}}
    78        - FAUCET_TIERS={{.FaucetTiers}}
    79        - GITHUB_USER={{.GitHubUser}}
    80        - GITHUB_TOKEN={{.GitHubToken}}
    81        - CAPTCHA_TOKEN={{.CaptchaToken}}
    82        - CAPTCHA_SECRET={{.CaptchaSecret}}{{if .VHost}}
    83        - VIRTUAL_HOST={{.VHost}}
    84        - VIRTUAL_PORT=8080{{end}}
    85      logging:
    86        driver: "json-file"
    87        options:
    88          max-size: "1m"
    89          max-file: "10"
    90      restart: always
    91  `
    92  
    93  // deployFaucet deploys a new faucet container to a remote machine via SSH,
    94  // docker and docker-compose. If an instance with the specified network name
    95  // already exists there, it will be overwritten!
    96  func deployFaucet(client *sshClient, network string, bootnodes []string, config *faucetInfos) ([]byte, error) {
    97  	// Generate the content to upload to the server
    98  	workdir := fmt.Sprintf("%d", rand.Int63())
    99  	files := make(map[string][]byte)
   100  
   101  	dockerfile := new(bytes.Buffer)
   102  	template.Must(template.New("").Parse(faucetDockerfile)).Execute(dockerfile, map[string]interface{}{
   103  		"NetworkID":     config.node.network,
   104  		"Bootnodes":     strings.Join(bootnodes, ","),
   105  		"Ethstats":      config.node.ethstats,
   106  		"EthPort":       config.node.portFull,
   107  		"GitHubUser":    config.githubUser,
   108  		"GitHubToken":   config.githubToken,
   109  		"CaptchaToken":  config.captchaToken,
   110  		"CaptchaSecret": config.captchaSecret,
   111  		"FaucetName":    strings.Title(network),
   112  		"FaucetAmount":  config.amount,
   113  		"FaucetMinutes": config.minutes,
   114  		"FaucetTiers":   config.tiers,
   115  	})
   116  	files[filepath.Join(workdir, "Dockerfile")] = dockerfile.Bytes()
   117  
   118  	composefile := new(bytes.Buffer)
   119  	template.Must(template.New("").Parse(faucetComposefile)).Execute(composefile, map[string]interface{}{
   120  		"Network":       network,
   121  		"Datadir":       config.node.datadir,
   122  		"VHost":         config.host,
   123  		"ApiPort":       config.port,
   124  		"EthPort":       config.node.portFull,
   125  		"EthName":       config.node.ethstats[:strings.Index(config.node.ethstats, ":")],
   126  		"GitHubUser":    config.githubUser,
   127  		"GitHubToken":   config.githubToken,
   128  		"CaptchaToken":  config.captchaToken,
   129  		"CaptchaSecret": config.captchaSecret,
   130  		"FaucetAmount":  config.amount,
   131  		"FaucetMinutes": config.minutes,
   132  		"FaucetTiers":   config.tiers,
   133  	})
   134  	files[filepath.Join(workdir, "docker-compose.yaml")] = composefile.Bytes()
   135  
   136  	files[filepath.Join(workdir, "genesis.json")] = []byte(config.node.genesis)
   137  	files[filepath.Join(workdir, "account.json")] = []byte(config.node.keyJSON)
   138  	files[filepath.Join(workdir, "account.pass")] = []byte(config.node.keyPass)
   139  
   140  	// Upload the deployment files to the remote server (and clean up afterwards)
   141  	if out, err := client.Upload(files); err != nil {
   142  		return out, err
   143  	}
   144  	defer client.Run("rm -rf " + workdir)
   145  
   146  	// Build and deploy the faucet service
   147  	return nil, client.Stream(fmt.Sprintf("cd %s && docker-compose -p %s up -d --build", workdir, network))
   148  }
   149  
   150  // faucetInfos is returned from an faucet status check to allow reporting various
   151  // configuration parameters.
   152  type faucetInfos struct {
   153  	node          *nodeInfos
   154  	host          string
   155  	port          int
   156  	amount        int
   157  	minutes       int
   158  	tiers         int
   159  	githubUser    string
   160  	githubToken   string
   161  	captchaToken  string
   162  	captchaSecret string
   163  }
   164  
   165  // String implements the stringer interface.
   166  func (info *faucetInfos) String() string {
   167  	return fmt.Sprintf("host=%s, api=%d, eth=%d, amount=%d, minutes=%d, tiers=%d, github=%s, captcha=%v, ethstats=%s", info.host, info.port, info.node.portFull, info.amount, info.minutes, info.tiers, info.githubUser, info.captchaToken != "", info.node.ethstats)
   168  }
   169  
   170  // checkFaucet does a health-check against an faucet server to verify whether
   171  // it's running, and if yes, gathering a collection of useful infos about it.
   172  func checkFaucet(client *sshClient, network string) (*faucetInfos, error) {
   173  	// Inspect a possible faucet container on the host
   174  	infos, err := inspectContainer(client, fmt.Sprintf("%s_faucet_1", network))
   175  	if err != nil {
   176  		return nil, err
   177  	}
   178  	if !infos.running {
   179  		return nil, ErrServiceOffline
   180  	}
   181  	// Resolve the port from the host, or the reverse proxy
   182  	port := infos.portmap["8080/tcp"]
   183  	if port == 0 {
   184  		if proxy, _ := checkNginx(client, network); proxy != nil {
   185  			port = proxy.port
   186  		}
   187  	}
   188  	if port == 0 {
   189  		return nil, ErrNotExposed
   190  	}
   191  	// Resolve the host from the reverse-proxy and the config values
   192  	host := infos.envvars["VIRTUAL_HOST"]
   193  	if host == "" {
   194  		host = client.server
   195  	}
   196  	amount, _ := strconv.Atoi(infos.envvars["FAUCET_AMOUNT"])
   197  	minutes, _ := strconv.Atoi(infos.envvars["FAUCET_MINUTES"])
   198  	tiers, _ := strconv.Atoi(infos.envvars["FAUCET_TIERS"])
   199  
   200  	// Retrieve the funding account informations
   201  	var out []byte
   202  	keyJSON, keyPass := "", ""
   203  	if out, err = client.Run(fmt.Sprintf("docker exec %s_faucet_1 cat /account.json", network)); err == nil {
   204  		keyJSON = string(bytes.TrimSpace(out))
   205  	}
   206  	if out, err = client.Run(fmt.Sprintf("docker exec %s_faucet_1 cat /account.pass", network)); err == nil {
   207  		keyPass = string(bytes.TrimSpace(out))
   208  	}
   209  	// Run a sanity check to see if the port is reachable
   210  	if err = checkPort(host, port); err != nil {
   211  		log.Warn("Faucet service seems unreachable", "server", host, "port", port, "err", err)
   212  	}
   213  	// Container available, assemble and return the useful infos
   214  	return &faucetInfos{
   215  		node: &nodeInfos{
   216  			datadir:  infos.volumes["/root/.faucet"],
   217  			portFull: infos.portmap[infos.envvars["ETH_PORT"]+"/tcp"],
   218  			ethstats: infos.envvars["ETH_NAME"],
   219  			keyJSON:  keyJSON,
   220  			keyPass:  keyPass,
   221  		},
   222  		host:          host,
   223  		port:          port,
   224  		amount:        amount,
   225  		minutes:       minutes,
   226  		tiers:         tiers,
   227  		githubUser:    infos.envvars["GITHUB_USER"],
   228  		githubToken:   infos.envvars["GITHUB_TOKEN"],
   229  		captchaToken:  infos.envvars["CAPTCHA_TOKEN"],
   230  		captchaSecret: infos.envvars["CAPTCHA_SECRET"],
   231  	}, nil
   232  }