ci.go 14 KB

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