ci.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497
  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 [ packages... ] -- builds packages and executables
  22. test [ -coverage ] [ -vet ] [ packages... ] -- runs the tests
  23. archive [ -type zip|tar ] -- archives build artefacts
  24. importkeys -- imports signing keys from env
  25. debsrc [ -sign 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. "io/ioutil"
  36. "log"
  37. "os"
  38. "os/exec"
  39. "path/filepath"
  40. "runtime"
  41. "strings"
  42. "time"
  43. "../internal/build"
  44. )
  45. var (
  46. // Files that end up in the geth*.zip archive.
  47. gethArchiveFiles = []string{
  48. "COPYING",
  49. executablePath("geth"),
  50. }
  51. // Files that end up in the geth-alltools*.zip archive.
  52. allToolsArchiveFiles = []string{
  53. "COPYING",
  54. executablePath("abigen"),
  55. executablePath("evm"),
  56. executablePath("geth"),
  57. executablePath("rlpdump"),
  58. }
  59. // A debian package is created for all executables listed here.
  60. debExecutables = []debExecutable{
  61. {
  62. Name: "geth",
  63. Description: "Ethereum CLI client.",
  64. },
  65. {
  66. Name: "rlpdump",
  67. Description: "Developer utility tool that prints RLP structures.",
  68. },
  69. {
  70. Name: "evm",
  71. Description: "Developer utility version of the EVM (Ethereum Virtual Machine) that is capable of running bytecode snippets within a configurable environment and execution mode.",
  72. },
  73. {
  74. Name: "abigen",
  75. Description: "Source code generator to convert Ethereum contract definitions into easy to use, compile-time type-safe Go packages.",
  76. },
  77. }
  78. // Distros for which packages are created.
  79. // Note: vivid is unsupported because there is no golang-1.6 package for it.
  80. debDistros = []string{"trusty", "wily", "xenial", "yakkety"}
  81. )
  82. var GOBIN, _ = filepath.Abs(filepath.Join("build", "bin"))
  83. func executablePath(name string) string {
  84. if runtime.GOOS == "windows" {
  85. name += ".exe"
  86. }
  87. return filepath.Join(GOBIN, name)
  88. }
  89. func main() {
  90. log.SetFlags(log.Lshortfile)
  91. if _, err := os.Stat(filepath.Join("build", "ci.go")); os.IsNotExist(err) {
  92. log.Fatal("this script must be run from the root of the repository")
  93. }
  94. if len(os.Args) < 2 {
  95. log.Fatal("need subcommand as first argument")
  96. }
  97. switch os.Args[1] {
  98. case "install":
  99. doInstall(os.Args[2:])
  100. case "test":
  101. doTest(os.Args[2:])
  102. case "archive":
  103. doArchive(os.Args[2:])
  104. case "debsrc":
  105. doDebianSource(os.Args[2:])
  106. case "travis-debsrc":
  107. doTravisDebianSource(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. commitHash := flag.String("gitcommit", "", "Git commit hash embedded into binary.")
  117. flag.CommandLine.Parse(cmdline)
  118. // Check Go version. People regularly open issues about compilation
  119. // failure with outdated Go. This should save them the trouble.
  120. if runtime.Version() < "go1.4" && !strings.HasPrefix(runtime.Version(), "devel") {
  121. log.Println("You have Go version", runtime.Version())
  122. log.Println("go-ethereum requires at least Go version 1.4 and cannot")
  123. log.Println("be compiled with an earlier version. Please upgrade your Go installation.")
  124. os.Exit(1)
  125. }
  126. // Compile packages given as arguments, or everything if there are no arguments.
  127. packages := []string{"./..."}
  128. if flag.NArg() > 0 {
  129. packages = flag.Args()
  130. }
  131. goinstall := goTool("install", makeBuildFlags(*commitHash)...)
  132. goinstall.Args = append(goinstall.Args, "-v")
  133. goinstall.Args = append(goinstall.Args, packages...)
  134. build.MustRun(goinstall)
  135. }
  136. func makeBuildFlags(commitHash string) (flags []string) {
  137. // Since Go 1.5, the separator char for link time assignments
  138. // is '=' and using ' ' prints a warning. However, Go < 1.5 does
  139. // not support using '='.
  140. sep := " "
  141. if runtime.Version() > "go1.5" || strings.Contains(runtime.Version(), "devel") {
  142. sep = "="
  143. }
  144. if os.Getenv("GO_OPENCL") != "" {
  145. flags = append(flags, "-tags", "opencl")
  146. }
  147. // Set gitCommit constant via link-time assignment. If this is a git checkout, we can
  148. // just get the current commit hash through git. Otherwise we fall back to the hash
  149. // that was passed as -gitcommit.
  150. //
  151. // -gitcommit is required for Debian package builds. The source package doesn't
  152. // contain .git but we still want to embed the commit hash into the packaged binary.
  153. // The hash is rendered into the debian/rules build script when the source package is
  154. // created.
  155. if _, err := os.Stat(filepath.Join(".git", "HEAD")); !os.IsNotExist(err) {
  156. if c := build.GitCommit(); c != "" {
  157. commitHash = c
  158. }
  159. }
  160. if commitHash != "" {
  161. flags = append(flags, "-ldflags", "-X main.gitCommit"+sep+commitHash)
  162. }
  163. return flags
  164. }
  165. func goTool(subcmd string, args ...string) *exec.Cmd {
  166. gocmd := filepath.Join(runtime.GOROOT(), "bin", "go")
  167. cmd := exec.Command(gocmd, subcmd)
  168. cmd.Args = append(cmd.Args, args...)
  169. cmd.Env = []string{
  170. "GOPATH=" + build.GOPATH(),
  171. "GOBIN=" + GOBIN,
  172. }
  173. for _, e := range os.Environ() {
  174. if strings.HasPrefix(e, "GOPATH=") || strings.HasPrefix(e, "GOBIN=") {
  175. continue
  176. }
  177. cmd.Env = append(cmd.Env, e)
  178. }
  179. return cmd
  180. }
  181. // Running The Tests
  182. //
  183. // "tests" also includes static analysis tools such as vet.
  184. func doTest(cmdline []string) {
  185. var (
  186. vet = flag.Bool("vet", false, "Whether to run go vet")
  187. coverage = flag.Bool("coverage", false, "Whether to record code coverage")
  188. )
  189. flag.CommandLine.Parse(cmdline)
  190. packages := []string{"./..."}
  191. if len(flag.CommandLine.Args()) > 0 {
  192. packages = flag.CommandLine.Args()
  193. }
  194. // Run analysis tools before the tests.
  195. if *vet {
  196. build.MustRun(goTool("vet", packages...))
  197. }
  198. // Run the actual tests.
  199. gotest := goTool("test")
  200. if *coverage {
  201. gotest.Args = append(gotest.Args, "-covermode=atomic", "-cover")
  202. }
  203. gotest.Args = append(gotest.Args, packages...)
  204. build.MustRun(gotest)
  205. }
  206. // Release Packaging
  207. func doArchive(cmdline []string) {
  208. var (
  209. atype = flag.String("type", "zip", "Type of archive to write (zip|tar)")
  210. ext string
  211. )
  212. flag.CommandLine.Parse(cmdline)
  213. switch *atype {
  214. case "zip":
  215. ext = ".zip"
  216. case "tar":
  217. ext = ".tar.gz"
  218. default:
  219. log.Fatal("unknown archive type: ", atype)
  220. }
  221. base := makeArchiveBasename()
  222. if err := build.WriteArchive("geth-"+base, ext, gethArchiveFiles); err != nil {
  223. log.Fatal(err)
  224. }
  225. if err := build.WriteArchive("geth-alltools-"+base, ext, allToolsArchiveFiles); err != nil {
  226. log.Fatal(err)
  227. }
  228. }
  229. func makeArchiveBasename() string {
  230. // date := time.Now().UTC().Format("200601021504")
  231. platform := runtime.GOOS + "-" + runtime.GOARCH
  232. archive := platform + "-" + build.VERSION()
  233. if commit := build.GitCommit(); commit != "" {
  234. archive += "-" + commit[:8]
  235. }
  236. return archive
  237. }
  238. // Debian Packaging
  239. // CLI entry point for Travis CI.
  240. func doTravisDebianSource(cmdline []string) {
  241. flag.CommandLine.Parse(cmdline)
  242. // Package only whitelisted branches.
  243. switch {
  244. case os.Getenv("TRAVIS_REPO_SLUG") != "ethereum/go-ethereum":
  245. log.Printf("skipping because this is a fork build")
  246. return
  247. case os.Getenv("TRAVIS_PULL_REQUEST") != "false":
  248. log.Printf("skipping because this is a PR build")
  249. return
  250. case os.Getenv("TRAVIS_BRANCH") != "develop" && !strings.HasPrefix(os.Getenv("TRAVIS_TAG"), "v1."):
  251. log.Printf("skipping because branch %q tag %q is not on the whitelist",
  252. os.Getenv("TRAVIS_BRANCH"),
  253. os.Getenv("TRAVIS_TAG"))
  254. return
  255. }
  256. // Import the signing key.
  257. if b64key := os.Getenv("PPA_SIGNING_KEY"); b64key != "" {
  258. key, err := base64.StdEncoding.DecodeString(b64key)
  259. if err != nil {
  260. log.Fatal("invalid base64 PPA_SIGNING_KEY")
  261. }
  262. gpg := exec.Command("gpg", "--import")
  263. gpg.Stdin = bytes.NewReader(key)
  264. build.MustRun(gpg)
  265. }
  266. // Assign unstable status to non-tag builds.
  267. unstable := "true"
  268. if os.Getenv("TRAVIS_BRANCH") != "develop" && os.Getenv("TRAVIS_TAG") != "" {
  269. unstable = "false"
  270. }
  271. doDebianSource([]string{
  272. "-signer", "Felix Lange (Geth CI Testing Key) <fjl@twurst.com>",
  273. "-buildnum", os.Getenv("TRAVIS_BUILD_NUMBER"),
  274. "-upload", "ppa:lp-fjl/geth-ci-testing",
  275. "-unstable", unstable,
  276. })
  277. }
  278. // CLI entry point for doing packaging locally.
  279. func doDebianSource(cmdline []string) {
  280. var (
  281. signer = flag.String("signer", "", `Signing key name, also used as package author`)
  282. upload = flag.String("upload", "", `Where to upload the source package (usually "ppa:ethereum/ethereum")`)
  283. buildnum = flag.String("buildnum", "", `Build number (included in version)`)
  284. unstable = flag.Bool("unstable", false, `Use package name suffix "-unstable"`)
  285. now = time.Now()
  286. )
  287. flag.CommandLine.Parse(cmdline)
  288. // Create the debian worktree in /tmp.
  289. tmpdir, err := ioutil.TempDir("", "eth-deb-build-")
  290. if err != nil {
  291. log.Fatal(err)
  292. }
  293. for _, distro := range debDistros {
  294. meta := newDebMetadata(distro, *signer, *buildnum, *unstable, now)
  295. pkgdir := stageDebianSource(tmpdir, meta)
  296. debuild := exec.Command("debuild", "-S", "-sa", "-us", "-uc")
  297. debuild.Dir = pkgdir
  298. build.MustRun(debuild)
  299. changes := fmt.Sprintf("%s_%s_source.changes", meta.Name(), meta.VersionString())
  300. changes = filepath.Join(tmpdir, changes)
  301. if *signer != "" {
  302. build.MustRunCommand("debsign", changes)
  303. }
  304. if *upload != "" {
  305. build.MustRunCommand("dput", *upload, changes)
  306. }
  307. }
  308. }
  309. type debExecutable struct {
  310. Name, Description string
  311. }
  312. type debMetadata struct {
  313. // go-ethereum version being built. Note that this
  314. // is not the debian package version. The package version
  315. // is constructed by VersionString.
  316. Version string
  317. Author string // "name <email>", also selects signing key
  318. Buildnum string // build number
  319. Distro, Commit, Time string
  320. Executables []debExecutable
  321. Unstable bool
  322. }
  323. func newDebMetadata(distro, author, buildnum string, unstable bool, t time.Time) debMetadata {
  324. if author == "" {
  325. // No signing key, use default author.
  326. author = "Ethereum Builds <fjl@ethereum.org>"
  327. }
  328. return debMetadata{
  329. Unstable: unstable,
  330. Author: author,
  331. Distro: distro,
  332. Commit: build.GitCommit(),
  333. Version: build.VERSION(),
  334. Buildnum: buildnum,
  335. Time: t.Format(time.RFC1123Z),
  336. Executables: debExecutables,
  337. }
  338. }
  339. // Name returns the name of the metapackage that depends
  340. // on all executable packages.
  341. func (meta debMetadata) Name() string {
  342. if meta.Unstable {
  343. return "ethereum-unstable"
  344. }
  345. return "ethereum"
  346. }
  347. // VersionString returns the debian version of the packages.
  348. func (meta debMetadata) VersionString() string {
  349. vsn := meta.Version
  350. if meta.Buildnum != "" {
  351. vsn += "+build" + meta.Buildnum
  352. }
  353. if meta.Distro != "" {
  354. vsn += "+" + meta.Distro
  355. }
  356. return vsn
  357. }
  358. // ExeList returns the list of all executable packages.
  359. func (meta debMetadata) ExeList() string {
  360. names := make([]string, len(meta.Executables))
  361. for i, e := range meta.Executables {
  362. names[i] = meta.ExeName(e)
  363. }
  364. return strings.Join(names, ", ")
  365. }
  366. // ExeName returns the package name of an executable package.
  367. func (meta debMetadata) ExeName(exe debExecutable) string {
  368. if meta.Unstable {
  369. return exe.Name + "-unstable"
  370. }
  371. return exe.Name
  372. }
  373. // ExeConflicts returns the content of the Conflicts field
  374. // for executable packages.
  375. func (meta debMetadata) ExeConflicts(exe debExecutable) string {
  376. if meta.Unstable {
  377. // Set up the conflicts list so that the *-unstable packages
  378. // cannot be installed alongside the regular version.
  379. //
  380. // https://www.debian.org/doc/debian-policy/ch-relationships.html
  381. // is very explicit about Conflicts: and says that Breaks: should
  382. // be preferred and the conflicting files should be handled via
  383. // alternates. We might do this eventually but using a conflict is
  384. // easier now.
  385. return "ethereum, " + exe.Name
  386. }
  387. return ""
  388. }
  389. func stageDebianSource(tmpdir string, meta debMetadata) (pkgdir string) {
  390. pkg := meta.Name() + "-" + meta.VersionString()
  391. pkgdir = filepath.Join(tmpdir, pkg)
  392. if err := os.Mkdir(pkgdir, 0755); err != nil {
  393. log.Fatal(err)
  394. }
  395. // Copy the source code.
  396. build.MustRunCommand("git", "checkout-index", "-a", "--prefix", pkgdir+string(filepath.Separator))
  397. // Put the debian build files in place.
  398. debian := filepath.Join(pkgdir, "debian")
  399. build.Render("build/deb.rules", filepath.Join(debian, "rules"), 0755, meta)
  400. build.Render("build/deb.changelog", filepath.Join(debian, "changelog"), 0644, meta)
  401. build.Render("build/deb.control", filepath.Join(debian, "control"), 0644, meta)
  402. build.Render("build/deb.copyright", filepath.Join(debian, "copyright"), 0644, meta)
  403. build.RenderString("8\n", filepath.Join(debian, "compat"), 0644, meta)
  404. build.RenderString("3.0 (native)\n", filepath.Join(debian, "source/format"), 0644, meta)
  405. for _, exe := range meta.Executables {
  406. install := filepath.Join(debian, exe.Name+".install")
  407. docs := filepath.Join(debian, exe.Name+".docs")
  408. build.Render("build/deb.install", install, 0644, exe)
  409. build.Render("build/deb.docs", docs, 0644, exe)
  410. }
  411. return pkgdir
  412. }
  413. // Cross compilation
  414. func doXgo(cmdline []string) {
  415. // Make sure xgo is available for cross compilation
  416. gogetxgo := goTool("get", "github.com/karalabe/xgo")
  417. build.MustRun(gogetxgo)
  418. // Execute the actual cross compilation
  419. pkg := cmdline[len(cmdline)-1]
  420. args := append(cmdline[:len(cmdline)-1], makeBuildFlags("")...)
  421. build.MustRun(xgoTool(append(args, pkg)...))
  422. }
  423. func xgoTool(args ...string) *exec.Cmd {
  424. cmd := exec.Command(filepath.Join(GOBIN, "xgo"), args...)
  425. cmd.Env = []string{
  426. "GOPATH=" + build.GOPATH(),
  427. "GOBIN=" + GOBIN,
  428. }
  429. for _, e := range os.Environ() {
  430. if strings.HasPrefix(e, "GOPATH=") || strings.HasPrefix(e, "GOBIN=") {
  431. continue
  432. }
  433. cmd.Env = append(cmd.Env, e)
  434. }
  435. return cmd
  436. }