ci.go 33 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078
  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. debDistros = []string{"trusty", "xenial", "bionic", "cosmic", "disco"}
  125. )
  126. var GOBIN, _ = filepath.Abs(filepath.Join("build", "bin"))
  127. func executablePath(name string) string {
  128. if runtime.GOOS == "windows" {
  129. name += ".exe"
  130. }
  131. return filepath.Join(GOBIN, name)
  132. }
  133. func main() {
  134. log.SetFlags(log.Lshortfile)
  135. if _, err := os.Stat(filepath.Join("build", "ci.go")); os.IsNotExist(err) {
  136. log.Fatal("this script must be run from the root of the repository")
  137. }
  138. if len(os.Args) < 2 {
  139. log.Fatal("need subcommand as first argument")
  140. }
  141. switch os.Args[1] {
  142. case "install":
  143. doInstall(os.Args[2:])
  144. case "test":
  145. doTest(os.Args[2:])
  146. case "lint":
  147. doLint(os.Args[2:])
  148. case "archive":
  149. doArchive(os.Args[2:])
  150. case "debsrc":
  151. doDebianSource(os.Args[2:])
  152. case "nsis":
  153. doWindowsInstaller(os.Args[2:])
  154. case "aar":
  155. doAndroidArchive(os.Args[2:])
  156. case "xcode":
  157. doXCodeFramework(os.Args[2:])
  158. case "xgo":
  159. doXgo(os.Args[2:])
  160. case "purge":
  161. doPurge(os.Args[2:])
  162. default:
  163. log.Fatal("unknown command ", os.Args[1])
  164. }
  165. }
  166. // Compiling
  167. func doInstall(cmdline []string) {
  168. var (
  169. arch = flag.String("arch", "", "Architecture to cross build for")
  170. cc = flag.String("cc", "", "C compiler to cross build with")
  171. )
  172. flag.CommandLine.Parse(cmdline)
  173. env := build.Env()
  174. // Check Go version. People regularly open issues about compilation
  175. // failure with outdated Go. This should save them the trouble.
  176. if !strings.Contains(runtime.Version(), "devel") {
  177. // Figure out the minor version number since we can't textually compare (1.10 < 1.9)
  178. var minor int
  179. fmt.Sscanf(strings.TrimPrefix(runtime.Version(), "go1."), "%d", &minor)
  180. if minor < 9 {
  181. log.Println("You have Go version", runtime.Version())
  182. log.Println("go-ethereum requires at least Go version 1.9 and cannot")
  183. log.Println("be compiled with an earlier version. Please upgrade your Go installation.")
  184. os.Exit(1)
  185. }
  186. }
  187. // Compile packages given as arguments, or everything if there are no arguments.
  188. packages := []string{"./..."}
  189. if flag.NArg() > 0 {
  190. packages = flag.Args()
  191. }
  192. packages = build.ExpandPackagesNoVendor(packages)
  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. packages = build.ExpandPackagesNoVendor(packages)
  281. // Run the actual tests.
  282. // Test a single package at a time. CI builders are slow
  283. // and some tests run into timeouts under load.
  284. gotest := goTool("test", buildFlags(env)...)
  285. gotest.Args = append(gotest.Args, "-p", "1", "-timeout", "5m")
  286. if *coverage {
  287. gotest.Args = append(gotest.Args, "-covermode=atomic", "-cover")
  288. }
  289. gotest.Args = append(gotest.Args, packages...)
  290. build.MustRun(gotest)
  291. }
  292. // runs gometalinter on requested packages
  293. func doLint(cmdline []string) {
  294. flag.CommandLine.Parse(cmdline)
  295. packages := []string{"./..."}
  296. if len(flag.CommandLine.Args()) > 0 {
  297. packages = flag.CommandLine.Args()
  298. }
  299. // Get metalinter and install all supported linters
  300. build.MustRun(goTool("get", "gopkg.in/alecthomas/gometalinter.v2"))
  301. build.MustRunCommand(filepath.Join(GOBIN, "gometalinter.v2"), "--install")
  302. // Run fast linters batched together
  303. configs := []string{
  304. "--vendor",
  305. "--tests",
  306. "--deadline=2m",
  307. "--disable-all",
  308. "--enable=goimports",
  309. "--enable=varcheck",
  310. "--enable=vet",
  311. "--enable=gofmt",
  312. "--enable=misspell",
  313. "--enable=goconst",
  314. "--min-occurrences=6", // for goconst
  315. }
  316. build.MustRunCommand(filepath.Join(GOBIN, "gometalinter.v2"), append(configs, packages...)...)
  317. // Run slow linters one by one
  318. for _, linter := range []string{"unconvert", "gosimple"} {
  319. configs = []string{"--vendor", "--tests", "--deadline=10m", "--disable-all", "--enable=" + linter}
  320. build.MustRunCommand(filepath.Join(GOBIN, "gometalinter.v2"), append(configs, packages...)...)
  321. }
  322. }
  323. // Release Packaging
  324. func doArchive(cmdline []string) {
  325. var (
  326. arch = flag.String("arch", runtime.GOARCH, "Architecture cross packaging")
  327. atype = flag.String("type", "zip", "Type of archive to write (zip|tar)")
  328. signer = flag.String("signer", "", `Environment variable holding the signing key (e.g. LINUX_SIGNING_KEY)`)
  329. upload = flag.String("upload", "", `Destination to upload the archives (usually "gethstore/builds")`)
  330. ext string
  331. )
  332. flag.CommandLine.Parse(cmdline)
  333. switch *atype {
  334. case "zip":
  335. ext = ".zip"
  336. case "tar":
  337. ext = ".tar.gz"
  338. default:
  339. log.Fatal("unknown archive type: ", atype)
  340. }
  341. var (
  342. env = build.Env()
  343. basegeth = archiveBasename(*arch, params.ArchiveVersion(env.Commit))
  344. geth = "geth-" + basegeth + ext
  345. alltools = "geth-alltools-" + basegeth + ext
  346. )
  347. maybeSkipArchive(env)
  348. if err := build.WriteArchive(geth, gethArchiveFiles); err != nil {
  349. log.Fatal(err)
  350. }
  351. if err := build.WriteArchive(alltools, allToolsArchiveFiles); err != nil {
  352. log.Fatal(err)
  353. }
  354. for _, archive := range []string{geth, alltools} {
  355. if err := archiveUpload(archive, *upload, *signer); err != nil {
  356. log.Fatal(err)
  357. }
  358. }
  359. }
  360. func archiveBasename(arch string, archiveVersion string) string {
  361. platform := runtime.GOOS + "-" + arch
  362. if arch == "arm" {
  363. platform += os.Getenv("GOARM")
  364. }
  365. if arch == "android" {
  366. platform = "android-all"
  367. }
  368. if arch == "ios" {
  369. platform = "ios-all"
  370. }
  371. return platform + "-" + archiveVersion
  372. }
  373. func archiveUpload(archive string, blobstore string, signer string) error {
  374. // If signing was requested, generate the signature files
  375. if signer != "" {
  376. key := getenvBase64(signer)
  377. if err := build.PGPSignFile(archive, archive+".asc", string(key)); err != nil {
  378. return err
  379. }
  380. }
  381. // If uploading to Azure was requested, push the archive possibly with its signature
  382. if blobstore != "" {
  383. auth := build.AzureBlobstoreConfig{
  384. Account: strings.Split(blobstore, "/")[0],
  385. Token: os.Getenv("AZURE_BLOBSTORE_TOKEN"),
  386. Container: strings.SplitN(blobstore, "/", 2)[1],
  387. }
  388. if err := build.AzureBlobstoreUpload(archive, filepath.Base(archive), auth); err != nil {
  389. return err
  390. }
  391. if signer != "" {
  392. if err := build.AzureBlobstoreUpload(archive+".asc", filepath.Base(archive+".asc"), auth); err != nil {
  393. return err
  394. }
  395. }
  396. }
  397. return nil
  398. }
  399. // skips archiving for some build configurations.
  400. func maybeSkipArchive(env build.Environment) {
  401. if env.IsPullRequest {
  402. log.Printf("skipping because this is a PR build")
  403. os.Exit(0)
  404. }
  405. if env.IsCronJob {
  406. log.Printf("skipping because this is a cron job")
  407. os.Exit(0)
  408. }
  409. if env.Branch != "master" && !strings.HasPrefix(env.Tag, "v1.") {
  410. log.Printf("skipping because branch %q, tag %q is not on the whitelist", env.Branch, env.Tag)
  411. os.Exit(0)
  412. }
  413. }
  414. // Debian Packaging
  415. func doDebianSource(cmdline []string) {
  416. var (
  417. signer = flag.String("signer", "", `Signing key name, also used as package author`)
  418. upload = flag.String("upload", "", `Where to upload the source package (usually "ethereum/ethereum")`)
  419. sshUser = flag.String("sftp-user", "", `Username for SFTP upload (usually "geth-ci")`)
  420. workdir = flag.String("workdir", "", `Output directory for packages (uses temp dir if unset)`)
  421. now = time.Now()
  422. )
  423. flag.CommandLine.Parse(cmdline)
  424. *workdir = makeWorkdir(*workdir)
  425. env := build.Env()
  426. maybeSkipArchive(env)
  427. // Import the signing key.
  428. if key := getenvBase64("PPA_SIGNING_KEY"); len(key) > 0 {
  429. gpg := exec.Command("gpg", "--import")
  430. gpg.Stdin = bytes.NewReader(key)
  431. build.MustRun(gpg)
  432. }
  433. // Create Debian packages and upload them
  434. for _, pkg := range debPackages {
  435. for _, distro := range debDistros {
  436. meta := newDebMetadata(distro, *signer, env, now, pkg.Name, pkg.Version, pkg.Executables)
  437. pkgdir := stageDebianSource(*workdir, meta)
  438. debuild := exec.Command("debuild", "-S", "-sa", "-us", "-uc", "-d", "-Zxz")
  439. debuild.Dir = pkgdir
  440. build.MustRun(debuild)
  441. var (
  442. basename = fmt.Sprintf("%s_%s", meta.Name(), meta.VersionString())
  443. source = filepath.Join(*workdir, basename+".tar.xz")
  444. dsc = filepath.Join(*workdir, basename+".dsc")
  445. changes = filepath.Join(*workdir, basename+"_source.changes")
  446. )
  447. if *signer != "" {
  448. build.MustRunCommand("debsign", changes)
  449. }
  450. if *upload != "" {
  451. ppaUpload(*workdir, *upload, *sshUser, []string{source, dsc, changes})
  452. }
  453. }
  454. }
  455. }
  456. func ppaUpload(workdir, ppa, sshUser string, files []string) {
  457. p := strings.Split(ppa, "/")
  458. if len(p) != 2 {
  459. log.Fatal("-upload PPA name must contain single /")
  460. }
  461. if sshUser == "" {
  462. sshUser = p[0]
  463. }
  464. incomingDir := fmt.Sprintf("~%s/ubuntu/%s", p[0], p[1])
  465. // Create the SSH identity file if it doesn't exist.
  466. var idfile string
  467. if sshkey := getenvBase64("PPA_SSH_KEY"); len(sshkey) > 0 {
  468. idfile = filepath.Join(workdir, "sshkey")
  469. if _, err := os.Stat(idfile); os.IsNotExist(err) {
  470. ioutil.WriteFile(idfile, sshkey, 0600)
  471. }
  472. }
  473. // Upload
  474. dest := sshUser + "@ppa.launchpad.net"
  475. if err := build.UploadSFTP(idfile, dest, incomingDir, files); err != nil {
  476. log.Fatal(err)
  477. }
  478. }
  479. func getenvBase64(variable string) []byte {
  480. dec, err := base64.StdEncoding.DecodeString(os.Getenv(variable))
  481. if err != nil {
  482. log.Fatal("invalid base64 " + variable)
  483. }
  484. return []byte(dec)
  485. }
  486. func makeWorkdir(wdflag string) string {
  487. var err error
  488. if wdflag != "" {
  489. err = os.MkdirAll(wdflag, 0744)
  490. } else {
  491. wdflag, err = ioutil.TempDir("", "geth-build-")
  492. }
  493. if err != nil {
  494. log.Fatal(err)
  495. }
  496. return wdflag
  497. }
  498. func isUnstableBuild(env build.Environment) bool {
  499. if env.Tag != "" {
  500. return false
  501. }
  502. return true
  503. }
  504. type debPackage struct {
  505. Name string // the name of the Debian package to produce, e.g. "ethereum"
  506. Version string // the clean version of the debPackage, e.g. 1.8.12, without any metadata
  507. Executables []debExecutable // executables to be included in the package
  508. }
  509. type debMetadata struct {
  510. Env build.Environment
  511. PackageName string
  512. // go-ethereum version being built. Note that this
  513. // is not the debian package version. The package version
  514. // is constructed by VersionString.
  515. Version string
  516. Author string // "name <email>", also selects signing key
  517. Distro, Time string
  518. Executables []debExecutable
  519. }
  520. type debExecutable struct {
  521. PackageName string
  522. BinaryName string
  523. Description string
  524. }
  525. // Package returns the name of the package if present, or
  526. // fallbacks to BinaryName
  527. func (d debExecutable) Package() string {
  528. if d.PackageName != "" {
  529. return d.PackageName
  530. }
  531. return d.BinaryName
  532. }
  533. func newDebMetadata(distro, author string, env build.Environment, t time.Time, name string, version string, exes []debExecutable) debMetadata {
  534. if author == "" {
  535. // No signing key, use default author.
  536. author = "Ethereum Builds <fjl@ethereum.org>"
  537. }
  538. return debMetadata{
  539. PackageName: name,
  540. Env: env,
  541. Author: author,
  542. Distro: distro,
  543. Version: version,
  544. Time: t.Format(time.RFC1123Z),
  545. Executables: exes,
  546. }
  547. }
  548. // Name returns the name of the metapackage that depends
  549. // on all executable packages.
  550. func (meta debMetadata) Name() string {
  551. if isUnstableBuild(meta.Env) {
  552. return meta.PackageName + "-unstable"
  553. }
  554. return meta.PackageName
  555. }
  556. // VersionString returns the debian version of the packages.
  557. func (meta debMetadata) VersionString() string {
  558. vsn := meta.Version
  559. if meta.Env.Buildnum != "" {
  560. vsn += "+build" + meta.Env.Buildnum
  561. }
  562. if meta.Distro != "" {
  563. vsn += "+" + meta.Distro
  564. }
  565. return vsn
  566. }
  567. // ExeList returns the list of all executable packages.
  568. func (meta debMetadata) ExeList() string {
  569. names := make([]string, len(meta.Executables))
  570. for i, e := range meta.Executables {
  571. names[i] = meta.ExeName(e)
  572. }
  573. return strings.Join(names, ", ")
  574. }
  575. // ExeName returns the package name of an executable package.
  576. func (meta debMetadata) ExeName(exe debExecutable) string {
  577. if isUnstableBuild(meta.Env) {
  578. return exe.Package() + "-unstable"
  579. }
  580. return exe.Package()
  581. }
  582. // ExeConflicts returns the content of the Conflicts field
  583. // for executable packages.
  584. func (meta debMetadata) ExeConflicts(exe debExecutable) string {
  585. if isUnstableBuild(meta.Env) {
  586. // Set up the conflicts list so that the *-unstable packages
  587. // cannot be installed alongside the regular version.
  588. //
  589. // https://www.debian.org/doc/debian-policy/ch-relationships.html
  590. // is very explicit about Conflicts: and says that Breaks: should
  591. // be preferred and the conflicting files should be handled via
  592. // alternates. We might do this eventually but using a conflict is
  593. // easier now.
  594. return "ethereum, " + exe.Package()
  595. }
  596. return ""
  597. }
  598. func stageDebianSource(tmpdir string, meta debMetadata) (pkgdir string) {
  599. pkg := meta.Name() + "-" + meta.VersionString()
  600. pkgdir = filepath.Join(tmpdir, pkg)
  601. if err := os.Mkdir(pkgdir, 0755); err != nil {
  602. log.Fatal(err)
  603. }
  604. // Copy the source code.
  605. build.MustRunCommand("git", "checkout-index", "-a", "--prefix", pkgdir+string(filepath.Separator))
  606. // Put the debian build files in place.
  607. debian := filepath.Join(pkgdir, "debian")
  608. build.Render("build/deb/"+meta.PackageName+"/deb.rules", filepath.Join(debian, "rules"), 0755, meta)
  609. build.Render("build/deb/"+meta.PackageName+"/deb.changelog", filepath.Join(debian, "changelog"), 0644, meta)
  610. build.Render("build/deb/"+meta.PackageName+"/deb.control", filepath.Join(debian, "control"), 0644, meta)
  611. build.Render("build/deb/"+meta.PackageName+"/deb.copyright", filepath.Join(debian, "copyright"), 0644, meta)
  612. build.RenderString("8\n", filepath.Join(debian, "compat"), 0644, meta)
  613. build.RenderString("3.0 (native)\n", filepath.Join(debian, "source/format"), 0644, meta)
  614. for _, exe := range meta.Executables {
  615. install := filepath.Join(debian, meta.ExeName(exe)+".install")
  616. docs := filepath.Join(debian, meta.ExeName(exe)+".docs")
  617. build.Render("build/deb/"+meta.PackageName+"/deb.install", install, 0644, exe)
  618. build.Render("build/deb/"+meta.PackageName+"/deb.docs", docs, 0644, exe)
  619. }
  620. return pkgdir
  621. }
  622. // Windows installer
  623. func doWindowsInstaller(cmdline []string) {
  624. // Parse the flags and make skip installer generation on PRs
  625. var (
  626. arch = flag.String("arch", runtime.GOARCH, "Architecture for cross build packaging")
  627. signer = flag.String("signer", "", `Environment variable holding the signing key (e.g. WINDOWS_SIGNING_KEY)`)
  628. upload = flag.String("upload", "", `Destination to upload the archives (usually "gethstore/builds")`)
  629. workdir = flag.String("workdir", "", `Output directory for packages (uses temp dir if unset)`)
  630. )
  631. flag.CommandLine.Parse(cmdline)
  632. *workdir = makeWorkdir(*workdir)
  633. env := build.Env()
  634. maybeSkipArchive(env)
  635. // Aggregate binaries that are included in the installer
  636. var (
  637. devTools []string
  638. allTools []string
  639. gethTool string
  640. )
  641. for _, file := range allToolsArchiveFiles {
  642. if file == "COPYING" { // license, copied later
  643. continue
  644. }
  645. allTools = append(allTools, filepath.Base(file))
  646. if filepath.Base(file) == "geth.exe" {
  647. gethTool = file
  648. } else {
  649. devTools = append(devTools, file)
  650. }
  651. }
  652. // Render NSIS scripts: Installer NSIS contains two installer sections,
  653. // first section contains the geth binary, second section holds the dev tools.
  654. templateData := map[string]interface{}{
  655. "License": "COPYING",
  656. "Geth": gethTool,
  657. "DevTools": devTools,
  658. }
  659. build.Render("build/nsis.geth.nsi", filepath.Join(*workdir, "geth.nsi"), 0644, nil)
  660. build.Render("build/nsis.install.nsh", filepath.Join(*workdir, "install.nsh"), 0644, templateData)
  661. build.Render("build/nsis.uninstall.nsh", filepath.Join(*workdir, "uninstall.nsh"), 0644, allTools)
  662. build.Render("build/nsis.pathupdate.nsh", filepath.Join(*workdir, "PathUpdate.nsh"), 0644, nil)
  663. build.Render("build/nsis.envvarupdate.nsh", filepath.Join(*workdir, "EnvVarUpdate.nsh"), 0644, nil)
  664. build.CopyFile(filepath.Join(*workdir, "SimpleFC.dll"), "build/nsis.simplefc.dll", 0755)
  665. build.CopyFile(filepath.Join(*workdir, "COPYING"), "COPYING", 0755)
  666. // Build the installer. This assumes that all the needed files have been previously
  667. // built (don't mix building and packaging to keep cross compilation complexity to a
  668. // minimum).
  669. version := strings.Split(params.Version, ".")
  670. if env.Commit != "" {
  671. version[2] += "-" + env.Commit[:8]
  672. }
  673. installer, _ := filepath.Abs("geth-" + archiveBasename(*arch, params.ArchiveVersion(env.Commit)) + ".exe")
  674. build.MustRunCommand("makensis.exe",
  675. "/DOUTPUTFILE="+installer,
  676. "/DMAJORVERSION="+version[0],
  677. "/DMINORVERSION="+version[1],
  678. "/DBUILDVERSION="+version[2],
  679. "/DARCH="+*arch,
  680. filepath.Join(*workdir, "geth.nsi"),
  681. )
  682. // Sign and publish installer.
  683. if err := archiveUpload(installer, *upload, *signer); err != nil {
  684. log.Fatal(err)
  685. }
  686. }
  687. // Android archives
  688. func doAndroidArchive(cmdline []string) {
  689. var (
  690. local = flag.Bool("local", false, `Flag whether we're only doing a local build (skip Maven artifacts)`)
  691. signer = flag.String("signer", "", `Environment variable holding the signing key (e.g. ANDROID_SIGNING_KEY)`)
  692. deploy = flag.String("deploy", "", `Destination to deploy the archive (usually "https://oss.sonatype.org")`)
  693. upload = flag.String("upload", "", `Destination to upload the archive (usually "gethstore/builds")`)
  694. )
  695. flag.CommandLine.Parse(cmdline)
  696. env := build.Env()
  697. // Sanity check that the SDK and NDK are installed and set
  698. if os.Getenv("ANDROID_HOME") == "" {
  699. log.Fatal("Please ensure ANDROID_HOME points to your Android SDK")
  700. }
  701. // Build the Android archive and Maven resources
  702. build.MustRun(goTool("get", "golang.org/x/mobile/cmd/gomobile", "golang.org/x/mobile/cmd/gobind"))
  703. build.MustRun(gomobileTool("bind", "-ldflags", "-s -w", "--target", "android", "--javapkg", "org.ethereum", "-v", "github.com/ethereum/go-ethereum/mobile"))
  704. if *local {
  705. // If we're building locally, copy bundle to build dir and skip Maven
  706. os.Rename("geth.aar", filepath.Join(GOBIN, "geth.aar"))
  707. return
  708. }
  709. meta := newMavenMetadata(env)
  710. build.Render("build/mvn.pom", meta.Package+".pom", 0755, meta)
  711. // Skip Maven deploy and Azure upload for PR builds
  712. maybeSkipArchive(env)
  713. // Sign and upload the archive to Azure
  714. archive := "geth-" + archiveBasename("android", params.ArchiveVersion(env.Commit)) + ".aar"
  715. os.Rename("geth.aar", archive)
  716. if err := archiveUpload(archive, *upload, *signer); err != nil {
  717. log.Fatal(err)
  718. }
  719. // Sign and upload all the artifacts to Maven Central
  720. os.Rename(archive, meta.Package+".aar")
  721. if *signer != "" && *deploy != "" {
  722. // Import the signing key into the local GPG instance
  723. key := getenvBase64(*signer)
  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 allToolsArchiveFiles {
  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. }