ci.go 34 KB

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