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