ci.go 36 KB

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