ci.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580
  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 ci.go <command> <command flags/arguments>
  20. Available commands are:
  21. install [-arch architecture] [ packages... ] -- builds packages and executables
  22. test [ -coverage ] [ -vet ] [ packages... ] -- runs the tests
  23. archive [-arch architecture] [ -type zip|tar ] [ -signer key-envvar ] [ -upload dest ] -- archives build artefacts
  24. importkeys -- imports signing keys from env
  25. debsrc [ -signer key-id ] [ -upload dest ] -- creates a debian source package
  26. xgo [ options ] -- cross builds according to options
  27. For all commands, -n prevents execution of external programs (dry run mode).
  28. */
  29. package main
  30. import (
  31. "bytes"
  32. "encoding/base64"
  33. "flag"
  34. "fmt"
  35. "go/parser"
  36. "go/token"
  37. "io/ioutil"
  38. "log"
  39. "os"
  40. "os/exec"
  41. "path/filepath"
  42. "runtime"
  43. "strings"
  44. "time"
  45. "github.com/ethereum/go-ethereum/internal/build"
  46. )
  47. var (
  48. // Files that end up in the geth*.zip archive.
  49. gethArchiveFiles = []string{
  50. "COPYING",
  51. executablePath("geth"),
  52. }
  53. // Files that end up in the geth-alltools*.zip archive.
  54. allToolsArchiveFiles = []string{
  55. "COPYING",
  56. executablePath("abigen"),
  57. executablePath("evm"),
  58. executablePath("geth"),
  59. executablePath("rlpdump"),
  60. }
  61. // A debian package is created for all executables listed here.
  62. debExecutables = []debExecutable{
  63. {
  64. Name: "geth",
  65. Description: "Ethereum CLI client.",
  66. },
  67. {
  68. Name: "rlpdump",
  69. Description: "Developer utility tool that prints RLP structures.",
  70. },
  71. {
  72. Name: "evm",
  73. Description: "Developer utility version of the EVM (Ethereum Virtual Machine) that is capable of running bytecode snippets within a configurable environment and execution mode.",
  74. },
  75. {
  76. Name: "abigen",
  77. Description: "Source code generator to convert Ethereum contract definitions into easy to use, compile-time type-safe Go packages.",
  78. },
  79. }
  80. // Distros for which packages are created.
  81. // Note: vivid is unsupported because there is no golang-1.6 package for it.
  82. debDistros = []string{"trusty", "wily", "xenial", "yakkety"}
  83. )
  84. var GOBIN, _ = filepath.Abs(filepath.Join("build", "bin"))
  85. func executablePath(name string) string {
  86. if runtime.GOOS == "windows" {
  87. name += ".exe"
  88. }
  89. return filepath.Join(GOBIN, name)
  90. }
  91. func main() {
  92. log.SetFlags(log.Lshortfile)
  93. if _, err := os.Stat(filepath.Join("build", "ci.go")); os.IsNotExist(err) {
  94. log.Fatal("this script must be run from the root of the repository")
  95. }
  96. if len(os.Args) < 2 {
  97. log.Fatal("need subcommand as first argument")
  98. }
  99. switch os.Args[1] {
  100. case "install":
  101. doInstall(os.Args[2:])
  102. case "test":
  103. doTest(os.Args[2:])
  104. case "archive":
  105. doArchive(os.Args[2:])
  106. case "debsrc":
  107. doDebianSource(os.Args[2:])
  108. case "xgo":
  109. doXgo(os.Args[2:])
  110. default:
  111. log.Fatal("unknown command ", os.Args[1])
  112. }
  113. }
  114. // Compiling
  115. func doInstall(cmdline []string) {
  116. var (
  117. arch = flag.String("arch", "", "Architecture to cross build for")
  118. )
  119. flag.CommandLine.Parse(cmdline)
  120. env := build.Env()
  121. // Check Go version. People regularly open issues about compilation
  122. // failure with outdated Go. This should save them the trouble.
  123. if runtime.Version() < "go1.4" && !strings.HasPrefix(runtime.Version(), "devel") {
  124. log.Println("You have Go version", runtime.Version())
  125. log.Println("go-ethereum requires at least Go version 1.4 and cannot")
  126. log.Println("be compiled with an earlier version. Please upgrade your Go installation.")
  127. os.Exit(1)
  128. }
  129. // Compile packages given as arguments, or everything if there are no arguments.
  130. packages := []string{"./..."}
  131. if flag.NArg() > 0 {
  132. packages = flag.Args()
  133. }
  134. if *arch == "" || *arch == runtime.GOARCH {
  135. goinstall := goTool("install", buildFlags(env)...)
  136. goinstall.Args = append(goinstall.Args, "-v")
  137. goinstall.Args = append(goinstall.Args, packages...)
  138. build.MustRun(goinstall)
  139. return
  140. }
  141. // Seems we are cross compiling, work around forbidden GOBIN
  142. goinstall := goToolArch(*arch, "install", buildFlags(env)...)
  143. goinstall.Args = append(goinstall.Args, "-v")
  144. goinstall.Args = append(goinstall.Args, []string{"-buildmode", "archive"}...)
  145. goinstall.Args = append(goinstall.Args, packages...)
  146. build.MustRun(goinstall)
  147. if cmds, err := ioutil.ReadDir("cmd"); err == nil {
  148. for _, cmd := range cmds {
  149. pkgs, err := parser.ParseDir(token.NewFileSet(), filepath.Join(".", "cmd", cmd.Name()), nil, parser.PackageClauseOnly)
  150. if err != nil {
  151. log.Fatal(err)
  152. }
  153. for name, _ := range pkgs {
  154. if name == "main" {
  155. gobuild := goToolArch(*arch, "build", buildFlags(env)...)
  156. gobuild.Args = append(gobuild.Args, "-v")
  157. gobuild.Args = append(gobuild.Args, []string{"-o", filepath.Join(GOBIN, cmd.Name())}...)
  158. gobuild.Args = append(gobuild.Args, "."+string(filepath.Separator)+filepath.Join("cmd", cmd.Name()))
  159. build.MustRun(gobuild)
  160. break
  161. }
  162. }
  163. }
  164. }
  165. }
  166. func buildFlags(env build.Environment) (flags []string) {
  167. if os.Getenv("GO_OPENCL") != "" {
  168. flags = append(flags, "-tags", "opencl")
  169. }
  170. // Since Go 1.5, the separator char for link time assignments
  171. // is '=' and using ' ' prints a warning. However, Go < 1.5 does
  172. // not support using '='.
  173. sep := " "
  174. if runtime.Version() > "go1.5" || strings.Contains(runtime.Version(), "devel") {
  175. sep = "="
  176. }
  177. // Set gitCommit constant via link-time assignment.
  178. if env.Commit != "" {
  179. flags = append(flags, "-ldflags", "-X main.gitCommit"+sep+env.Commit)
  180. }
  181. return flags
  182. }
  183. func goTool(subcmd string, args ...string) *exec.Cmd {
  184. return goToolArch(runtime.GOARCH, subcmd, args...)
  185. }
  186. func goToolArch(arch string, subcmd string, args ...string) *exec.Cmd {
  187. gocmd := filepath.Join(runtime.GOROOT(), "bin", "go")
  188. cmd := exec.Command(gocmd, subcmd)
  189. cmd.Args = append(cmd.Args, args...)
  190. cmd.Env = []string{
  191. "GO15VENDOREXPERIMENT=1",
  192. "GOPATH=" + build.GOPATH(),
  193. }
  194. if arch == "" || arch == runtime.GOARCH {
  195. cmd.Env = append(cmd.Env, "GOBIN="+GOBIN)
  196. } else {
  197. cmd.Env = append(cmd.Env, "CGO_ENABLED=1")
  198. cmd.Env = append(cmd.Env, "GOARCH="+arch)
  199. }
  200. for _, e := range os.Environ() {
  201. if strings.HasPrefix(e, "GOPATH=") || strings.HasPrefix(e, "GOBIN=") {
  202. continue
  203. }
  204. cmd.Env = append(cmd.Env, e)
  205. }
  206. return cmd
  207. }
  208. // Running The Tests
  209. //
  210. // "tests" also includes static analysis tools such as vet.
  211. func doTest(cmdline []string) {
  212. var (
  213. vet = flag.Bool("vet", false, "Whether to run go vet")
  214. coverage = flag.Bool("coverage", false, "Whether to record code coverage")
  215. )
  216. flag.CommandLine.Parse(cmdline)
  217. packages := []string{"./..."}
  218. if len(flag.CommandLine.Args()) > 0 {
  219. packages = flag.CommandLine.Args()
  220. }
  221. if len(packages) == 1 && packages[0] == "./..." {
  222. // Resolve ./... manually since go vet will fail on vendored stuff
  223. out, err := goTool("list", "./...").CombinedOutput()
  224. if err != nil {
  225. log.Fatalf("package listing failed: %v\n%s", err, string(out))
  226. }
  227. packages = []string{}
  228. for _, line := range strings.Split(string(out), "\n") {
  229. if !strings.Contains(line, "vendor") {
  230. packages = append(packages, strings.TrimSpace(line))
  231. }
  232. }
  233. }
  234. // Run analysis tools before the tests.
  235. if *vet {
  236. build.MustRun(goTool("vet", packages...))
  237. }
  238. // Run the actual tests.
  239. gotest := goTool("test")
  240. // Test a single package at a time. CI builders are slow
  241. // and some tests run into timeouts under load.
  242. gotest.Args = append(gotest.Args, "-p", "1")
  243. if *coverage {
  244. gotest.Args = append(gotest.Args, "-covermode=atomic", "-cover")
  245. }
  246. gotest.Args = append(gotest.Args, packages...)
  247. build.MustRun(gotest)
  248. }
  249. // Release Packaging
  250. func doArchive(cmdline []string) {
  251. var (
  252. arch = flag.String("arch", runtime.GOARCH, "Architecture cross packaging")
  253. atype = flag.String("type", "zip", "Type of archive to write (zip|tar)")
  254. signer = flag.String("signer", "", `Environment variable holding the signing key (e.g. LINUX_SIGNING_KEY)`)
  255. upload = flag.String("upload", "", `Destination to upload the archives (usually "gethstore/builds")`)
  256. ext string
  257. )
  258. flag.CommandLine.Parse(cmdline)
  259. switch *atype {
  260. case "zip":
  261. ext = ".zip"
  262. case "tar":
  263. ext = ".tar.gz"
  264. default:
  265. log.Fatal("unknown archive type: ", atype)
  266. }
  267. var (
  268. env = build.Env()
  269. base = archiveBasename(*arch, env)
  270. geth = "geth-" + base + ext
  271. alltools = "geth-alltools-" + base + ext
  272. )
  273. maybeSkipArchive(env)
  274. if err := build.WriteArchive(geth, gethArchiveFiles); err != nil {
  275. log.Fatal(err)
  276. }
  277. if err := build.WriteArchive(alltools, allToolsArchiveFiles); err != nil {
  278. log.Fatal(err)
  279. }
  280. for _, archive := range []string{geth, alltools} {
  281. if err := archiveUpload(archive, *upload, *signer); err != nil {
  282. log.Fatal(err)
  283. }
  284. }
  285. }
  286. func archiveBasename(arch string, env build.Environment) string {
  287. platform := runtime.GOOS + "-" + arch
  288. archive := platform + "-" + build.VERSION()
  289. if isUnstableBuild(env) {
  290. archive += "-unstable"
  291. }
  292. if env.Commit != "" {
  293. archive += "-" + env.Commit[:8]
  294. }
  295. return archive
  296. }
  297. func archiveUpload(archive string, blobstore string, signer string) error {
  298. // If signing was requested, generate the signature files
  299. if signer != "" {
  300. pgpkey, err := base64.StdEncoding.DecodeString(os.Getenv(signer))
  301. if err != nil {
  302. return fmt.Errorf("invalid base64 %s", signer)
  303. }
  304. if err := build.PGPSignFile(archive, archive+".asc", string(pgpkey)); err != nil {
  305. return err
  306. }
  307. }
  308. // If uploading to Azure was requested, push the archive possibly with its signature
  309. if blobstore != "" {
  310. auth := build.AzureBlobstoreConfig{
  311. Account: strings.Split(blobstore, "/")[0],
  312. Token: os.Getenv("AZURE_BLOBSTORE_TOKEN"),
  313. Container: strings.SplitN(blobstore, "/", 2)[1],
  314. }
  315. if err := build.AzureBlobstoreUpload(archive, archive, auth); err != nil {
  316. return err
  317. }
  318. if signer != "" {
  319. if err := build.AzureBlobstoreUpload(archive+".asc", archive+".asc", auth); err != nil {
  320. return err
  321. }
  322. }
  323. }
  324. return nil
  325. }
  326. // skips archiving for some build configurations.
  327. func maybeSkipArchive(env build.Environment) {
  328. if env.IsPullRequest {
  329. log.Printf("skipping because this is a PR build")
  330. os.Exit(0)
  331. }
  332. if env.Branch != "develop" && !strings.HasPrefix(env.Tag, "v1.") {
  333. log.Printf("skipping because branch %q, tag %q is not on the whitelist", env.Branch, env.Tag)
  334. os.Exit(0)
  335. }
  336. }
  337. // Debian Packaging
  338. func doDebianSource(cmdline []string) {
  339. var (
  340. signer = flag.String("signer", "", `Signing key name, also used as package author`)
  341. upload = flag.String("upload", "", `Where to upload the source package (usually "ppa:ethereum/ethereum")`)
  342. workdir = flag.String("workdir", "", `Output directory for packages (uses temp dir if unset)`)
  343. now = time.Now()
  344. )
  345. flag.CommandLine.Parse(cmdline)
  346. *workdir = makeWorkdir(*workdir)
  347. env := build.Env()
  348. maybeSkipArchive(env)
  349. // Import the signing key.
  350. if b64key := os.Getenv("PPA_SIGNING_KEY"); b64key != "" {
  351. key, err := base64.StdEncoding.DecodeString(b64key)
  352. if err != nil {
  353. log.Fatal("invalid base64 PPA_SIGNING_KEY")
  354. }
  355. gpg := exec.Command("gpg", "--import")
  356. gpg.Stdin = bytes.NewReader(key)
  357. build.MustRun(gpg)
  358. }
  359. // Create the packages.
  360. for _, distro := range debDistros {
  361. meta := newDebMetadata(distro, *signer, env, now)
  362. pkgdir := stageDebianSource(*workdir, meta)
  363. debuild := exec.Command("debuild", "-S", "-sa", "-us", "-uc")
  364. debuild.Dir = pkgdir
  365. build.MustRun(debuild)
  366. changes := fmt.Sprintf("%s_%s_source.changes", meta.Name(), meta.VersionString())
  367. changes = filepath.Join(*workdir, changes)
  368. if *signer != "" {
  369. build.MustRunCommand("debsign", changes)
  370. }
  371. if *upload != "" {
  372. build.MustRunCommand("dput", *upload, changes)
  373. }
  374. }
  375. }
  376. func makeWorkdir(wdflag string) string {
  377. var err error
  378. if wdflag != "" {
  379. err = os.MkdirAll(wdflag, 0744)
  380. } else {
  381. wdflag, err = ioutil.TempDir("", "eth-deb-build-")
  382. }
  383. if err != nil {
  384. log.Fatal(err)
  385. }
  386. return wdflag
  387. }
  388. func isUnstableBuild(env build.Environment) bool {
  389. if env.Branch != "develop" && env.Tag != "" {
  390. return false
  391. }
  392. return true
  393. }
  394. type debMetadata struct {
  395. Env build.Environment
  396. // go-ethereum version being built. Note that this
  397. // is not the debian package version. The package version
  398. // is constructed by VersionString.
  399. Version string
  400. Author string // "name <email>", also selects signing key
  401. Distro, Time string
  402. Executables []debExecutable
  403. }
  404. type debExecutable struct {
  405. Name, Description string
  406. }
  407. func newDebMetadata(distro, author string, env build.Environment, t time.Time) debMetadata {
  408. if author == "" {
  409. // No signing key, use default author.
  410. author = "Ethereum Builds <fjl@ethereum.org>"
  411. }
  412. return debMetadata{
  413. Env: env,
  414. Author: author,
  415. Distro: distro,
  416. Version: build.VERSION(),
  417. Time: t.Format(time.RFC1123Z),
  418. Executables: debExecutables,
  419. }
  420. }
  421. // Name returns the name of the metapackage that depends
  422. // on all executable packages.
  423. func (meta debMetadata) Name() string {
  424. if isUnstableBuild(meta.Env) {
  425. return "ethereum-unstable"
  426. }
  427. return "ethereum"
  428. }
  429. // VersionString returns the debian version of the packages.
  430. func (meta debMetadata) VersionString() string {
  431. vsn := meta.Version
  432. if meta.Env.Buildnum != "" {
  433. vsn += "+build" + meta.Env.Buildnum
  434. }
  435. if meta.Distro != "" {
  436. vsn += "+" + meta.Distro
  437. }
  438. return vsn
  439. }
  440. // ExeList returns the list of all executable packages.
  441. func (meta debMetadata) ExeList() string {
  442. names := make([]string, len(meta.Executables))
  443. for i, e := range meta.Executables {
  444. names[i] = meta.ExeName(e)
  445. }
  446. return strings.Join(names, ", ")
  447. }
  448. // ExeName returns the package name of an executable package.
  449. func (meta debMetadata) ExeName(exe debExecutable) string {
  450. if isUnstableBuild(meta.Env) {
  451. return exe.Name + "-unstable"
  452. }
  453. return exe.Name
  454. }
  455. // ExeConflicts returns the content of the Conflicts field
  456. // for executable packages.
  457. func (meta debMetadata) ExeConflicts(exe debExecutable) string {
  458. if isUnstableBuild(meta.Env) {
  459. // Set up the conflicts list so that the *-unstable packages
  460. // cannot be installed alongside the regular version.
  461. //
  462. // https://www.debian.org/doc/debian-policy/ch-relationships.html
  463. // is very explicit about Conflicts: and says that Breaks: should
  464. // be preferred and the conflicting files should be handled via
  465. // alternates. We might do this eventually but using a conflict is
  466. // easier now.
  467. return "ethereum, " + exe.Name
  468. }
  469. return ""
  470. }
  471. func stageDebianSource(tmpdir string, meta debMetadata) (pkgdir string) {
  472. pkg := meta.Name() + "-" + meta.VersionString()
  473. pkgdir = filepath.Join(tmpdir, pkg)
  474. if err := os.Mkdir(pkgdir, 0755); err != nil {
  475. log.Fatal(err)
  476. }
  477. // Copy the source code.
  478. build.MustRunCommand("git", "checkout-index", "-a", "--prefix", pkgdir+string(filepath.Separator))
  479. // Put the debian build files in place.
  480. debian := filepath.Join(pkgdir, "debian")
  481. build.Render("build/deb.rules", filepath.Join(debian, "rules"), 0755, meta)
  482. build.Render("build/deb.changelog", filepath.Join(debian, "changelog"), 0644, meta)
  483. build.Render("build/deb.control", filepath.Join(debian, "control"), 0644, meta)
  484. build.Render("build/deb.copyright", filepath.Join(debian, "copyright"), 0644, meta)
  485. build.RenderString("8\n", filepath.Join(debian, "compat"), 0644, meta)
  486. build.RenderString("3.0 (native)\n", filepath.Join(debian, "source/format"), 0644, meta)
  487. for _, exe := range meta.Executables {
  488. install := filepath.Join(debian, meta.ExeName(exe)+".install")
  489. docs := filepath.Join(debian, meta.ExeName(exe)+".docs")
  490. build.Render("build/deb.install", install, 0644, exe)
  491. build.Render("build/deb.docs", docs, 0644, exe)
  492. }
  493. return pkgdir
  494. }
  495. // Cross compilation
  496. func doXgo(cmdline []string) {
  497. flag.CommandLine.Parse(cmdline)
  498. env := build.Env()
  499. // Make sure xgo is available for cross compilation
  500. gogetxgo := goTool("get", "github.com/karalabe/xgo")
  501. build.MustRun(gogetxgo)
  502. // Execute the actual cross compilation
  503. xgo := xgoTool(append(buildFlags(env), flag.Args()...))
  504. build.MustRun(xgo)
  505. }
  506. func xgoTool(args []string) *exec.Cmd {
  507. cmd := exec.Command(filepath.Join(GOBIN, "xgo"), args...)
  508. cmd.Env = []string{
  509. "GOPATH=" + build.GOPATH(),
  510. "GOBIN=" + GOBIN,
  511. }
  512. for _, e := range os.Environ() {
  513. if strings.HasPrefix(e, "GOPATH=") || strings.HasPrefix(e, "GOBIN=") {
  514. continue
  515. }
  516. cmd.Env = append(cmd.Env, e)
  517. }
  518. return cmd
  519. }