ci.go 34 KB

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