ci.go 37 KB

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