ci.go 36 KB

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