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