ci.go 37 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135
  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{"./accounts/...", "./common/...", "./consensus/...", "./console/...", "./core/...",
  268. "./crypto/...", "./eth/...", "./ethclient/...", "./ethdb/...", "./event/...", "./graphql/...", "./les/...",
  269. "./light/...", "./log/...", "./metrics/...", "./miner/...", "./mobile/...", "./node/...",
  270. "./p2p/...", "./params/...", "./rlp/...", "./rpc/...", "./tests/...", "./trie/..."}
  271. if len(flag.CommandLine.Args()) > 0 {
  272. packages = flag.CommandLine.Args()
  273. }
  274. gotest.Args = append(gotest.Args, packages...)
  275. build.MustRun(gotest)
  276. }
  277. // doLint runs golangci-lint on requested packages.
  278. func doLint(cmdline []string) {
  279. var (
  280. cachedir = flag.String("cachedir", "./build/cache", "directory for caching golangci-lint binary.")
  281. )
  282. flag.CommandLine.Parse(cmdline)
  283. packages := []string{"./..."}
  284. if len(flag.CommandLine.Args()) > 0 {
  285. packages = flag.CommandLine.Args()
  286. }
  287. linter := downloadLinter(*cachedir)
  288. lflags := []string{"run", "--config", ".golangci.yml"}
  289. build.MustRunCommand(linter, append(lflags, packages...)...)
  290. fmt.Println("You have achieved perfection.")
  291. }
  292. // downloadLinter downloads and unpacks golangci-lint.
  293. func downloadLinter(cachedir string) string {
  294. const version = "1.39.0"
  295. csdb := build.MustLoadChecksums("build/checksums.txt")
  296. base := fmt.Sprintf("golangci-lint-%s-%s-%s", version, runtime.GOOS, runtime.GOARCH)
  297. url := fmt.Sprintf("https://github.com/golangci/golangci-lint/releases/download/v%s/%s.tar.gz", version, base)
  298. archivePath := filepath.Join(cachedir, base+".tar.gz")
  299. if err := csdb.DownloadFile(url, archivePath); err != nil {
  300. log.Fatal(err)
  301. }
  302. if err := build.ExtractArchive(archivePath, cachedir); err != nil {
  303. log.Fatal(err)
  304. }
  305. return filepath.Join(cachedir, base, "golangci-lint")
  306. }
  307. // Release Packaging
  308. func doArchive(cmdline []string) {
  309. var (
  310. arch = flag.String("arch", runtime.GOARCH, "Architecture cross packaging")
  311. atype = flag.String("type", "zip", "Type of archive to write (zip|tar)")
  312. signer = flag.String("signer", "", `Environment variable holding the signing key (e.g. LINUX_SIGNING_KEY)`)
  313. signify = flag.String("signify", "", `Environment variable holding the signify key (e.g. LINUX_SIGNIFY_KEY)`)
  314. upload = flag.String("upload", "", `Destination to upload the archives (usually "gethstore/builds")`)
  315. ext string
  316. )
  317. flag.CommandLine.Parse(cmdline)
  318. switch *atype {
  319. case "zip":
  320. ext = ".zip"
  321. case "tar":
  322. ext = ".tar.gz"
  323. default:
  324. log.Fatal("unknown archive type: ", atype)
  325. }
  326. var (
  327. env = build.Env()
  328. basegeth = archiveBasename(*arch, params.ArchiveVersion(env.Commit))
  329. geth = "geth-" + basegeth + ext
  330. alltools = "geth-alltools-" + basegeth + ext
  331. )
  332. maybeSkipArchive(env)
  333. if err := build.WriteArchive(geth, gethArchiveFiles); err != nil {
  334. log.Fatal(err)
  335. }
  336. if err := build.WriteArchive(alltools, allToolsArchiveFiles); err != nil {
  337. log.Fatal(err)
  338. }
  339. for _, archive := range []string{geth, alltools} {
  340. if err := archiveUpload(archive, *upload, *signer, *signify); err != nil {
  341. log.Fatal(err)
  342. }
  343. }
  344. }
  345. func archiveBasename(arch string, archiveVersion string) string {
  346. platform := runtime.GOOS + "-" + arch
  347. if arch == "arm" {
  348. platform += os.Getenv("GOARM")
  349. }
  350. if arch == "android" {
  351. platform = "android-all"
  352. }
  353. if arch == "ios" {
  354. platform = "ios-all"
  355. }
  356. return platform + "-" + archiveVersion
  357. }
  358. func archiveUpload(archive string, blobstore string, signer string, signifyVar string) error {
  359. // If signing was requested, generate the signature files
  360. if signer != "" {
  361. key := getenvBase64(signer)
  362. if err := build.PGPSignFile(archive, archive+".asc", string(key)); err != nil {
  363. return err
  364. }
  365. }
  366. if signifyVar != "" {
  367. key := os.Getenv(signifyVar)
  368. untrustedComment := "verify with geth-release.pub"
  369. trustedComment := fmt.Sprintf("%s (%s)", archive, time.Now().UTC().Format(time.RFC1123))
  370. if err := signify.SignFile(archive, archive+".sig", key, untrustedComment, trustedComment); err != nil {
  371. return err
  372. }
  373. }
  374. // If uploading to Azure was requested, push the archive possibly with its signature
  375. if blobstore != "" {
  376. auth := build.AzureBlobstoreConfig{
  377. Account: strings.Split(blobstore, "/")[0],
  378. Token: os.Getenv("AZURE_BLOBSTORE_TOKEN"),
  379. Container: strings.SplitN(blobstore, "/", 2)[1],
  380. }
  381. if err := build.AzureBlobstoreUpload(archive, filepath.Base(archive), auth); err != nil {
  382. return err
  383. }
  384. if signer != "" {
  385. if err := build.AzureBlobstoreUpload(archive+".asc", filepath.Base(archive+".asc"), auth); err != nil {
  386. return err
  387. }
  388. }
  389. if signifyVar != "" {
  390. if err := build.AzureBlobstoreUpload(archive+".sig", filepath.Base(archive+".sig"), auth); err != nil {
  391. return err
  392. }
  393. }
  394. }
  395. return nil
  396. }
  397. // skips archiving for some build configurations.
  398. func maybeSkipArchive(env build.Environment) {
  399. if env.IsPullRequest {
  400. log.Printf("skipping archive creation because this is a PR build")
  401. os.Exit(0)
  402. }
  403. if env.IsCronJob {
  404. log.Printf("skipping archive creation because this is a cron job")
  405. os.Exit(0)
  406. }
  407. if env.Branch != "master" && !strings.HasPrefix(env.Tag, "v1.") {
  408. log.Printf("skipping archive creation because branch %q, tag %q is not on the whitelist", env.Branch, env.Tag)
  409. os.Exit(0)
  410. }
  411. }
  412. // Debian Packaging
  413. func doDebianSource(cmdline []string) {
  414. var (
  415. cachedir = flag.String("cachedir", "./build/cache", `Filesystem path to cache the downloaded Go bundles at`)
  416. signer = flag.String("signer", "", `Signing key name, also used as package author`)
  417. upload = flag.String("upload", "", `Where to upload the source package (usually "ethereum/ethereum")`)
  418. sshUser = flag.String("sftp-user", "", `Username for SFTP upload (usually "geth-ci")`)
  419. workdir = flag.String("workdir", "", `Output directory for packages (uses temp dir if unset)`)
  420. now = time.Now()
  421. )
  422. flag.CommandLine.Parse(cmdline)
  423. *workdir = makeWorkdir(*workdir)
  424. env := build.Env()
  425. tc := new(build.GoToolchain)
  426. maybeSkipArchive(env)
  427. // Import the signing key.
  428. if key := getenvBase64("PPA_SIGNING_KEY"); len(key) > 0 {
  429. gpg := exec.Command("gpg", "--import")
  430. gpg.Stdin = bytes.NewReader(key)
  431. build.MustRun(gpg)
  432. }
  433. // Download and verify the Go source package.
  434. gobundle := downloadGoSources(*cachedir)
  435. // Download all the dependencies needed to build the sources and run the ci script
  436. srcdepfetch := tc.Go("mod", "download")
  437. srcdepfetch.Env = append(srcdepfetch.Env, "GOPATH="+filepath.Join(*workdir, "modgopath"))
  438. build.MustRun(srcdepfetch)
  439. cidepfetch := tc.Go("run", "./build/ci.go")
  440. cidepfetch.Env = append(cidepfetch.Env, "GOPATH="+filepath.Join(*workdir, "modgopath"))
  441. cidepfetch.Run() // Command fails, don't care, we only need the deps to start it
  442. // Create Debian packages and upload them.
  443. for _, pkg := range debPackages {
  444. for distro, goboot := range debDistroGoBoots {
  445. // Prepare the debian package with the go-ethereum sources.
  446. meta := newDebMetadata(distro, goboot, *signer, env, now, pkg.Name, pkg.Version, pkg.Executables)
  447. pkgdir := stageDebianSource(*workdir, meta)
  448. // Add Go source code
  449. if err := build.ExtractArchive(gobundle, pkgdir); err != nil {
  450. log.Fatalf("Failed to extract Go sources: %v", err)
  451. }
  452. if err := os.Rename(filepath.Join(pkgdir, "go"), filepath.Join(pkgdir, ".go")); err != nil {
  453. log.Fatalf("Failed to rename Go source folder: %v", err)
  454. }
  455. // Add all dependency modules in compressed form
  456. os.MkdirAll(filepath.Join(pkgdir, ".mod", "cache"), 0755)
  457. if err := cp.CopyAll(filepath.Join(pkgdir, ".mod", "cache", "download"), filepath.Join(*workdir, "modgopath", "pkg", "mod", "cache", "download")); err != nil {
  458. log.Fatalf("Failed to copy Go module dependencies: %v", err)
  459. }
  460. // Run the packaging and upload to the PPA
  461. debuild := exec.Command("debuild", "-S", "-sa", "-us", "-uc", "-d", "-Zxz", "-nc")
  462. debuild.Dir = pkgdir
  463. build.MustRun(debuild)
  464. var (
  465. basename = fmt.Sprintf("%s_%s", meta.Name(), meta.VersionString())
  466. source = filepath.Join(*workdir, basename+".tar.xz")
  467. dsc = filepath.Join(*workdir, basename+".dsc")
  468. changes = filepath.Join(*workdir, basename+"_source.changes")
  469. buildinfo = filepath.Join(*workdir, basename+"_source.buildinfo")
  470. )
  471. if *signer != "" {
  472. build.MustRunCommand("debsign", changes)
  473. }
  474. if *upload != "" {
  475. ppaUpload(*workdir, *upload, *sshUser, []string{source, dsc, changes, buildinfo})
  476. }
  477. }
  478. }
  479. }
  480. // downloadGoSources downloads the Go source tarball.
  481. func downloadGoSources(cachedir string) string {
  482. csdb := build.MustLoadChecksums("build/checksums.txt")
  483. file := fmt.Sprintf("go%s.src.tar.gz", dlgoVersion)
  484. url := "https://dl.google.com/go/" + file
  485. dst := filepath.Join(cachedir, file)
  486. if err := csdb.DownloadFile(url, dst); err != nil {
  487. log.Fatal(err)
  488. }
  489. return dst
  490. }
  491. func ppaUpload(workdir, ppa, sshUser string, files []string) {
  492. p := strings.Split(ppa, "/")
  493. if len(p) != 2 {
  494. log.Fatal("-upload PPA name must contain single /")
  495. }
  496. if sshUser == "" {
  497. sshUser = p[0]
  498. }
  499. incomingDir := fmt.Sprintf("~%s/ubuntu/%s", p[0], p[1])
  500. // Create the SSH identity file if it doesn't exist.
  501. var idfile string
  502. if sshkey := getenvBase64("PPA_SSH_KEY"); len(sshkey) > 0 {
  503. idfile = filepath.Join(workdir, "sshkey")
  504. if _, err := os.Stat(idfile); os.IsNotExist(err) {
  505. ioutil.WriteFile(idfile, sshkey, 0600)
  506. }
  507. }
  508. // Upload
  509. dest := sshUser + "@ppa.launchpad.net"
  510. if err := build.UploadSFTP(idfile, dest, incomingDir, files); err != nil {
  511. log.Fatal(err)
  512. }
  513. }
  514. func getenvBase64(variable string) []byte {
  515. dec, err := base64.StdEncoding.DecodeString(os.Getenv(variable))
  516. if err != nil {
  517. log.Fatal("invalid base64 " + variable)
  518. }
  519. return []byte(dec)
  520. }
  521. func makeWorkdir(wdflag string) string {
  522. var err error
  523. if wdflag != "" {
  524. err = os.MkdirAll(wdflag, 0744)
  525. } else {
  526. wdflag, err = ioutil.TempDir("", "geth-build-")
  527. }
  528. if err != nil {
  529. log.Fatal(err)
  530. }
  531. return wdflag
  532. }
  533. func isUnstableBuild(env build.Environment) bool {
  534. if env.Tag != "" {
  535. return false
  536. }
  537. return true
  538. }
  539. type debPackage struct {
  540. Name string // the name of the Debian package to produce, e.g. "ethereum"
  541. Version string // the clean version of the debPackage, e.g. 1.8.12, without any metadata
  542. Executables []debExecutable // executables to be included in the package
  543. }
  544. type debMetadata struct {
  545. Env build.Environment
  546. GoBootPackage string
  547. GoBootPath string
  548. PackageName string
  549. // go-ethereum version being built. Note that this
  550. // is not the debian package version. The package version
  551. // is constructed by VersionString.
  552. Version string
  553. Author string // "name <email>", also selects signing key
  554. Distro, Time string
  555. Executables []debExecutable
  556. }
  557. type debExecutable struct {
  558. PackageName string
  559. BinaryName string
  560. Description string
  561. }
  562. // Package returns the name of the package if present, or
  563. // fallbacks to BinaryName
  564. func (d debExecutable) Package() string {
  565. if d.PackageName != "" {
  566. return d.PackageName
  567. }
  568. return d.BinaryName
  569. }
  570. func newDebMetadata(distro, goboot, author string, env build.Environment, t time.Time, name string, version string, exes []debExecutable) debMetadata {
  571. if author == "" {
  572. // No signing key, use default author.
  573. author = "Ethereum Builds <fjl@ethereum.org>"
  574. }
  575. return debMetadata{
  576. GoBootPackage: goboot,
  577. GoBootPath: debGoBootPaths[goboot],
  578. PackageName: name,
  579. Env: env,
  580. Author: author,
  581. Distro: distro,
  582. Version: version,
  583. Time: t.Format(time.RFC1123Z),
  584. Executables: exes,
  585. }
  586. }
  587. // Name returns the name of the metapackage that depends
  588. // on all executable packages.
  589. func (meta debMetadata) Name() string {
  590. if isUnstableBuild(meta.Env) {
  591. return meta.PackageName + "-unstable"
  592. }
  593. return meta.PackageName
  594. }
  595. // VersionString returns the debian version of the packages.
  596. func (meta debMetadata) VersionString() string {
  597. vsn := meta.Version
  598. if meta.Env.Buildnum != "" {
  599. vsn += "+build" + meta.Env.Buildnum
  600. }
  601. if meta.Distro != "" {
  602. vsn += "+" + meta.Distro
  603. }
  604. return vsn
  605. }
  606. // ExeList returns the list of all executable packages.
  607. func (meta debMetadata) ExeList() string {
  608. names := make([]string, len(meta.Executables))
  609. for i, e := range meta.Executables {
  610. names[i] = meta.ExeName(e)
  611. }
  612. return strings.Join(names, ", ")
  613. }
  614. // ExeName returns the package name of an executable package.
  615. func (meta debMetadata) ExeName(exe debExecutable) string {
  616. if isUnstableBuild(meta.Env) {
  617. return exe.Package() + "-unstable"
  618. }
  619. return exe.Package()
  620. }
  621. // ExeConflicts returns the content of the Conflicts field
  622. // for executable packages.
  623. func (meta debMetadata) ExeConflicts(exe debExecutable) string {
  624. if isUnstableBuild(meta.Env) {
  625. // Set up the conflicts list so that the *-unstable packages
  626. // cannot be installed alongside the regular version.
  627. //
  628. // https://www.debian.org/doc/debian-policy/ch-relationships.html
  629. // is very explicit about Conflicts: and says that Breaks: should
  630. // be preferred and the conflicting files should be handled via
  631. // alternates. We might do this eventually but using a conflict is
  632. // easier now.
  633. return "ethereum, " + exe.Package()
  634. }
  635. return ""
  636. }
  637. func stageDebianSource(tmpdir string, meta debMetadata) (pkgdir string) {
  638. pkg := meta.Name() + "-" + meta.VersionString()
  639. pkgdir = filepath.Join(tmpdir, pkg)
  640. if err := os.Mkdir(pkgdir, 0755); err != nil {
  641. log.Fatal(err)
  642. }
  643. // Copy the source code.
  644. build.MustRunCommand("git", "checkout-index", "-a", "--prefix", pkgdir+string(filepath.Separator))
  645. // Put the debian build files in place.
  646. debian := filepath.Join(pkgdir, "debian")
  647. build.Render("build/deb/"+meta.PackageName+"/deb.rules", filepath.Join(debian, "rules"), 0755, meta)
  648. build.Render("build/deb/"+meta.PackageName+"/deb.changelog", filepath.Join(debian, "changelog"), 0644, meta)
  649. build.Render("build/deb/"+meta.PackageName+"/deb.control", filepath.Join(debian, "control"), 0644, meta)
  650. build.Render("build/deb/"+meta.PackageName+"/deb.copyright", filepath.Join(debian, "copyright"), 0644, meta)
  651. build.RenderString("8\n", filepath.Join(debian, "compat"), 0644, meta)
  652. build.RenderString("3.0 (native)\n", filepath.Join(debian, "source/format"), 0644, meta)
  653. for _, exe := range meta.Executables {
  654. install := filepath.Join(debian, meta.ExeName(exe)+".install")
  655. docs := filepath.Join(debian, meta.ExeName(exe)+".docs")
  656. build.Render("build/deb/"+meta.PackageName+"/deb.install", install, 0644, exe)
  657. build.Render("build/deb/"+meta.PackageName+"/deb.docs", docs, 0644, exe)
  658. }
  659. return pkgdir
  660. }
  661. // Windows installer
  662. func doWindowsInstaller(cmdline []string) {
  663. // Parse the flags and make skip installer generation on PRs
  664. var (
  665. arch = flag.String("arch", runtime.GOARCH, "Architecture for cross build packaging")
  666. signer = flag.String("signer", "", `Environment variable holding the signing key (e.g. WINDOWS_SIGNING_KEY)`)
  667. signify = flag.String("signify key", "", `Environment variable holding the signify signing key (e.g. WINDOWS_SIGNIFY_KEY)`)
  668. upload = flag.String("upload", "", `Destination to upload the archives (usually "gethstore/builds")`)
  669. workdir = flag.String("workdir", "", `Output directory for packages (uses temp dir if unset)`)
  670. )
  671. flag.CommandLine.Parse(cmdline)
  672. *workdir = makeWorkdir(*workdir)
  673. env := build.Env()
  674. maybeSkipArchive(env)
  675. // Aggregate binaries that are included in the installer
  676. var (
  677. devTools []string
  678. allTools []string
  679. gethTool string
  680. )
  681. for _, file := range allToolsArchiveFiles {
  682. if file == "COPYING" { // license, copied later
  683. continue
  684. }
  685. allTools = append(allTools, filepath.Base(file))
  686. if filepath.Base(file) == "geth.exe" {
  687. gethTool = file
  688. } else {
  689. devTools = append(devTools, file)
  690. }
  691. }
  692. // Render NSIS scripts: Installer NSIS contains two installer sections,
  693. // first section contains the geth binary, second section holds the dev tools.
  694. templateData := map[string]interface{}{
  695. "License": "COPYING",
  696. "Geth": gethTool,
  697. "DevTools": devTools,
  698. }
  699. build.Render("build/nsis.geth.nsi", filepath.Join(*workdir, "geth.nsi"), 0644, nil)
  700. build.Render("build/nsis.install.nsh", filepath.Join(*workdir, "install.nsh"), 0644, templateData)
  701. build.Render("build/nsis.uninstall.nsh", filepath.Join(*workdir, "uninstall.nsh"), 0644, allTools)
  702. build.Render("build/nsis.pathupdate.nsh", filepath.Join(*workdir, "PathUpdate.nsh"), 0644, nil)
  703. build.Render("build/nsis.envvarupdate.nsh", filepath.Join(*workdir, "EnvVarUpdate.nsh"), 0644, nil)
  704. if err := cp.CopyFile(filepath.Join(*workdir, "SimpleFC.dll"), "build/nsis.simplefc.dll"); err != nil {
  705. log.Fatal("Failed to copy SimpleFC.dll: %v", err)
  706. }
  707. if err := cp.CopyFile(filepath.Join(*workdir, "COPYING"), "COPYING"); err != nil {
  708. log.Fatal("Failed to copy copyright note: %v", err)
  709. }
  710. // Build the installer. This assumes that all the needed files have been previously
  711. // built (don't mix building and packaging to keep cross compilation complexity to a
  712. // minimum).
  713. version := strings.Split(params.Version, ".")
  714. if env.Commit != "" {
  715. version[2] += "-" + env.Commit[:8]
  716. }
  717. installer, _ := filepath.Abs("geth-" + archiveBasename(*arch, params.ArchiveVersion(env.Commit)) + ".exe")
  718. build.MustRunCommand("makensis.exe",
  719. "/DOUTPUTFILE="+installer,
  720. "/DMAJORVERSION="+version[0],
  721. "/DMINORVERSION="+version[1],
  722. "/DBUILDVERSION="+version[2],
  723. "/DARCH="+*arch,
  724. filepath.Join(*workdir, "geth.nsi"),
  725. )
  726. // Sign and publish installer.
  727. if err := archiveUpload(installer, *upload, *signer, *signify); err != nil {
  728. log.Fatal(err)
  729. }
  730. }
  731. // Android archives
  732. func doAndroidArchive(cmdline []string) {
  733. var (
  734. local = flag.Bool("local", false, `Flag whether we're only doing a local build (skip Maven artifacts)`)
  735. signer = flag.String("signer", "", `Environment variable holding the signing key (e.g. ANDROID_SIGNING_KEY)`)
  736. signify = flag.String("signify", "", `Environment variable holding the signify signing key (e.g. ANDROID_SIGNIFY_KEY)`)
  737. deploy = flag.String("deploy", "", `Destination to deploy the archive (usually "https://oss.sonatype.org")`)
  738. upload = flag.String("upload", "", `Destination to upload the archive (usually "gethstore/builds")`)
  739. )
  740. flag.CommandLine.Parse(cmdline)
  741. env := build.Env()
  742. tc := new(build.GoToolchain)
  743. // Sanity check that the SDK and NDK are installed and set
  744. if os.Getenv("ANDROID_HOME") == "" {
  745. log.Fatal("Please ensure ANDROID_HOME points to your Android SDK")
  746. }
  747. // Build gomobile.
  748. install := tc.Install(GOBIN, "golang.org/x/mobile/cmd/gomobile@latest", "golang.org/x/mobile/cmd/gobind@latest")
  749. install.Env = append(install.Env)
  750. build.MustRun(install)
  751. // Ensure all dependencies are available. This is required to make
  752. // gomobile bind work because it expects go.sum to contain all checksums.
  753. build.MustRun(tc.Go("mod", "download"))
  754. // Build the Android archive and Maven resources
  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. os.Rename("geth-sources.jar", filepath.Join(GOBIN, "geth-sources.jar"))
  760. return
  761. }
  762. meta := newMavenMetadata(env)
  763. build.Render("build/mvn.pom", meta.Package+".pom", 0755, meta)
  764. // Skip Maven deploy and Azure upload for PR builds
  765. maybeSkipArchive(env)
  766. // Sign and upload the archive to Azure
  767. archive := "geth-" + archiveBasename("android", params.ArchiveVersion(env.Commit)) + ".aar"
  768. os.Rename("geth.aar", archive)
  769. if err := archiveUpload(archive, *upload, *signer, *signify); err != nil {
  770. log.Fatal(err)
  771. }
  772. // Sign and upload all the artifacts to Maven Central
  773. os.Rename(archive, meta.Package+".aar")
  774. if *signer != "" && *deploy != "" {
  775. // Import the signing key into the local GPG instance
  776. key := getenvBase64(*signer)
  777. gpg := exec.Command("gpg", "--import")
  778. gpg.Stdin = bytes.NewReader(key)
  779. build.MustRun(gpg)
  780. keyID, err := build.PGPKeyID(string(key))
  781. if err != nil {
  782. log.Fatal(err)
  783. }
  784. // Upload the artifacts to Sonatype and/or Maven Central
  785. repo := *deploy + "/service/local/staging/deploy/maven2"
  786. if meta.Develop {
  787. repo = *deploy + "/content/repositories/snapshots"
  788. }
  789. build.MustRunCommand("mvn", "gpg:sign-and-deploy-file", "-e", "-X",
  790. "-settings=build/mvn.settings", "-Durl="+repo, "-DrepositoryId=ossrh",
  791. "-Dgpg.keyname="+keyID,
  792. "-DpomFile="+meta.Package+".pom", "-Dfile="+meta.Package+".aar")
  793. }
  794. }
  795. func gomobileTool(subcmd string, args ...string) *exec.Cmd {
  796. cmd := exec.Command(filepath.Join(GOBIN, "gomobile"), subcmd)
  797. cmd.Args = append(cmd.Args, args...)
  798. cmd.Env = []string{
  799. "PATH=" + GOBIN + string(os.PathListSeparator) + os.Getenv("PATH"),
  800. }
  801. for _, e := range os.Environ() {
  802. if strings.HasPrefix(e, "GOPATH=") || strings.HasPrefix(e, "PATH=") || strings.HasPrefix(e, "GOBIN=") {
  803. continue
  804. }
  805. cmd.Env = append(cmd.Env, e)
  806. }
  807. cmd.Env = append(cmd.Env, "GOBIN="+GOBIN)
  808. return cmd
  809. }
  810. type mavenMetadata struct {
  811. Version string
  812. Package string
  813. Develop bool
  814. Contributors []mavenContributor
  815. }
  816. type mavenContributor struct {
  817. Name string
  818. Email string
  819. }
  820. func newMavenMetadata(env build.Environment) mavenMetadata {
  821. // Collect the list of authors from the repo root
  822. contribs := []mavenContributor{}
  823. if authors, err := os.Open("AUTHORS"); err == nil {
  824. defer authors.Close()
  825. scanner := bufio.NewScanner(authors)
  826. for scanner.Scan() {
  827. // Skip any whitespace from the authors list
  828. line := strings.TrimSpace(scanner.Text())
  829. if line == "" || line[0] == '#' {
  830. continue
  831. }
  832. // Split the author and insert as a contributor
  833. re := regexp.MustCompile("([^<]+) <(.+)>")
  834. parts := re.FindStringSubmatch(line)
  835. if len(parts) == 3 {
  836. contribs = append(contribs, mavenContributor{Name: parts[1], Email: parts[2]})
  837. }
  838. }
  839. }
  840. // Render the version and package strings
  841. version := params.Version
  842. if isUnstableBuild(env) {
  843. version += "-SNAPSHOT"
  844. }
  845. return mavenMetadata{
  846. Version: version,
  847. Package: "geth-" + version,
  848. Develop: isUnstableBuild(env),
  849. Contributors: contribs,
  850. }
  851. }
  852. // XCode frameworks
  853. func doXCodeFramework(cmdline []string) {
  854. var (
  855. local = flag.Bool("local", false, `Flag whether we're only doing a local build (skip Maven artifacts)`)
  856. signer = flag.String("signer", "", `Environment variable holding the signing key (e.g. IOS_SIGNING_KEY)`)
  857. signify = flag.String("signify", "", `Environment variable holding the signify signing key (e.g. IOS_SIGNIFY_KEY)`)
  858. deploy = flag.String("deploy", "", `Destination to deploy the archive (usually "trunk")`)
  859. upload = flag.String("upload", "", `Destination to upload the archives (usually "gethstore/builds")`)
  860. )
  861. flag.CommandLine.Parse(cmdline)
  862. env := build.Env()
  863. tc := new(build.GoToolchain)
  864. // Build gomobile.
  865. build.MustRun(tc.Install(GOBIN, "golang.org/x/mobile/cmd/gomobile@latest", "golang.org/x/mobile/cmd/gobind@latest"))
  866. // Ensure all dependencies are available. This is required to make
  867. // gomobile bind work because it expects go.sum to contain all checksums.
  868. build.MustRun(tc.Go("mod", "download"))
  869. // Build the iOS XCode framework
  870. bind := gomobileTool("bind", "-ldflags", "-s -w", "--target", "ios", "-v", "github.com/ethereum/go-ethereum/mobile")
  871. if *local {
  872. // If we're building locally, use the build folder and stop afterwards
  873. bind.Dir = GOBIN
  874. build.MustRun(bind)
  875. return
  876. }
  877. // Create the archive.
  878. maybeSkipArchive(env)
  879. archive := "geth-" + archiveBasename("ios", params.ArchiveVersion(env.Commit))
  880. if err := os.MkdirAll(archive, 0755); err != nil {
  881. log.Fatal(err)
  882. }
  883. bind.Dir, _ = filepath.Abs(archive)
  884. build.MustRun(bind)
  885. build.MustRunCommand("tar", "-zcvf", archive+".tar.gz", archive)
  886. // Sign and upload the framework to Azure
  887. if err := archiveUpload(archive+".tar.gz", *upload, *signer, *signify); err != nil {
  888. log.Fatal(err)
  889. }
  890. // Prepare and upload a PodSpec to CocoaPods
  891. if *deploy != "" {
  892. meta := newPodMetadata(env, archive)
  893. build.Render("build/pod.podspec", "Geth.podspec", 0755, meta)
  894. build.MustRunCommand("pod", *deploy, "push", "Geth.podspec", "--allow-warnings")
  895. }
  896. }
  897. type podMetadata struct {
  898. Version string
  899. Commit string
  900. Archive string
  901. Contributors []podContributor
  902. }
  903. type podContributor struct {
  904. Name string
  905. Email string
  906. }
  907. func newPodMetadata(env build.Environment, archive string) podMetadata {
  908. // Collect the list of authors from the repo root
  909. contribs := []podContributor{}
  910. if authors, err := os.Open("AUTHORS"); err == nil {
  911. defer authors.Close()
  912. scanner := bufio.NewScanner(authors)
  913. for scanner.Scan() {
  914. // Skip any whitespace from the authors list
  915. line := strings.TrimSpace(scanner.Text())
  916. if line == "" || line[0] == '#' {
  917. continue
  918. }
  919. // Split the author and insert as a contributor
  920. re := regexp.MustCompile("([^<]+) <(.+)>")
  921. parts := re.FindStringSubmatch(line)
  922. if len(parts) == 3 {
  923. contribs = append(contribs, podContributor{Name: parts[1], Email: parts[2]})
  924. }
  925. }
  926. }
  927. version := params.Version
  928. if isUnstableBuild(env) {
  929. version += "-unstable." + env.Buildnum
  930. }
  931. return podMetadata{
  932. Archive: archive,
  933. Version: version,
  934. Commit: env.Commit,
  935. Contributors: contribs,
  936. }
  937. }
  938. // Cross compilation
  939. func doXgo(cmdline []string) {
  940. var (
  941. alltools = flag.Bool("alltools", false, `Flag whether we're building all known tools, or only on in particular`)
  942. )
  943. flag.CommandLine.Parse(cmdline)
  944. env := build.Env()
  945. var tc build.GoToolchain
  946. // Make sure xgo is available for cross compilation
  947. build.MustRun(tc.Install(GOBIN, "github.com/karalabe/xgo@latest"))
  948. // If all tools building is requested, build everything the builder wants
  949. args := append(buildFlags(env), flag.Args()...)
  950. if *alltools {
  951. args = append(args, []string{"--dest", GOBIN}...)
  952. for _, res := range allToolsArchiveFiles {
  953. if strings.HasPrefix(res, GOBIN) {
  954. // Binary tool found, cross build it explicitly
  955. args = append(args, "./"+filepath.Join("cmd", filepath.Base(res)))
  956. build.MustRun(xgoTool(args))
  957. args = args[:len(args)-1]
  958. }
  959. }
  960. return
  961. }
  962. // Otherwise execute the explicit cross compilation
  963. path := args[len(args)-1]
  964. args = append(args[:len(args)-1], []string{"--dest", GOBIN, path}...)
  965. build.MustRun(xgoTool(args))
  966. }
  967. func xgoTool(args []string) *exec.Cmd {
  968. cmd := exec.Command(filepath.Join(GOBIN, "xgo"), args...)
  969. cmd.Env = os.Environ()
  970. cmd.Env = append(cmd.Env, []string{"GOBIN=" + GOBIN}...)
  971. return cmd
  972. }
  973. // Binary distribution cleanups
  974. func doPurge(cmdline []string) {
  975. var (
  976. store = flag.String("store", "", `Destination from where to purge archives (usually "gethstore/builds")`)
  977. limit = flag.Int("days", 30, `Age threshold above which to delete unstable archives`)
  978. )
  979. flag.CommandLine.Parse(cmdline)
  980. if env := build.Env(); !env.IsCronJob {
  981. log.Printf("skipping because not a cron job")
  982. os.Exit(0)
  983. }
  984. // Create the azure authentication and list the current archives
  985. auth := build.AzureBlobstoreConfig{
  986. Account: strings.Split(*store, "/")[0],
  987. Token: os.Getenv("AZURE_BLOBSTORE_TOKEN"),
  988. Container: strings.SplitN(*store, "/", 2)[1],
  989. }
  990. blobs, err := build.AzureBlobstoreList(auth)
  991. if err != nil {
  992. log.Fatal(err)
  993. }
  994. fmt.Printf("Found %d blobs\n", len(blobs))
  995. // Iterate over the blobs, collect and sort all unstable builds
  996. for i := 0; i < len(blobs); i++ {
  997. if !strings.Contains(blobs[i].Name, "unstable") {
  998. blobs = append(blobs[:i], blobs[i+1:]...)
  999. i--
  1000. }
  1001. }
  1002. for i := 0; i < len(blobs); i++ {
  1003. for j := i + 1; j < len(blobs); j++ {
  1004. if blobs[i].Properties.LastModified.After(blobs[j].Properties.LastModified) {
  1005. blobs[i], blobs[j] = blobs[j], blobs[i]
  1006. }
  1007. }
  1008. }
  1009. // Filter out all archives more recent that the given threshold
  1010. for i, blob := range blobs {
  1011. if time.Since(blob.Properties.LastModified) < time.Duration(*limit)*24*time.Hour {
  1012. blobs = blobs[:i]
  1013. break
  1014. }
  1015. }
  1016. fmt.Printf("Deleting %d blobs\n", len(blobs))
  1017. // Delete all marked as such and return
  1018. if err := build.AzureBlobstoreDelete(auth, blobs); err != nil {
  1019. log.Fatal(err)
  1020. }
  1021. }