ci.go 36 KB

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