ci.go 35 KB

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