ci.go 39 KB

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