ci.go 36 KB

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