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