ci.go 36 KB

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