ci.go 33 KB

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