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