ci.go 34 KB

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