ci.go 36 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126
  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. "focal": "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 < 11 {
  194. log.Println("You have Go version", runtime.Version())
  195. log.Println("go-ethereum requires at least Go version 1.11 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. // Seems we are cross compiling, work around forbidden GOBIN
  216. goinstall := goToolArch(*arch, *cc, "install", buildFlags(env)...)
  217. goinstall.Args = append(goinstall.Args, "-v")
  218. goinstall.Args = append(goinstall.Args, []string{"-buildmode", "archive"}...)
  219. goinstall.Args = append(goinstall.Args, packages...)
  220. build.MustRun(goinstall)
  221. if cmds, err := ioutil.ReadDir("cmd"); err == nil {
  222. for _, cmd := range cmds {
  223. pkgs, err := parser.ParseDir(token.NewFileSet(), filepath.Join(".", "cmd", cmd.Name()), nil, parser.PackageClauseOnly)
  224. if err != nil {
  225. log.Fatal(err)
  226. }
  227. for name := range pkgs {
  228. if name == "main" {
  229. gobuild := goToolArch(*arch, *cc, "build", buildFlags(env)...)
  230. gobuild.Args = append(gobuild.Args, "-v")
  231. gobuild.Args = append(gobuild.Args, []string{"-o", executablePath(cmd.Name())}...)
  232. gobuild.Args = append(gobuild.Args, "."+string(filepath.Separator)+filepath.Join("cmd", cmd.Name()))
  233. build.MustRun(gobuild)
  234. break
  235. }
  236. }
  237. }
  238. }
  239. }
  240. func buildFlags(env build.Environment) (flags []string) {
  241. var ld []string
  242. if env.Commit != "" {
  243. ld = append(ld, "-X", "main.gitCommit="+env.Commit)
  244. ld = append(ld, "-X", "main.gitDate="+env.Date)
  245. }
  246. if runtime.GOOS == "darwin" {
  247. ld = append(ld, "-s")
  248. }
  249. if len(ld) > 0 {
  250. flags = append(flags, "-ldflags", strings.Join(ld, " "))
  251. }
  252. return flags
  253. }
  254. func goTool(subcmd string, args ...string) *exec.Cmd {
  255. return goToolArch(runtime.GOARCH, os.Getenv("CC"), subcmd, args...)
  256. }
  257. func goToolArch(arch string, cc string, subcmd string, args ...string) *exec.Cmd {
  258. cmd := build.GoTool(subcmd, args...)
  259. if arch == "" || arch == runtime.GOARCH {
  260. cmd.Env = append(cmd.Env, "GOBIN="+GOBIN)
  261. } else {
  262. cmd.Env = append(cmd.Env, "CGO_ENABLED=1")
  263. cmd.Env = append(cmd.Env, "GOARCH="+arch)
  264. }
  265. if cc != "" {
  266. cmd.Env = append(cmd.Env, "CC="+cc)
  267. }
  268. for _, e := range os.Environ() {
  269. if strings.HasPrefix(e, "GOBIN=") {
  270. continue
  271. }
  272. cmd.Env = append(cmd.Env, e)
  273. }
  274. return cmd
  275. }
  276. // Running The Tests
  277. //
  278. // "tests" also includes static analysis tools such as vet.
  279. func doTest(cmdline []string) {
  280. coverage := flag.Bool("coverage", false, "Whether to record code coverage")
  281. verbose := flag.Bool("v", false, "Whether to log verbosely")
  282. flag.CommandLine.Parse(cmdline)
  283. env := build.Env()
  284. packages := []string{"./..."}
  285. if len(flag.CommandLine.Args()) > 0 {
  286. packages = flag.CommandLine.Args()
  287. }
  288. // Run the actual tests.
  289. // Test a single package at a time. CI builders are slow
  290. // and some tests run into timeouts under load.
  291. gotest := goTool("test", buildFlags(env)...)
  292. gotest.Args = append(gotest.Args, "-p", "1")
  293. if *coverage {
  294. gotest.Args = append(gotest.Args, "-covermode=atomic", "-cover")
  295. }
  296. if *verbose {
  297. gotest.Args = append(gotest.Args, "-v")
  298. }
  299. gotest.Args = append(gotest.Args, packages...)
  300. build.MustRun(gotest)
  301. }
  302. // doLint runs golangci-lint on requested packages.
  303. func doLint(cmdline []string) {
  304. var (
  305. cachedir = flag.String("cachedir", "./build/cache", "directory for caching golangci-lint binary.")
  306. )
  307. flag.CommandLine.Parse(cmdline)
  308. packages := []string{"./..."}
  309. if len(flag.CommandLine.Args()) > 0 {
  310. packages = flag.CommandLine.Args()
  311. }
  312. linter := downloadLinter(*cachedir)
  313. lflags := []string{"run", "--config", ".golangci.yml"}
  314. build.MustRunCommand(linter, append(lflags, packages...)...)
  315. fmt.Println("You have achieved perfection.")
  316. }
  317. // downloadLinter downloads and unpacks golangci-lint.
  318. func downloadLinter(cachedir string) string {
  319. const version = "1.27.0"
  320. csdb := build.MustLoadChecksums("build/checksums.txt")
  321. base := fmt.Sprintf("golangci-lint-%s-%s-%s", version, runtime.GOOS, runtime.GOARCH)
  322. url := fmt.Sprintf("https://github.com/golangci/golangci-lint/releases/download/v%s/%s.tar.gz", version, base)
  323. archivePath := filepath.Join(cachedir, base+".tar.gz")
  324. if err := csdb.DownloadFile(url, archivePath); err != nil {
  325. log.Fatal(err)
  326. }
  327. if err := build.ExtractTarballArchive(archivePath, cachedir); err != nil {
  328. log.Fatal(err)
  329. }
  330. return filepath.Join(cachedir, base, "golangci-lint")
  331. }
  332. // Release Packaging
  333. func doArchive(cmdline []string) {
  334. var (
  335. arch = flag.String("arch", runtime.GOARCH, "Architecture cross packaging")
  336. atype = flag.String("type", "zip", "Type of archive to write (zip|tar)")
  337. signer = flag.String("signer", "", `Environment variable holding the signing key (e.g. LINUX_SIGNING_KEY)`)
  338. upload = flag.String("upload", "", `Destination to upload the archives (usually "gethstore/builds")`)
  339. ext string
  340. )
  341. flag.CommandLine.Parse(cmdline)
  342. switch *atype {
  343. case "zip":
  344. ext = ".zip"
  345. case "tar":
  346. ext = ".tar.gz"
  347. default:
  348. log.Fatal("unknown archive type: ", atype)
  349. }
  350. var (
  351. env = build.Env()
  352. basegeth = archiveBasename(*arch, params.ArchiveVersion(env.Commit))
  353. geth = "geth-" + basegeth + ext
  354. alltools = "geth-alltools-" + basegeth + ext
  355. )
  356. maybeSkipArchive(env)
  357. if err := build.WriteArchive(geth, gethArchiveFiles); err != nil {
  358. log.Fatal(err)
  359. }
  360. if err := build.WriteArchive(alltools, allToolsArchiveFiles); err != nil {
  361. log.Fatal(err)
  362. }
  363. for _, archive := range []string{geth, alltools} {
  364. if err := archiveUpload(archive, *upload, *signer); err != nil {
  365. log.Fatal(err)
  366. }
  367. }
  368. }
  369. func archiveBasename(arch string, archiveVersion string) string {
  370. platform := runtime.GOOS + "-" + arch
  371. if arch == "arm" {
  372. platform += os.Getenv("GOARM")
  373. }
  374. if arch == "android" {
  375. platform = "android-all"
  376. }
  377. if arch == "ios" {
  378. platform = "ios-all"
  379. }
  380. return platform + "-" + archiveVersion
  381. }
  382. func archiveUpload(archive string, blobstore string, signer string) error {
  383. // If signing was requested, generate the signature files
  384. if signer != "" {
  385. key := getenvBase64(signer)
  386. if err := build.PGPSignFile(archive, archive+".asc", string(key)); err != nil {
  387. return err
  388. }
  389. }
  390. // If uploading to Azure was requested, push the archive possibly with its signature
  391. if blobstore != "" {
  392. auth := build.AzureBlobstoreConfig{
  393. Account: strings.Split(blobstore, "/")[0],
  394. Token: os.Getenv("AZURE_BLOBSTORE_TOKEN"),
  395. Container: strings.SplitN(blobstore, "/", 2)[1],
  396. }
  397. if err := build.AzureBlobstoreUpload(archive, filepath.Base(archive), auth); err != nil {
  398. return err
  399. }
  400. if signer != "" {
  401. if err := build.AzureBlobstoreUpload(archive+".asc", filepath.Base(archive+".asc"), auth); err != nil {
  402. return err
  403. }
  404. }
  405. }
  406. return nil
  407. }
  408. // skips archiving for some build configurations.
  409. func maybeSkipArchive(env build.Environment) {
  410. if env.IsPullRequest {
  411. log.Printf("skipping because this is a PR build")
  412. os.Exit(0)
  413. }
  414. if env.IsCronJob {
  415. log.Printf("skipping because this is a cron job")
  416. os.Exit(0)
  417. }
  418. if env.Branch != "master" && !strings.HasPrefix(env.Tag, "v1.") {
  419. log.Printf("skipping because branch %q, tag %q is not on the whitelist", env.Branch, env.Tag)
  420. os.Exit(0)
  421. }
  422. }
  423. // Debian Packaging
  424. func doDebianSource(cmdline []string) {
  425. var (
  426. goversion = flag.String("goversion", "", `Go version to build with (will be included in the source package)`)
  427. cachedir = flag.String("cachedir", "./build/cache", `Filesystem path to cache the downloaded Go bundles at`)
  428. signer = flag.String("signer", "", `Signing key name, also used as package author`)
  429. upload = flag.String("upload", "", `Where to upload the source package (usually "ethereum/ethereum")`)
  430. sshUser = flag.String("sftp-user", "", `Username for SFTP upload (usually "geth-ci")`)
  431. workdir = flag.String("workdir", "", `Output directory for packages (uses temp dir if unset)`)
  432. now = time.Now()
  433. )
  434. flag.CommandLine.Parse(cmdline)
  435. *workdir = makeWorkdir(*workdir)
  436. env := build.Env()
  437. maybeSkipArchive(env)
  438. // Import the signing key.
  439. if key := getenvBase64("PPA_SIGNING_KEY"); len(key) > 0 {
  440. gpg := exec.Command("gpg", "--import")
  441. gpg.Stdin = bytes.NewReader(key)
  442. build.MustRun(gpg)
  443. }
  444. // Download and verify the Go source package.
  445. gobundle := downloadGoSources(*goversion, *cachedir)
  446. // Download all the dependencies needed to build the sources and run the ci script
  447. srcdepfetch := goTool("install", "-n", "./...")
  448. srcdepfetch.Env = append(os.Environ(), "GOPATH="+filepath.Join(*workdir, "modgopath"))
  449. build.MustRun(srcdepfetch)
  450. cidepfetch := goTool("run", "./build/ci.go")
  451. cidepfetch.Env = append(os.Environ(), "GOPATH="+filepath.Join(*workdir, "modgopath"))
  452. cidepfetch.Run() // Command fails, don't care, we only need the deps to start it
  453. // Create Debian packages and upload them.
  454. for _, pkg := range debPackages {
  455. for distro, goboot := range debDistroGoBoots {
  456. // Prepare the debian package with the go-ethereum sources.
  457. meta := newDebMetadata(distro, goboot, *signer, env, now, pkg.Name, pkg.Version, pkg.Executables)
  458. pkgdir := stageDebianSource(*workdir, meta)
  459. // Add Go source code
  460. if err := build.ExtractTarballArchive(gobundle, pkgdir); err != nil {
  461. log.Fatalf("Failed to extract Go sources: %v", err)
  462. }
  463. if err := os.Rename(filepath.Join(pkgdir, "go"), filepath.Join(pkgdir, ".go")); err != nil {
  464. log.Fatalf("Failed to rename Go source folder: %v", err)
  465. }
  466. // Add all dependency modules in compressed form
  467. os.MkdirAll(filepath.Join(pkgdir, ".mod", "cache"), 0755)
  468. if err := cp.CopyAll(filepath.Join(pkgdir, ".mod", "cache", "download"), filepath.Join(*workdir, "modgopath", "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", "-nc")
  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. "PATH=" + GOBIN + string(os.PathListSeparator) + os.Getenv("PATH"),
  799. }
  800. for _, e := range os.Environ() {
  801. if strings.HasPrefix(e, "GOPATH=") || strings.HasPrefix(e, "PATH=") {
  802. continue
  803. }
  804. cmd.Env = append(cmd.Env, e)
  805. }
  806. return cmd
  807. }
  808. type mavenMetadata struct {
  809. Version string
  810. Package string
  811. Develop bool
  812. Contributors []mavenContributor
  813. }
  814. type mavenContributor struct {
  815. Name string
  816. Email string
  817. }
  818. func newMavenMetadata(env build.Environment) mavenMetadata {
  819. // Collect the list of authors from the repo root
  820. contribs := []mavenContributor{}
  821. if authors, err := os.Open("AUTHORS"); err == nil {
  822. defer authors.Close()
  823. scanner := bufio.NewScanner(authors)
  824. for scanner.Scan() {
  825. // Skip any whitespace from the authors list
  826. line := strings.TrimSpace(scanner.Text())
  827. if line == "" || line[0] == '#' {
  828. continue
  829. }
  830. // Split the author and insert as a contributor
  831. re := regexp.MustCompile("([^<]+) <(.+)>")
  832. parts := re.FindStringSubmatch(line)
  833. if len(parts) == 3 {
  834. contribs = append(contribs, mavenContributor{Name: parts[1], Email: parts[2]})
  835. }
  836. }
  837. }
  838. // Render the version and package strings
  839. version := params.Version
  840. if isUnstableBuild(env) {
  841. version += "-SNAPSHOT"
  842. }
  843. return mavenMetadata{
  844. Version: version,
  845. Package: "geth-" + version,
  846. Develop: isUnstableBuild(env),
  847. Contributors: contribs,
  848. }
  849. }
  850. // XCode frameworks
  851. func doXCodeFramework(cmdline []string) {
  852. var (
  853. local = flag.Bool("local", false, `Flag whether we're only doing a local build (skip Maven artifacts)`)
  854. signer = flag.String("signer", "", `Environment variable holding the signing key (e.g. IOS_SIGNING_KEY)`)
  855. deploy = flag.String("deploy", "", `Destination to deploy the archive (usually "trunk")`)
  856. upload = flag.String("upload", "", `Destination to upload the archives (usually "gethstore/builds")`)
  857. )
  858. flag.CommandLine.Parse(cmdline)
  859. env := build.Env()
  860. // Build the iOS XCode framework
  861. build.MustRun(goTool("get", "golang.org/x/mobile/cmd/gomobile", "golang.org/x/mobile/cmd/gobind"))
  862. build.MustRun(gomobileTool("init"))
  863. bind := gomobileTool("bind", "-ldflags", "-s -w", "--target", "ios", "-v", "github.com/ethereum/go-ethereum/mobile")
  864. if *local {
  865. // If we're building locally, use the build folder and stop afterwards
  866. bind.Dir, _ = filepath.Abs(GOBIN)
  867. build.MustRun(bind)
  868. return
  869. }
  870. archive := "geth-" + archiveBasename("ios", params.ArchiveVersion(env.Commit))
  871. if err := os.Mkdir(archive, os.ModePerm); err != nil {
  872. log.Fatal(err)
  873. }
  874. bind.Dir, _ = filepath.Abs(archive)
  875. build.MustRun(bind)
  876. build.MustRunCommand("tar", "-zcvf", archive+".tar.gz", archive)
  877. // Skip CocoaPods deploy and Azure upload for PR builds
  878. maybeSkipArchive(env)
  879. // Sign and upload the framework to Azure
  880. if err := archiveUpload(archive+".tar.gz", *upload, *signer); err != nil {
  881. log.Fatal(err)
  882. }
  883. // Prepare and upload a PodSpec to CocoaPods
  884. if *deploy != "" {
  885. meta := newPodMetadata(env, archive)
  886. build.Render("build/pod.podspec", "Geth.podspec", 0755, meta)
  887. build.MustRunCommand("pod", *deploy, "push", "Geth.podspec", "--allow-warnings", "--verbose")
  888. }
  889. }
  890. type podMetadata struct {
  891. Version string
  892. Commit string
  893. Archive string
  894. Contributors []podContributor
  895. }
  896. type podContributor struct {
  897. Name string
  898. Email string
  899. }
  900. func newPodMetadata(env build.Environment, archive string) podMetadata {
  901. // Collect the list of authors from the repo root
  902. contribs := []podContributor{}
  903. if authors, err := os.Open("AUTHORS"); err == nil {
  904. defer authors.Close()
  905. scanner := bufio.NewScanner(authors)
  906. for scanner.Scan() {
  907. // Skip any whitespace from the authors list
  908. line := strings.TrimSpace(scanner.Text())
  909. if line == "" || line[0] == '#' {
  910. continue
  911. }
  912. // Split the author and insert as a contributor
  913. re := regexp.MustCompile("([^<]+) <(.+)>")
  914. parts := re.FindStringSubmatch(line)
  915. if len(parts) == 3 {
  916. contribs = append(contribs, podContributor{Name: parts[1], Email: parts[2]})
  917. }
  918. }
  919. }
  920. version := params.Version
  921. if isUnstableBuild(env) {
  922. version += "-unstable." + env.Buildnum
  923. }
  924. return podMetadata{
  925. Archive: archive,
  926. Version: version,
  927. Commit: env.Commit,
  928. Contributors: contribs,
  929. }
  930. }
  931. // Cross compilation
  932. func doXgo(cmdline []string) {
  933. var (
  934. alltools = flag.Bool("alltools", false, `Flag whether we're building all known tools, or only on in particular`)
  935. )
  936. flag.CommandLine.Parse(cmdline)
  937. env := build.Env()
  938. // Make sure xgo is available for cross compilation
  939. gogetxgo := goTool("get", "github.com/karalabe/xgo")
  940. build.MustRun(gogetxgo)
  941. // If all tools building is requested, build everything the builder wants
  942. args := append(buildFlags(env), flag.Args()...)
  943. if *alltools {
  944. args = append(args, []string{"--dest", GOBIN}...)
  945. for _, res := range allToolsArchiveFiles {
  946. if strings.HasPrefix(res, GOBIN) {
  947. // Binary tool found, cross build it explicitly
  948. args = append(args, "./"+filepath.Join("cmd", filepath.Base(res)))
  949. xgo := xgoTool(args)
  950. build.MustRun(xgo)
  951. args = args[:len(args)-1]
  952. }
  953. }
  954. return
  955. }
  956. // Otherwise xxecute the explicit cross compilation
  957. path := args[len(args)-1]
  958. args = append(args[:len(args)-1], []string{"--dest", GOBIN, path}...)
  959. xgo := xgoTool(args)
  960. build.MustRun(xgo)
  961. }
  962. func xgoTool(args []string) *exec.Cmd {
  963. cmd := exec.Command(filepath.Join(GOBIN, "xgo"), args...)
  964. cmd.Env = os.Environ()
  965. cmd.Env = append(cmd.Env, []string{
  966. "GOBIN=" + GOBIN,
  967. }...)
  968. return cmd
  969. }
  970. // Binary distribution cleanups
  971. func doPurge(cmdline []string) {
  972. var (
  973. store = flag.String("store", "", `Destination from where to purge archives (usually "gethstore/builds")`)
  974. limit = flag.Int("days", 30, `Age threshold above which to delete unstable archives`)
  975. )
  976. flag.CommandLine.Parse(cmdline)
  977. if env := build.Env(); !env.IsCronJob {
  978. log.Printf("skipping because not a cron job")
  979. os.Exit(0)
  980. }
  981. // Create the azure authentication and list the current archives
  982. auth := build.AzureBlobstoreConfig{
  983. Account: strings.Split(*store, "/")[0],
  984. Token: os.Getenv("AZURE_BLOBSTORE_TOKEN"),
  985. Container: strings.SplitN(*store, "/", 2)[1],
  986. }
  987. blobs, err := build.AzureBlobstoreList(auth)
  988. if err != nil {
  989. log.Fatal(err)
  990. }
  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. // Delete all marked as such and return
  1013. if err := build.AzureBlobstoreDelete(auth, blobs); err != nil {
  1014. log.Fatal(err)
  1015. }
  1016. }