ci.go 34 KB

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