ci.go 33 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081
  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. coverage := flag.Bool("coverage", false, "Whether to record code coverage")
  289. flag.CommandLine.Parse(cmdline)
  290. env := build.Env()
  291. packages := []string{"./..."}
  292. if len(flag.CommandLine.Args()) > 0 {
  293. packages = flag.CommandLine.Args()
  294. }
  295. packages = build.ExpandPackagesNoVendor(packages)
  296. // Run the actual tests.
  297. // Test a single package at a time. CI builders are slow
  298. // and some tests run into timeouts under load.
  299. gotest := goTool("test", buildFlags(env)...)
  300. gotest.Args = append(gotest.Args, "-p", "1", "-timeout", "5m")
  301. if *coverage {
  302. gotest.Args = append(gotest.Args, "-covermode=atomic", "-cover")
  303. }
  304. gotest.Args = append(gotest.Args, packages...)
  305. build.MustRun(gotest)
  306. }
  307. // runs gometalinter on requested packages
  308. func doLint(cmdline []string) {
  309. flag.CommandLine.Parse(cmdline)
  310. packages := []string{"./..."}
  311. if len(flag.CommandLine.Args()) > 0 {
  312. packages = flag.CommandLine.Args()
  313. }
  314. // Get metalinter and install all supported linters
  315. build.MustRun(goTool("get", "gopkg.in/alecthomas/gometalinter.v2"))
  316. build.MustRunCommand(filepath.Join(GOBIN, "gometalinter.v2"), "--install")
  317. // Run fast linters batched together
  318. configs := []string{
  319. "--vendor",
  320. "--tests",
  321. "--deadline=2m",
  322. "--disable-all",
  323. "--enable=goimports",
  324. "--enable=varcheck",
  325. "--enable=vet",
  326. "--enable=gofmt",
  327. "--enable=misspell",
  328. "--enable=goconst",
  329. "--min-occurrences=6", // for goconst
  330. }
  331. build.MustRunCommand(filepath.Join(GOBIN, "gometalinter.v2"), append(configs, packages...)...)
  332. // Run slow linters one by one
  333. for _, linter := range []string{"unconvert", "gosimple"} {
  334. configs = []string{"--vendor", "--tests", "--deadline=10m", "--disable-all", "--enable=" + linter}
  335. build.MustRunCommand(filepath.Join(GOBIN, "gometalinter.v2"), append(configs, packages...)...)
  336. }
  337. }
  338. // Release Packaging
  339. func doArchive(cmdline []string) {
  340. var (
  341. arch = flag.String("arch", runtime.GOARCH, "Architecture cross packaging")
  342. atype = flag.String("type", "zip", "Type of archive to write (zip|tar)")
  343. signer = flag.String("signer", "", `Environment variable holding the signing key (e.g. LINUX_SIGNING_KEY)`)
  344. upload = flag.String("upload", "", `Destination to upload the archives (usually "gethstore/builds")`)
  345. ext string
  346. )
  347. flag.CommandLine.Parse(cmdline)
  348. switch *atype {
  349. case "zip":
  350. ext = ".zip"
  351. case "tar":
  352. ext = ".tar.gz"
  353. default:
  354. log.Fatal("unknown archive type: ", atype)
  355. }
  356. var (
  357. env = build.Env()
  358. basegeth = archiveBasename(*arch, params.ArchiveVersion(env.Commit))
  359. geth = "geth-" + basegeth + ext
  360. alltools = "geth-alltools-" + basegeth + ext
  361. baseswarm = archiveBasename(*arch, sv.ArchiveVersion(env.Commit))
  362. swarm = "swarm-" + baseswarm + ext
  363. )
  364. maybeSkipArchive(env)
  365. if err := build.WriteArchive(geth, gethArchiveFiles); err != nil {
  366. log.Fatal(err)
  367. }
  368. if err := build.WriteArchive(alltools, allToolsArchiveFiles); err != nil {
  369. log.Fatal(err)
  370. }
  371. if err := build.WriteArchive(swarm, swarmArchiveFiles); err != nil {
  372. log.Fatal(err)
  373. }
  374. for _, archive := range []string{geth, alltools, swarm} {
  375. if err := archiveUpload(archive, *upload, *signer); err != nil {
  376. log.Fatal(err)
  377. }
  378. }
  379. }
  380. func archiveBasename(arch string, archiveVersion string) string {
  381. platform := runtime.GOOS + "-" + arch
  382. if arch == "arm" {
  383. platform += os.Getenv("GOARM")
  384. }
  385. if arch == "android" {
  386. platform = "android-all"
  387. }
  388. if arch == "ios" {
  389. platform = "ios-all"
  390. }
  391. return platform + "-" + archiveVersion
  392. }
  393. func archiveUpload(archive string, blobstore string, signer string) error {
  394. // If signing was requested, generate the signature files
  395. if signer != "" {
  396. pgpkey, err := base64.StdEncoding.DecodeString(os.Getenv(signer))
  397. if err != nil {
  398. return fmt.Errorf("invalid base64 %s", signer)
  399. }
  400. if err := build.PGPSignFile(archive, archive+".asc", string(pgpkey)); err != nil {
  401. return err
  402. }
  403. }
  404. // If uploading to Azure was requested, push the archive possibly with its signature
  405. if blobstore != "" {
  406. auth := build.AzureBlobstoreConfig{
  407. Account: strings.Split(blobstore, "/")[0],
  408. Token: os.Getenv("AZURE_BLOBSTORE_TOKEN"),
  409. Container: strings.SplitN(blobstore, "/", 2)[1],
  410. }
  411. if err := build.AzureBlobstoreUpload(archive, filepath.Base(archive), auth); err != nil {
  412. return err
  413. }
  414. if signer != "" {
  415. if err := build.AzureBlobstoreUpload(archive+".asc", filepath.Base(archive+".asc"), auth); err != nil {
  416. return err
  417. }
  418. }
  419. }
  420. return nil
  421. }
  422. // skips archiving for some build configurations.
  423. func maybeSkipArchive(env build.Environment) {
  424. if env.IsPullRequest {
  425. log.Printf("skipping because this is a PR build")
  426. os.Exit(0)
  427. }
  428. if env.IsCronJob {
  429. log.Printf("skipping because this is a cron job")
  430. os.Exit(0)
  431. }
  432. if env.Branch != "master" && !strings.HasPrefix(env.Tag, "v1.") {
  433. log.Printf("skipping because branch %q, tag %q is not on the whitelist", env.Branch, env.Tag)
  434. os.Exit(0)
  435. }
  436. }
  437. // Debian Packaging
  438. func doDebianSource(cmdline []string) {
  439. var (
  440. signer = flag.String("signer", "", `Signing key name, also used as package author`)
  441. upload = flag.String("upload", "", `Where to upload the source package (usually "ppa:ethereum/ethereum")`)
  442. workdir = flag.String("workdir", "", `Output directory for packages (uses temp dir if unset)`)
  443. now = time.Now()
  444. )
  445. flag.CommandLine.Parse(cmdline)
  446. *workdir = makeWorkdir(*workdir)
  447. env := build.Env()
  448. maybeSkipArchive(env)
  449. // Import the signing key.
  450. if b64key := os.Getenv("PPA_SIGNING_KEY"); b64key != "" {
  451. key, err := base64.StdEncoding.DecodeString(b64key)
  452. if err != nil {
  453. log.Fatal("invalid base64 PPA_SIGNING_KEY")
  454. }
  455. gpg := exec.Command("gpg", "--import")
  456. gpg.Stdin = bytes.NewReader(key)
  457. build.MustRun(gpg)
  458. }
  459. // Create Debian packages and upload them
  460. for _, pkg := range debPackages {
  461. for _, distro := range debDistros {
  462. meta := newDebMetadata(distro, *signer, env, now, pkg.Name, pkg.Version, pkg.Executables)
  463. pkgdir := stageDebianSource(*workdir, meta)
  464. debuild := exec.Command("debuild", "-S", "-sa", "-us", "-uc")
  465. debuild.Dir = pkgdir
  466. build.MustRun(debuild)
  467. changes := fmt.Sprintf("%s_%s_source.changes", meta.Name(), meta.VersionString())
  468. changes = filepath.Join(*workdir, changes)
  469. if *signer != "" {
  470. build.MustRunCommand("debsign", changes)
  471. }
  472. if *upload != "" {
  473. build.MustRunCommand("dput", *upload, changes)
  474. }
  475. }
  476. }
  477. }
  478. func makeWorkdir(wdflag string) string {
  479. var err error
  480. if wdflag != "" {
  481. err = os.MkdirAll(wdflag, 0744)
  482. } else {
  483. wdflag, err = ioutil.TempDir("", "geth-build-")
  484. }
  485. if err != nil {
  486. log.Fatal(err)
  487. }
  488. return wdflag
  489. }
  490. func isUnstableBuild(env build.Environment) bool {
  491. if env.Tag != "" {
  492. return false
  493. }
  494. return true
  495. }
  496. type debPackage struct {
  497. Name string // the name of the Debian package to produce, e.g. "ethereum", or "ethereum-swarm"
  498. Version string // the clean version of the debPackage, e.g. 1.8.12 or 0.3.0, without any metadata
  499. Executables []debExecutable // executables to be included in the package
  500. }
  501. type debMetadata struct {
  502. Env build.Environment
  503. PackageName string
  504. // go-ethereum version being built. Note that this
  505. // is not the debian package version. The package version
  506. // is constructed by VersionString.
  507. Version string
  508. Author string // "name <email>", also selects signing key
  509. Distro, Time string
  510. Executables []debExecutable
  511. }
  512. type debExecutable struct {
  513. PackageName string
  514. BinaryName string
  515. Description string
  516. }
  517. // Package returns the name of the package if present, or
  518. // fallbacks to BinaryName
  519. func (d debExecutable) Package() string {
  520. if d.PackageName != "" {
  521. return d.PackageName
  522. }
  523. return d.BinaryName
  524. }
  525. func newDebMetadata(distro, author string, env build.Environment, t time.Time, name string, version string, exes []debExecutable) debMetadata {
  526. if author == "" {
  527. // No signing key, use default author.
  528. author = "Ethereum Builds <fjl@ethereum.org>"
  529. }
  530. return debMetadata{
  531. PackageName: name,
  532. Env: env,
  533. Author: author,
  534. Distro: distro,
  535. Version: version,
  536. Time: t.Format(time.RFC1123Z),
  537. Executables: exes,
  538. }
  539. }
  540. // Name returns the name of the metapackage that depends
  541. // on all executable packages.
  542. func (meta debMetadata) Name() string {
  543. if isUnstableBuild(meta.Env) {
  544. return meta.PackageName + "-unstable"
  545. }
  546. return meta.PackageName
  547. }
  548. // VersionString returns the debian version of the packages.
  549. func (meta debMetadata) VersionString() string {
  550. vsn := meta.Version
  551. if meta.Env.Buildnum != "" {
  552. vsn += "+build" + meta.Env.Buildnum
  553. }
  554. if meta.Distro != "" {
  555. vsn += "+" + meta.Distro
  556. }
  557. return vsn
  558. }
  559. // ExeList returns the list of all executable packages.
  560. func (meta debMetadata) ExeList() string {
  561. names := make([]string, len(meta.Executables))
  562. for i, e := range meta.Executables {
  563. names[i] = meta.ExeName(e)
  564. }
  565. return strings.Join(names, ", ")
  566. }
  567. // ExeName returns the package name of an executable package.
  568. func (meta debMetadata) ExeName(exe debExecutable) string {
  569. if isUnstableBuild(meta.Env) {
  570. return exe.Package() + "-unstable"
  571. }
  572. return exe.Package()
  573. }
  574. // ExeConflicts returns the content of the Conflicts field
  575. // for executable packages.
  576. func (meta debMetadata) ExeConflicts(exe debExecutable) string {
  577. if isUnstableBuild(meta.Env) {
  578. // Set up the conflicts list so that the *-unstable packages
  579. // cannot be installed alongside the regular version.
  580. //
  581. // https://www.debian.org/doc/debian-policy/ch-relationships.html
  582. // is very explicit about Conflicts: and says that Breaks: should
  583. // be preferred and the conflicting files should be handled via
  584. // alternates. We might do this eventually but using a conflict is
  585. // easier now.
  586. return "ethereum, " + exe.Package()
  587. }
  588. return ""
  589. }
  590. func stageDebianSource(tmpdir string, meta debMetadata) (pkgdir string) {
  591. pkg := meta.Name() + "-" + meta.VersionString()
  592. pkgdir = filepath.Join(tmpdir, pkg)
  593. if err := os.Mkdir(pkgdir, 0755); err != nil {
  594. log.Fatal(err)
  595. }
  596. // Copy the source code.
  597. build.MustRunCommand("git", "checkout-index", "-a", "--prefix", pkgdir+string(filepath.Separator))
  598. // Put the debian build files in place.
  599. debian := filepath.Join(pkgdir, "debian")
  600. build.Render("build/deb/"+meta.PackageName+"/deb.rules", filepath.Join(debian, "rules"), 0755, meta)
  601. build.Render("build/deb/"+meta.PackageName+"/deb.changelog", filepath.Join(debian, "changelog"), 0644, meta)
  602. build.Render("build/deb/"+meta.PackageName+"/deb.control", filepath.Join(debian, "control"), 0644, meta)
  603. build.Render("build/deb/"+meta.PackageName+"/deb.copyright", filepath.Join(debian, "copyright"), 0644, meta)
  604. build.RenderString("8\n", filepath.Join(debian, "compat"), 0644, meta)
  605. build.RenderString("3.0 (native)\n", filepath.Join(debian, "source/format"), 0644, meta)
  606. for _, exe := range meta.Executables {
  607. install := filepath.Join(debian, meta.ExeName(exe)+".install")
  608. docs := filepath.Join(debian, meta.ExeName(exe)+".docs")
  609. build.Render("build/deb/"+meta.PackageName+"/deb.install", install, 0644, exe)
  610. build.Render("build/deb/"+meta.PackageName+"/deb.docs", docs, 0644, exe)
  611. }
  612. return pkgdir
  613. }
  614. // Windows installer
  615. func doWindowsInstaller(cmdline []string) {
  616. // Parse the flags and make skip installer generation on PRs
  617. var (
  618. arch = flag.String("arch", runtime.GOARCH, "Architecture for cross build packaging")
  619. signer = flag.String("signer", "", `Environment variable holding the signing key (e.g. WINDOWS_SIGNING_KEY)`)
  620. upload = flag.String("upload", "", `Destination to upload the archives (usually "gethstore/builds")`)
  621. workdir = flag.String("workdir", "", `Output directory for packages (uses temp dir if unset)`)
  622. )
  623. flag.CommandLine.Parse(cmdline)
  624. *workdir = makeWorkdir(*workdir)
  625. env := build.Env()
  626. maybeSkipArchive(env)
  627. // Aggregate binaries that are included in the installer
  628. var (
  629. devTools []string
  630. allTools []string
  631. gethTool string
  632. )
  633. for _, file := range allToolsArchiveFiles {
  634. if file == "COPYING" { // license, copied later
  635. continue
  636. }
  637. allTools = append(allTools, filepath.Base(file))
  638. if filepath.Base(file) == "geth.exe" {
  639. gethTool = file
  640. } else {
  641. devTools = append(devTools, file)
  642. }
  643. }
  644. // Render NSIS scripts: Installer NSIS contains two installer sections,
  645. // first section contains the geth binary, second section holds the dev tools.
  646. templateData := map[string]interface{}{
  647. "License": "COPYING",
  648. "Geth": gethTool,
  649. "DevTools": devTools,
  650. }
  651. build.Render("build/nsis.geth.nsi", filepath.Join(*workdir, "geth.nsi"), 0644, nil)
  652. build.Render("build/nsis.install.nsh", filepath.Join(*workdir, "install.nsh"), 0644, templateData)
  653. build.Render("build/nsis.uninstall.nsh", filepath.Join(*workdir, "uninstall.nsh"), 0644, allTools)
  654. build.Render("build/nsis.pathupdate.nsh", filepath.Join(*workdir, "PathUpdate.nsh"), 0644, nil)
  655. build.Render("build/nsis.envvarupdate.nsh", filepath.Join(*workdir, "EnvVarUpdate.nsh"), 0644, nil)
  656. build.CopyFile(filepath.Join(*workdir, "SimpleFC.dll"), "build/nsis.simplefc.dll", 0755)
  657. build.CopyFile(filepath.Join(*workdir, "COPYING"), "COPYING", 0755)
  658. // Build the installer. This assumes that all the needed files have been previously
  659. // built (don't mix building and packaging to keep cross compilation complexity to a
  660. // minimum).
  661. version := strings.Split(params.Version, ".")
  662. if env.Commit != "" {
  663. version[2] += "-" + env.Commit[:8]
  664. }
  665. installer, _ := filepath.Abs("geth-" + archiveBasename(*arch, params.ArchiveVersion(env.Commit)) + ".exe")
  666. build.MustRunCommand("makensis.exe",
  667. "/DOUTPUTFILE="+installer,
  668. "/DMAJORVERSION="+version[0],
  669. "/DMINORVERSION="+version[1],
  670. "/DBUILDVERSION="+version[2],
  671. "/DARCH="+*arch,
  672. filepath.Join(*workdir, "geth.nsi"),
  673. )
  674. // Sign and publish installer.
  675. if err := archiveUpload(installer, *upload, *signer); err != nil {
  676. log.Fatal(err)
  677. }
  678. }
  679. // Android archives
  680. func doAndroidArchive(cmdline []string) {
  681. var (
  682. local = flag.Bool("local", false, `Flag whether we're only doing a local build (skip Maven artifacts)`)
  683. signer = flag.String("signer", "", `Environment variable holding the signing key (e.g. ANDROID_SIGNING_KEY)`)
  684. deploy = flag.String("deploy", "", `Destination to deploy the archive (usually "https://oss.sonatype.org")`)
  685. upload = flag.String("upload", "", `Destination to upload the archive (usually "gethstore/builds")`)
  686. )
  687. flag.CommandLine.Parse(cmdline)
  688. env := build.Env()
  689. // Sanity check that the SDK and NDK are installed and set
  690. if os.Getenv("ANDROID_HOME") == "" {
  691. log.Fatal("Please ensure ANDROID_HOME points to your Android SDK")
  692. }
  693. if os.Getenv("ANDROID_NDK") == "" {
  694. log.Fatal("Please ensure ANDROID_NDK points to your Android NDK")
  695. }
  696. // Build the Android archive and Maven resources
  697. build.MustRun(goTool("get", "golang.org/x/mobile/cmd/gomobile", "golang.org/x/mobile/cmd/gobind"))
  698. build.MustRun(gomobileTool("init", "--ndk", os.Getenv("ANDROID_NDK")))
  699. build.MustRun(gomobileTool("bind", "-ldflags", "-s -w", "--target", "android", "--javapkg", "org.ethereum", "-v", "github.com/ethereum/go-ethereum/mobile"))
  700. if *local {
  701. // If we're building locally, copy bundle to build dir and skip Maven
  702. os.Rename("geth.aar", filepath.Join(GOBIN, "geth.aar"))
  703. return
  704. }
  705. meta := newMavenMetadata(env)
  706. build.Render("build/mvn.pom", meta.Package+".pom", 0755, meta)
  707. // Skip Maven deploy and Azure upload for PR builds
  708. maybeSkipArchive(env)
  709. // Sign and upload the archive to Azure
  710. archive := "geth-" + archiveBasename("android", params.ArchiveVersion(env.Commit)) + ".aar"
  711. os.Rename("geth.aar", archive)
  712. if err := archiveUpload(archive, *upload, *signer); err != nil {
  713. log.Fatal(err)
  714. }
  715. // Sign and upload all the artifacts to Maven Central
  716. os.Rename(archive, meta.Package+".aar")
  717. if *signer != "" && *deploy != "" {
  718. // Import the signing key into the local GPG instance
  719. b64key := os.Getenv(*signer)
  720. key, err := base64.StdEncoding.DecodeString(b64key)
  721. if err != nil {
  722. log.Fatalf("invalid base64 %s", *signer)
  723. }
  724. gpg := exec.Command("gpg", "--import")
  725. gpg.Stdin = bytes.NewReader(key)
  726. build.MustRun(gpg)
  727. keyID, err := build.PGPKeyID(string(key))
  728. if err != nil {
  729. log.Fatal(err)
  730. }
  731. // Upload the artifacts to Sonatype and/or Maven Central
  732. repo := *deploy + "/service/local/staging/deploy/maven2"
  733. if meta.Develop {
  734. repo = *deploy + "/content/repositories/snapshots"
  735. }
  736. build.MustRunCommand("mvn", "gpg:sign-and-deploy-file", "-e", "-X",
  737. "-settings=build/mvn.settings", "-Durl="+repo, "-DrepositoryId=ossrh",
  738. "-Dgpg.keyname="+keyID,
  739. "-DpomFile="+meta.Package+".pom", "-Dfile="+meta.Package+".aar")
  740. }
  741. }
  742. func gomobileTool(subcmd string, args ...string) *exec.Cmd {
  743. cmd := exec.Command(filepath.Join(GOBIN, "gomobile"), subcmd)
  744. cmd.Args = append(cmd.Args, args...)
  745. cmd.Env = []string{
  746. "GOPATH=" + build.GOPATH(),
  747. "PATH=" + GOBIN + string(os.PathListSeparator) + os.Getenv("PATH"),
  748. }
  749. for _, e := range os.Environ() {
  750. if strings.HasPrefix(e, "GOPATH=") || strings.HasPrefix(e, "PATH=") {
  751. continue
  752. }
  753. cmd.Env = append(cmd.Env, e)
  754. }
  755. return cmd
  756. }
  757. type mavenMetadata struct {
  758. Version string
  759. Package string
  760. Develop bool
  761. Contributors []mavenContributor
  762. }
  763. type mavenContributor struct {
  764. Name string
  765. Email string
  766. }
  767. func newMavenMetadata(env build.Environment) mavenMetadata {
  768. // Collect the list of authors from the repo root
  769. contribs := []mavenContributor{}
  770. if authors, err := os.Open("AUTHORS"); err == nil {
  771. defer authors.Close()
  772. scanner := bufio.NewScanner(authors)
  773. for scanner.Scan() {
  774. // Skip any whitespace from the authors list
  775. line := strings.TrimSpace(scanner.Text())
  776. if line == "" || line[0] == '#' {
  777. continue
  778. }
  779. // Split the author and insert as a contributor
  780. re := regexp.MustCompile("([^<]+) <(.+)>")
  781. parts := re.FindStringSubmatch(line)
  782. if len(parts) == 3 {
  783. contribs = append(contribs, mavenContributor{Name: parts[1], Email: parts[2]})
  784. }
  785. }
  786. }
  787. // Render the version and package strings
  788. version := params.Version
  789. if isUnstableBuild(env) {
  790. version += "-SNAPSHOT"
  791. }
  792. return mavenMetadata{
  793. Version: version,
  794. Package: "geth-" + version,
  795. Develop: isUnstableBuild(env),
  796. Contributors: contribs,
  797. }
  798. }
  799. // XCode frameworks
  800. func doXCodeFramework(cmdline []string) {
  801. var (
  802. local = flag.Bool("local", false, `Flag whether we're only doing a local build (skip Maven artifacts)`)
  803. signer = flag.String("signer", "", `Environment variable holding the signing key (e.g. IOS_SIGNING_KEY)`)
  804. deploy = flag.String("deploy", "", `Destination to deploy the archive (usually "trunk")`)
  805. upload = flag.String("upload", "", `Destination to upload the archives (usually "gethstore/builds")`)
  806. )
  807. flag.CommandLine.Parse(cmdline)
  808. env := build.Env()
  809. // Build the iOS XCode framework
  810. build.MustRun(goTool("get", "golang.org/x/mobile/cmd/gomobile", "golang.org/x/mobile/cmd/gobind"))
  811. build.MustRun(gomobileTool("init"))
  812. bind := gomobileTool("bind", "-ldflags", "-s -w", "--target", "ios", "--tags", "ios", "-v", "github.com/ethereum/go-ethereum/mobile")
  813. if *local {
  814. // If we're building locally, use the build folder and stop afterwards
  815. bind.Dir, _ = filepath.Abs(GOBIN)
  816. build.MustRun(bind)
  817. return
  818. }
  819. archive := "geth-" + archiveBasename("ios", params.ArchiveVersion(env.Commit))
  820. if err := os.Mkdir(archive, os.ModePerm); err != nil {
  821. log.Fatal(err)
  822. }
  823. bind.Dir, _ = filepath.Abs(archive)
  824. build.MustRun(bind)
  825. build.MustRunCommand("tar", "-zcvf", archive+".tar.gz", archive)
  826. // Skip CocoaPods deploy and Azure upload for PR builds
  827. maybeSkipArchive(env)
  828. // Sign and upload the framework to Azure
  829. if err := archiveUpload(archive+".tar.gz", *upload, *signer); err != nil {
  830. log.Fatal(err)
  831. }
  832. // Prepare and upload a PodSpec to CocoaPods
  833. if *deploy != "" {
  834. meta := newPodMetadata(env, archive)
  835. build.Render("build/pod.podspec", "Geth.podspec", 0755, meta)
  836. build.MustRunCommand("pod", *deploy, "push", "Geth.podspec", "--allow-warnings", "--verbose")
  837. }
  838. }
  839. type podMetadata struct {
  840. Version string
  841. Commit string
  842. Archive string
  843. Contributors []podContributor
  844. }
  845. type podContributor struct {
  846. Name string
  847. Email string
  848. }
  849. func newPodMetadata(env build.Environment, archive string) podMetadata {
  850. // Collect the list of authors from the repo root
  851. contribs := []podContributor{}
  852. if authors, err := os.Open("AUTHORS"); err == nil {
  853. defer authors.Close()
  854. scanner := bufio.NewScanner(authors)
  855. for scanner.Scan() {
  856. // Skip any whitespace from the authors list
  857. line := strings.TrimSpace(scanner.Text())
  858. if line == "" || line[0] == '#' {
  859. continue
  860. }
  861. // Split the author and insert as a contributor
  862. re := regexp.MustCompile("([^<]+) <(.+)>")
  863. parts := re.FindStringSubmatch(line)
  864. if len(parts) == 3 {
  865. contribs = append(contribs, podContributor{Name: parts[1], Email: parts[2]})
  866. }
  867. }
  868. }
  869. version := params.Version
  870. if isUnstableBuild(env) {
  871. version += "-unstable." + env.Buildnum
  872. }
  873. return podMetadata{
  874. Archive: archive,
  875. Version: version,
  876. Commit: env.Commit,
  877. Contributors: contribs,
  878. }
  879. }
  880. // Cross compilation
  881. func doXgo(cmdline []string) {
  882. var (
  883. alltools = flag.Bool("alltools", false, `Flag whether we're building all known tools, or only on in particular`)
  884. )
  885. flag.CommandLine.Parse(cmdline)
  886. env := build.Env()
  887. // Make sure xgo is available for cross compilation
  888. gogetxgo := goTool("get", "github.com/karalabe/xgo")
  889. build.MustRun(gogetxgo)
  890. // If all tools building is requested, build everything the builder wants
  891. args := append(buildFlags(env), flag.Args()...)
  892. if *alltools {
  893. args = append(args, []string{"--dest", GOBIN}...)
  894. for _, res := range allCrossCompiledArchiveFiles {
  895. if strings.HasPrefix(res, GOBIN) {
  896. // Binary tool found, cross build it explicitly
  897. args = append(args, "./"+filepath.Join("cmd", filepath.Base(res)))
  898. xgo := xgoTool(args)
  899. build.MustRun(xgo)
  900. args = args[:len(args)-1]
  901. }
  902. }
  903. return
  904. }
  905. // Otherwise xxecute the explicit cross compilation
  906. path := args[len(args)-1]
  907. args = append(args[:len(args)-1], []string{"--dest", GOBIN, path}...)
  908. xgo := xgoTool(args)
  909. build.MustRun(xgo)
  910. }
  911. func xgoTool(args []string) *exec.Cmd {
  912. cmd := exec.Command(filepath.Join(GOBIN, "xgo"), args...)
  913. cmd.Env = []string{
  914. "GOPATH=" + build.GOPATH(),
  915. "GOBIN=" + GOBIN,
  916. }
  917. for _, e := range os.Environ() {
  918. if strings.HasPrefix(e, "GOPATH=") || strings.HasPrefix(e, "GOBIN=") {
  919. continue
  920. }
  921. cmd.Env = append(cmd.Env, e)
  922. }
  923. return cmd
  924. }
  925. // Binary distribution cleanups
  926. func doPurge(cmdline []string) {
  927. var (
  928. store = flag.String("store", "", `Destination from where to purge archives (usually "gethstore/builds")`)
  929. limit = flag.Int("days", 30, `Age threshold above which to delete unstable archives`)
  930. )
  931. flag.CommandLine.Parse(cmdline)
  932. if env := build.Env(); !env.IsCronJob {
  933. log.Printf("skipping because not a cron job")
  934. os.Exit(0)
  935. }
  936. // Create the azure authentication and list the current archives
  937. auth := build.AzureBlobstoreConfig{
  938. Account: strings.Split(*store, "/")[0],
  939. Token: os.Getenv("AZURE_BLOBSTORE_TOKEN"),
  940. Container: strings.SplitN(*store, "/", 2)[1],
  941. }
  942. blobs, err := build.AzureBlobstoreList(auth)
  943. if err != nil {
  944. log.Fatal(err)
  945. }
  946. // Iterate over the blobs, collect and sort all unstable builds
  947. for i := 0; i < len(blobs); i++ {
  948. if !strings.Contains(blobs[i].Name, "unstable") {
  949. blobs = append(blobs[:i], blobs[i+1:]...)
  950. i--
  951. }
  952. }
  953. for i := 0; i < len(blobs); i++ {
  954. for j := i + 1; j < len(blobs); j++ {
  955. if blobs[i].Properties.LastModified.After(blobs[j].Properties.LastModified) {
  956. blobs[i], blobs[j] = blobs[j], blobs[i]
  957. }
  958. }
  959. }
  960. // Filter out all archives more recent that the given threshold
  961. for i, blob := range blobs {
  962. if time.Since(blob.Properties.LastModified) < time.Duration(*limit)*24*time.Hour {
  963. blobs = blobs[:i]
  964. break
  965. }
  966. }
  967. // Delete all marked as such and return
  968. if err := build.AzureBlobstoreDelete(auth, blobs); err != nil {
  969. log.Fatal(err)
  970. }
  971. }