github.com/theQRL/go-zond@v0.1.1/build/ci.go (about)

     1  // Copyright 2016 The go-ethereum Authors
     2  // This file is part of the go-ethereum library.
     3  //
     4  // The go-ethereum library is free software: you can redistribute it and/or modify
     5  // it under the terms of the GNU Lesser 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  // The go-ethereum library 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 Lesser General Public License for more details.
    13  //
    14  // You should have received a copy of the GNU Lesser General Public License
    15  // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
    16  
    17  //go:build none
    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 ] [ -signify 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  	purge      [ -store blobstore ] [ -days threshold ]                                         -- purges old archives from the blobstore
    35  
    36  For all commands, -n prevents execution of external programs (dry run mode).
    37  */
    38  package main
    39  
    40  import (
    41  	"bytes"
    42  	"encoding/base64"
    43  	"flag"
    44  	"fmt"
    45  	"log"
    46  	"os"
    47  	"os/exec"
    48  	"path"
    49  	"path/filepath"
    50  	"runtime"
    51  	"strconv"
    52  	"strings"
    53  	"time"
    54  
    55  	"github.com/cespare/cp"
    56  	"github.com/theQRL/go-zond/common"
    57  	"github.com/theQRL/go-zond/crypto/signify"
    58  	"github.com/theQRL/go-zond/internal/build"
    59  	"github.com/theQRL/go-zond/params"
    60  )
    61  
    62  var (
    63  	// Files that end up in the gzond*.zip archive.
    64  	gzondArchiveFiles = []string{
    65  		"COPYING",
    66  		executablePath("gzond"),
    67  	}
    68  
    69  	// Files that end up in the gzond-alltools*.zip archive.
    70  	allToolsArchiveFiles = []string{
    71  		"COPYING",
    72  		executablePath("abigen"),
    73  		executablePath("bootnode"),
    74  		executablePath("evm"),
    75  		executablePath("gzond"),
    76  		executablePath("rlpdump"),
    77  		executablePath("clef"),
    78  	}
    79  
    80  	// A debian package is created for all executables listed here.
    81  	debExecutables = []debExecutable{
    82  		{
    83  			BinaryName:  "abigen",
    84  			Description: "Source code generator to convert Ethereum contract definitions into easy to use, compile-time type-safe Go packages.",
    85  		},
    86  		{
    87  			BinaryName:  "bootnode",
    88  			Description: "Ethereum bootnode.",
    89  		},
    90  		{
    91  			BinaryName:  "evm",
    92  			Description: "Developer utility version of the EVM (Ethereum Virtual Machine) that is capable of running bytecode snippets within a configurable environment and execution mode.",
    93  		},
    94  		{
    95  			BinaryName:  "gzond",
    96  			Description: "Ethereum CLI client.",
    97  		},
    98  		{
    99  			BinaryName:  "rlpdump",
   100  			Description: "Developer utility tool that prints RLP structures.",
   101  		},
   102  		{
   103  			BinaryName:  "clef",
   104  			Description: "Ethereum account management tool.",
   105  		},
   106  	}
   107  
   108  	// A debian package is created for all executables listed here.
   109  	debEthereum = debPackage{
   110  		Name:        "ethereum",
   111  		Version:     params.Version,
   112  		Executables: debExecutables,
   113  	}
   114  
   115  	// Debian meta packages to build and push to Ubuntu PPA
   116  	debPackages = []debPackage{
   117  		debEthereum,
   118  	}
   119  
   120  	// Distros for which packages are created.
   121  	// Note: vivid is unsupported because there is no golang-1.6 package for it.
   122  	// Note: the following Ubuntu releases have been officially deprecated on Launchpad:
   123  	//   wily, yakkety, zesty, artful, cosmic, disco, eoan, groovy, hirsuite, impish,
   124  	//   kinetic
   125  	debDistroGoBoots = map[string]string{
   126  		"trusty": "golang-1.11", // EOL: 04/2024
   127  		"xenial": "golang-go",   // EOL: 04/2026
   128  		"bionic": "golang-go",   // EOL: 04/2028
   129  		"focal":  "golang-go",   // EOL: 04/2030
   130  		"jammy":  "golang-go",   // EOL: 04/2032
   131  		"lunar":  "golang-go",   // EOL: 01/2024
   132  	}
   133  
   134  	debGoBootPaths = map[string]string{
   135  		"golang-1.11": "/usr/lib/go-1.11",
   136  		"golang-go":   "/usr/lib/go",
   137  	}
   138  
   139  	// This is the version of Go that will be downloaded by
   140  	//
   141  	//     go run ci.go install -dlgo
   142  	dlgoVersion = "1.21.1"
   143  
   144  	// This is the version of Go that will be used to bootstrap the PPA builder.
   145  	//
   146  	// This version is fine to be old and full of security holes, we just use it
   147  	// to build the latest Go. Don't change it. If it ever becomes insufficient,
   148  	// we need to switch over to a recursive builder to jumpt across supported
   149  	// versions.
   150  	gobootVersion = "1.19.6"
   151  
   152  	// This is the version of execution-spec-tests that we are using.
   153  	// When updating, you must also update build/checksums.txt.
   154  	executionSpecTestsVersion = "1.0.2"
   155  
   156  	// This is where the tests should be unpacked.
   157  	executionSpecTestsDir = "tests/spec-tests"
   158  )
   159  
   160  var GOBIN, _ = filepath.Abs(filepath.Join("build", "bin"))
   161  
   162  func executablePath(name string) string {
   163  	if runtime.GOOS == "windows" {
   164  		name += ".exe"
   165  	}
   166  	return filepath.Join(GOBIN, name)
   167  }
   168  
   169  func main() {
   170  	log.SetFlags(log.Lshortfile)
   171  
   172  	if !common.FileExist(filepath.Join("build", "ci.go")) {
   173  		log.Fatal("this script must be run from the root of the repository")
   174  	}
   175  	if len(os.Args) < 2 {
   176  		log.Fatal("need subcommand as first argument")
   177  	}
   178  	switch os.Args[1] {
   179  	case "install":
   180  		doInstall(os.Args[2:])
   181  	case "test":
   182  		doTest(os.Args[2:])
   183  	case "lint":
   184  		doLint(os.Args[2:])
   185  	case "archive":
   186  		doArchive(os.Args[2:])
   187  	case "docker":
   188  		doDocker(os.Args[2:])
   189  	case "debsrc":
   190  		doDebianSource(os.Args[2:])
   191  	case "nsis":
   192  		doWindowsInstaller(os.Args[2:])
   193  	case "purge":
   194  		doPurge(os.Args[2:])
   195  	default:
   196  		log.Fatal("unknown command ", os.Args[1])
   197  	}
   198  }
   199  
   200  // Compiling
   201  
   202  func doInstall(cmdline []string) {
   203  	var (
   204  		dlgo       = flag.Bool("dlgo", false, "Download Go and build with it")
   205  		arch       = flag.String("arch", "", "Architecture to cross build for")
   206  		cc         = flag.String("cc", "", "C compiler to cross build with")
   207  		staticlink = flag.Bool("static", false, "Create statically-linked executable")
   208  	)
   209  	flag.CommandLine.Parse(cmdline)
   210  	env := build.Env()
   211  
   212  	// Configure the toolchain.
   213  	tc := build.GoToolchain{GOARCH: *arch, CC: *cc}
   214  	if *dlgo {
   215  		csdb := build.MustLoadChecksums("build/checksums.txt")
   216  		tc.Root = build.DownloadGo(csdb, dlgoVersion)
   217  	}
   218  
   219  	// Disable CLI markdown doc generation in release builds.
   220  	buildTags := []string{"urfave_cli_no_docs"}
   221  
   222  	// Enable linking the CKZG library since we can make it work with additional flags.
   223  	if env.UbuntuVersion != "trusty" {
   224  		buildTags = append(buildTags, "ckzg")
   225  	}
   226  
   227  	// Configure the build.
   228  	gobuild := tc.Go("build", buildFlags(env, *staticlink, buildTags)...)
   229  
   230  	// arm64 CI builders are memory-constrained and can't handle concurrent builds,
   231  	// better disable it. This check isn't the best, it should probably
   232  	// check for something in env instead.
   233  	if env.CI && runtime.GOARCH == "arm64" {
   234  		gobuild.Args = append(gobuild.Args, "-p", "1")
   235  	}
   236  	// We use -trimpath to avoid leaking local paths into the built executables.
   237  	gobuild.Args = append(gobuild.Args, "-trimpath")
   238  
   239  	// Show packages during build.
   240  	gobuild.Args = append(gobuild.Args, "-v")
   241  
   242  	// Now we choose what we're even building.
   243  	// Default: collect all 'main' packages in cmd/ and build those.
   244  	packages := flag.Args()
   245  	if len(packages) == 0 {
   246  		packages = build.FindMainPackages("./cmd")
   247  	}
   248  
   249  	// Do the build!
   250  	for _, pkg := range packages {
   251  		args := make([]string, len(gobuild.Args))
   252  		copy(args, gobuild.Args)
   253  		args = append(args, "-o", executablePath(path.Base(pkg)))
   254  		args = append(args, pkg)
   255  		build.MustRun(&exec.Cmd{Path: gobuild.Path, Args: args, Env: gobuild.Env})
   256  	}
   257  }
   258  
   259  // buildFlags returns the go tool flags for building.
   260  func buildFlags(env build.Environment, staticLinking bool, buildTags []string) (flags []string) {
   261  	var ld []string
   262  	if env.Commit != "" {
   263  		ld = append(ld, "-X", "github.com/theQRL/go-zond/internal/version.gitCommit="+env.Commit)
   264  		ld = append(ld, "-X", "github.com/theQRL/go-zond/internal/version.gitDate="+env.Date)
   265  	}
   266  	// Strip DWARF on darwin. This used to be required for certain things,
   267  	// and there is no downside to this, so we just keep doing it.
   268  	if runtime.GOOS == "darwin" {
   269  		ld = append(ld, "-s")
   270  	}
   271  	if runtime.GOOS == "linux" {
   272  		// Enforce the stacksize to 8M, which is the case on most platforms apart from
   273  		// alpine Linux.
   274  		extld := []string{"-Wl,-z,stack-size=0x800000"}
   275  		if staticLinking {
   276  			extld = append(extld, "-static")
   277  			// Under static linking, use of certain glibc features must be
   278  			// disabled to avoid shared library dependencies.
   279  			buildTags = append(buildTags, "osusergo", "netgo")
   280  		}
   281  		ld = append(ld, "-extldflags", "'"+strings.Join(extld, " ")+"'")
   282  	}
   283  	if len(ld) > 0 {
   284  		flags = append(flags, "-ldflags", strings.Join(ld, " "))
   285  	}
   286  	if len(buildTags) > 0 {
   287  		flags = append(flags, "-tags", strings.Join(buildTags, ","))
   288  	}
   289  	return flags
   290  }
   291  
   292  // Running The Tests
   293  //
   294  // "tests" also includes static analysis tools such as vet.
   295  
   296  func doTest(cmdline []string) {
   297  	var (
   298  		dlgo     = flag.Bool("dlgo", false, "Download Go and build with it")
   299  		arch     = flag.String("arch", "", "Run tests for given architecture")
   300  		cc       = flag.String("cc", "", "Sets C compiler binary")
   301  		coverage = flag.Bool("coverage", false, "Whether to record code coverage")
   302  		verbose  = flag.Bool("v", false, "Whether to log verbosely")
   303  		race     = flag.Bool("race", false, "Execute the race detector")
   304  		cachedir = flag.String("cachedir", "./build/cache", "directory for caching downloads")
   305  	)
   306  	flag.CommandLine.Parse(cmdline)
   307  
   308  	// Get test fixtures.
   309  	csdb := build.MustLoadChecksums("build/checksums.txt")
   310  	downloadSpecTestFixtures(csdb, *cachedir)
   311  
   312  	// Configure the toolchain.
   313  	tc := build.GoToolchain{GOARCH: *arch, CC: *cc}
   314  	if *dlgo {
   315  		tc.Root = build.DownloadGo(csdb, dlgoVersion)
   316  	}
   317  	gotest := tc.Go("test")
   318  
   319  	// CI needs a bit more time for the statetests (default 10m).
   320  	gotest.Args = append(gotest.Args, "-timeout=20m")
   321  
   322  	// Enable CKZG backend in CI.
   323  	gotest.Args = append(gotest.Args, "-tags=ckzg")
   324  
   325  	// Test a single package at a time. CI builders are slow
   326  	// and some tests run into timeouts under load.
   327  	gotest.Args = append(gotest.Args, "-p", "1")
   328  	if *coverage {
   329  		gotest.Args = append(gotest.Args, "-covermode=atomic", "-cover")
   330  	}
   331  	if *verbose {
   332  		gotest.Args = append(gotest.Args, "-v")
   333  	}
   334  	if *race {
   335  		gotest.Args = append(gotest.Args, "-race")
   336  	}
   337  
   338  	packages := []string{"./..."}
   339  	if len(flag.CommandLine.Args()) > 0 {
   340  		packages = flag.CommandLine.Args()
   341  	}
   342  	gotest.Args = append(gotest.Args, packages...)
   343  	build.MustRun(gotest)
   344  }
   345  
   346  // downloadSpecTestFixtures downloads and extracts the execution-spec-tests fixtures.
   347  func downloadSpecTestFixtures(csdb *build.ChecksumDB, cachedir string) string {
   348  	ext := ".tar.gz"
   349  	base := "fixtures" // TODO(MariusVanDerWijden) rename once the version becomes part of the filename
   350  	url := fmt.Sprintf("https://github.com/ethereum/execution-spec-tests/releases/download/v%s/%s%s", executionSpecTestsVersion, base, ext)
   351  	archivePath := filepath.Join(cachedir, base+ext)
   352  	if err := csdb.DownloadFile(url, archivePath); err != nil {
   353  		log.Fatal(err)
   354  	}
   355  	if err := build.ExtractArchive(archivePath, executionSpecTestsDir); err != nil {
   356  		log.Fatal(err)
   357  	}
   358  	return filepath.Join(cachedir, base)
   359  }
   360  
   361  // doLint runs golangci-lint on requested packages.
   362  func doLint(cmdline []string) {
   363  	var (
   364  		cachedir = flag.String("cachedir", "./build/cache", "directory for caching golangci-lint binary.")
   365  	)
   366  	flag.CommandLine.Parse(cmdline)
   367  	packages := []string{"./..."}
   368  	if len(flag.CommandLine.Args()) > 0 {
   369  		packages = flag.CommandLine.Args()
   370  	}
   371  
   372  	linter := downloadLinter(*cachedir)
   373  	lflags := []string{"run", "--config", ".golangci.yml"}
   374  	build.MustRunCommand(linter, append(lflags, packages...)...)
   375  	fmt.Println("You have achieved perfection.")
   376  }
   377  
   378  // downloadLinter downloads and unpacks golangci-lint.
   379  func downloadLinter(cachedir string) string {
   380  	const version = "1.51.1"
   381  
   382  	csdb := build.MustLoadChecksums("build/checksums.txt")
   383  	arch := runtime.GOARCH
   384  	ext := ".tar.gz"
   385  
   386  	if runtime.GOOS == "windows" {
   387  		ext = ".zip"
   388  	}
   389  	if arch == "arm" {
   390  		arch += "v" + os.Getenv("GOARM")
   391  	}
   392  	base := fmt.Sprintf("golangci-lint-%s-%s-%s", version, runtime.GOOS, arch)
   393  	url := fmt.Sprintf("https://github.com/golangci/golangci-lint/releases/download/v%s/%s%s", version, base, ext)
   394  	archivePath := filepath.Join(cachedir, base+ext)
   395  	if err := csdb.DownloadFile(url, archivePath); err != nil {
   396  		log.Fatal(err)
   397  	}
   398  	if err := build.ExtractArchive(archivePath, cachedir); err != nil {
   399  		log.Fatal(err)
   400  	}
   401  	return filepath.Join(cachedir, base, "golangci-lint")
   402  }
   403  
   404  // Release Packaging
   405  func doArchive(cmdline []string) {
   406  	var (
   407  		arch    = flag.String("arch", runtime.GOARCH, "Architecture cross packaging")
   408  		atype   = flag.String("type", "zip", "Type of archive to write (zip|tar)")
   409  		signer  = flag.String("signer", "", `Environment variable holding the signing key (e.g. LINUX_SIGNING_KEY)`)
   410  		signify = flag.String("signify", "", `Environment variable holding the signify key (e.g. LINUX_SIGNIFY_KEY)`)
   411  		upload  = flag.String("upload", "", `Destination to upload the archives (usually "gethstore/builds")`)
   412  		ext     string
   413  	)
   414  	flag.CommandLine.Parse(cmdline)
   415  	switch *atype {
   416  	case "zip":
   417  		ext = ".zip"
   418  	case "tar":
   419  		ext = ".tar.gz"
   420  	default:
   421  		log.Fatal("unknown archive type: ", atype)
   422  	}
   423  
   424  	var (
   425  		env       = build.Env()
   426  		basegzond = archiveBasename(*arch, params.ArchiveVersion(env.Commit))
   427  		gzond     = "gzond-" + basegzond + ext
   428  		alltools  = "gzond-alltools-" + basegzond + ext
   429  	)
   430  	maybeSkipArchive(env)
   431  	if err := build.WriteArchive(gzond, gzondArchiveFiles); err != nil {
   432  		log.Fatal(err)
   433  	}
   434  	if err := build.WriteArchive(alltools, allToolsArchiveFiles); err != nil {
   435  		log.Fatal(err)
   436  	}
   437  	for _, archive := range []string{gzond, alltools} {
   438  		if err := archiveUpload(archive, *upload, *signer, *signify); err != nil {
   439  			log.Fatal(err)
   440  		}
   441  	}
   442  }
   443  
   444  func archiveBasename(arch string, archiveVersion string) string {
   445  	platform := runtime.GOOS + "-" + arch
   446  	if arch == "arm" {
   447  		platform += os.Getenv("GOARM")
   448  	}
   449  	if arch == "android" {
   450  		platform = "android-all"
   451  	}
   452  	if arch == "ios" {
   453  		platform = "ios-all"
   454  	}
   455  	return platform + "-" + archiveVersion
   456  }
   457  
   458  func archiveUpload(archive string, blobstore string, signer string, signifyVar string) error {
   459  	// If signing was requested, generate the signature files
   460  	if signer != "" {
   461  		key := getenvBase64(signer)
   462  		if err := build.PGPSignFile(archive, archive+".asc", string(key)); err != nil {
   463  			return err
   464  		}
   465  	}
   466  	if signifyVar != "" {
   467  		key := os.Getenv(signifyVar)
   468  		untrustedComment := "verify with gzond-release.pub"
   469  		trustedComment := fmt.Sprintf("%s (%s)", archive, time.Now().UTC().Format(time.RFC1123))
   470  		if err := signify.SignFile(archive, archive+".sig", key, untrustedComment, trustedComment); err != nil {
   471  			return err
   472  		}
   473  	}
   474  	// If uploading to Azure was requested, push the archive possibly with its signature
   475  	if blobstore != "" {
   476  		auth := build.AzureBlobstoreConfig{
   477  			Account:   strings.Split(blobstore, "/")[0],
   478  			Token:     os.Getenv("AZURE_BLOBSTORE_TOKEN"),
   479  			Container: strings.SplitN(blobstore, "/", 2)[1],
   480  		}
   481  		if err := build.AzureBlobstoreUpload(archive, filepath.Base(archive), auth); err != nil {
   482  			return err
   483  		}
   484  		if signer != "" {
   485  			if err := build.AzureBlobstoreUpload(archive+".asc", filepath.Base(archive+".asc"), auth); err != nil {
   486  				return err
   487  			}
   488  		}
   489  		if signifyVar != "" {
   490  			if err := build.AzureBlobstoreUpload(archive+".sig", filepath.Base(archive+".sig"), auth); err != nil {
   491  				return err
   492  			}
   493  		}
   494  	}
   495  	return nil
   496  }
   497  
   498  // skips archiving for some build configurations.
   499  func maybeSkipArchive(env build.Environment) {
   500  	if env.IsPullRequest {
   501  		log.Printf("skipping archive creation because this is a PR build")
   502  		os.Exit(0)
   503  	}
   504  	if env.Branch != "master" && !strings.HasPrefix(env.Tag, "v1.") {
   505  		log.Printf("skipping archive creation because branch %q, tag %q is not on the inclusion list", env.Branch, env.Tag)
   506  		os.Exit(0)
   507  	}
   508  }
   509  
   510  // Builds the docker images and optionally uploads them to Docker Hub.
   511  func doDocker(cmdline []string) {
   512  	var (
   513  		image    = flag.Bool("image", false, `Whether to build and push an arch specific docker image`)
   514  		manifest = flag.String("manifest", "", `Push a multi-arch docker image for the specified architectures (usually "amd64,arm64")`)
   515  		upload   = flag.String("upload", "", `Where to upload the docker image (usually "ethereum/client-go")`)
   516  	)
   517  	flag.CommandLine.Parse(cmdline)
   518  
   519  	// Skip building and pushing docker images for PR builds
   520  	env := build.Env()
   521  	maybeSkipArchive(env)
   522  
   523  	// Retrieve the upload credentials and authenticate
   524  	user := getenvBase64("DOCKER_HUB_USERNAME")
   525  	pass := getenvBase64("DOCKER_HUB_PASSWORD")
   526  
   527  	if len(user) > 0 && len(pass) > 0 {
   528  		auther := exec.Command("docker", "login", "-u", string(user), "--password-stdin")
   529  		auther.Stdin = bytes.NewReader(pass)
   530  		build.MustRun(auther)
   531  	}
   532  	// Retrieve the version infos to build and push to the following paths:
   533  	//  - ethereum/client-go:latest                            - Pushes to the master branch, Gzond only
   534  	//  - ethereum/client-go:stable                            - Version tag publish on GitHub, Gzond only
   535  	//  - ethereum/client-go:alltools-latest                   - Pushes to the master branch, Gzond & tools
   536  	//  - ethereum/client-go:alltools-stable                   - Version tag publish on GitHub, Gzond & tools
   537  	//  - ethereum/client-go:release-<major>.<minor>           - Version tag publish on GitHub, Gzond only
   538  	//  - ethereum/client-go:alltools-release-<major>.<minor>  - Version tag publish on GitHub, Gzond & tools
   539  	//  - ethereum/client-go:v<major>.<minor>.<patch>          - Version tag publish on GitHub, Gzond only
   540  	//  - ethereum/client-go:alltools-v<major>.<minor>.<patch> - Version tag publish on GitHub, Gzond & tools
   541  	var tags []string
   542  
   543  	switch {
   544  	case env.Branch == "master":
   545  		tags = []string{"latest"}
   546  	case strings.HasPrefix(env.Tag, "v1."):
   547  		tags = []string{"stable", fmt.Sprintf("release-1.%d", params.VersionMinor), "v" + params.Version}
   548  	}
   549  	// If architecture specific image builds are requested, build and push them
   550  	if *image {
   551  		build.MustRunCommand("docker", "build", "--build-arg", "COMMIT="+env.Commit, "--build-arg", "VERSION="+params.VersionWithMeta, "--build-arg", "BUILDNUM="+env.Buildnum, "--tag", fmt.Sprintf("%s:TAG", *upload), ".")
   552  		build.MustRunCommand("docker", "build", "--build-arg", "COMMIT="+env.Commit, "--build-arg", "VERSION="+params.VersionWithMeta, "--build-arg", "BUILDNUM="+env.Buildnum, "--tag", fmt.Sprintf("%s:alltools-TAG", *upload), "-f", "Dockerfile.alltools", ".")
   553  
   554  		// Tag and upload the images to Docker Hub
   555  		for _, tag := range tags {
   556  			gzondImage := fmt.Sprintf("%s:%s-%s", *upload, tag, runtime.GOARCH)
   557  			toolImage := fmt.Sprintf("%s:alltools-%s-%s", *upload, tag, runtime.GOARCH)
   558  
   559  			// If the image already exists (non version tag), check the build
   560  			// number to prevent overwriting a newer commit if concurrent builds
   561  			// are running. This is still a tiny bit racey if two published are
   562  			// done at the same time, but that's extremely unlikely even on the
   563  			// master branch.
   564  			for _, img := range []string{gzondImage, toolImage} {
   565  				if exec.Command("docker", "pull", img).Run() != nil {
   566  					continue // Generally the only failure is a missing image, which is good
   567  				}
   568  				buildnum, err := exec.Command("docker", "inspect", "--format", "{{index .Config.Labels \"buildnum\"}}", img).CombinedOutput()
   569  				if err != nil {
   570  					log.Fatalf("Failed to inspect container: %v\nOutput: %s", err, string(buildnum))
   571  				}
   572  				buildnum = bytes.TrimSpace(buildnum)
   573  
   574  				if len(buildnum) > 0 && len(env.Buildnum) > 0 {
   575  					oldnum, err := strconv.Atoi(string(buildnum))
   576  					if err != nil {
   577  						log.Fatalf("Failed to parse old image build number: %v", err)
   578  					}
   579  					newnum, err := strconv.Atoi(env.Buildnum)
   580  					if err != nil {
   581  						log.Fatalf("Failed to parse current build number: %v", err)
   582  					}
   583  					if oldnum > newnum {
   584  						log.Fatalf("Current build number %d not newer than existing %d", newnum, oldnum)
   585  					} else {
   586  						log.Printf("Updating %s from build %d to %d", img, oldnum, newnum)
   587  					}
   588  				}
   589  			}
   590  			build.MustRunCommand("docker", "image", "tag", fmt.Sprintf("%s:TAG", *upload), gzondImage)
   591  			build.MustRunCommand("docker", "image", "tag", fmt.Sprintf("%s:alltools-TAG", *upload), toolImage)
   592  			build.MustRunCommand("docker", "push", gzondImage)
   593  			build.MustRunCommand("docker", "push", toolImage)
   594  		}
   595  	}
   596  	// If multi-arch image manifest push is requested, assemble it
   597  	if len(*manifest) != 0 {
   598  		// Since different architectures are pushed by different builders, wait
   599  		// until all required images are updated.
   600  		var mismatch bool
   601  		for i := 0; i < 2; i++ { // 2 attempts, second is race check
   602  			mismatch = false // hope there's no mismatch now
   603  
   604  			for _, tag := range tags {
   605  				for _, arch := range strings.Split(*manifest, ",") {
   606  					gzondImage := fmt.Sprintf("%s:%s-%s", *upload, tag, arch)
   607  					toolImage := fmt.Sprintf("%s:alltools-%s-%s", *upload, tag, arch)
   608  
   609  					for _, img := range []string{gzondImage, toolImage} {
   610  						if out, err := exec.Command("docker", "pull", img).CombinedOutput(); err != nil {
   611  							log.Printf("Required image %s unavailable: %v\nOutput: %s", img, err, out)
   612  							mismatch = true
   613  							break
   614  						}
   615  						buildnum, err := exec.Command("docker", "inspect", "--format", "{{index .Config.Labels \"buildnum\"}}", img).CombinedOutput()
   616  						if err != nil {
   617  							log.Fatalf("Failed to inspect container: %v\nOutput: %s", err, string(buildnum))
   618  						}
   619  						buildnum = bytes.TrimSpace(buildnum)
   620  
   621  						if string(buildnum) != env.Buildnum {
   622  							log.Printf("Build number mismatch on %s: want %s, have %s", img, env.Buildnum, buildnum)
   623  							mismatch = true
   624  							break
   625  						}
   626  					}
   627  					if mismatch {
   628  						break
   629  					}
   630  				}
   631  				if mismatch {
   632  					break
   633  				}
   634  			}
   635  			if mismatch {
   636  				// Build numbers mismatching, retry in a short time to
   637  				// avoid concurrent fails in both publisher images. If
   638  				// however the retry failed too, it means the concurrent
   639  				// builder is still crunching, let that do the publish.
   640  				if i == 0 {
   641  					time.Sleep(30 * time.Second)
   642  				}
   643  				continue
   644  			}
   645  			break
   646  		}
   647  		if mismatch {
   648  			log.Println("Relinquishing publish to other builder")
   649  			return
   650  		}
   651  		// Assemble and push the Gzond manifest image
   652  		for _, tag := range tags {
   653  			gzondImage := fmt.Sprintf("%s:%s", *upload, tag)
   654  
   655  			var gzondSubImages []string
   656  			for _, arch := range strings.Split(*manifest, ",") {
   657  				gzondSubImages = append(gzondSubImages, gzondImage+"-"+arch)
   658  			}
   659  			build.MustRunCommand("docker", append([]string{"manifest", "create", gzondImage}, gzondSubImages...)...)
   660  			build.MustRunCommand("docker", "manifest", "push", gzondImage)
   661  		}
   662  		// Assemble and push the alltools manifest image
   663  		for _, tag := range tags {
   664  			toolImage := fmt.Sprintf("%s:alltools-%s", *upload, tag)
   665  
   666  			var toolSubImages []string
   667  			for _, arch := range strings.Split(*manifest, ",") {
   668  				toolSubImages = append(toolSubImages, toolImage+"-"+arch)
   669  			}
   670  			build.MustRunCommand("docker", append([]string{"manifest", "create", toolImage}, toolSubImages...)...)
   671  			build.MustRunCommand("docker", "manifest", "push", toolImage)
   672  		}
   673  	}
   674  }
   675  
   676  // Debian Packaging
   677  func doDebianSource(cmdline []string) {
   678  	var (
   679  		cachedir = flag.String("cachedir", "./build/cache", `Filesystem path to cache the downloaded Go bundles at`)
   680  		signer   = flag.String("signer", "", `Signing key name, also used as package author`)
   681  		upload   = flag.String("upload", "", `Where to upload the source package (usually "ethereum/ethereum")`)
   682  		sshUser  = flag.String("sftp-user", "", `Username for SFTP upload (usually "gzond-ci")`)
   683  		workdir  = flag.String("workdir", "", `Output directory for packages (uses temp dir if unset)`)
   684  		now      = time.Now()
   685  	)
   686  	flag.CommandLine.Parse(cmdline)
   687  	*workdir = makeWorkdir(*workdir)
   688  	env := build.Env()
   689  	tc := new(build.GoToolchain)
   690  	maybeSkipArchive(env)
   691  
   692  	// Import the signing key.
   693  	if key := getenvBase64("PPA_SIGNING_KEY"); len(key) > 0 {
   694  		gpg := exec.Command("gpg", "--import")
   695  		gpg.Stdin = bytes.NewReader(key)
   696  		build.MustRun(gpg)
   697  	}
   698  	// Download and verify the Go source packages.
   699  	var (
   700  		gobootbundle = downloadGoBootstrapSources(*cachedir)
   701  		gobundle     = downloadGoSources(*cachedir)
   702  	)
   703  	// Download all the dependencies needed to build the sources and run the ci script
   704  	srcdepfetch := tc.Go("mod", "download")
   705  	srcdepfetch.Env = append(srcdepfetch.Env, "GOPATH="+filepath.Join(*workdir, "modgopath"))
   706  	build.MustRun(srcdepfetch)
   707  
   708  	cidepfetch := tc.Go("run", "./build/ci.go")
   709  	cidepfetch.Env = append(cidepfetch.Env, "GOPATH="+filepath.Join(*workdir, "modgopath"))
   710  	cidepfetch.Run() // Command fails, don't care, we only need the deps to start it
   711  
   712  	// Create Debian packages and upload them.
   713  	for _, pkg := range debPackages {
   714  		for distro, goboot := range debDistroGoBoots {
   715  			// Prepare the debian package with the go-ethereum sources.
   716  			meta := newDebMetadata(distro, goboot, *signer, env, now, pkg.Name, pkg.Version, pkg.Executables)
   717  			pkgdir := stageDebianSource(*workdir, meta)
   718  
   719  			// Add bootstrapper Go source code
   720  			if err := build.ExtractArchive(gobootbundle, pkgdir); err != nil {
   721  				log.Fatalf("Failed to extract bootstrapper Go sources: %v", err)
   722  			}
   723  			if err := os.Rename(filepath.Join(pkgdir, "go"), filepath.Join(pkgdir, ".goboot")); err != nil {
   724  				log.Fatalf("Failed to rename bootstrapper Go source folder: %v", err)
   725  			}
   726  			// Add builder Go source code
   727  			if err := build.ExtractArchive(gobundle, pkgdir); err != nil {
   728  				log.Fatalf("Failed to extract builder Go sources: %v", err)
   729  			}
   730  			if err := os.Rename(filepath.Join(pkgdir, "go"), filepath.Join(pkgdir, ".go")); err != nil {
   731  				log.Fatalf("Failed to rename builder Go source folder: %v", err)
   732  			}
   733  			// Add all dependency modules in compressed form
   734  			os.MkdirAll(filepath.Join(pkgdir, ".mod", "cache"), 0755)
   735  			if err := cp.CopyAll(filepath.Join(pkgdir, ".mod", "cache", "download"), filepath.Join(*workdir, "modgopath", "pkg", "mod", "cache", "download")); err != nil {
   736  				log.Fatalf("Failed to copy Go module dependencies: %v", err)
   737  			}
   738  			// Run the packaging and upload to the PPA
   739  			debuild := exec.Command("debuild", "-S", "-sa", "-us", "-uc", "-d", "-Zxz", "-nc")
   740  			debuild.Dir = pkgdir
   741  			build.MustRun(debuild)
   742  
   743  			var (
   744  				basename  = fmt.Sprintf("%s_%s", meta.Name(), meta.VersionString())
   745  				source    = filepath.Join(*workdir, basename+".tar.xz")
   746  				dsc       = filepath.Join(*workdir, basename+".dsc")
   747  				changes   = filepath.Join(*workdir, basename+"_source.changes")
   748  				buildinfo = filepath.Join(*workdir, basename+"_source.buildinfo")
   749  			)
   750  			if *signer != "" {
   751  				build.MustRunCommand("debsign", changes)
   752  			}
   753  			if *upload != "" {
   754  				ppaUpload(*workdir, *upload, *sshUser, []string{source, dsc, changes, buildinfo})
   755  			}
   756  		}
   757  	}
   758  }
   759  
   760  // downloadGoBootstrapSources downloads the Go source tarball that will be used
   761  // to bootstrap the builder Go.
   762  func downloadGoBootstrapSources(cachedir string) string {
   763  	csdb := build.MustLoadChecksums("build/checksums.txt")
   764  	file := fmt.Sprintf("go%s.src.tar.gz", gobootVersion)
   765  	url := "https://dl.google.com/go/" + file
   766  	dst := filepath.Join(cachedir, file)
   767  	if err := csdb.DownloadFile(url, dst); err != nil {
   768  		log.Fatal(err)
   769  	}
   770  	return dst
   771  }
   772  
   773  // downloadGoSources downloads the Go source tarball.
   774  func downloadGoSources(cachedir string) string {
   775  	csdb := build.MustLoadChecksums("build/checksums.txt")
   776  	file := fmt.Sprintf("go%s.src.tar.gz", dlgoVersion)
   777  	url := "https://dl.google.com/go/" + file
   778  	dst := filepath.Join(cachedir, file)
   779  	if err := csdb.DownloadFile(url, dst); err != nil {
   780  		log.Fatal(err)
   781  	}
   782  	return dst
   783  }
   784  
   785  func ppaUpload(workdir, ppa, sshUser string, files []string) {
   786  	p := strings.Split(ppa, "/")
   787  	if len(p) != 2 {
   788  		log.Fatal("-upload PPA name must contain single /")
   789  	}
   790  	if sshUser == "" {
   791  		sshUser = p[0]
   792  	}
   793  	incomingDir := fmt.Sprintf("~%s/ubuntu/%s", p[0], p[1])
   794  	// Create the SSH identity file if it doesn't exist.
   795  	var idfile string
   796  	if sshkey := getenvBase64("PPA_SSH_KEY"); len(sshkey) > 0 {
   797  		idfile = filepath.Join(workdir, "sshkey")
   798  		if !common.FileExist(idfile) {
   799  			os.WriteFile(idfile, sshkey, 0600)
   800  		}
   801  	}
   802  	// Upload
   803  	dest := sshUser + "@ppa.launchpad.net"
   804  	if err := build.UploadSFTP(idfile, dest, incomingDir, files); err != nil {
   805  		log.Fatal(err)
   806  	}
   807  }
   808  
   809  func getenvBase64(variable string) []byte {
   810  	dec, err := base64.StdEncoding.DecodeString(os.Getenv(variable))
   811  	if err != nil {
   812  		log.Fatal("invalid base64 " + variable)
   813  	}
   814  	return []byte(dec)
   815  }
   816  
   817  func makeWorkdir(wdflag string) string {
   818  	var err error
   819  	if wdflag != "" {
   820  		err = os.MkdirAll(wdflag, 0744)
   821  	} else {
   822  		wdflag, err = os.MkdirTemp("", "gzond-build-")
   823  	}
   824  	if err != nil {
   825  		log.Fatal(err)
   826  	}
   827  	return wdflag
   828  }
   829  
   830  func isUnstableBuild(env build.Environment) bool {
   831  	if env.Tag != "" {
   832  		return false
   833  	}
   834  	return true
   835  }
   836  
   837  type debPackage struct {
   838  	Name        string          // the name of the Debian package to produce, e.g. "ethereum"
   839  	Version     string          // the clean version of the debPackage, e.g. 1.8.12, without any metadata
   840  	Executables []debExecutable // executables to be included in the package
   841  }
   842  
   843  type debMetadata struct {
   844  	Env           build.Environment
   845  	GoBootPackage string
   846  	GoBootPath    string
   847  
   848  	PackageName string
   849  
   850  	// go-ethereum version being built. Note that this
   851  	// is not the debian package version. The package version
   852  	// is constructed by VersionString.
   853  	Version string
   854  
   855  	Author       string // "name <email>", also selects signing key
   856  	Distro, Time string
   857  	Executables  []debExecutable
   858  }
   859  
   860  type debExecutable struct {
   861  	PackageName string
   862  	BinaryName  string
   863  	Description string
   864  }
   865  
   866  // Package returns the name of the package if present, or
   867  // fallbacks to BinaryName
   868  func (d debExecutable) Package() string {
   869  	if d.PackageName != "" {
   870  		return d.PackageName
   871  	}
   872  	return d.BinaryName
   873  }
   874  
   875  func newDebMetadata(distro, goboot, author string, env build.Environment, t time.Time, name string, version string, exes []debExecutable) debMetadata {
   876  	if author == "" {
   877  		// No signing key, use default author.
   878  		author = "Ethereum Builds <fjl@ethereum.org>"
   879  	}
   880  	return debMetadata{
   881  		GoBootPackage: goboot,
   882  		GoBootPath:    debGoBootPaths[goboot],
   883  		PackageName:   name,
   884  		Env:           env,
   885  		Author:        author,
   886  		Distro:        distro,
   887  		Version:       version,
   888  		Time:          t.Format(time.RFC1123Z),
   889  		Executables:   exes,
   890  	}
   891  }
   892  
   893  // Name returns the name of the metapackage that depends
   894  // on all executable packages.
   895  func (meta debMetadata) Name() string {
   896  	if isUnstableBuild(meta.Env) {
   897  		return meta.PackageName + "-unstable"
   898  	}
   899  	return meta.PackageName
   900  }
   901  
   902  // VersionString returns the debian version of the packages.
   903  func (meta debMetadata) VersionString() string {
   904  	vsn := meta.Version
   905  	if meta.Env.Buildnum != "" {
   906  		vsn += "+build" + meta.Env.Buildnum
   907  	}
   908  	if meta.Distro != "" {
   909  		vsn += "+" + meta.Distro
   910  	}
   911  	return vsn
   912  }
   913  
   914  // ExeList returns the list of all executable packages.
   915  func (meta debMetadata) ExeList() string {
   916  	names := make([]string, len(meta.Executables))
   917  	for i, e := range meta.Executables {
   918  		names[i] = meta.ExeName(e)
   919  	}
   920  	return strings.Join(names, ", ")
   921  }
   922  
   923  // ExeName returns the package name of an executable package.
   924  func (meta debMetadata) ExeName(exe debExecutable) string {
   925  	if isUnstableBuild(meta.Env) {
   926  		return exe.Package() + "-unstable"
   927  	}
   928  	return exe.Package()
   929  }
   930  
   931  // ExeConflicts returns the content of the Conflicts field
   932  // for executable packages.
   933  func (meta debMetadata) ExeConflicts(exe debExecutable) string {
   934  	if isUnstableBuild(meta.Env) {
   935  		// Set up the conflicts list so that the *-unstable packages
   936  		// cannot be installed alongside the regular version.
   937  		//
   938  		// https://www.debian.org/doc/debian-policy/ch-relationships.html
   939  		// is very explicit about Conflicts: and says that Breaks: should
   940  		// be preferred and the conflicting files should be handled via
   941  		// alternates. We might do this eventually but using a conflict is
   942  		// easier now.
   943  		return "ethereum, " + exe.Package()
   944  	}
   945  	return ""
   946  }
   947  
   948  func stageDebianSource(tmpdir string, meta debMetadata) (pkgdir string) {
   949  	pkg := meta.Name() + "-" + meta.VersionString()
   950  	pkgdir = filepath.Join(tmpdir, pkg)
   951  	if err := os.Mkdir(pkgdir, 0755); err != nil {
   952  		log.Fatal(err)
   953  	}
   954  	// Copy the source code.
   955  	build.MustRunCommand("git", "checkout-index", "-a", "--prefix", pkgdir+string(filepath.Separator))
   956  
   957  	// Put the debian build files in place.
   958  	debian := filepath.Join(pkgdir, "debian")
   959  	build.Render("build/deb/"+meta.PackageName+"/deb.rules", filepath.Join(debian, "rules"), 0755, meta)
   960  	build.Render("build/deb/"+meta.PackageName+"/deb.changelog", filepath.Join(debian, "changelog"), 0644, meta)
   961  	build.Render("build/deb/"+meta.PackageName+"/deb.control", filepath.Join(debian, "control"), 0644, meta)
   962  	build.Render("build/deb/"+meta.PackageName+"/deb.copyright", filepath.Join(debian, "copyright"), 0644, meta)
   963  	build.RenderString("8\n", filepath.Join(debian, "compat"), 0644, meta)
   964  	build.RenderString("3.0 (native)\n", filepath.Join(debian, "source/format"), 0644, meta)
   965  	for _, exe := range meta.Executables {
   966  		install := filepath.Join(debian, meta.ExeName(exe)+".install")
   967  		docs := filepath.Join(debian, meta.ExeName(exe)+".docs")
   968  		build.Render("build/deb/"+meta.PackageName+"/deb.install", install, 0644, exe)
   969  		build.Render("build/deb/"+meta.PackageName+"/deb.docs", docs, 0644, exe)
   970  	}
   971  	return pkgdir
   972  }
   973  
   974  // Windows installer
   975  func doWindowsInstaller(cmdline []string) {
   976  	// Parse the flags and make skip installer generation on PRs
   977  	var (
   978  		arch    = flag.String("arch", runtime.GOARCH, "Architecture for cross build packaging")
   979  		signer  = flag.String("signer", "", `Environment variable holding the signing key (e.g. WINDOWS_SIGNING_KEY)`)
   980  		signify = flag.String("signify key", "", `Environment variable holding the signify signing key (e.g. WINDOWS_SIGNIFY_KEY)`)
   981  		upload  = flag.String("upload", "", `Destination to upload the archives (usually "gzondstore/builds")`)
   982  		workdir = flag.String("workdir", "", `Output directory for packages (uses temp dir if unset)`)
   983  	)
   984  	flag.CommandLine.Parse(cmdline)
   985  	*workdir = makeWorkdir(*workdir)
   986  	env := build.Env()
   987  	maybeSkipArchive(env)
   988  
   989  	// Aggregate binaries that are included in the installer
   990  	var (
   991  		devTools  []string
   992  		allTools  []string
   993  		gzondTool string
   994  	)
   995  	for _, file := range allToolsArchiveFiles {
   996  		if file == "COPYING" { // license, copied later
   997  			continue
   998  		}
   999  		allTools = append(allTools, filepath.Base(file))
  1000  		if filepath.Base(file) == "gzond.exe" {
  1001  			gzondTool = file
  1002  		} else {
  1003  			devTools = append(devTools, file)
  1004  		}
  1005  	}
  1006  
  1007  	// Render NSIS scripts: Installer NSIS contains two installer sections,
  1008  	// first section contains the gzond binary, second section holds the dev tools.
  1009  	templateData := map[string]interface{}{
  1010  		"License":  "COPYING",
  1011  		"Gzond":    gzondTool,
  1012  		"DevTools": devTools,
  1013  	}
  1014  	build.Render("build/nsis.gzond.nsi", filepath.Join(*workdir, "gzond.nsi"), 0644, nil)
  1015  	build.Render("build/nsis.install.nsh", filepath.Join(*workdir, "install.nsh"), 0644, templateData)
  1016  	build.Render("build/nsis.uninstall.nsh", filepath.Join(*workdir, "uninstall.nsh"), 0644, allTools)
  1017  	build.Render("build/nsis.pathupdate.nsh", filepath.Join(*workdir, "PathUpdate.nsh"), 0644, nil)
  1018  	build.Render("build/nsis.envvarupdate.nsh", filepath.Join(*workdir, "EnvVarUpdate.nsh"), 0644, nil)
  1019  	if err := cp.CopyFile(filepath.Join(*workdir, "SimpleFC.dll"), "build/nsis.simplefc.dll"); err != nil {
  1020  		log.Fatalf("Failed to copy SimpleFC.dll: %v", err)
  1021  	}
  1022  	if err := cp.CopyFile(filepath.Join(*workdir, "COPYING"), "COPYING"); err != nil {
  1023  		log.Fatalf("Failed to copy copyright note: %v", err)
  1024  	}
  1025  	// Build the installer. This assumes that all the needed files have been previously
  1026  	// built (don't mix building and packaging to keep cross compilation complexity to a
  1027  	// minimum).
  1028  	version := strings.Split(params.Version, ".")
  1029  	if env.Commit != "" {
  1030  		version[2] += "-" + env.Commit[:8]
  1031  	}
  1032  	installer, err := filepath.Abs("gzond-" + archiveBasename(*arch, params.ArchiveVersion(env.Commit)) + ".exe")
  1033  	if err != nil {
  1034  		log.Fatalf("Failed to convert installer file path: %v", err)
  1035  	}
  1036  	build.MustRunCommand("makensis.exe",
  1037  		"/DOUTPUTFILE="+installer,
  1038  		"/DMAJORVERSION="+version[0],
  1039  		"/DMINORVERSION="+version[1],
  1040  		"/DBUILDVERSION="+version[2],
  1041  		"/DARCH="+*arch,
  1042  		filepath.Join(*workdir, "gzond.nsi"),
  1043  	)
  1044  	// Sign and publish installer.
  1045  	if err := archiveUpload(installer, *upload, *signer, *signify); err != nil {
  1046  		log.Fatal(err)
  1047  	}
  1048  }
  1049  
  1050  // Binary distribution cleanups
  1051  
  1052  func doPurge(cmdline []string) {
  1053  	var (
  1054  		store = flag.String("store", "", `Destination from where to purge archives (usually "gzondstore/builds")`)
  1055  		limit = flag.Int("days", 30, `Age threshold above which to delete unstable archives`)
  1056  	)
  1057  	flag.CommandLine.Parse(cmdline)
  1058  
  1059  	if env := build.Env(); !env.IsCronJob {
  1060  		log.Printf("skipping because not a cron job")
  1061  		os.Exit(0)
  1062  	}
  1063  	// Create the azure authentication and list the current archives
  1064  	auth := build.AzureBlobstoreConfig{
  1065  		Account:   strings.Split(*store, "/")[0],
  1066  		Token:     os.Getenv("AZURE_BLOBSTORE_TOKEN"),
  1067  		Container: strings.SplitN(*store, "/", 2)[1],
  1068  	}
  1069  	blobs, err := build.AzureBlobstoreList(auth)
  1070  	if err != nil {
  1071  		log.Fatal(err)
  1072  	}
  1073  	fmt.Printf("Found %d blobs\n", len(blobs))
  1074  
  1075  	// Iterate over the blobs, collect and sort all unstable builds
  1076  	for i := 0; i < len(blobs); i++ {
  1077  		if !strings.Contains(*blobs[i].Name, "unstable") {
  1078  			blobs = append(blobs[:i], blobs[i+1:]...)
  1079  			i--
  1080  		}
  1081  	}
  1082  	for i := 0; i < len(blobs); i++ {
  1083  		for j := i + 1; j < len(blobs); j++ {
  1084  			if blobs[i].Properties.LastModified.After(*blobs[j].Properties.LastModified) {
  1085  				blobs[i], blobs[j] = blobs[j], blobs[i]
  1086  			}
  1087  		}
  1088  	}
  1089  	// Filter out all archives more recent that the given threshold
  1090  	for i, blob := range blobs {
  1091  		if time.Since(*blob.Properties.LastModified) < time.Duration(*limit)*24*time.Hour {
  1092  			blobs = blobs[:i]
  1093  			break
  1094  		}
  1095  	}
  1096  	fmt.Printf("Deleting %d blobs\n", len(blobs))
  1097  	// Delete all marked as such and return
  1098  	if err := build.AzureBlobstoreDelete(auth, blobs); err != nil {
  1099  		log.Fatal(err)
  1100  	}
  1101  }