ci.go 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281
  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. //go:build none
  17. // +build none
  18. /*
  19. The ci command is called from Continuous Integration scripts.
  20. Usage: go run build/ci.go <command> <command flags/arguments>
  21. Available commands are:
  22. install [ -arch architecture ] [ -cc compiler ] [ packages... ] -- builds packages and executables
  23. test [ -coverage ] [ packages... ] -- runs the tests
  24. lint -- runs certain pre-selected linters
  25. archive [ -arch architecture ] [ -type zip|tar ] [ -signer key-envvar ] [ -signify key-envvar ] [ -upload dest ] -- archives build artifacts
  26. importkeys -- imports signing keys from env
  27. debsrc [ -signer key-id ] [ -upload dest ] -- creates a debian source package
  28. nsis -- creates a Windows NSIS installer
  29. aar [ -local ] [ -sign key-id ] [-deploy repo] [ -upload dest ] -- creates an Android archive
  30. xcode [ -local ] [ -sign key-id ] [-deploy repo] [ -upload dest ] -- creates an iOS XCode framework
  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. "log"
  42. "os"
  43. "os/exec"
  44. "path"
  45. "path/filepath"
  46. "regexp"
  47. "runtime"
  48. "strconv"
  49. "strings"
  50. "time"
  51. "github.com/cespare/cp"
  52. "github.com/ethereum/go-ethereum/common"
  53. "github.com/ethereum/go-ethereum/crypto/signify"
  54. "github.com/ethereum/go-ethereum/internal/build"
  55. "github.com/ethereum/go-ethereum/params"
  56. )
  57. var (
  58. // Files that end up in the geth*.zip archive.
  59. gethArchiveFiles = []string{
  60. "COPYING",
  61. executablePath("geth"),
  62. }
  63. // Files that end up in the geth-alltools*.zip archive.
  64. allToolsArchiveFiles = []string{
  65. "COPYING",
  66. executablePath("abigen"),
  67. executablePath("bootnode"),
  68. executablePath("evm"),
  69. executablePath("geth"),
  70. executablePath("puppeth"),
  71. executablePath("rlpdump"),
  72. executablePath("clef"),
  73. }
  74. // A debian package is created for all executables listed here.
  75. debExecutables = []debExecutable{
  76. {
  77. BinaryName: "abigen",
  78. Description: "Source code generator to convert Ethereum contract definitions into easy to use, compile-time type-safe Go packages.",
  79. },
  80. {
  81. BinaryName: "bootnode",
  82. Description: "Ethereum bootnode.",
  83. },
  84. {
  85. BinaryName: "evm",
  86. Description: "Developer utility version of the EVM (Ethereum Virtual Machine) that is capable of running bytecode snippets within a configurable environment and execution mode.",
  87. },
  88. {
  89. BinaryName: "geth",
  90. Description: "Ethereum CLI client.",
  91. },
  92. {
  93. BinaryName: "puppeth",
  94. Description: "Ethereum private network manager.",
  95. },
  96. {
  97. BinaryName: "rlpdump",
  98. Description: "Developer utility tool that prints RLP structures.",
  99. },
  100. {
  101. BinaryName: "clef",
  102. Description: "Ethereum account management tool.",
  103. },
  104. }
  105. // A debian package is created for all executables listed here.
  106. debEthereum = debPackage{
  107. Name: "ethereum",
  108. Version: params.Version,
  109. Executables: debExecutables,
  110. }
  111. // Debian meta packages to build and push to Ubuntu PPA
  112. debPackages = []debPackage{
  113. debEthereum,
  114. }
  115. // Distros for which packages are created.
  116. // Note: vivid is unsupported because there is no golang-1.6 package for it.
  117. // Note: the following Ubuntu releases have been officially deprecated on Launchpad:
  118. // wily, yakkety, zesty, artful, cosmic, disco, eoan, groovy, hirsuite
  119. debDistroGoBoots = map[string]string{
  120. "trusty": "golang-1.11", // EOL: 04/2024
  121. "xenial": "golang-go", // EOL: 04/2026
  122. "bionic": "golang-go", // EOL: 04/2028
  123. "focal": "golang-go", // EOL: 04/2030
  124. "impish": "golang-go", // EOL: 07/2022
  125. "jammy": "golang-go", // EOL: 04/2032
  126. //"kinetic": "golang-go", // EOL: 07/2023
  127. }
  128. debGoBootPaths = map[string]string{
  129. "golang-1.11": "/usr/lib/go-1.11",
  130. "golang-go": "/usr/lib/go",
  131. }
  132. // This is the version of go that will be downloaded by
  133. //
  134. // go run ci.go install -dlgo
  135. dlgoVersion = "1.18.5"
  136. )
  137. var GOBIN, _ = filepath.Abs(filepath.Join("build", "bin"))
  138. func executablePath(name string) string {
  139. if runtime.GOOS == "windows" {
  140. name += ".exe"
  141. }
  142. return filepath.Join(GOBIN, name)
  143. }
  144. func main() {
  145. log.SetFlags(log.Lshortfile)
  146. if !common.FileExist(filepath.Join("build", "ci.go")) {
  147. log.Fatal("this script must be run from the root of the repository")
  148. }
  149. if len(os.Args) < 2 {
  150. log.Fatal("need subcommand as first argument")
  151. }
  152. switch os.Args[1] {
  153. case "install":
  154. doInstall(os.Args[2:])
  155. case "test":
  156. doTest(os.Args[2:])
  157. case "lint":
  158. doLint(os.Args[2:])
  159. case "archive":
  160. doArchive(os.Args[2:])
  161. case "docker":
  162. doDocker(os.Args[2:])
  163. case "debsrc":
  164. doDebianSource(os.Args[2:])
  165. case "nsis":
  166. doWindowsInstaller(os.Args[2:])
  167. case "aar":
  168. doAndroidArchive(os.Args[2:])
  169. case "xcode":
  170. doXCodeFramework(os.Args[2:])
  171. case "purge":
  172. doPurge(os.Args[2:])
  173. default:
  174. log.Fatal("unknown command ", os.Args[1])
  175. }
  176. }
  177. // Compiling
  178. func doInstall(cmdline []string) {
  179. var (
  180. dlgo = flag.Bool("dlgo", false, "Download Go and build with it")
  181. arch = flag.String("arch", "", "Architecture to cross build for")
  182. cc = flag.String("cc", "", "C compiler to cross build with")
  183. staticlink = flag.Bool("static", false, "Create statically-linked executable")
  184. )
  185. flag.CommandLine.Parse(cmdline)
  186. // Configure the toolchain.
  187. tc := build.GoToolchain{GOARCH: *arch, CC: *cc}
  188. if *dlgo {
  189. csdb := build.MustLoadChecksums("build/checksums.txt")
  190. tc.Root = build.DownloadGo(csdb, dlgoVersion)
  191. }
  192. // Disable CLI markdown doc generation in release builds.
  193. buildTags := []string{"urfave_cli_no_docs"}
  194. // Configure the build.
  195. env := build.Env()
  196. gobuild := tc.Go("build", buildFlags(env, *staticlink, buildTags)...)
  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, staticLinking bool, buildTags []string) (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 runtime.GOOS == "linux" {
  235. // Enforce the stacksize to 8M, which is the case on most platforms apart from
  236. // alpine Linux.
  237. extld := []string{"-Wl,-z,stack-size=0x800000"}
  238. if staticLinking {
  239. extld = append(extld, "-static")
  240. // Under static linking, use of certain glibc features must be
  241. // disabled to avoid shared library dependencies.
  242. buildTags = append(buildTags, "osusergo", "netgo")
  243. }
  244. ld = append(ld, "-extldflags", "'"+strings.Join(extld, " ")+"'")
  245. }
  246. if len(ld) > 0 {
  247. flags = append(flags, "-ldflags", strings.Join(ld, " "))
  248. }
  249. if len(buildTags) > 0 {
  250. flags = append(flags, "-tags", strings.Join(buildTags, ","))
  251. }
  252. return flags
  253. }
  254. // Running The Tests
  255. //
  256. // "tests" also includes static analysis tools such as vet.
  257. func doTest(cmdline []string) {
  258. var (
  259. dlgo = flag.Bool("dlgo", false, "Download Go and build with it")
  260. arch = flag.String("arch", "", "Run tests for given architecture")
  261. cc = flag.String("cc", "", "Sets C compiler binary")
  262. coverage = flag.Bool("coverage", false, "Whether to record code coverage")
  263. verbose = flag.Bool("v", false, "Whether to log verbosely")
  264. race = flag.Bool("race", false, "Execute the race detector")
  265. )
  266. flag.CommandLine.Parse(cmdline)
  267. // Configure the toolchain.
  268. tc := build.GoToolchain{GOARCH: *arch, CC: *cc}
  269. if *dlgo {
  270. csdb := build.MustLoadChecksums("build/checksums.txt")
  271. tc.Root = build.DownloadGo(csdb, dlgoVersion)
  272. }
  273. gotest := tc.Go("test")
  274. // Test a single package at a time. CI builders are slow
  275. // and some tests run into timeouts under load.
  276. gotest.Args = append(gotest.Args, "-p", "1")
  277. if *coverage {
  278. gotest.Args = append(gotest.Args, "-covermode=atomic", "-cover")
  279. }
  280. if *verbose {
  281. gotest.Args = append(gotest.Args, "-v")
  282. }
  283. if *race {
  284. gotest.Args = append(gotest.Args, "-race")
  285. }
  286. packages := []string{"./..."}
  287. if len(flag.CommandLine.Args()) > 0 {
  288. packages = flag.CommandLine.Args()
  289. }
  290. gotest.Args = append(gotest.Args, packages...)
  291. build.MustRun(gotest)
  292. }
  293. // doLint runs golangci-lint on requested packages.
  294. func doLint(cmdline []string) {
  295. var (
  296. cachedir = flag.String("cachedir", "./build/cache", "directory for caching golangci-lint binary.")
  297. )
  298. flag.CommandLine.Parse(cmdline)
  299. packages := []string{"./..."}
  300. if len(flag.CommandLine.Args()) > 0 {
  301. packages = flag.CommandLine.Args()
  302. }
  303. linter := downloadLinter(*cachedir)
  304. lflags := []string{"run", "--config", ".golangci.yml"}
  305. build.MustRunCommand(linter, append(lflags, packages...)...)
  306. fmt.Println("You have achieved perfection.")
  307. }
  308. // downloadLinter downloads and unpacks golangci-lint.
  309. func downloadLinter(cachedir string) string {
  310. const version = "1.46.2"
  311. csdb := build.MustLoadChecksums("build/checksums.txt")
  312. arch := runtime.GOARCH
  313. ext := ".tar.gz"
  314. if runtime.GOOS == "windows" {
  315. ext = ".zip"
  316. }
  317. if arch == "arm" {
  318. arch += "v" + os.Getenv("GOARM")
  319. }
  320. base := fmt.Sprintf("golangci-lint-%s-%s-%s", version, runtime.GOOS, arch)
  321. url := fmt.Sprintf("https://github.com/golangci/golangci-lint/releases/download/v%s/%s%s", version, base, ext)
  322. archivePath := filepath.Join(cachedir, base+ext)
  323. if err := csdb.DownloadFile(url, archivePath); err != nil {
  324. log.Fatal(err)
  325. }
  326. if err := build.ExtractArchive(archivePath, cachedir); err != nil {
  327. log.Fatal(err)
  328. }
  329. return filepath.Join(cachedir, base, "golangci-lint")
  330. }
  331. // Release Packaging
  332. func doArchive(cmdline []string) {
  333. var (
  334. arch = flag.String("arch", runtime.GOARCH, "Architecture cross packaging")
  335. atype = flag.String("type", "zip", "Type of archive to write (zip|tar)")
  336. signer = flag.String("signer", "", `Environment variable holding the signing key (e.g. LINUX_SIGNING_KEY)`)
  337. signify = flag.String("signify", "", `Environment variable holding the signify key (e.g. LINUX_SIGNIFY_KEY)`)
  338. upload = flag.String("upload", "", `Destination to upload the archives (usually "gethstore/builds")`)
  339. ext string
  340. )
  341. flag.CommandLine.Parse(cmdline)
  342. switch *atype {
  343. case "zip":
  344. ext = ".zip"
  345. case "tar":
  346. ext = ".tar.gz"
  347. default:
  348. log.Fatal("unknown archive type: ", atype)
  349. }
  350. var (
  351. env = build.Env()
  352. basegeth = archiveBasename(*arch, params.ArchiveVersion(env.Commit))
  353. geth = "geth-" + basegeth + ext
  354. alltools = "geth-alltools-" + basegeth + ext
  355. )
  356. maybeSkipArchive(env)
  357. if err := build.WriteArchive(geth, gethArchiveFiles); err != nil {
  358. log.Fatal(err)
  359. }
  360. if err := build.WriteArchive(alltools, allToolsArchiveFiles); err != nil {
  361. log.Fatal(err)
  362. }
  363. for _, archive := range []string{geth, alltools} {
  364. if err := archiveUpload(archive, *upload, *signer, *signify); err != nil {
  365. log.Fatal(err)
  366. }
  367. }
  368. }
  369. func archiveBasename(arch string, archiveVersion string) string {
  370. platform := runtime.GOOS + "-" + arch
  371. if arch == "arm" {
  372. platform += os.Getenv("GOARM")
  373. }
  374. if arch == "android" {
  375. platform = "android-all"
  376. }
  377. if arch == "ios" {
  378. platform = "ios-all"
  379. }
  380. return platform + "-" + archiveVersion
  381. }
  382. func archiveUpload(archive string, blobstore string, signer string, signifyVar string) error {
  383. // If signing was requested, generate the signature files
  384. if signer != "" {
  385. key := getenvBase64(signer)
  386. if err := build.PGPSignFile(archive, archive+".asc", string(key)); err != nil {
  387. return err
  388. }
  389. }
  390. if signifyVar != "" {
  391. key := os.Getenv(signifyVar)
  392. untrustedComment := "verify with geth-release.pub"
  393. trustedComment := fmt.Sprintf("%s (%s)", archive, time.Now().UTC().Format(time.RFC1123))
  394. if err := signify.SignFile(archive, archive+".sig", key, untrustedComment, trustedComment); err != nil {
  395. return err
  396. }
  397. }
  398. // If uploading to Azure was requested, push the archive possibly with its signature
  399. if blobstore != "" {
  400. auth := build.AzureBlobstoreConfig{
  401. Account: strings.Split(blobstore, "/")[0],
  402. Token: os.Getenv("AZURE_BLOBSTORE_TOKEN"),
  403. Container: strings.SplitN(blobstore, "/", 2)[1],
  404. }
  405. if err := build.AzureBlobstoreUpload(archive, filepath.Base(archive), auth); err != nil {
  406. return err
  407. }
  408. if signer != "" {
  409. if err := build.AzureBlobstoreUpload(archive+".asc", filepath.Base(archive+".asc"), auth); err != nil {
  410. return err
  411. }
  412. }
  413. if signifyVar != "" {
  414. if err := build.AzureBlobstoreUpload(archive+".sig", filepath.Base(archive+".sig"), auth); err != nil {
  415. return err
  416. }
  417. }
  418. }
  419. return nil
  420. }
  421. // skips archiving for some build configurations.
  422. func maybeSkipArchive(env build.Environment) {
  423. if env.IsPullRequest {
  424. log.Printf("skipping archive creation because this is a PR build")
  425. os.Exit(0)
  426. }
  427. if env.IsCronJob {
  428. log.Printf("skipping archive creation because this is a cron job")
  429. os.Exit(0)
  430. }
  431. if env.Branch != "master" && !strings.HasPrefix(env.Tag, "v1.") {
  432. log.Printf("skipping archive creation because branch %q, tag %q is not on the inclusion list", env.Branch, env.Tag)
  433. os.Exit(0)
  434. }
  435. }
  436. // Builds the docker images and optionally uploads them to Docker Hub.
  437. func doDocker(cmdline []string) {
  438. var (
  439. image = flag.Bool("image", false, `Whether to build and push an arch specific docker image`)
  440. manifest = flag.String("manifest", "", `Push a multi-arch docker image for the specified architectures (usually "amd64,arm64")`)
  441. upload = flag.String("upload", "", `Where to upload the docker image (usually "ethereum/client-go")`)
  442. )
  443. flag.CommandLine.Parse(cmdline)
  444. // Skip building and pushing docker images for PR builds
  445. env := build.Env()
  446. maybeSkipArchive(env)
  447. // Retrieve the upload credentials and authenticate
  448. user := getenvBase64("DOCKER_HUB_USERNAME")
  449. pass := getenvBase64("DOCKER_HUB_PASSWORD")
  450. if len(user) > 0 && len(pass) > 0 {
  451. auther := exec.Command("docker", "login", "-u", string(user), "--password-stdin")
  452. auther.Stdin = bytes.NewReader(pass)
  453. build.MustRun(auther)
  454. }
  455. // Retrieve the version infos to build and push to the following paths:
  456. // - ethereum/client-go:latest - Pushes to the master branch, Geth only
  457. // - ethereum/client-go:stable - Version tag publish on GitHub, Geth only
  458. // - ethereum/client-go:alltools-latest - Pushes to the master branch, Geth & tools
  459. // - ethereum/client-go:alltools-stable - Version tag publish on GitHub, Geth & tools
  460. // - ethereum/client-go:release-<major>.<minor> - Version tag publish on GitHub, Geth only
  461. // - ethereum/client-go:alltools-release-<major>.<minor> - Version tag publish on GitHub, Geth & tools
  462. // - ethereum/client-go:v<major>.<minor>.<patch> - Version tag publish on GitHub, Geth only
  463. // - ethereum/client-go:alltools-v<major>.<minor>.<patch> - Version tag publish on GitHub, Geth & tools
  464. var tags []string
  465. switch {
  466. case env.Branch == "master":
  467. tags = []string{"latest"}
  468. case strings.HasPrefix(env.Tag, "v1."):
  469. tags = []string{"stable", fmt.Sprintf("release-1.%d", params.VersionMinor), "v" + params.Version}
  470. }
  471. // If architecture specific image builds are requested, build and push them
  472. if *image {
  473. build.MustRunCommand("docker", "build", "--build-arg", "COMMIT="+env.Commit, "--build-arg", "VERSION="+params.VersionWithMeta, "--build-arg", "BUILDNUM="+env.Buildnum, "--tag", fmt.Sprintf("%s:TAG", *upload), ".")
  474. build.MustRunCommand("docker", "build", "--build-arg", "COMMIT="+env.Commit, "--build-arg", "VERSION="+params.VersionWithMeta, "--build-arg", "BUILDNUM="+env.Buildnum, "--tag", fmt.Sprintf("%s:alltools-TAG", *upload), "-f", "Dockerfile.alltools", ".")
  475. // Tag and upload the images to Docker Hub
  476. for _, tag := range tags {
  477. gethImage := fmt.Sprintf("%s:%s-%s", *upload, tag, runtime.GOARCH)
  478. toolImage := fmt.Sprintf("%s:alltools-%s-%s", *upload, tag, runtime.GOARCH)
  479. // If the image already exists (non version tag), check the build
  480. // number to prevent overwriting a newer commit if concurrent builds
  481. // are running. This is still a tiny bit racey if two published are
  482. // done at the same time, but that's extremely unlikely even on the
  483. // master branch.
  484. for _, img := range []string{gethImage, toolImage} {
  485. if exec.Command("docker", "pull", img).Run() != nil {
  486. continue // Generally the only failure is a missing image, which is good
  487. }
  488. buildnum, err := exec.Command("docker", "inspect", "--format", "{{index .Config.Labels \"buildnum\"}}", img).CombinedOutput()
  489. if err != nil {
  490. log.Fatalf("Failed to inspect container: %v\nOutput: %s", err, string(buildnum))
  491. }
  492. buildnum = bytes.TrimSpace(buildnum)
  493. if len(buildnum) > 0 && len(env.Buildnum) > 0 {
  494. oldnum, err := strconv.Atoi(string(buildnum))
  495. if err != nil {
  496. log.Fatalf("Failed to parse old image build number: %v", err)
  497. }
  498. newnum, err := strconv.Atoi(env.Buildnum)
  499. if err != nil {
  500. log.Fatalf("Failed to parse current build number: %v", err)
  501. }
  502. if oldnum > newnum {
  503. log.Fatalf("Current build number %d not newer than existing %d", newnum, oldnum)
  504. } else {
  505. log.Printf("Updating %s from build %d to %d", img, oldnum, newnum)
  506. }
  507. }
  508. }
  509. build.MustRunCommand("docker", "image", "tag", fmt.Sprintf("%s:TAG", *upload), gethImage)
  510. build.MustRunCommand("docker", "image", "tag", fmt.Sprintf("%s:alltools-TAG", *upload), toolImage)
  511. build.MustRunCommand("docker", "push", gethImage)
  512. build.MustRunCommand("docker", "push", toolImage)
  513. }
  514. }
  515. // If multi-arch image manifest push is requested, assemble it
  516. if len(*manifest) != 0 {
  517. // Since different architectures are pushed by different builders, wait
  518. // until all required images are updated.
  519. var mismatch bool
  520. for i := 0; i < 2; i++ { // 2 attempts, second is race check
  521. mismatch = false // hope there's no mismatch now
  522. for _, tag := range tags {
  523. for _, arch := range strings.Split(*manifest, ",") {
  524. gethImage := fmt.Sprintf("%s:%s-%s", *upload, tag, arch)
  525. toolImage := fmt.Sprintf("%s:alltools-%s-%s", *upload, tag, arch)
  526. for _, img := range []string{gethImage, toolImage} {
  527. if out, err := exec.Command("docker", "pull", img).CombinedOutput(); err != nil {
  528. log.Printf("Required image %s unavailable: %v\nOutput: %s", img, err, out)
  529. mismatch = true
  530. break
  531. }
  532. buildnum, err := exec.Command("docker", "inspect", "--format", "{{index .Config.Labels \"buildnum\"}}", img).CombinedOutput()
  533. if err != nil {
  534. log.Fatalf("Failed to inspect container: %v\nOutput: %s", err, string(buildnum))
  535. }
  536. buildnum = bytes.TrimSpace(buildnum)
  537. if string(buildnum) != env.Buildnum {
  538. log.Printf("Build number mismatch on %s: want %s, have %s", img, env.Buildnum, buildnum)
  539. mismatch = true
  540. break
  541. }
  542. }
  543. if mismatch {
  544. break
  545. }
  546. }
  547. if mismatch {
  548. break
  549. }
  550. }
  551. if mismatch {
  552. // Build numbers mismatching, retry in a short time to
  553. // avoid concurrent fails in both publisher images. If
  554. // however the retry failed too, it means the concurrent
  555. // builder is still crunching, let that do the publish.
  556. if i == 0 {
  557. time.Sleep(30 * time.Second)
  558. }
  559. continue
  560. }
  561. break
  562. }
  563. if mismatch {
  564. log.Println("Relinquishing publish to other builder")
  565. return
  566. }
  567. // Assemble and push the Geth manifest image
  568. for _, tag := range tags {
  569. gethImage := fmt.Sprintf("%s:%s", *upload, tag)
  570. var gethSubImages []string
  571. for _, arch := range strings.Split(*manifest, ",") {
  572. gethSubImages = append(gethSubImages, gethImage+"-"+arch)
  573. }
  574. build.MustRunCommand("docker", append([]string{"manifest", "create", gethImage}, gethSubImages...)...)
  575. build.MustRunCommand("docker", "manifest", "push", gethImage)
  576. }
  577. // Assemble and push the alltools manifest image
  578. for _, tag := range tags {
  579. toolImage := fmt.Sprintf("%s:alltools-%s", *upload, tag)
  580. var toolSubImages []string
  581. for _, arch := range strings.Split(*manifest, ",") {
  582. toolSubImages = append(toolSubImages, toolImage+"-"+arch)
  583. }
  584. build.MustRunCommand("docker", append([]string{"manifest", "create", toolImage}, toolSubImages...)...)
  585. build.MustRunCommand("docker", "manifest", "push", toolImage)
  586. }
  587. }
  588. }
  589. // Debian Packaging
  590. func doDebianSource(cmdline []string) {
  591. var (
  592. cachedir = flag.String("cachedir", "./build/cache", `Filesystem path to cache the downloaded Go bundles at`)
  593. signer = flag.String("signer", "", `Signing key name, also used as package author`)
  594. upload = flag.String("upload", "", `Where to upload the source package (usually "ethereum/ethereum")`)
  595. sshUser = flag.String("sftp-user", "", `Username for SFTP upload (usually "geth-ci")`)
  596. workdir = flag.String("workdir", "", `Output directory for packages (uses temp dir if unset)`)
  597. now = time.Now()
  598. )
  599. flag.CommandLine.Parse(cmdline)
  600. *workdir = makeWorkdir(*workdir)
  601. env := build.Env()
  602. tc := new(build.GoToolchain)
  603. maybeSkipArchive(env)
  604. // Import the signing key.
  605. if key := getenvBase64("PPA_SIGNING_KEY"); len(key) > 0 {
  606. gpg := exec.Command("gpg", "--import")
  607. gpg.Stdin = bytes.NewReader(key)
  608. build.MustRun(gpg)
  609. }
  610. // Download and verify the Go source package.
  611. gobundle := downloadGoSources(*cachedir)
  612. // Download all the dependencies needed to build the sources and run the ci script
  613. srcdepfetch := tc.Go("mod", "download")
  614. srcdepfetch.Env = append(srcdepfetch.Env, "GOPATH="+filepath.Join(*workdir, "modgopath"))
  615. build.MustRun(srcdepfetch)
  616. cidepfetch := tc.Go("run", "./build/ci.go")
  617. cidepfetch.Env = append(cidepfetch.Env, "GOPATH="+filepath.Join(*workdir, "modgopath"))
  618. cidepfetch.Run() // Command fails, don't care, we only need the deps to start it
  619. // Create Debian packages and upload them.
  620. for _, pkg := range debPackages {
  621. for distro, goboot := range debDistroGoBoots {
  622. // Prepare the debian package with the go-ethereum sources.
  623. meta := newDebMetadata(distro, goboot, *signer, env, now, pkg.Name, pkg.Version, pkg.Executables)
  624. pkgdir := stageDebianSource(*workdir, meta)
  625. // Add Go source code
  626. if err := build.ExtractArchive(gobundle, pkgdir); err != nil {
  627. log.Fatalf("Failed to extract Go sources: %v", err)
  628. }
  629. if err := os.Rename(filepath.Join(pkgdir, "go"), filepath.Join(pkgdir, ".go")); err != nil {
  630. log.Fatalf("Failed to rename Go source folder: %v", err)
  631. }
  632. // Add all dependency modules in compressed form
  633. os.MkdirAll(filepath.Join(pkgdir, ".mod", "cache"), 0755)
  634. if err := cp.CopyAll(filepath.Join(pkgdir, ".mod", "cache", "download"), filepath.Join(*workdir, "modgopath", "pkg", "mod", "cache", "download")); err != nil {
  635. log.Fatalf("Failed to copy Go module dependencies: %v", err)
  636. }
  637. // Run the packaging and upload to the PPA
  638. debuild := exec.Command("debuild", "-S", "-sa", "-us", "-uc", "-d", "-Zxz", "-nc")
  639. debuild.Dir = pkgdir
  640. build.MustRun(debuild)
  641. var (
  642. basename = fmt.Sprintf("%s_%s", meta.Name(), meta.VersionString())
  643. source = filepath.Join(*workdir, basename+".tar.xz")
  644. dsc = filepath.Join(*workdir, basename+".dsc")
  645. changes = filepath.Join(*workdir, basename+"_source.changes")
  646. buildinfo = filepath.Join(*workdir, basename+"_source.buildinfo")
  647. )
  648. if *signer != "" {
  649. build.MustRunCommand("debsign", changes)
  650. }
  651. if *upload != "" {
  652. ppaUpload(*workdir, *upload, *sshUser, []string{source, dsc, changes, buildinfo})
  653. }
  654. }
  655. }
  656. }
  657. // downloadGoSources downloads the Go source tarball.
  658. func downloadGoSources(cachedir string) string {
  659. csdb := build.MustLoadChecksums("build/checksums.txt")
  660. file := fmt.Sprintf("go%s.src.tar.gz", dlgoVersion)
  661. url := "https://dl.google.com/go/" + file
  662. dst := filepath.Join(cachedir, file)
  663. if err := csdb.DownloadFile(url, dst); err != nil {
  664. log.Fatal(err)
  665. }
  666. return dst
  667. }
  668. func ppaUpload(workdir, ppa, sshUser string, files []string) {
  669. p := strings.Split(ppa, "/")
  670. if len(p) != 2 {
  671. log.Fatal("-upload PPA name must contain single /")
  672. }
  673. if sshUser == "" {
  674. sshUser = p[0]
  675. }
  676. incomingDir := fmt.Sprintf("~%s/ubuntu/%s", p[0], p[1])
  677. // Create the SSH identity file if it doesn't exist.
  678. var idfile string
  679. if sshkey := getenvBase64("PPA_SSH_KEY"); len(sshkey) > 0 {
  680. idfile = filepath.Join(workdir, "sshkey")
  681. if !common.FileExist(idfile) {
  682. os.WriteFile(idfile, sshkey, 0600)
  683. }
  684. }
  685. // Upload
  686. dest := sshUser + "@ppa.launchpad.net"
  687. if err := build.UploadSFTP(idfile, dest, incomingDir, files); err != nil {
  688. log.Fatal(err)
  689. }
  690. }
  691. func getenvBase64(variable string) []byte {
  692. dec, err := base64.StdEncoding.DecodeString(os.Getenv(variable))
  693. if err != nil {
  694. log.Fatal("invalid base64 " + variable)
  695. }
  696. return []byte(dec)
  697. }
  698. func makeWorkdir(wdflag string) string {
  699. var err error
  700. if wdflag != "" {
  701. err = os.MkdirAll(wdflag, 0744)
  702. } else {
  703. wdflag, err = os.MkdirTemp("", "geth-build-")
  704. }
  705. if err != nil {
  706. log.Fatal(err)
  707. }
  708. return wdflag
  709. }
  710. func isUnstableBuild(env build.Environment) bool {
  711. if env.Tag != "" {
  712. return false
  713. }
  714. return true
  715. }
  716. type debPackage struct {
  717. Name string // the name of the Debian package to produce, e.g. "ethereum"
  718. Version string // the clean version of the debPackage, e.g. 1.8.12, without any metadata
  719. Executables []debExecutable // executables to be included in the package
  720. }
  721. type debMetadata struct {
  722. Env build.Environment
  723. GoBootPackage string
  724. GoBootPath string
  725. PackageName string
  726. // go-ethereum version being built. Note that this
  727. // is not the debian package version. The package version
  728. // is constructed by VersionString.
  729. Version string
  730. Author string // "name <email>", also selects signing key
  731. Distro, Time string
  732. Executables []debExecutable
  733. }
  734. type debExecutable struct {
  735. PackageName string
  736. BinaryName string
  737. Description string
  738. }
  739. // Package returns the name of the package if present, or
  740. // fallbacks to BinaryName
  741. func (d debExecutable) Package() string {
  742. if d.PackageName != "" {
  743. return d.PackageName
  744. }
  745. return d.BinaryName
  746. }
  747. func newDebMetadata(distro, goboot, author string, env build.Environment, t time.Time, name string, version string, exes []debExecutable) debMetadata {
  748. if author == "" {
  749. // No signing key, use default author.
  750. author = "Ethereum Builds <fjl@ethereum.org>"
  751. }
  752. return debMetadata{
  753. GoBootPackage: goboot,
  754. GoBootPath: debGoBootPaths[goboot],
  755. PackageName: name,
  756. Env: env,
  757. Author: author,
  758. Distro: distro,
  759. Version: version,
  760. Time: t.Format(time.RFC1123Z),
  761. Executables: exes,
  762. }
  763. }
  764. // Name returns the name of the metapackage that depends
  765. // on all executable packages.
  766. func (meta debMetadata) Name() string {
  767. if isUnstableBuild(meta.Env) {
  768. return meta.PackageName + "-unstable"
  769. }
  770. return meta.PackageName
  771. }
  772. // VersionString returns the debian version of the packages.
  773. func (meta debMetadata) VersionString() string {
  774. vsn := meta.Version
  775. if meta.Env.Buildnum != "" {
  776. vsn += "+build" + meta.Env.Buildnum
  777. }
  778. if meta.Distro != "" {
  779. vsn += "+" + meta.Distro
  780. }
  781. return vsn
  782. }
  783. // ExeList returns the list of all executable packages.
  784. func (meta debMetadata) ExeList() string {
  785. names := make([]string, len(meta.Executables))
  786. for i, e := range meta.Executables {
  787. names[i] = meta.ExeName(e)
  788. }
  789. return strings.Join(names, ", ")
  790. }
  791. // ExeName returns the package name of an executable package.
  792. func (meta debMetadata) ExeName(exe debExecutable) string {
  793. if isUnstableBuild(meta.Env) {
  794. return exe.Package() + "-unstable"
  795. }
  796. return exe.Package()
  797. }
  798. // ExeConflicts returns the content of the Conflicts field
  799. // for executable packages.
  800. func (meta debMetadata) ExeConflicts(exe debExecutable) string {
  801. if isUnstableBuild(meta.Env) {
  802. // Set up the conflicts list so that the *-unstable packages
  803. // cannot be installed alongside the regular version.
  804. //
  805. // https://www.debian.org/doc/debian-policy/ch-relationships.html
  806. // is very explicit about Conflicts: and says that Breaks: should
  807. // be preferred and the conflicting files should be handled via
  808. // alternates. We might do this eventually but using a conflict is
  809. // easier now.
  810. return "ethereum, " + exe.Package()
  811. }
  812. return ""
  813. }
  814. func stageDebianSource(tmpdir string, meta debMetadata) (pkgdir string) {
  815. pkg := meta.Name() + "-" + meta.VersionString()
  816. pkgdir = filepath.Join(tmpdir, pkg)
  817. if err := os.Mkdir(pkgdir, 0755); err != nil {
  818. log.Fatal(err)
  819. }
  820. // Copy the source code.
  821. build.MustRunCommand("git", "checkout-index", "-a", "--prefix", pkgdir+string(filepath.Separator))
  822. // Put the debian build files in place.
  823. debian := filepath.Join(pkgdir, "debian")
  824. build.Render("build/deb/"+meta.PackageName+"/deb.rules", filepath.Join(debian, "rules"), 0755, meta)
  825. build.Render("build/deb/"+meta.PackageName+"/deb.changelog", filepath.Join(debian, "changelog"), 0644, meta)
  826. build.Render("build/deb/"+meta.PackageName+"/deb.control", filepath.Join(debian, "control"), 0644, meta)
  827. build.Render("build/deb/"+meta.PackageName+"/deb.copyright", filepath.Join(debian, "copyright"), 0644, meta)
  828. build.RenderString("8\n", filepath.Join(debian, "compat"), 0644, meta)
  829. build.RenderString("3.0 (native)\n", filepath.Join(debian, "source/format"), 0644, meta)
  830. for _, exe := range meta.Executables {
  831. install := filepath.Join(debian, meta.ExeName(exe)+".install")
  832. docs := filepath.Join(debian, meta.ExeName(exe)+".docs")
  833. build.Render("build/deb/"+meta.PackageName+"/deb.install", install, 0644, exe)
  834. build.Render("build/deb/"+meta.PackageName+"/deb.docs", docs, 0644, exe)
  835. }
  836. return pkgdir
  837. }
  838. // Windows installer
  839. func doWindowsInstaller(cmdline []string) {
  840. // Parse the flags and make skip installer generation on PRs
  841. var (
  842. arch = flag.String("arch", runtime.GOARCH, "Architecture for cross build packaging")
  843. signer = flag.String("signer", "", `Environment variable holding the signing key (e.g. WINDOWS_SIGNING_KEY)`)
  844. signify = flag.String("signify key", "", `Environment variable holding the signify signing key (e.g. WINDOWS_SIGNIFY_KEY)`)
  845. upload = flag.String("upload", "", `Destination to upload the archives (usually "gethstore/builds")`)
  846. workdir = flag.String("workdir", "", `Output directory for packages (uses temp dir if unset)`)
  847. )
  848. flag.CommandLine.Parse(cmdline)
  849. *workdir = makeWorkdir(*workdir)
  850. env := build.Env()
  851. maybeSkipArchive(env)
  852. // Aggregate binaries that are included in the installer
  853. var (
  854. devTools []string
  855. allTools []string
  856. gethTool string
  857. )
  858. for _, file := range allToolsArchiveFiles {
  859. if file == "COPYING" { // license, copied later
  860. continue
  861. }
  862. allTools = append(allTools, filepath.Base(file))
  863. if filepath.Base(file) == "geth.exe" {
  864. gethTool = file
  865. } else {
  866. devTools = append(devTools, file)
  867. }
  868. }
  869. // Render NSIS scripts: Installer NSIS contains two installer sections,
  870. // first section contains the geth binary, second section holds the dev tools.
  871. templateData := map[string]interface{}{
  872. "License": "COPYING",
  873. "Geth": gethTool,
  874. "DevTools": devTools,
  875. }
  876. build.Render("build/nsis.geth.nsi", filepath.Join(*workdir, "geth.nsi"), 0644, nil)
  877. build.Render("build/nsis.install.nsh", filepath.Join(*workdir, "install.nsh"), 0644, templateData)
  878. build.Render("build/nsis.uninstall.nsh", filepath.Join(*workdir, "uninstall.nsh"), 0644, allTools)
  879. build.Render("build/nsis.pathupdate.nsh", filepath.Join(*workdir, "PathUpdate.nsh"), 0644, nil)
  880. build.Render("build/nsis.envvarupdate.nsh", filepath.Join(*workdir, "EnvVarUpdate.nsh"), 0644, nil)
  881. if err := cp.CopyFile(filepath.Join(*workdir, "SimpleFC.dll"), "build/nsis.simplefc.dll"); err != nil {
  882. log.Fatalf("Failed to copy SimpleFC.dll: %v", err)
  883. }
  884. if err := cp.CopyFile(filepath.Join(*workdir, "COPYING"), "COPYING"); err != nil {
  885. log.Fatalf("Failed to copy copyright note: %v", err)
  886. }
  887. // Build the installer. This assumes that all the needed files have been previously
  888. // built (don't mix building and packaging to keep cross compilation complexity to a
  889. // minimum).
  890. version := strings.Split(params.Version, ".")
  891. if env.Commit != "" {
  892. version[2] += "-" + env.Commit[:8]
  893. }
  894. installer, _ := filepath.Abs("geth-" + archiveBasename(*arch, params.ArchiveVersion(env.Commit)) + ".exe")
  895. build.MustRunCommand("makensis.exe",
  896. "/DOUTPUTFILE="+installer,
  897. "/DMAJORVERSION="+version[0],
  898. "/DMINORVERSION="+version[1],
  899. "/DBUILDVERSION="+version[2],
  900. "/DARCH="+*arch,
  901. filepath.Join(*workdir, "geth.nsi"),
  902. )
  903. // Sign and publish installer.
  904. if err := archiveUpload(installer, *upload, *signer, *signify); err != nil {
  905. log.Fatal(err)
  906. }
  907. }
  908. // Android archives
  909. func doAndroidArchive(cmdline []string) {
  910. var (
  911. local = flag.Bool("local", false, `Flag whether we're only doing a local build (skip Maven artifacts)`)
  912. signer = flag.String("signer", "", `Environment variable holding the signing key (e.g. ANDROID_SIGNING_KEY)`)
  913. signify = flag.String("signify", "", `Environment variable holding the signify signing key (e.g. ANDROID_SIGNIFY_KEY)`)
  914. deploy = flag.String("deploy", "", `Destination to deploy the archive (usually "https://oss.sonatype.org")`)
  915. upload = flag.String("upload", "", `Destination to upload the archive (usually "gethstore/builds")`)
  916. )
  917. flag.CommandLine.Parse(cmdline)
  918. env := build.Env()
  919. tc := new(build.GoToolchain)
  920. // Sanity check that the SDK and NDK are installed and set
  921. if os.Getenv("ANDROID_HOME") == "" {
  922. log.Fatal("Please ensure ANDROID_HOME points to your Android SDK")
  923. }
  924. // Build gomobile.
  925. install := tc.Install(GOBIN, "golang.org/x/mobile/cmd/gomobile@latest", "golang.org/x/mobile/cmd/gobind@latest")
  926. install.Env = append(install.Env)
  927. build.MustRun(install)
  928. // Ensure all dependencies are available. This is required to make
  929. // gomobile bind work because it expects go.sum to contain all checksums.
  930. build.MustRun(tc.Go("mod", "download"))
  931. // Build the Android archive and Maven resources
  932. build.MustRun(gomobileTool("bind", "-ldflags", "-s -w", "--target", "android", "--javapkg", "org.ethereum", "-v", "github.com/ethereum/go-ethereum/mobile"))
  933. if *local {
  934. // If we're building locally, copy bundle to build dir and skip Maven
  935. os.Rename("geth.aar", filepath.Join(GOBIN, "geth.aar"))
  936. os.Rename("geth-sources.jar", filepath.Join(GOBIN, "geth-sources.jar"))
  937. return
  938. }
  939. meta := newMavenMetadata(env)
  940. build.Render("build/mvn.pom", meta.Package+".pom", 0755, meta)
  941. // Skip Maven deploy and Azure upload for PR builds
  942. maybeSkipArchive(env)
  943. // Sign and upload the archive to Azure
  944. archive := "geth-" + archiveBasename("android", params.ArchiveVersion(env.Commit)) + ".aar"
  945. os.Rename("geth.aar", archive)
  946. if err := archiveUpload(archive, *upload, *signer, *signify); err != nil {
  947. log.Fatal(err)
  948. }
  949. // Sign and upload all the artifacts to Maven Central
  950. os.Rename(archive, meta.Package+".aar")
  951. if *signer != "" && *deploy != "" {
  952. // Import the signing key into the local GPG instance
  953. key := getenvBase64(*signer)
  954. gpg := exec.Command("gpg", "--import")
  955. gpg.Stdin = bytes.NewReader(key)
  956. build.MustRun(gpg)
  957. keyID, err := build.PGPKeyID(string(key))
  958. if err != nil {
  959. log.Fatal(err)
  960. }
  961. // Upload the artifacts to Sonatype and/or Maven Central
  962. repo := *deploy + "/service/local/staging/deploy/maven2"
  963. if meta.Develop {
  964. repo = *deploy + "/content/repositories/snapshots"
  965. }
  966. build.MustRunCommand("mvn", "gpg:sign-and-deploy-file", "-e", "-X",
  967. "-settings=build/mvn.settings", "-Durl="+repo, "-DrepositoryId=ossrh",
  968. "-Dgpg.keyname="+keyID,
  969. "-DpomFile="+meta.Package+".pom", "-Dfile="+meta.Package+".aar")
  970. }
  971. }
  972. func gomobileTool(subcmd string, args ...string) *exec.Cmd {
  973. cmd := exec.Command(filepath.Join(GOBIN, "gomobile"), subcmd)
  974. cmd.Args = append(cmd.Args, args...)
  975. cmd.Env = []string{
  976. "PATH=" + GOBIN + string(os.PathListSeparator) + os.Getenv("PATH"),
  977. }
  978. for _, e := range os.Environ() {
  979. if strings.HasPrefix(e, "GOPATH=") || strings.HasPrefix(e, "PATH=") || strings.HasPrefix(e, "GOBIN=") {
  980. continue
  981. }
  982. cmd.Env = append(cmd.Env, e)
  983. }
  984. cmd.Env = append(cmd.Env, "GOBIN="+GOBIN)
  985. return cmd
  986. }
  987. type mavenMetadata struct {
  988. Version string
  989. Package string
  990. Develop bool
  991. Contributors []mavenContributor
  992. }
  993. type mavenContributor struct {
  994. Name string
  995. Email string
  996. }
  997. func newMavenMetadata(env build.Environment) mavenMetadata {
  998. // Collect the list of authors from the repo root
  999. contribs := []mavenContributor{}
  1000. if authors, err := os.Open("AUTHORS"); err == nil {
  1001. defer authors.Close()
  1002. scanner := bufio.NewScanner(authors)
  1003. for scanner.Scan() {
  1004. // Skip any whitespace from the authors list
  1005. line := strings.TrimSpace(scanner.Text())
  1006. if line == "" || line[0] == '#' {
  1007. continue
  1008. }
  1009. // Split the author and insert as a contributor
  1010. re := regexp.MustCompile("([^<]+) <(.+)>")
  1011. parts := re.FindStringSubmatch(line)
  1012. if len(parts) == 3 {
  1013. contribs = append(contribs, mavenContributor{Name: parts[1], Email: parts[2]})
  1014. }
  1015. }
  1016. }
  1017. // Render the version and package strings
  1018. version := params.Version
  1019. if isUnstableBuild(env) {
  1020. version += "-SNAPSHOT"
  1021. }
  1022. return mavenMetadata{
  1023. Version: version,
  1024. Package: "geth-" + version,
  1025. Develop: isUnstableBuild(env),
  1026. Contributors: contribs,
  1027. }
  1028. }
  1029. // XCode frameworks
  1030. func doXCodeFramework(cmdline []string) {
  1031. var (
  1032. local = flag.Bool("local", false, `Flag whether we're only doing a local build (skip Maven artifacts)`)
  1033. signer = flag.String("signer", "", `Environment variable holding the signing key (e.g. IOS_SIGNING_KEY)`)
  1034. signify = flag.String("signify", "", `Environment variable holding the signify signing key (e.g. IOS_SIGNIFY_KEY)`)
  1035. deploy = flag.String("deploy", "", `Destination to deploy the archive (usually "trunk")`)
  1036. upload = flag.String("upload", "", `Destination to upload the archives (usually "gethstore/builds")`)
  1037. )
  1038. flag.CommandLine.Parse(cmdline)
  1039. env := build.Env()
  1040. tc := new(build.GoToolchain)
  1041. // Build gomobile.
  1042. build.MustRun(tc.Install(GOBIN, "golang.org/x/mobile/cmd/gomobile", "golang.org/x/mobile/cmd/gobind"))
  1043. // Build the iOS XCode framework
  1044. bind := gomobileTool("bind", "-ldflags", "-s -w", "--target", "ios", "-v", "github.com/ethereum/go-ethereum/mobile")
  1045. if *local {
  1046. // If we're building locally, use the build folder and stop afterwards
  1047. bind.Dir = GOBIN
  1048. build.MustRun(bind)
  1049. return
  1050. }
  1051. // Create the archive.
  1052. maybeSkipArchive(env)
  1053. archive := "geth-" + archiveBasename("ios", params.ArchiveVersion(env.Commit))
  1054. if err := os.MkdirAll(archive, 0755); err != nil {
  1055. log.Fatal(err)
  1056. }
  1057. bind.Dir, _ = filepath.Abs(archive)
  1058. build.MustRun(bind)
  1059. build.MustRunCommand("tar", "-zcvf", archive+".tar.gz", archive)
  1060. // Sign and upload the framework to Azure
  1061. if err := archiveUpload(archive+".tar.gz", *upload, *signer, *signify); err != nil {
  1062. log.Fatal(err)
  1063. }
  1064. // Prepare and upload a PodSpec to CocoaPods
  1065. if *deploy != "" {
  1066. meta := newPodMetadata(env, archive)
  1067. build.Render("build/pod.podspec", "Geth.podspec", 0755, meta)
  1068. build.MustRunCommand("pod", *deploy, "push", "Geth.podspec", "--allow-warnings")
  1069. }
  1070. }
  1071. type podMetadata struct {
  1072. Version string
  1073. Commit string
  1074. Archive string
  1075. Contributors []podContributor
  1076. }
  1077. type podContributor struct {
  1078. Name string
  1079. Email string
  1080. }
  1081. func newPodMetadata(env build.Environment, archive string) podMetadata {
  1082. // Collect the list of authors from the repo root
  1083. contribs := []podContributor{}
  1084. if authors, err := os.Open("AUTHORS"); err == nil {
  1085. defer authors.Close()
  1086. scanner := bufio.NewScanner(authors)
  1087. for scanner.Scan() {
  1088. // Skip any whitespace from the authors list
  1089. line := strings.TrimSpace(scanner.Text())
  1090. if line == "" || line[0] == '#' {
  1091. continue
  1092. }
  1093. // Split the author and insert as a contributor
  1094. re := regexp.MustCompile("([^<]+) <(.+)>")
  1095. parts := re.FindStringSubmatch(line)
  1096. if len(parts) == 3 {
  1097. contribs = append(contribs, podContributor{Name: parts[1], Email: parts[2]})
  1098. }
  1099. }
  1100. }
  1101. version := params.Version
  1102. if isUnstableBuild(env) {
  1103. version += "-unstable." + env.Buildnum
  1104. }
  1105. return podMetadata{
  1106. Archive: archive,
  1107. Version: version,
  1108. Commit: env.Commit,
  1109. Contributors: contribs,
  1110. }
  1111. }
  1112. // Binary distribution cleanups
  1113. func doPurge(cmdline []string) {
  1114. var (
  1115. store = flag.String("store", "", `Destination from where to purge archives (usually "gethstore/builds")`)
  1116. limit = flag.Int("days", 30, `Age threshold above which to delete unstable archives`)
  1117. )
  1118. flag.CommandLine.Parse(cmdline)
  1119. if env := build.Env(); !env.IsCronJob {
  1120. log.Printf("skipping because not a cron job")
  1121. os.Exit(0)
  1122. }
  1123. // Create the azure authentication and list the current archives
  1124. auth := build.AzureBlobstoreConfig{
  1125. Account: strings.Split(*store, "/")[0],
  1126. Token: os.Getenv("AZURE_BLOBSTORE_TOKEN"),
  1127. Container: strings.SplitN(*store, "/", 2)[1],
  1128. }
  1129. blobs, err := build.AzureBlobstoreList(auth)
  1130. if err != nil {
  1131. log.Fatal(err)
  1132. }
  1133. fmt.Printf("Found %d blobs\n", len(blobs))
  1134. // Iterate over the blobs, collect and sort all unstable builds
  1135. for i := 0; i < len(blobs); i++ {
  1136. if !strings.Contains(*blobs[i].Name, "unstable") {
  1137. blobs = append(blobs[:i], blobs[i+1:]...)
  1138. i--
  1139. }
  1140. }
  1141. for i := 0; i < len(blobs); i++ {
  1142. for j := i + 1; j < len(blobs); j++ {
  1143. if blobs[i].Properties.LastModified.After(*blobs[j].Properties.LastModified) {
  1144. blobs[i], blobs[j] = blobs[j], blobs[i]
  1145. }
  1146. }
  1147. }
  1148. // Filter out all archives more recent that the given threshold
  1149. for i, blob := range blobs {
  1150. if time.Since(*blob.Properties.LastModified) < time.Duration(*limit)*24*time.Hour {
  1151. blobs = blobs[:i]
  1152. break
  1153. }
  1154. }
  1155. fmt.Printf("Deleting %d blobs\n", len(blobs))
  1156. // Delete all marked as such and return
  1157. if err := build.AzureBlobstoreDelete(auth, blobs); err != nil {
  1158. log.Fatal(err)
  1159. }
  1160. }