ci.go 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206
  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. }
  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.16"
  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, signifyVar 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 signifyVar != "" {
  409. key := os.Getenv(signifyVar)
  410. untrustedComment := "verify with geth-release.pub"
  411. trustedComment := fmt.Sprintf("%s (%s)", archive, time.Now().UTC().Format(time.RFC1123))
  412. if err := signify.SignFile(archive, archive+".sig", key, untrustedComment, trustedComment); err != nil {
  413. return err
  414. }
  415. }
  416. // If uploading to Azure was requested, push the archive possibly with its signature
  417. if blobstore != "" {
  418. auth := build.AzureBlobstoreConfig{
  419. Account: strings.Split(blobstore, "/")[0],
  420. Token: os.Getenv("AZURE_BLOBSTORE_TOKEN"),
  421. Container: strings.SplitN(blobstore, "/", 2)[1],
  422. }
  423. if err := build.AzureBlobstoreUpload(archive, filepath.Base(archive), auth); err != nil {
  424. return err
  425. }
  426. if signer != "" {
  427. if err := build.AzureBlobstoreUpload(archive+".asc", filepath.Base(archive+".asc"), auth); err != nil {
  428. return err
  429. }
  430. }
  431. if signifyVar != "" {
  432. if err := build.AzureBlobstoreUpload(archive+".sig", filepath.Base(archive+".sig"), auth); err != nil {
  433. return err
  434. }
  435. }
  436. }
  437. return nil
  438. }
  439. // skips archiving for some build configurations.
  440. func maybeSkipArchive(env build.Environment) {
  441. if env.IsPullRequest {
  442. log.Printf("skipping because this is a PR build")
  443. os.Exit(0)
  444. }
  445. if env.IsCronJob {
  446. log.Printf("skipping because this is a cron job")
  447. os.Exit(0)
  448. }
  449. if env.Branch != "master" && !strings.HasPrefix(env.Tag, "v1.") {
  450. log.Printf("skipping because branch %q, tag %q is not on the whitelist", env.Branch, env.Tag)
  451. os.Exit(0)
  452. }
  453. }
  454. // Debian Packaging
  455. func doDebianSource(cmdline []string) {
  456. var (
  457. cachedir = flag.String("cachedir", "./build/cache", `Filesystem path to cache the downloaded Go bundles at`)
  458. signer = flag.String("signer", "", `Signing key name, also used as package author`)
  459. upload = flag.String("upload", "", `Where to upload the source package (usually "ethereum/ethereum")`)
  460. sshUser = flag.String("sftp-user", "", `Username for SFTP upload (usually "geth-ci")`)
  461. workdir = flag.String("workdir", "", `Output directory for packages (uses temp dir if unset)`)
  462. now = time.Now()
  463. )
  464. flag.CommandLine.Parse(cmdline)
  465. *workdir = makeWorkdir(*workdir)
  466. env := build.Env()
  467. maybeSkipArchive(env)
  468. // Import the signing key.
  469. if key := getenvBase64("PPA_SIGNING_KEY"); len(key) > 0 {
  470. gpg := exec.Command("gpg", "--import")
  471. gpg.Stdin = bytes.NewReader(key)
  472. build.MustRun(gpg)
  473. }
  474. // Download and verify the Go source package.
  475. gobundle := downloadGoSources(*cachedir)
  476. // Download all the dependencies needed to build the sources and run the ci script
  477. srcdepfetch := goTool("mod", "download")
  478. srcdepfetch.Env = append(os.Environ(), "GOPATH="+filepath.Join(*workdir, "modgopath"))
  479. build.MustRun(srcdepfetch)
  480. cidepfetch := goTool("run", "./build/ci.go")
  481. cidepfetch.Env = append(os.Environ(), "GOPATH="+filepath.Join(*workdir, "modgopath"))
  482. cidepfetch.Run() // Command fails, don't care, we only need the deps to start it
  483. // Create Debian packages and upload them.
  484. for _, pkg := range debPackages {
  485. for distro, goboot := range debDistroGoBoots {
  486. // Prepare the debian package with the go-ethereum sources.
  487. meta := newDebMetadata(distro, goboot, *signer, env, now, pkg.Name, pkg.Version, pkg.Executables)
  488. pkgdir := stageDebianSource(*workdir, meta)
  489. // Add Go source code
  490. if err := build.ExtractArchive(gobundle, pkgdir); err != nil {
  491. log.Fatalf("Failed to extract Go sources: %v", err)
  492. }
  493. if err := os.Rename(filepath.Join(pkgdir, "go"), filepath.Join(pkgdir, ".go")); err != nil {
  494. log.Fatalf("Failed to rename Go source folder: %v", err)
  495. }
  496. // Add all dependency modules in compressed form
  497. os.MkdirAll(filepath.Join(pkgdir, ".mod", "cache"), 0755)
  498. if err := cp.CopyAll(filepath.Join(pkgdir, ".mod", "cache", "download"), filepath.Join(*workdir, "modgopath", "pkg", "mod", "cache", "download")); err != nil {
  499. log.Fatalf("Failed to copy Go module dependencies: %v", err)
  500. }
  501. // Run the packaging and upload to the PPA
  502. debuild := exec.Command("debuild", "-S", "-sa", "-us", "-uc", "-d", "-Zxz", "-nc")
  503. debuild.Dir = pkgdir
  504. build.MustRun(debuild)
  505. var (
  506. basename = fmt.Sprintf("%s_%s", meta.Name(), meta.VersionString())
  507. source = filepath.Join(*workdir, basename+".tar.xz")
  508. dsc = filepath.Join(*workdir, basename+".dsc")
  509. changes = filepath.Join(*workdir, basename+"_source.changes")
  510. )
  511. if *signer != "" {
  512. build.MustRunCommand("debsign", changes)
  513. }
  514. if *upload != "" {
  515. ppaUpload(*workdir, *upload, *sshUser, []string{source, dsc, changes})
  516. }
  517. }
  518. }
  519. }
  520. // downloadGoSources downloads the Go source tarball.
  521. func downloadGoSources(cachedir string) string {
  522. csdb := build.MustLoadChecksums("build/checksums.txt")
  523. file := fmt.Sprintf("go%s.src.tar.gz", dlgoVersion)
  524. url := "https://dl.google.com/go/" + file
  525. dst := filepath.Join(cachedir, file)
  526. if err := csdb.DownloadFile(url, dst); err != nil {
  527. log.Fatal(err)
  528. }
  529. return dst
  530. }
  531. // downloadGo downloads the Go binary distribution and unpacks it into a temporary
  532. // directory. It returns the GOROOT of the unpacked toolchain.
  533. func downloadGo(goarch, goos, cachedir string) string {
  534. if goarch == "arm" {
  535. goarch = "armv6l"
  536. }
  537. csdb := build.MustLoadChecksums("build/checksums.txt")
  538. file := fmt.Sprintf("go%s.%s-%s", dlgoVersion, goos, goarch)
  539. if goos == "windows" {
  540. file += ".zip"
  541. } else {
  542. file += ".tar.gz"
  543. }
  544. url := "https://golang.org/dl/" + file
  545. dst := filepath.Join(cachedir, file)
  546. if err := csdb.DownloadFile(url, dst); err != nil {
  547. log.Fatal(err)
  548. }
  549. ucache, err := os.UserCacheDir()
  550. if err != nil {
  551. log.Fatal(err)
  552. }
  553. godir := filepath.Join(ucache, fmt.Sprintf("geth-go-%s-%s-%s", dlgoVersion, goos, goarch))
  554. if err := build.ExtractArchive(dst, godir); err != nil {
  555. log.Fatal(err)
  556. }
  557. goroot, err := filepath.Abs(filepath.Join(godir, "go"))
  558. if err != nil {
  559. log.Fatal(err)
  560. }
  561. return goroot
  562. }
  563. func ppaUpload(workdir, ppa, sshUser string, files []string) {
  564. p := strings.Split(ppa, "/")
  565. if len(p) != 2 {
  566. log.Fatal("-upload PPA name must contain single /")
  567. }
  568. if sshUser == "" {
  569. sshUser = p[0]
  570. }
  571. incomingDir := fmt.Sprintf("~%s/ubuntu/%s", p[0], p[1])
  572. // Create the SSH identity file if it doesn't exist.
  573. var idfile string
  574. if sshkey := getenvBase64("PPA_SSH_KEY"); len(sshkey) > 0 {
  575. idfile = filepath.Join(workdir, "sshkey")
  576. if _, err := os.Stat(idfile); os.IsNotExist(err) {
  577. ioutil.WriteFile(idfile, sshkey, 0600)
  578. }
  579. }
  580. // Upload
  581. dest := sshUser + "@ppa.launchpad.net"
  582. if err := build.UploadSFTP(idfile, dest, incomingDir, files); err != nil {
  583. log.Fatal(err)
  584. }
  585. }
  586. func getenvBase64(variable string) []byte {
  587. dec, err := base64.StdEncoding.DecodeString(os.Getenv(variable))
  588. if err != nil {
  589. log.Fatal("invalid base64 " + variable)
  590. }
  591. return []byte(dec)
  592. }
  593. func makeWorkdir(wdflag string) string {
  594. var err error
  595. if wdflag != "" {
  596. err = os.MkdirAll(wdflag, 0744)
  597. } else {
  598. wdflag, err = ioutil.TempDir("", "geth-build-")
  599. }
  600. if err != nil {
  601. log.Fatal(err)
  602. }
  603. return wdflag
  604. }
  605. func isUnstableBuild(env build.Environment) bool {
  606. if env.Tag != "" {
  607. return false
  608. }
  609. return true
  610. }
  611. type debPackage struct {
  612. Name string // the name of the Debian package to produce, e.g. "ethereum"
  613. Version string // the clean version of the debPackage, e.g. 1.8.12, without any metadata
  614. Executables []debExecutable // executables to be included in the package
  615. }
  616. type debMetadata struct {
  617. Env build.Environment
  618. GoBootPackage string
  619. GoBootPath string
  620. PackageName string
  621. // go-ethereum version being built. Note that this
  622. // is not the debian package version. The package version
  623. // is constructed by VersionString.
  624. Version string
  625. Author string // "name <email>", also selects signing key
  626. Distro, Time string
  627. Executables []debExecutable
  628. }
  629. type debExecutable struct {
  630. PackageName string
  631. BinaryName string
  632. Description string
  633. }
  634. // Package returns the name of the package if present, or
  635. // fallbacks to BinaryName
  636. func (d debExecutable) Package() string {
  637. if d.PackageName != "" {
  638. return d.PackageName
  639. }
  640. return d.BinaryName
  641. }
  642. func newDebMetadata(distro, goboot, author string, env build.Environment, t time.Time, name string, version string, exes []debExecutable) debMetadata {
  643. if author == "" {
  644. // No signing key, use default author.
  645. author = "Ethereum Builds <fjl@ethereum.org>"
  646. }
  647. return debMetadata{
  648. GoBootPackage: goboot,
  649. GoBootPath: debGoBootPaths[goboot],
  650. PackageName: name,
  651. Env: env,
  652. Author: author,
  653. Distro: distro,
  654. Version: version,
  655. Time: t.Format(time.RFC1123Z),
  656. Executables: exes,
  657. }
  658. }
  659. // Name returns the name of the metapackage that depends
  660. // on all executable packages.
  661. func (meta debMetadata) Name() string {
  662. if isUnstableBuild(meta.Env) {
  663. return meta.PackageName + "-unstable"
  664. }
  665. return meta.PackageName
  666. }
  667. // VersionString returns the debian version of the packages.
  668. func (meta debMetadata) VersionString() string {
  669. vsn := meta.Version
  670. if meta.Env.Buildnum != "" {
  671. vsn += "+build" + meta.Env.Buildnum
  672. }
  673. if meta.Distro != "" {
  674. vsn += "+" + meta.Distro
  675. }
  676. return vsn
  677. }
  678. // ExeList returns the list of all executable packages.
  679. func (meta debMetadata) ExeList() string {
  680. names := make([]string, len(meta.Executables))
  681. for i, e := range meta.Executables {
  682. names[i] = meta.ExeName(e)
  683. }
  684. return strings.Join(names, ", ")
  685. }
  686. // ExeName returns the package name of an executable package.
  687. func (meta debMetadata) ExeName(exe debExecutable) string {
  688. if isUnstableBuild(meta.Env) {
  689. return exe.Package() + "-unstable"
  690. }
  691. return exe.Package()
  692. }
  693. // ExeConflicts returns the content of the Conflicts field
  694. // for executable packages.
  695. func (meta debMetadata) ExeConflicts(exe debExecutable) string {
  696. if isUnstableBuild(meta.Env) {
  697. // Set up the conflicts list so that the *-unstable packages
  698. // cannot be installed alongside the regular version.
  699. //
  700. // https://www.debian.org/doc/debian-policy/ch-relationships.html
  701. // is very explicit about Conflicts: and says that Breaks: should
  702. // be preferred and the conflicting files should be handled via
  703. // alternates. We might do this eventually but using a conflict is
  704. // easier now.
  705. return "ethereum, " + exe.Package()
  706. }
  707. return ""
  708. }
  709. func stageDebianSource(tmpdir string, meta debMetadata) (pkgdir string) {
  710. pkg := meta.Name() + "-" + meta.VersionString()
  711. pkgdir = filepath.Join(tmpdir, pkg)
  712. if err := os.Mkdir(pkgdir, 0755); err != nil {
  713. log.Fatal(err)
  714. }
  715. // Copy the source code.
  716. build.MustRunCommand("git", "checkout-index", "-a", "--prefix", pkgdir+string(filepath.Separator))
  717. // Put the debian build files in place.
  718. debian := filepath.Join(pkgdir, "debian")
  719. build.Render("build/deb/"+meta.PackageName+"/deb.rules", filepath.Join(debian, "rules"), 0755, meta)
  720. build.Render("build/deb/"+meta.PackageName+"/deb.changelog", filepath.Join(debian, "changelog"), 0644, meta)
  721. build.Render("build/deb/"+meta.PackageName+"/deb.control", filepath.Join(debian, "control"), 0644, meta)
  722. build.Render("build/deb/"+meta.PackageName+"/deb.copyright", filepath.Join(debian, "copyright"), 0644, meta)
  723. build.RenderString("8\n", filepath.Join(debian, "compat"), 0644, meta)
  724. build.RenderString("3.0 (native)\n", filepath.Join(debian, "source/format"), 0644, meta)
  725. for _, exe := range meta.Executables {
  726. install := filepath.Join(debian, meta.ExeName(exe)+".install")
  727. docs := filepath.Join(debian, meta.ExeName(exe)+".docs")
  728. build.Render("build/deb/"+meta.PackageName+"/deb.install", install, 0644, exe)
  729. build.Render("build/deb/"+meta.PackageName+"/deb.docs", docs, 0644, exe)
  730. }
  731. return pkgdir
  732. }
  733. // Windows installer
  734. func doWindowsInstaller(cmdline []string) {
  735. // Parse the flags and make skip installer generation on PRs
  736. var (
  737. arch = flag.String("arch", runtime.GOARCH, "Architecture for cross build packaging")
  738. signer = flag.String("signer", "", `Environment variable holding the signing key (e.g. WINDOWS_SIGNING_KEY)`)
  739. signify = flag.String("signify key", "", `Environment variable holding the signify signing key (e.g. WINDOWS_SIGNIFY_KEY)`)
  740. upload = flag.String("upload", "", `Destination to upload the archives (usually "gethstore/builds")`)
  741. workdir = flag.String("workdir", "", `Output directory for packages (uses temp dir if unset)`)
  742. )
  743. flag.CommandLine.Parse(cmdline)
  744. *workdir = makeWorkdir(*workdir)
  745. env := build.Env()
  746. maybeSkipArchive(env)
  747. // Aggregate binaries that are included in the installer
  748. var (
  749. devTools []string
  750. allTools []string
  751. gethTool string
  752. )
  753. for _, file := range allToolsArchiveFiles {
  754. if file == "COPYING" { // license, copied later
  755. continue
  756. }
  757. allTools = append(allTools, filepath.Base(file))
  758. if filepath.Base(file) == "geth.exe" {
  759. gethTool = file
  760. } else {
  761. devTools = append(devTools, file)
  762. }
  763. }
  764. // Render NSIS scripts: Installer NSIS contains two installer sections,
  765. // first section contains the geth binary, second section holds the dev tools.
  766. templateData := map[string]interface{}{
  767. "License": "COPYING",
  768. "Geth": gethTool,
  769. "DevTools": devTools,
  770. }
  771. build.Render("build/nsis.geth.nsi", filepath.Join(*workdir, "geth.nsi"), 0644, nil)
  772. build.Render("build/nsis.install.nsh", filepath.Join(*workdir, "install.nsh"), 0644, templateData)
  773. build.Render("build/nsis.uninstall.nsh", filepath.Join(*workdir, "uninstall.nsh"), 0644, allTools)
  774. build.Render("build/nsis.pathupdate.nsh", filepath.Join(*workdir, "PathUpdate.nsh"), 0644, nil)
  775. build.Render("build/nsis.envvarupdate.nsh", filepath.Join(*workdir, "EnvVarUpdate.nsh"), 0644, nil)
  776. if err := cp.CopyFile(filepath.Join(*workdir, "SimpleFC.dll"), "build/nsis.simplefc.dll"); err != nil {
  777. log.Fatal("Failed to copy SimpleFC.dll: %v", err)
  778. }
  779. if err := cp.CopyFile(filepath.Join(*workdir, "COPYING"), "COPYING"); err != nil {
  780. log.Fatal("Failed to copy copyright note: %v", err)
  781. }
  782. // Build the installer. This assumes that all the needed files have been previously
  783. // built (don't mix building and packaging to keep cross compilation complexity to a
  784. // minimum).
  785. version := strings.Split(params.Version, ".")
  786. if env.Commit != "" {
  787. version[2] += "-" + env.Commit[:8]
  788. }
  789. installer, _ := filepath.Abs("geth-" + archiveBasename(*arch, params.ArchiveVersion(env.Commit)) + ".exe")
  790. build.MustRunCommand("makensis.exe",
  791. "/DOUTPUTFILE="+installer,
  792. "/DMAJORVERSION="+version[0],
  793. "/DMINORVERSION="+version[1],
  794. "/DBUILDVERSION="+version[2],
  795. "/DARCH="+*arch,
  796. filepath.Join(*workdir, "geth.nsi"),
  797. )
  798. // Sign and publish installer.
  799. if err := archiveUpload(installer, *upload, *signer, *signify); err != nil {
  800. log.Fatal(err)
  801. }
  802. }
  803. // Android archives
  804. func doAndroidArchive(cmdline []string) {
  805. var (
  806. local = flag.Bool("local", false, `Flag whether we're only doing a local build (skip Maven artifacts)`)
  807. signer = flag.String("signer", "", `Environment variable holding the signing key (e.g. ANDROID_SIGNING_KEY)`)
  808. signify = flag.String("signify", "", `Environment variable holding the signify signing key (e.g. ANDROID_SIGNIFY_KEY)`)
  809. deploy = flag.String("deploy", "", `Destination to deploy the archive (usually "https://oss.sonatype.org")`)
  810. upload = flag.String("upload", "", `Destination to upload the archive (usually "gethstore/builds")`)
  811. )
  812. flag.CommandLine.Parse(cmdline)
  813. env := build.Env()
  814. // Sanity check that the SDK and NDK are installed and set
  815. if os.Getenv("ANDROID_HOME") == "" {
  816. log.Fatal("Please ensure ANDROID_HOME points to your Android SDK")
  817. }
  818. // Build the Android archive and Maven resources
  819. build.MustRun(goTool("get", "golang.org/x/mobile/cmd/gomobile", "golang.org/x/mobile/cmd/gobind"))
  820. build.MustRun(gomobileTool("bind", "-ldflags", "-s -w", "--target", "android", "--javapkg", "org.ethereum", "-v", "github.com/ethereum/go-ethereum/mobile"))
  821. if *local {
  822. // If we're building locally, copy bundle to build dir and skip Maven
  823. os.Rename("geth.aar", filepath.Join(GOBIN, "geth.aar"))
  824. os.Rename("geth-sources.jar", filepath.Join(GOBIN, "geth-sources.jar"))
  825. return
  826. }
  827. meta := newMavenMetadata(env)
  828. build.Render("build/mvn.pom", meta.Package+".pom", 0755, meta)
  829. // Skip Maven deploy and Azure upload for PR builds
  830. maybeSkipArchive(env)
  831. // Sign and upload the archive to Azure
  832. archive := "geth-" + archiveBasename("android", params.ArchiveVersion(env.Commit)) + ".aar"
  833. os.Rename("geth.aar", archive)
  834. if err := archiveUpload(archive, *upload, *signer, *signify); err != nil {
  835. log.Fatal(err)
  836. }
  837. // Sign and upload all the artifacts to Maven Central
  838. os.Rename(archive, meta.Package+".aar")
  839. if *signer != "" && *deploy != "" {
  840. // Import the signing key into the local GPG instance
  841. key := getenvBase64(*signer)
  842. gpg := exec.Command("gpg", "--import")
  843. gpg.Stdin = bytes.NewReader(key)
  844. build.MustRun(gpg)
  845. keyID, err := build.PGPKeyID(string(key))
  846. if err != nil {
  847. log.Fatal(err)
  848. }
  849. // Upload the artifacts to Sonatype and/or Maven Central
  850. repo := *deploy + "/service/local/staging/deploy/maven2"
  851. if meta.Develop {
  852. repo = *deploy + "/content/repositories/snapshots"
  853. }
  854. build.MustRunCommand("mvn", "gpg:sign-and-deploy-file", "-e", "-X",
  855. "-settings=build/mvn.settings", "-Durl="+repo, "-DrepositoryId=ossrh",
  856. "-Dgpg.keyname="+keyID,
  857. "-DpomFile="+meta.Package+".pom", "-Dfile="+meta.Package+".aar")
  858. }
  859. }
  860. func gomobileTool(subcmd string, args ...string) *exec.Cmd {
  861. cmd := exec.Command(filepath.Join(GOBIN, "gomobile"), subcmd)
  862. cmd.Args = append(cmd.Args, args...)
  863. cmd.Env = []string{
  864. "PATH=" + GOBIN + string(os.PathListSeparator) + os.Getenv("PATH"),
  865. }
  866. for _, e := range os.Environ() {
  867. if strings.HasPrefix(e, "GOPATH=") || strings.HasPrefix(e, "PATH=") || strings.HasPrefix(e, "GOBIN=") {
  868. continue
  869. }
  870. cmd.Env = append(cmd.Env, e)
  871. }
  872. cmd.Env = append(cmd.Env, "GOBIN="+GOBIN)
  873. return cmd
  874. }
  875. type mavenMetadata struct {
  876. Version string
  877. Package string
  878. Develop bool
  879. Contributors []mavenContributor
  880. }
  881. type mavenContributor struct {
  882. Name string
  883. Email string
  884. }
  885. func newMavenMetadata(env build.Environment) mavenMetadata {
  886. // Collect the list of authors from the repo root
  887. contribs := []mavenContributor{}
  888. if authors, err := os.Open("AUTHORS"); err == nil {
  889. defer authors.Close()
  890. scanner := bufio.NewScanner(authors)
  891. for scanner.Scan() {
  892. // Skip any whitespace from the authors list
  893. line := strings.TrimSpace(scanner.Text())
  894. if line == "" || line[0] == '#' {
  895. continue
  896. }
  897. // Split the author and insert as a contributor
  898. re := regexp.MustCompile("([^<]+) <(.+)>")
  899. parts := re.FindStringSubmatch(line)
  900. if len(parts) == 3 {
  901. contribs = append(contribs, mavenContributor{Name: parts[1], Email: parts[2]})
  902. }
  903. }
  904. }
  905. // Render the version and package strings
  906. version := params.Version
  907. if isUnstableBuild(env) {
  908. version += "-SNAPSHOT"
  909. }
  910. return mavenMetadata{
  911. Version: version,
  912. Package: "geth-" + version,
  913. Develop: isUnstableBuild(env),
  914. Contributors: contribs,
  915. }
  916. }
  917. // XCode frameworks
  918. func doXCodeFramework(cmdline []string) {
  919. var (
  920. local = flag.Bool("local", false, `Flag whether we're only doing a local build (skip Maven artifacts)`)
  921. signer = flag.String("signer", "", `Environment variable holding the signing key (e.g. IOS_SIGNING_KEY)`)
  922. signify = flag.String("signify", "", `Environment variable holding the signify signing key (e.g. IOS_SIGNIFY_KEY)`)
  923. deploy = flag.String("deploy", "", `Destination to deploy the archive (usually "trunk")`)
  924. upload = flag.String("upload", "", `Destination to upload the archives (usually "gethstore/builds")`)
  925. )
  926. flag.CommandLine.Parse(cmdline)
  927. env := build.Env()
  928. // Build the iOS XCode framework
  929. build.MustRun(goTool("get", "golang.org/x/mobile/cmd/gomobile", "golang.org/x/mobile/cmd/gobind"))
  930. build.MustRun(gomobileTool("init"))
  931. bind := gomobileTool("bind", "-ldflags", "-s -w", "--target", "ios", "-v", "github.com/ethereum/go-ethereum/mobile")
  932. if *local {
  933. // If we're building locally, use the build folder and stop afterwards
  934. bind.Dir = GOBIN
  935. build.MustRun(bind)
  936. return
  937. }
  938. archive := "geth-" + archiveBasename("ios", params.ArchiveVersion(env.Commit))
  939. if err := os.Mkdir(archive, os.ModePerm); err != nil {
  940. log.Fatal(err)
  941. }
  942. bind.Dir, _ = filepath.Abs(archive)
  943. build.MustRun(bind)
  944. build.MustRunCommand("tar", "-zcvf", archive+".tar.gz", archive)
  945. // Skip CocoaPods deploy and Azure upload for PR builds
  946. maybeSkipArchive(env)
  947. // Sign and upload the framework to Azure
  948. if err := archiveUpload(archive+".tar.gz", *upload, *signer, *signify); err != nil {
  949. log.Fatal(err)
  950. }
  951. // Prepare and upload a PodSpec to CocoaPods
  952. if *deploy != "" {
  953. meta := newPodMetadata(env, archive)
  954. build.Render("build/pod.podspec", "Geth.podspec", 0755, meta)
  955. build.MustRunCommand("pod", *deploy, "push", "Geth.podspec", "--allow-warnings")
  956. }
  957. }
  958. type podMetadata struct {
  959. Version string
  960. Commit string
  961. Archive string
  962. Contributors []podContributor
  963. }
  964. type podContributor struct {
  965. Name string
  966. Email string
  967. }
  968. func newPodMetadata(env build.Environment, archive string) podMetadata {
  969. // Collect the list of authors from the repo root
  970. contribs := []podContributor{}
  971. if authors, err := os.Open("AUTHORS"); err == nil {
  972. defer authors.Close()
  973. scanner := bufio.NewScanner(authors)
  974. for scanner.Scan() {
  975. // Skip any whitespace from the authors list
  976. line := strings.TrimSpace(scanner.Text())
  977. if line == "" || line[0] == '#' {
  978. continue
  979. }
  980. // Split the author and insert as a contributor
  981. re := regexp.MustCompile("([^<]+) <(.+)>")
  982. parts := re.FindStringSubmatch(line)
  983. if len(parts) == 3 {
  984. contribs = append(contribs, podContributor{Name: parts[1], Email: parts[2]})
  985. }
  986. }
  987. }
  988. version := params.Version
  989. if isUnstableBuild(env) {
  990. version += "-unstable." + env.Buildnum
  991. }
  992. return podMetadata{
  993. Archive: archive,
  994. Version: version,
  995. Commit: env.Commit,
  996. Contributors: contribs,
  997. }
  998. }
  999. // Cross compilation
  1000. func doXgo(cmdline []string) {
  1001. var (
  1002. alltools = flag.Bool("alltools", false, `Flag whether we're building all known tools, or only on in particular`)
  1003. )
  1004. flag.CommandLine.Parse(cmdline)
  1005. env := build.Env()
  1006. // Make sure xgo is available for cross compilation
  1007. gogetxgo := goTool("get", "github.com/karalabe/xgo")
  1008. build.MustRun(gogetxgo)
  1009. // If all tools building is requested, build everything the builder wants
  1010. args := append(buildFlags(env), flag.Args()...)
  1011. if *alltools {
  1012. args = append(args, []string{"--dest", GOBIN}...)
  1013. for _, res := range allToolsArchiveFiles {
  1014. if strings.HasPrefix(res, GOBIN) {
  1015. // Binary tool found, cross build it explicitly
  1016. args = append(args, "./"+filepath.Join("cmd", filepath.Base(res)))
  1017. xgo := xgoTool(args)
  1018. build.MustRun(xgo)
  1019. args = args[:len(args)-1]
  1020. }
  1021. }
  1022. return
  1023. }
  1024. // Otherwise xxecute the explicit cross compilation
  1025. path := args[len(args)-1]
  1026. args = append(args[:len(args)-1], []string{"--dest", GOBIN, path}...)
  1027. xgo := xgoTool(args)
  1028. build.MustRun(xgo)
  1029. }
  1030. func xgoTool(args []string) *exec.Cmd {
  1031. cmd := exec.Command(filepath.Join(GOBIN, "xgo"), args...)
  1032. cmd.Env = os.Environ()
  1033. cmd.Env = append(cmd.Env, []string{
  1034. "GOBIN=" + GOBIN,
  1035. }...)
  1036. return cmd
  1037. }
  1038. // Binary distribution cleanups
  1039. func doPurge(cmdline []string) {
  1040. var (
  1041. store = flag.String("store", "", `Destination from where to purge archives (usually "gethstore/builds")`)
  1042. limit = flag.Int("days", 30, `Age threshold above which to delete unstable archives`)
  1043. )
  1044. flag.CommandLine.Parse(cmdline)
  1045. if env := build.Env(); !env.IsCronJob {
  1046. log.Printf("skipping because not a cron job")
  1047. os.Exit(0)
  1048. }
  1049. // Create the azure authentication and list the current archives
  1050. auth := build.AzureBlobstoreConfig{
  1051. Account: strings.Split(*store, "/")[0],
  1052. Token: os.Getenv("AZURE_BLOBSTORE_TOKEN"),
  1053. Container: strings.SplitN(*store, "/", 2)[1],
  1054. }
  1055. blobs, err := build.AzureBlobstoreList(auth)
  1056. if err != nil {
  1057. log.Fatal(err)
  1058. }
  1059. fmt.Printf("Found %d blobs\n", len(blobs))
  1060. // Iterate over the blobs, collect and sort all unstable builds
  1061. for i := 0; i < len(blobs); i++ {
  1062. if !strings.Contains(blobs[i].Name, "unstable") {
  1063. blobs = append(blobs[:i], blobs[i+1:]...)
  1064. i--
  1065. }
  1066. }
  1067. for i := 0; i < len(blobs); i++ {
  1068. for j := i + 1; j < len(blobs); j++ {
  1069. if blobs[i].Properties.LastModified.After(blobs[j].Properties.LastModified) {
  1070. blobs[i], blobs[j] = blobs[j], blobs[i]
  1071. }
  1072. }
  1073. }
  1074. // Filter out all archives more recent that the given threshold
  1075. for i, blob := range blobs {
  1076. if time.Since(blob.Properties.LastModified) < time.Duration(*limit)*24*time.Hour {
  1077. blobs = blobs[:i]
  1078. break
  1079. }
  1080. }
  1081. fmt.Printf("Deleting %d blobs\n", len(blobs))
  1082. // Delete all marked as such and return
  1083. if err := build.AzureBlobstoreDelete(auth, blobs); err != nil {
  1084. log.Fatal(err)
  1085. }
  1086. }