ci.go 39 KB

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