github.com/aigarnetwork/aigar@v0.0.0-20191115204914-d59a6eb70f8e/build/ci.go (about)

     1  //  Copyright 2018 The go-ethereum Authors
     2  //  Copyright 2019 The go-aigar Authors
     3  //  This file is part of the go-aigar library.
     4  //
     5  //  The go-aigar library is free software: you can redistribute it and/or modify
     6  //  it under the terms of the GNU Lesser 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  //  The go-aigar library 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 Lesser General Public License for more details.
    14  //
    15  //  You should have received a copy of the GNU Lesser General Public License
    16  //  along with the go-aigar library. If not, see <http://www.gnu.org/licenses/>.
    17  
    18  // +build none
    19  
    20  /*
    21  The ci command is called from Continuous Integration scripts.
    22  
    23  Usage: go run build/ci.go <command> <command flags/arguments>
    24  
    25  Available commands are:
    26  
    27     install    [ -arch architecture ] [ -cc compiler ] [ packages... ]                          -- builds packages and executables
    28     test       [ -coverage ] [ packages... ]                                                    -- runs the tests
    29     lint                                                                                        -- runs certain pre-selected linters
    30     archive    [ -arch architecture ] [ -type zip|tar ] [ -signer key-envvar ] [ -upload dest ] -- archives build artifacts
    31     importkeys                                                                                  -- imports signing keys from env
    32     debsrc     [ -signer key-id ] [ -upload dest ]                                              -- creates a debian source package
    33     nsis                                                                                        -- creates a Windows NSIS installer
    34     aar        [ -local ] [ -sign key-id ] [-deploy repo] [ -upload dest ]                      -- creates an Android archive
    35     xcode      [ -local ] [ -sign key-id ] [-deploy repo] [ -upload dest ]                      -- creates an iOS XCode framework
    36     xgo        [ -alltools ] [ options ]                                                        -- cross builds according to options
    37     purge      [ -store blobstore ] [ -days threshold ]                                         -- purges old archives from the blobstore
    38  
    39  For all commands, -n prevents execution of external programs (dry run mode).
    40  
    41  */
    42  package main
    43  
    44  import (
    45  	"bufio"
    46  	"bytes"
    47  	"encoding/base64"
    48  	"flag"
    49  	"fmt"
    50  	"go/parser"
    51  	"go/token"
    52  	"io/ioutil"
    53  	"log"
    54  	"os"
    55  	"os/exec"
    56  	"path/filepath"
    57  	"regexp"
    58  	"runtime"
    59  	"strings"
    60  	"time"
    61  
    62  	"github.com/AigarNetwork/aigar/common/hexutil"
    63  	"github.com/AigarNetwork/aigar/internal/build"
    64  	"github.com/AigarNetwork/aigar/params"
    65  )
    66  
    67  var (
    68  	// Files that end up in the geth*.zip archive.
    69  	gethArchiveFiles = []string{
    70  		"COPYING",
    71  		executablePath("geth"),
    72  	}
    73  
    74  	// Files that end up in the geth-alltools*.zip archive.
    75  	allToolsArchiveFiles = []string{
    76  		"COPYING",
    77  		executablePath("abigen"),
    78  		executablePath("bootnode"),
    79  		executablePath("evm"),
    80  		executablePath("geth"),
    81  		executablePath("puppeth"),
    82  		executablePath("rlpdump"),
    83  		executablePath("wnode"),
    84  		executablePath("clef"),
    85  	}
    86  
    87  	// A debian package is created for all executables listed here.
    88  	debExecutables = []debExecutable{
    89  		{
    90  			BinaryName:  "abigen",
    91  			Description: "Source code generator to convert Ethereum contract definitions into easy to use, compile-time type-safe Go packages.",
    92  		},
    93  		{
    94  			BinaryName:  "bootnode",
    95  			Description: "Ethereum bootnode.",
    96  		},
    97  		{
    98  			BinaryName:  "evm",
    99  			Description: "Developer utility version of the EVM (Ethereum Virtual Machine) that is capable of running bytecode snippets within a configurable environment and execution mode.",
   100  		},
   101  		{
   102  			BinaryName:  "geth",
   103  			Description: "Ethereum CLI client.",
   104  		},
   105  		{
   106  			BinaryName:  "puppeth",
   107  			Description: "Ethereum private network manager.",
   108  		},
   109  		{
   110  			BinaryName:  "rlpdump",
   111  			Description: "Developer utility tool that prints RLP structures.",
   112  		},
   113  		{
   114  			BinaryName:  "wnode",
   115  			Description: "Ethereum Whisper diagnostic tool",
   116  		},
   117  		{
   118  			BinaryName:  "clef",
   119  			Description: "Ethereum account management tool.",
   120  		},
   121  	}
   122  
   123  	// A debian package is created for all executables listed here.
   124  
   125  	debEthereum = debPackage{
   126  		Name:        "ethereum",
   127  		Version:     params.Version,
   128  		Executables: debExecutables,
   129  	}
   130  
   131  	// Debian meta packages to build and push to Ubuntu PPA
   132  	debPackages = []debPackage{
   133  		debEthereum,
   134  	}
   135  
   136  	// Distros for which packages are created.
   137  	// Note: vivid is unsupported because there is no golang-1.6 package for it.
   138  	// Note: wily is unsupported because it was officially deprecated on Launchpad.
   139  	// Note: yakkety is unsupported because it was officially deprecated on Launchpad.
   140  	// Note: zesty is unsupported because it was officially deprecated on Launchpad.
   141  	// Note: artful is unsupported because it was officially deprecated on Launchpad.
   142  	// Note: cosmic is unsupported because it was officially deprecated on Launchpad.
   143  	debDistroGoBoots = map[string]string{
   144  		"trusty": "golang-1.11",
   145  		"xenial": "golang-go",
   146  		"bionic": "golang-go",
   147  		"disco":  "golang-go",
   148  		"eoan":   "golang-go",
   149  	}
   150  
   151  	debGoBootPaths = map[string]string{
   152  		"golang-1.11": "/usr/lib/go-1.11",
   153  		"golang-go":   "/usr/lib/go",
   154  	}
   155  )
   156  
   157  var GOBIN, _ = filepath.Abs(filepath.Join("build", "bin"))
   158  
   159  func executablePath(name string) string {
   160  	if runtime.GOOS == "windows" {
   161  		name += ".exe"
   162  	}
   163  	return filepath.Join(GOBIN, name)
   164  }
   165  
   166  func main() {
   167  	log.SetFlags(log.Lshortfile)
   168  
   169  	if _, err := os.Stat(filepath.Join("build", "ci.go")); os.IsNotExist(err) {
   170  		log.Fatal("this script must be run from the root of the repository")
   171  	}
   172  	if len(os.Args) < 2 {
   173  		log.Fatal("need subcommand as first argument")
   174  	}
   175  	switch os.Args[1] {
   176  	case "install":
   177  		doInstall(os.Args[2:])
   178  	case "test":
   179  		doTest(os.Args[2:])
   180  	case "lint":
   181  		doLint(os.Args[2:])
   182  	case "archive":
   183  		doArchive(os.Args[2:])
   184  	case "debsrc":
   185  		doDebianSource(os.Args[2:])
   186  	case "nsis":
   187  		doWindowsInstaller(os.Args[2:])
   188  	case "aar":
   189  		doAndroidArchive(os.Args[2:])
   190  	case "xcode":
   191  		doXCodeFramework(os.Args[2:])
   192  	case "xgo":
   193  		doXgo(os.Args[2:])
   194  	case "purge":
   195  		doPurge(os.Args[2:])
   196  	default:
   197  		log.Fatal("unknown command ", os.Args[1])
   198  	}
   199  }
   200  
   201  // Compiling
   202  
   203  func doInstall(cmdline []string) {
   204  	var (
   205  		arch = flag.String("arch", "", "Architecture to cross build for")
   206  		cc   = flag.String("cc", "", "C compiler to cross build with")
   207  	)
   208  	flag.CommandLine.Parse(cmdline)
   209  	env := build.Env()
   210  
   211  	// Check Go version. People regularly open issues about compilation
   212  	// failure with outdated Go. This should save them the trouble.
   213  	if !strings.Contains(runtime.Version(), "devel") {
   214  		// Figure out the minor version number since we can't textually compare (1.10 < 1.9)
   215  		var minor int
   216  		fmt.Sscanf(strings.TrimPrefix(runtime.Version(), "go1."), "%d", &minor)
   217  
   218  		if minor < 9 {
   219  			log.Println("You have Go version", runtime.Version())
   220  			log.Println("go-ethereum requires at least Go version 1.9 and cannot")
   221  			log.Println("be compiled with an earlier version. Please upgrade your Go installation.")
   222  			os.Exit(1)
   223  		}
   224  	}
   225  	// Compile packages given as arguments, or everything if there are no arguments.
   226  	packages := []string{"./..."}
   227  	if flag.NArg() > 0 {
   228  		packages = flag.Args()
   229  	}
   230  
   231  	if *arch == "" || *arch == runtime.GOARCH {
   232  		goinstall := goTool("install", buildFlags(env)...)
   233  		if runtime.GOARCH == "arm64" {
   234  			goinstall.Args = append(goinstall.Args, "-p", "1")
   235  		}
   236  		goinstall.Args = append(goinstall.Args, "-v")
   237  		goinstall.Args = append(goinstall.Args, packages...)
   238  		build.MustRun(goinstall)
   239  		return
   240  	}
   241  	// If we are cross compiling to ARMv5 ARMv6 or ARMv7, clean any previous builds
   242  	if *arch == "arm" {
   243  		os.RemoveAll(filepath.Join(runtime.GOROOT(), "pkg", runtime.GOOS+"_arm"))
   244  		for _, path := range filepath.SplitList(build.GOPATH()) {
   245  			os.RemoveAll(filepath.Join(path, "pkg", runtime.GOOS+"_arm"))
   246  		}
   247  	}
   248  
   249  	// Seems we are cross compiling, work around forbidden GOBIN
   250  	goinstall := goToolArch(*arch, *cc, "install", buildFlags(env)...)
   251  	goinstall.Args = append(goinstall.Args, "-v")
   252  	goinstall.Args = append(goinstall.Args, []string{"-buildmode", "archive"}...)
   253  	goinstall.Args = append(goinstall.Args, packages...)
   254  	build.MustRun(goinstall)
   255  
   256  	if cmds, err := ioutil.ReadDir("cmd"); err == nil {
   257  		for _, cmd := range cmds {
   258  			pkgs, err := parser.ParseDir(token.NewFileSet(), filepath.Join(".", "cmd", cmd.Name()), nil, parser.PackageClauseOnly)
   259  			if err != nil {
   260  				log.Fatal(err)
   261  			}
   262  			for name := range pkgs {
   263  				if name == "main" {
   264  					gobuild := goToolArch(*arch, *cc, "build", buildFlags(env)...)
   265  					gobuild.Args = append(gobuild.Args, "-v")
   266  					gobuild.Args = append(gobuild.Args, []string{"-o", executablePath(cmd.Name())}...)
   267  					gobuild.Args = append(gobuild.Args, "."+string(filepath.Separator)+filepath.Join("cmd", cmd.Name()))
   268  					build.MustRun(gobuild)
   269  					break
   270  				}
   271  			}
   272  		}
   273  	}
   274  }
   275  
   276  func buildFlags(env build.Environment) (flags []string) {
   277  	var ld []string
   278  	if env.Commit != "" {
   279  		ld = append(ld, "-X", "main.gitCommit="+env.Commit)
   280  		ld = append(ld, "-X", "main.gitDate="+env.Date)
   281  	}
   282  	if runtime.GOOS == "darwin" {
   283  		ld = append(ld, "-s")
   284  	}
   285  
   286  	if len(ld) > 0 {
   287  		flags = append(flags, "-ldflags", strings.Join(ld, " "))
   288  	}
   289  	return flags
   290  }
   291  
   292  func goTool(subcmd string, args ...string) *exec.Cmd {
   293  	return goToolArch(runtime.GOARCH, os.Getenv("CC"), subcmd, args...)
   294  }
   295  
   296  func goToolArch(arch string, cc string, subcmd string, args ...string) *exec.Cmd {
   297  	cmd := build.GoTool(subcmd, args...)
   298  	cmd.Env = []string{"GOPATH=" + build.GOPATH()}
   299  	if arch == "" || arch == runtime.GOARCH {
   300  		cmd.Env = append(cmd.Env, "GOBIN="+GOBIN)
   301  	} else {
   302  		cmd.Env = append(cmd.Env, "CGO_ENABLED=1")
   303  		cmd.Env = append(cmd.Env, "GOARCH="+arch)
   304  	}
   305  	if cc != "" {
   306  		cmd.Env = append(cmd.Env, "CC="+cc)
   307  	}
   308  	for _, e := range os.Environ() {
   309  		if strings.HasPrefix(e, "GOPATH=") || strings.HasPrefix(e, "GOBIN=") {
   310  			continue
   311  		}
   312  		cmd.Env = append(cmd.Env, e)
   313  	}
   314  	return cmd
   315  }
   316  
   317  // Running The Tests
   318  //
   319  // "tests" also includes static analysis tools such as vet.
   320  
   321  func doTest(cmdline []string) {
   322  	coverage := flag.Bool("coverage", false, "Whether to record code coverage")
   323  	flag.CommandLine.Parse(cmdline)
   324  	env := build.Env()
   325  
   326  	packages := []string{"./..."}
   327  	if len(flag.CommandLine.Args()) > 0 {
   328  		packages = flag.CommandLine.Args()
   329  	}
   330  
   331  	// Run the actual tests.
   332  	// Test a single package at a time. CI builders are slow
   333  	// and some tests run into timeouts under load.
   334  	gotest := goTool("test", buildFlags(env)...)
   335  	gotest.Args = append(gotest.Args, "-p", "1", "-timeout", "5m", "--short")
   336  	if *coverage {
   337  		gotest.Args = append(gotest.Args, "-covermode=atomic", "-cover")
   338  	}
   339  
   340  	gotest.Args = append(gotest.Args, packages...)
   341  	build.MustRun(gotest)
   342  }
   343  
   344  // runs gometalinter on requested packages
   345  func doLint(cmdline []string) {
   346  	flag.CommandLine.Parse(cmdline)
   347  
   348  	packages := []string{"./..."}
   349  	if len(flag.CommandLine.Args()) > 0 {
   350  		packages = flag.CommandLine.Args()
   351  	}
   352  	// Get metalinter and install all supported linters
   353  	build.MustRun(goTool("get", "gopkg.in/alecthomas/gometalinter.v2"))
   354  	build.MustRunCommand(filepath.Join(GOBIN, "gometalinter.v2"), "--install")
   355  
   356  	// Run fast linters batched together
   357  	configs := []string{
   358  		"--vendor",
   359  		"--tests",
   360  		"--deadline=2m",
   361  		"--disable-all",
   362  		"--enable=goimports",
   363  		"--enable=varcheck",
   364  		"--enable=vet",
   365  		"--enable=gofmt",
   366  		"--enable=misspell",
   367  		"--enable=goconst",
   368  		"--min-occurrences=6", // for goconst
   369  	}
   370  	build.MustRunCommand(filepath.Join(GOBIN, "gometalinter.v2"), append(configs, packages...)...)
   371  
   372  	// Run slow linters one by one
   373  	for _, linter := range []string{"unconvert", "gosimple"} {
   374  		configs = []string{"--vendor", "--tests", "--deadline=10m", "--disable-all", "--enable=" + linter}
   375  		build.MustRunCommand(filepath.Join(GOBIN, "gometalinter.v2"), append(configs, packages...)...)
   376  	}
   377  }
   378  
   379  // Release Packaging
   380  func doArchive(cmdline []string) {
   381  	var (
   382  		arch   = flag.String("arch", runtime.GOARCH, "Architecture cross packaging")
   383  		atype  = flag.String("type", "zip", "Type of archive to write (zip|tar)")
   384  		signer = flag.String("signer", "", `Environment variable holding the signing key (e.g. LINUX_SIGNING_KEY)`)
   385  		upload = flag.String("upload", "", `Destination to upload the archives (usually "gethstore/builds")`)
   386  		ext    string
   387  	)
   388  	flag.CommandLine.Parse(cmdline)
   389  	switch *atype {
   390  	case "zip":
   391  		ext = ".zip"
   392  	case "tar":
   393  		ext = ".tar.gz"
   394  	default:
   395  		log.Fatal("unknown archive type: ", atype)
   396  	}
   397  
   398  	var (
   399  		env = build.Env()
   400  
   401  		basegeth = archiveBasename(*arch, params.ArchiveVersion(env.Commit))
   402  		geth     = "geth-" + basegeth + ext
   403  		alltools = "geth-alltools-" + basegeth + ext
   404  	)
   405  	maybeSkipArchive(env)
   406  	if err := build.WriteArchive(geth, gethArchiveFiles); err != nil {
   407  		log.Fatal(err)
   408  	}
   409  	if err := build.WriteArchive(alltools, allToolsArchiveFiles); err != nil {
   410  		log.Fatal(err)
   411  	}
   412  	for _, archive := range []string{geth, alltools} {
   413  		if err := archiveUpload(archive, *upload, *signer); err != nil {
   414  			log.Fatal(err)
   415  		}
   416  	}
   417  }
   418  
   419  func archiveBasename(arch string, archiveVersion string) string {
   420  	platform := runtime.GOOS + "-" + arch
   421  	if arch == "arm" {
   422  		platform += os.Getenv("GOARM")
   423  	}
   424  	if arch == "android" {
   425  		platform = "android-all"
   426  	}
   427  	if arch == "ios" {
   428  		platform = "ios-all"
   429  	}
   430  	return platform + "-" + archiveVersion
   431  }
   432  
   433  func archiveUpload(archive string, blobstore string, signer string) error {
   434  	// If signing was requested, generate the signature files
   435  	if signer != "" {
   436  		key := getenvBase64(signer)
   437  		if err := build.PGPSignFile(archive, archive+".asc", string(key)); err != nil {
   438  			return err
   439  		}
   440  	}
   441  	// If uploading to Azure was requested, push the archive possibly with its signature
   442  	if blobstore != "" {
   443  		auth := build.AzureBlobstoreConfig{
   444  			Account:   strings.Split(blobstore, "/")[0],
   445  			Token:     os.Getenv("AZURE_BLOBSTORE_TOKEN"),
   446  			Container: strings.SplitN(blobstore, "/", 2)[1],
   447  		}
   448  		if err := build.AzureBlobstoreUpload(archive, filepath.Base(archive), auth); err != nil {
   449  			return err
   450  		}
   451  		if signer != "" {
   452  			if err := build.AzureBlobstoreUpload(archive+".asc", filepath.Base(archive+".asc"), auth); err != nil {
   453  				return err
   454  			}
   455  		}
   456  	}
   457  	return nil
   458  }
   459  
   460  // skips archiving for some build configurations.
   461  func maybeSkipArchive(env build.Environment) {
   462  	if env.IsPullRequest {
   463  		log.Printf("skipping because this is a PR build")
   464  		os.Exit(0)
   465  	}
   466  	if env.IsCronJob {
   467  		log.Printf("skipping because this is a cron job")
   468  		os.Exit(0)
   469  	}
   470  	if env.Branch != "master" && !strings.HasPrefix(env.Tag, "v1.") {
   471  		log.Printf("skipping because branch %q, tag %q is not on the whitelist", env.Branch, env.Tag)
   472  		os.Exit(0)
   473  	}
   474  }
   475  
   476  // Debian Packaging
   477  func doDebianSource(cmdline []string) {
   478  	var (
   479  		goversion = flag.String("goversion", "", `Go version to build with (will be included in the source package)`)
   480  		gobundle  = flag.String("gobundle", "/tmp/go.tar.gz", `Filesystem path to cache the downloaded Go bundles at`)
   481  		gohash    = flag.String("gohash", "", `SHA256 checksum of the Go sources requested to build with`)
   482  		signer    = flag.String("signer", "", `Signing key name, also used as package author`)
   483  		upload    = flag.String("upload", "", `Where to upload the source package (usually "ethereum/ethereum")`)
   484  		sshUser   = flag.String("sftp-user", "", `Username for SFTP upload (usually "geth-ci")`)
   485  		workdir   = flag.String("workdir", "", `Output directory for packages (uses temp dir if unset)`)
   486  		now       = time.Now()
   487  	)
   488  	flag.CommandLine.Parse(cmdline)
   489  	*workdir = makeWorkdir(*workdir)
   490  	env := build.Env()
   491  	maybeSkipArchive(env)
   492  
   493  	// Import the signing key.
   494  	if key := getenvBase64("PPA_SIGNING_KEY"); len(key) > 0 {
   495  		gpg := exec.Command("gpg", "--import")
   496  		gpg.Stdin = bytes.NewReader(key)
   497  		build.MustRun(gpg)
   498  	}
   499  	// Download and verify the Go source package
   500  	if err := build.EnsureGoSources(*goversion, hexutil.MustDecode("0x"+*gohash), *gobundle); err != nil {
   501  		log.Fatalf("Failed to ensure Go source package: %v", err)
   502  	}
   503  	// Create Debian packages and upload them
   504  	for _, pkg := range debPackages {
   505  		for distro, goboot := range debDistroGoBoots {
   506  			// Prepare the debian package with the go-ethereum sources
   507  			meta := newDebMetadata(distro, goboot, *signer, env, now, pkg.Name, pkg.Version, pkg.Executables)
   508  			pkgdir := stageDebianSource(*workdir, meta)
   509  
   510  			// Ship the Go sources along so we have a proper thing to build with
   511  			if err := build.ExtractTarballArchive(*gobundle, pkgdir); err != nil {
   512  				log.Fatalf("Failed to extract Go sources: %v", err)
   513  			}
   514  			if err := os.Rename(filepath.Join(pkgdir, "go"), filepath.Join(pkgdir, ".go")); err != nil {
   515  				log.Fatalf("Failed to rename Go source folder: %v", err)
   516  			}
   517  			// Run the packaging and upload to the PPA
   518  			debuild := exec.Command("debuild", "-S", "-sa", "-us", "-uc", "-d", "-Zxz")
   519  			debuild.Dir = pkgdir
   520  			build.MustRun(debuild)
   521  
   522  			var (
   523  				basename = fmt.Sprintf("%s_%s", meta.Name(), meta.VersionString())
   524  				source   = filepath.Join(*workdir, basename+".tar.xz")
   525  				dsc      = filepath.Join(*workdir, basename+".dsc")
   526  				changes  = filepath.Join(*workdir, basename+"_source.changes")
   527  			)
   528  			if *signer != "" {
   529  				build.MustRunCommand("debsign", changes)
   530  			}
   531  			if *upload != "" {
   532  				ppaUpload(*workdir, *upload, *sshUser, []string{source, dsc, changes})
   533  			}
   534  		}
   535  	}
   536  }
   537  
   538  func ppaUpload(workdir, ppa, sshUser string, files []string) {
   539  	p := strings.Split(ppa, "/")
   540  	if len(p) != 2 {
   541  		log.Fatal("-upload PPA name must contain single /")
   542  	}
   543  	if sshUser == "" {
   544  		sshUser = p[0]
   545  	}
   546  	incomingDir := fmt.Sprintf("~%s/ubuntu/%s", p[0], p[1])
   547  	// Create the SSH identity file if it doesn't exist.
   548  	var idfile string
   549  	if sshkey := getenvBase64("PPA_SSH_KEY"); len(sshkey) > 0 {
   550  		idfile = filepath.Join(workdir, "sshkey")
   551  		if _, err := os.Stat(idfile); os.IsNotExist(err) {
   552  			ioutil.WriteFile(idfile, sshkey, 0600)
   553  		}
   554  	}
   555  	// Upload
   556  	dest := sshUser + "@ppa.launchpad.net"
   557  	if err := build.UploadSFTP(idfile, dest, incomingDir, files); err != nil {
   558  		log.Fatal(err)
   559  	}
   560  }
   561  
   562  func getenvBase64(variable string) []byte {
   563  	dec, err := base64.StdEncoding.DecodeString(os.Getenv(variable))
   564  	if err != nil {
   565  		log.Fatal("invalid base64 " + variable)
   566  	}
   567  	return []byte(dec)
   568  }
   569  
   570  func makeWorkdir(wdflag string) string {
   571  	var err error
   572  	if wdflag != "" {
   573  		err = os.MkdirAll(wdflag, 0744)
   574  	} else {
   575  		wdflag, err = ioutil.TempDir("", "geth-build-")
   576  	}
   577  	if err != nil {
   578  		log.Fatal(err)
   579  	}
   580  	return wdflag
   581  }
   582  
   583  func isUnstableBuild(env build.Environment) bool {
   584  	if env.Tag != "" {
   585  		return false
   586  	}
   587  	return true
   588  }
   589  
   590  type debPackage struct {
   591  	Name        string          // the name of the Debian package to produce, e.g. "ethereum"
   592  	Version     string          // the clean version of the debPackage, e.g. 1.8.12, without any metadata
   593  	Executables []debExecutable // executables to be included in the package
   594  }
   595  
   596  type debMetadata struct {
   597  	Env           build.Environment
   598  	GoBootPackage string
   599  	GoBootPath    string
   600  
   601  	PackageName string
   602  
   603  	// go-ethereum version being built. Note that this
   604  	// is not the debian package version. The package version
   605  	// is constructed by VersionString.
   606  	Version string
   607  
   608  	Author       string // "name <email>", also selects signing key
   609  	Distro, Time string
   610  	Executables  []debExecutable
   611  }
   612  
   613  type debExecutable struct {
   614  	PackageName string
   615  	BinaryName  string
   616  	Description string
   617  }
   618  
   619  // Package returns the name of the package if present, or
   620  // fallbacks to BinaryName
   621  func (d debExecutable) Package() string {
   622  	if d.PackageName != "" {
   623  		return d.PackageName
   624  	}
   625  	return d.BinaryName
   626  }
   627  
   628  func newDebMetadata(distro, goboot, author string, env build.Environment, t time.Time, name string, version string, exes []debExecutable) debMetadata {
   629  	if author == "" {
   630  		// No signing key, use default author.
   631  		author = "Ethereum Builds <fjl@ethereum.org>"
   632  	}
   633  	return debMetadata{
   634  		GoBootPackage: goboot,
   635  		GoBootPath:    debGoBootPaths[goboot],
   636  		PackageName:   name,
   637  		Env:           env,
   638  		Author:        author,
   639  		Distro:        distro,
   640  		Version:       version,
   641  		Time:          t.Format(time.RFC1123Z),
   642  		Executables:   exes,
   643  	}
   644  }
   645  
   646  // Name returns the name of the metapackage that depends
   647  // on all executable packages.
   648  func (meta debMetadata) Name() string {
   649  	if isUnstableBuild(meta.Env) {
   650  		return meta.PackageName + "-unstable"
   651  	}
   652  	return meta.PackageName
   653  }
   654  
   655  // VersionString returns the debian version of the packages.
   656  func (meta debMetadata) VersionString() string {
   657  	vsn := meta.Version
   658  	if meta.Env.Buildnum != "" {
   659  		vsn += "+build" + meta.Env.Buildnum
   660  	}
   661  	if meta.Distro != "" {
   662  		vsn += "+" + meta.Distro
   663  	}
   664  	return vsn
   665  }
   666  
   667  // ExeList returns the list of all executable packages.
   668  func (meta debMetadata) ExeList() string {
   669  	names := make([]string, len(meta.Executables))
   670  	for i, e := range meta.Executables {
   671  		names[i] = meta.ExeName(e)
   672  	}
   673  	return strings.Join(names, ", ")
   674  }
   675  
   676  // ExeName returns the package name of an executable package.
   677  func (meta debMetadata) ExeName(exe debExecutable) string {
   678  	if isUnstableBuild(meta.Env) {
   679  		return exe.Package() + "-unstable"
   680  	}
   681  	return exe.Package()
   682  }
   683  
   684  // ExeConflicts returns the content of the Conflicts field
   685  // for executable packages.
   686  func (meta debMetadata) ExeConflicts(exe debExecutable) string {
   687  	if isUnstableBuild(meta.Env) {
   688  		// Set up the conflicts list so that the *-unstable packages
   689  		// cannot be installed alongside the regular version.
   690  		//
   691  		// https://www.debian.org/doc/debian-policy/ch-relationships.html
   692  		// is very explicit about Conflicts: and says that Breaks: should
   693  		// be preferred and the conflicting files should be handled via
   694  		// alternates. We might do this eventually but using a conflict is
   695  		// easier now.
   696  		return "ethereum, " + exe.Package()
   697  	}
   698  	return ""
   699  }
   700  
   701  func stageDebianSource(tmpdir string, meta debMetadata) (pkgdir string) {
   702  	pkg := meta.Name() + "-" + meta.VersionString()
   703  	pkgdir = filepath.Join(tmpdir, pkg)
   704  	if err := os.Mkdir(pkgdir, 0755); err != nil {
   705  		log.Fatal(err)
   706  	}
   707  	// Copy the source code.
   708  	build.MustRunCommand("git", "checkout-index", "-a", "--prefix", pkgdir+string(filepath.Separator))
   709  
   710  	// Put the debian build files in place.
   711  	debian := filepath.Join(pkgdir, "debian")
   712  	build.Render("build/deb/"+meta.PackageName+"/deb.rules", filepath.Join(debian, "rules"), 0755, meta)
   713  	build.Render("build/deb/"+meta.PackageName+"/deb.changelog", filepath.Join(debian, "changelog"), 0644, meta)
   714  	build.Render("build/deb/"+meta.PackageName+"/deb.control", filepath.Join(debian, "control"), 0644, meta)
   715  	build.Render("build/deb/"+meta.PackageName+"/deb.copyright", filepath.Join(debian, "copyright"), 0644, meta)
   716  	build.RenderString("8\n", filepath.Join(debian, "compat"), 0644, meta)
   717  	build.RenderString("3.0 (native)\n", filepath.Join(debian, "source/format"), 0644, meta)
   718  	for _, exe := range meta.Executables {
   719  		install := filepath.Join(debian, meta.ExeName(exe)+".install")
   720  		docs := filepath.Join(debian, meta.ExeName(exe)+".docs")
   721  		build.Render("build/deb/"+meta.PackageName+"/deb.install", install, 0644, exe)
   722  		build.Render("build/deb/"+meta.PackageName+"/deb.docs", docs, 0644, exe)
   723  	}
   724  	return pkgdir
   725  }
   726  
   727  // Windows installer
   728  func doWindowsInstaller(cmdline []string) {
   729  	// Parse the flags and make skip installer generation on PRs
   730  	var (
   731  		arch    = flag.String("arch", runtime.GOARCH, "Architecture for cross build packaging")
   732  		signer  = flag.String("signer", "", `Environment variable holding the signing key (e.g. WINDOWS_SIGNING_KEY)`)
   733  		upload  = flag.String("upload", "", `Destination to upload the archives (usually "gethstore/builds")`)
   734  		workdir = flag.String("workdir", "", `Output directory for packages (uses temp dir if unset)`)
   735  	)
   736  	flag.CommandLine.Parse(cmdline)
   737  	*workdir = makeWorkdir(*workdir)
   738  	env := build.Env()
   739  	maybeSkipArchive(env)
   740  
   741  	// Aggregate binaries that are included in the installer
   742  	var (
   743  		devTools []string
   744  		allTools []string
   745  		gethTool string
   746  	)
   747  	for _, file := range allToolsArchiveFiles {
   748  		if file == "COPYING" { // license, copied later
   749  			continue
   750  		}
   751  		allTools = append(allTools, filepath.Base(file))
   752  		if filepath.Base(file) == "geth.exe" {
   753  			gethTool = file
   754  		} else {
   755  			devTools = append(devTools, file)
   756  		}
   757  	}
   758  
   759  	// Render NSIS scripts: Installer NSIS contains two installer sections,
   760  	// first section contains the geth binary, second section holds the dev tools.
   761  	templateData := map[string]interface{}{
   762  		"License":  "COPYING",
   763  		"Geth":     gethTool,
   764  		"DevTools": devTools,
   765  	}
   766  	build.Render("build/nsis.geth.nsi", filepath.Join(*workdir, "geth.nsi"), 0644, nil)
   767  	build.Render("build/nsis.install.nsh", filepath.Join(*workdir, "install.nsh"), 0644, templateData)
   768  	build.Render("build/nsis.uninstall.nsh", filepath.Join(*workdir, "uninstall.nsh"), 0644, allTools)
   769  	build.Render("build/nsis.pathupdate.nsh", filepath.Join(*workdir, "PathUpdate.nsh"), 0644, nil)
   770  	build.Render("build/nsis.envvarupdate.nsh", filepath.Join(*workdir, "EnvVarUpdate.nsh"), 0644, nil)
   771  	build.CopyFile(filepath.Join(*workdir, "SimpleFC.dll"), "build/nsis.simplefc.dll", 0755)
   772  	build.CopyFile(filepath.Join(*workdir, "COPYING"), "COPYING", 0755)
   773  
   774  	// Build the installer. This assumes that all the needed files have been previously
   775  	// built (don't mix building and packaging to keep cross compilation complexity to a
   776  	// minimum).
   777  	version := strings.Split(params.Version, ".")
   778  	if env.Commit != "" {
   779  		version[2] += "-" + env.Commit[:8]
   780  	}
   781  	installer, _ := filepath.Abs("geth-" + archiveBasename(*arch, params.ArchiveVersion(env.Commit)) + ".exe")
   782  	build.MustRunCommand("makensis.exe",
   783  		"/DOUTPUTFILE="+installer,
   784  		"/DMAJORVERSION="+version[0],
   785  		"/DMINORVERSION="+version[1],
   786  		"/DBUILDVERSION="+version[2],
   787  		"/DARCH="+*arch,
   788  		filepath.Join(*workdir, "geth.nsi"),
   789  	)
   790  
   791  	// Sign and publish installer.
   792  	if err := archiveUpload(installer, *upload, *signer); err != nil {
   793  		log.Fatal(err)
   794  	}
   795  }
   796  
   797  // Android archives
   798  
   799  func doAndroidArchive(cmdline []string) {
   800  	var (
   801  		local  = flag.Bool("local", false, `Flag whether we're only doing a local build (skip Maven artifacts)`)
   802  		signer = flag.String("signer", "", `Environment variable holding the signing key (e.g. ANDROID_SIGNING_KEY)`)
   803  		deploy = flag.String("deploy", "", `Destination to deploy the archive (usually "https://oss.sonatype.org")`)
   804  		upload = flag.String("upload", "", `Destination to upload the archive (usually "gethstore/builds")`)
   805  	)
   806  	flag.CommandLine.Parse(cmdline)
   807  	env := build.Env()
   808  
   809  	// Sanity check that the SDK and NDK are installed and set
   810  	if os.Getenv("ANDROID_HOME") == "" {
   811  		log.Fatal("Please ensure ANDROID_HOME points to your Android SDK")
   812  	}
   813  	// Build the Android archive and Maven resources
   814  	build.MustRun(goTool("get", "golang.org/x/mobile/cmd/gomobile", "golang.org/x/mobile/cmd/gobind"))
   815  	build.MustRun(gomobileTool("bind", "-ldflags", "-s -w", "--target", "android", "--javapkg", "org.ethereum", "-v", "github.com/AigarNetwork/aigar/mobile"))
   816  
   817  	if *local {
   818  		// If we're building locally, copy bundle to build dir and skip Maven
   819  		os.Rename("geth.aar", filepath.Join(GOBIN, "geth.aar"))
   820  		return
   821  	}
   822  	meta := newMavenMetadata(env)
   823  	build.Render("build/mvn.pom", meta.Package+".pom", 0755, meta)
   824  
   825  	// Skip Maven deploy and Azure upload for PR builds
   826  	maybeSkipArchive(env)
   827  
   828  	// Sign and upload the archive to Azure
   829  	archive := "geth-" + archiveBasename("android", params.ArchiveVersion(env.Commit)) + ".aar"
   830  	os.Rename("geth.aar", archive)
   831  
   832  	if err := archiveUpload(archive, *upload, *signer); err != nil {
   833  		log.Fatal(err)
   834  	}
   835  	// Sign and upload all the artifacts to Maven Central
   836  	os.Rename(archive, meta.Package+".aar")
   837  	if *signer != "" && *deploy != "" {
   838  		// Import the signing key into the local GPG instance
   839  		key := getenvBase64(*signer)
   840  		gpg := exec.Command("gpg", "--import")
   841  		gpg.Stdin = bytes.NewReader(key)
   842  		build.MustRun(gpg)
   843  		keyID, err := build.PGPKeyID(string(key))
   844  		if err != nil {
   845  			log.Fatal(err)
   846  		}
   847  		// Upload the artifacts to Sonatype and/or Maven Central
   848  		repo := *deploy + "/service/local/staging/deploy/maven2"
   849  		if meta.Develop {
   850  			repo = *deploy + "/content/repositories/snapshots"
   851  		}
   852  		build.MustRunCommand("mvn", "gpg:sign-and-deploy-file", "-e", "-X",
   853  			"-settings=build/mvn.settings", "-Durl="+repo, "-DrepositoryId=ossrh",
   854  			"-Dgpg.keyname="+keyID,
   855  			"-DpomFile="+meta.Package+".pom", "-Dfile="+meta.Package+".aar")
   856  	}
   857  }
   858  
   859  func gomobileTool(subcmd string, args ...string) *exec.Cmd {
   860  	cmd := exec.Command(filepath.Join(GOBIN, "gomobile"), subcmd)
   861  	cmd.Args = append(cmd.Args, args...)
   862  	cmd.Env = []string{
   863  		"GOPATH=" + build.GOPATH(),
   864  		"PATH=" + GOBIN + string(os.PathListSeparator) + os.Getenv("PATH"),
   865  	}
   866  	for _, e := range os.Environ() {
   867  		if strings.HasPrefix(e, "GOPATH=") || strings.HasPrefix(e, "PATH=") {
   868  			continue
   869  		}
   870  		cmd.Env = append(cmd.Env, e)
   871  	}
   872  	return cmd
   873  }
   874  
   875  type mavenMetadata struct {
   876  	Version      string
   877  	Package      string
   878  	Develop      bool
   879  	Contributors []mavenContributor
   880  }
   881  
   882  type mavenContributor struct {
   883  	Name  string
   884  	Email string
   885  }
   886  
   887  func newMavenMetadata(env build.Environment) mavenMetadata {
   888  	// Collect the list of authors from the repo root
   889  	contribs := []mavenContributor{}
   890  	if authors, err := os.Open("AUTHORS"); err == nil {
   891  		defer authors.Close()
   892  
   893  		scanner := bufio.NewScanner(authors)
   894  		for scanner.Scan() {
   895  			// Skip any whitespace from the authors list
   896  			line := strings.TrimSpace(scanner.Text())
   897  			if line == "" || line[0] == '#' {
   898  				continue
   899  			}
   900  			// Split the author and insert as a contributor
   901  			re := regexp.MustCompile("([^<]+) <(.+)>")
   902  			parts := re.FindStringSubmatch(line)
   903  			if len(parts) == 3 {
   904  				contribs = append(contribs, mavenContributor{Name: parts[1], Email: parts[2]})
   905  			}
   906  		}
   907  	}
   908  	// Render the version and package strings
   909  	version := params.Version
   910  	if isUnstableBuild(env) {
   911  		version += "-SNAPSHOT"
   912  	}
   913  	return mavenMetadata{
   914  		Version:      version,
   915  		Package:      "geth-" + version,
   916  		Develop:      isUnstableBuild(env),
   917  		Contributors: contribs,
   918  	}
   919  }
   920  
   921  // XCode frameworks
   922  
   923  func doXCodeFramework(cmdline []string) {
   924  	var (
   925  		local  = flag.Bool("local", false, `Flag whether we're only doing a local build (skip Maven artifacts)`)
   926  		signer = flag.String("signer", "", `Environment variable holding the signing key (e.g. IOS_SIGNING_KEY)`)
   927  		deploy = flag.String("deploy", "", `Destination to deploy the archive (usually "trunk")`)
   928  		upload = flag.String("upload", "", `Destination to upload the archives (usually "gethstore/builds")`)
   929  	)
   930  	flag.CommandLine.Parse(cmdline)
   931  	env := build.Env()
   932  
   933  	// Build the iOS XCode framework
   934  	build.MustRun(goTool("get", "golang.org/x/mobile/cmd/gomobile", "golang.org/x/mobile/cmd/gobind"))
   935  	build.MustRun(gomobileTool("init"))
   936  	bind := gomobileTool("bind", "-ldflags", "-s -w", "--target", "ios", "-v", "github.com/AigarNetwork/aigar/mobile")
   937  
   938  	if *local {
   939  		// If we're building locally, use the build folder and stop afterwards
   940  		bind.Dir, _ = filepath.Abs(GOBIN)
   941  		build.MustRun(bind)
   942  		return
   943  	}
   944  	archive := "geth-" + archiveBasename("ios", params.ArchiveVersion(env.Commit))
   945  	if err := os.Mkdir(archive, os.ModePerm); err != nil {
   946  		log.Fatal(err)
   947  	}
   948  	bind.Dir, _ = filepath.Abs(archive)
   949  	build.MustRun(bind)
   950  	build.MustRunCommand("tar", "-zcvf", archive+".tar.gz", archive)
   951  
   952  	// Skip CocoaPods deploy and Azure upload for PR builds
   953  	maybeSkipArchive(env)
   954  
   955  	// Sign and upload the framework to Azure
   956  	if err := archiveUpload(archive+".tar.gz", *upload, *signer); err != nil {
   957  		log.Fatal(err)
   958  	}
   959  	// Prepare and upload a PodSpec to CocoaPods
   960  	if *deploy != "" {
   961  		meta := newPodMetadata(env, archive)
   962  		build.Render("build/pod.podspec", "Geth.podspec", 0755, meta)
   963  		build.MustRunCommand("pod", *deploy, "push", "Geth.podspec", "--allow-warnings", "--verbose")
   964  	}
   965  }
   966  
   967  type podMetadata struct {
   968  	Version      string
   969  	Commit       string
   970  	Archive      string
   971  	Contributors []podContributor
   972  }
   973  
   974  type podContributor struct {
   975  	Name  string
   976  	Email string
   977  }
   978  
   979  func newPodMetadata(env build.Environment, archive string) podMetadata {
   980  	// Collect the list of authors from the repo root
   981  	contribs := []podContributor{}
   982  	if authors, err := os.Open("AUTHORS"); err == nil {
   983  		defer authors.Close()
   984  
   985  		scanner := bufio.NewScanner(authors)
   986  		for scanner.Scan() {
   987  			// Skip any whitespace from the authors list
   988  			line := strings.TrimSpace(scanner.Text())
   989  			if line == "" || line[0] == '#' {
   990  				continue
   991  			}
   992  			// Split the author and insert as a contributor
   993  			re := regexp.MustCompile("([^<]+) <(.+)>")
   994  			parts := re.FindStringSubmatch(line)
   995  			if len(parts) == 3 {
   996  				contribs = append(contribs, podContributor{Name: parts[1], Email: parts[2]})
   997  			}
   998  		}
   999  	}
  1000  	version := params.Version
  1001  	if isUnstableBuild(env) {
  1002  		version += "-unstable." + env.Buildnum
  1003  	}
  1004  	return podMetadata{
  1005  		Archive:      archive,
  1006  		Version:      version,
  1007  		Commit:       env.Commit,
  1008  		Contributors: contribs,
  1009  	}
  1010  }
  1011  
  1012  // Cross compilation
  1013  
  1014  func doXgo(cmdline []string) {
  1015  	var (
  1016  		alltools = flag.Bool("alltools", false, `Flag whether we're building all known tools, or only on in particular`)
  1017  	)
  1018  	flag.CommandLine.Parse(cmdline)
  1019  	env := build.Env()
  1020  
  1021  	// Make sure xgo is available for cross compilation
  1022  	gogetxgo := goTool("get", "github.com/karalabe/xgo")
  1023  	build.MustRun(gogetxgo)
  1024  
  1025  	// If all tools building is requested, build everything the builder wants
  1026  	args := append(buildFlags(env), flag.Args()...)
  1027  
  1028  	if *alltools {
  1029  		args = append(args, []string{"--dest", GOBIN}...)
  1030  		for _, res := range allToolsArchiveFiles {
  1031  			if strings.HasPrefix(res, GOBIN) {
  1032  				// Binary tool found, cross build it explicitly
  1033  				args = append(args, "./"+filepath.Join("cmd", filepath.Base(res)))
  1034  				xgo := xgoTool(args)
  1035  				build.MustRun(xgo)
  1036  				args = args[:len(args)-1]
  1037  			}
  1038  		}
  1039  		return
  1040  	}
  1041  	// Otherwise xxecute the explicit cross compilation
  1042  	path := args[len(args)-1]
  1043  	args = append(args[:len(args)-1], []string{"--dest", GOBIN, path}...)
  1044  
  1045  	xgo := xgoTool(args)
  1046  	build.MustRun(xgo)
  1047  }
  1048  
  1049  func xgoTool(args []string) *exec.Cmd {
  1050  	cmd := exec.Command(filepath.Join(GOBIN, "xgo"), args...)
  1051  	cmd.Env = []string{
  1052  		"GOPATH=" + build.GOPATH(),
  1053  		"GOBIN=" + GOBIN,
  1054  	}
  1055  	for _, e := range os.Environ() {
  1056  		if strings.HasPrefix(e, "GOPATH=") || strings.HasPrefix(e, "GOBIN=") {
  1057  			continue
  1058  		}
  1059  		cmd.Env = append(cmd.Env, e)
  1060  	}
  1061  	return cmd
  1062  }
  1063  
  1064  // Binary distribution cleanups
  1065  
  1066  func doPurge(cmdline []string) {
  1067  	var (
  1068  		store = flag.String("store", "", `Destination from where to purge archives (usually "gethstore/builds")`)
  1069  		limit = flag.Int("days", 30, `Age threshold above which to delete unstable archives`)
  1070  	)
  1071  	flag.CommandLine.Parse(cmdline)
  1072  
  1073  	if env := build.Env(); !env.IsCronJob {
  1074  		log.Printf("skipping because not a cron job")
  1075  		os.Exit(0)
  1076  	}
  1077  	// Create the azure authentication and list the current archives
  1078  	auth := build.AzureBlobstoreConfig{
  1079  		Account:   strings.Split(*store, "/")[0],
  1080  		Token:     os.Getenv("AZURE_BLOBSTORE_TOKEN"),
  1081  		Container: strings.SplitN(*store, "/", 2)[1],
  1082  	}
  1083  	blobs, err := build.AzureBlobstoreList(auth)
  1084  	if err != nil {
  1085  		log.Fatal(err)
  1086  	}
  1087  	// Iterate over the blobs, collect and sort all unstable builds
  1088  	for i := 0; i < len(blobs); i++ {
  1089  		if !strings.Contains(blobs[i].Name, "unstable") {
  1090  			blobs = append(blobs[:i], blobs[i+1:]...)
  1091  			i--
  1092  		}
  1093  	}
  1094  	for i := 0; i < len(blobs); i++ {
  1095  		for j := i + 1; j < len(blobs); j++ {
  1096  			if blobs[i].Properties.LastModified.After(blobs[j].Properties.LastModified) {
  1097  				blobs[i], blobs[j] = blobs[j], blobs[i]
  1098  			}
  1099  		}
  1100  	}
  1101  	// Filter out all archives more recent that the given threshold
  1102  	for i, blob := range blobs {
  1103  		if time.Since(blob.Properties.LastModified) < time.Duration(*limit)*24*time.Hour {
  1104  			blobs = blobs[:i]
  1105  			break
  1106  		}
  1107  	}
  1108  	// Delete all marked as such and return
  1109  	if err := build.AzureBlobstoreDelete(auth, blobs); err != nil {
  1110  		log.Fatal(err)
  1111  	}
  1112  }