ci.go 37 KB

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