build.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646
  1. // +build ignore
  2. package main
  3. import (
  4. "bytes"
  5. "crypto/md5"
  6. "crypto/sha256"
  7. "encoding/json"
  8. "flag"
  9. "fmt"
  10. "io"
  11. "io/ioutil"
  12. "log"
  13. "os"
  14. "os/exec"
  15. "path"
  16. "path/filepath"
  17. "runtime"
  18. "strconv"
  19. "strings"
  20. "time"
  21. )
  22. const (
  23. windows = "windows"
  24. linux = "linux"
  25. )
  26. var (
  27. //versionRe = regexp.MustCompile(`-[0-9]{1,3}-g[0-9a-f]{5,10}`)
  28. goarch string
  29. goos string
  30. gocc string
  31. cgo bool
  32. pkgArch string
  33. version string = "v1"
  34. // deb & rpm does not support semver so have to handle their version a little differently
  35. linuxPackageVersion string = "v1"
  36. linuxPackageIteration string = ""
  37. race bool
  38. phjsToRelease string
  39. workingDir string
  40. includeBuildId bool = true
  41. buildId string = "0"
  42. binaries []string = []string{"grafana-server", "grafana-cli"}
  43. isDev bool = false
  44. enterprise bool = false
  45. )
  46. func main() {
  47. log.SetOutput(os.Stdout)
  48. log.SetFlags(0)
  49. ensureGoPath()
  50. var buildIdRaw string
  51. flag.StringVar(&goarch, "goarch", runtime.GOARCH, "GOARCH")
  52. flag.StringVar(&goos, "goos", runtime.GOOS, "GOOS")
  53. flag.StringVar(&gocc, "cc", "", "CC")
  54. flag.BoolVar(&cgo, "cgo-enabled", cgo, "Enable cgo")
  55. flag.StringVar(&pkgArch, "pkg-arch", "", "PKG ARCH")
  56. flag.StringVar(&phjsToRelease, "phjs", "", "PhantomJS binary")
  57. flag.BoolVar(&race, "race", race, "Use race detector")
  58. flag.BoolVar(&includeBuildId, "includeBuildId", includeBuildId, "IncludeBuildId in package name")
  59. flag.BoolVar(&enterprise, "enterprise", enterprise, "Build enterprise version of Grafana")
  60. flag.StringVar(&buildIdRaw, "buildId", "0", "Build ID from CI system")
  61. flag.BoolVar(&isDev, "dev", isDev, "optimal for development, skips certain steps")
  62. flag.Parse()
  63. buildId = shortenBuildId(buildIdRaw)
  64. readVersionFromPackageJson()
  65. if pkgArch == "" {
  66. pkgArch = goarch
  67. }
  68. log.Printf("Version: %s, Linux Version: %s, Package Iteration: %s\n", version, linuxPackageVersion, linuxPackageIteration)
  69. if flag.NArg() == 0 {
  70. log.Println("Usage: go run build.go build")
  71. return
  72. }
  73. workingDir, _ = os.Getwd()
  74. for _, cmd := range flag.Args() {
  75. switch cmd {
  76. case "setup":
  77. setup()
  78. case "build-srv":
  79. clean()
  80. build("grafana-server", "./pkg/cmd/grafana-server", []string{})
  81. case "build-cli":
  82. clean()
  83. build("grafana-cli", "./pkg/cmd/grafana-cli", []string{})
  84. case "build-server":
  85. clean()
  86. build("grafana-server", "./pkg/cmd/grafana-server", []string{})
  87. case "build":
  88. //clean()
  89. for _, binary := range binaries {
  90. build(binary, "./pkg/cmd/"+binary, []string{})
  91. }
  92. case "build-frontend":
  93. grunt(gruntBuildArg("build")...)
  94. case "test":
  95. test("./pkg/...")
  96. grunt("test")
  97. case "package":
  98. grunt(gruntBuildArg("build")...)
  99. grunt(gruntBuildArg("package")...)
  100. if goos == linux {
  101. createLinuxPackages()
  102. }
  103. case "package-only":
  104. grunt(gruntBuildArg("package")...)
  105. if goos == linux {
  106. createLinuxPackages()
  107. }
  108. case "pkg-rpm":
  109. grunt(gruntBuildArg("release")...)
  110. createRpmPackages()
  111. case "pkg-deb":
  112. grunt(gruntBuildArg("release")...)
  113. createDebPackages()
  114. case "sha-dist":
  115. shaFilesInDist()
  116. case "latest":
  117. makeLatestDistCopies()
  118. case "clean":
  119. clean()
  120. default:
  121. log.Fatalf("Unknown command %q", cmd)
  122. }
  123. }
  124. }
  125. func makeLatestDistCopies() {
  126. files, err := ioutil.ReadDir("dist")
  127. if err != nil {
  128. log.Fatalf("failed to create latest copies. Cannot read from /dist")
  129. }
  130. latestMapping := map[string]string{
  131. "_amd64.deb": "dist/grafana_latest_amd64.deb",
  132. ".x86_64.rpm": "dist/grafana-latest-1.x86_64.rpm",
  133. ".linux-amd64.tar.gz": "dist/grafana-latest.linux-x64.tar.gz",
  134. }
  135. for _, file := range files {
  136. for extension, fullName := range latestMapping {
  137. if strings.HasSuffix(file.Name(), extension) {
  138. runError("cp", path.Join("dist", file.Name()), fullName)
  139. }
  140. }
  141. }
  142. }
  143. func readVersionFromPackageJson() {
  144. reader, err := os.Open("package.json")
  145. if err != nil {
  146. log.Fatal("Failed to open package.json")
  147. return
  148. }
  149. defer reader.Close()
  150. jsonObj := map[string]interface{}{}
  151. jsonParser := json.NewDecoder(reader)
  152. if err := jsonParser.Decode(&jsonObj); err != nil {
  153. log.Fatal("Failed to decode package.json")
  154. }
  155. version = jsonObj["version"].(string)
  156. linuxPackageVersion = version
  157. linuxPackageIteration = ""
  158. // handle pre version stuff (deb / rpm does not support semver)
  159. parts := strings.Split(version, "-")
  160. if len(parts) > 1 {
  161. linuxPackageVersion = parts[0]
  162. linuxPackageIteration = parts[1]
  163. }
  164. // add timestamp to iteration
  165. if includeBuildId {
  166. if buildId != "0" {
  167. linuxPackageIteration = fmt.Sprintf("%s%s", buildId, linuxPackageIteration)
  168. } else {
  169. linuxPackageIteration = fmt.Sprintf("%d%s", time.Now().Unix(), linuxPackageIteration)
  170. }
  171. }
  172. }
  173. type linuxPackageOptions struct {
  174. packageType string
  175. homeDir string
  176. binPath string
  177. serverBinPath string
  178. cliBinPath string
  179. configDir string
  180. ldapFilePath string
  181. etcDefaultPath string
  182. etcDefaultFilePath string
  183. initdScriptFilePath string
  184. systemdServiceFilePath string
  185. postinstSrc string
  186. initdScriptSrc string
  187. defaultFileSrc string
  188. systemdFileSrc string
  189. depends []string
  190. }
  191. func createDebPackages() {
  192. previousPkgArch := pkgArch
  193. if pkgArch == "armv7" {
  194. pkgArch = "armhf"
  195. }
  196. createPackage(linuxPackageOptions{
  197. packageType: "deb",
  198. homeDir: "/usr/share/grafana",
  199. binPath: "/usr/sbin",
  200. configDir: "/etc/grafana",
  201. etcDefaultPath: "/etc/default",
  202. etcDefaultFilePath: "/etc/default/grafana-server",
  203. initdScriptFilePath: "/etc/init.d/grafana-server",
  204. systemdServiceFilePath: "/usr/lib/systemd/system/grafana-server.service",
  205. postinstSrc: "packaging/deb/control/postinst",
  206. initdScriptSrc: "packaging/deb/init.d/grafana-server",
  207. defaultFileSrc: "packaging/deb/default/grafana-server",
  208. systemdFileSrc: "packaging/deb/systemd/grafana-server.service",
  209. depends: []string{"adduser", "libfontconfig"},
  210. })
  211. pkgArch = previousPkgArch
  212. }
  213. func createRpmPackages() {
  214. previousPkgArch := pkgArch
  215. switch {
  216. case pkgArch == "armv7":
  217. pkgArch = "armhfp"
  218. case pkgArch == "arm64":
  219. pkgArch = "aarch64"
  220. }
  221. createPackage(linuxPackageOptions{
  222. packageType: "rpm",
  223. homeDir: "/usr/share/grafana",
  224. binPath: "/usr/sbin",
  225. configDir: "/etc/grafana",
  226. etcDefaultPath: "/etc/sysconfig",
  227. etcDefaultFilePath: "/etc/sysconfig/grafana-server",
  228. initdScriptFilePath: "/etc/init.d/grafana-server",
  229. systemdServiceFilePath: "/usr/lib/systemd/system/grafana-server.service",
  230. postinstSrc: "packaging/rpm/control/postinst",
  231. initdScriptSrc: "packaging/rpm/init.d/grafana-server",
  232. defaultFileSrc: "packaging/rpm/sysconfig/grafana-server",
  233. systemdFileSrc: "packaging/rpm/systemd/grafana-server.service",
  234. depends: []string{"/sbin/service", "fontconfig", "freetype", "urw-fonts"},
  235. })
  236. pkgArch = previousPkgArch
  237. }
  238. func createLinuxPackages() {
  239. createDebPackages()
  240. createRpmPackages()
  241. }
  242. func createPackage(options linuxPackageOptions) {
  243. packageRoot, _ := ioutil.TempDir("", "grafana-linux-pack")
  244. // create directories
  245. runPrint("mkdir", "-p", filepath.Join(packageRoot, options.homeDir))
  246. runPrint("mkdir", "-p", filepath.Join(packageRoot, options.configDir))
  247. runPrint("mkdir", "-p", filepath.Join(packageRoot, "/etc/init.d"))
  248. runPrint("mkdir", "-p", filepath.Join(packageRoot, options.etcDefaultPath))
  249. runPrint("mkdir", "-p", filepath.Join(packageRoot, "/usr/lib/systemd/system"))
  250. runPrint("mkdir", "-p", filepath.Join(packageRoot, "/usr/sbin"))
  251. // copy binary
  252. for _, binary := range binaries {
  253. runPrint("cp", "-p", filepath.Join(workingDir, "tmp/bin/"+binary), filepath.Join(packageRoot, "/usr/sbin/"+binary))
  254. }
  255. // copy init.d script
  256. runPrint("cp", "-p", options.initdScriptSrc, filepath.Join(packageRoot, options.initdScriptFilePath))
  257. // copy environment var file
  258. runPrint("cp", "-p", options.defaultFileSrc, filepath.Join(packageRoot, options.etcDefaultFilePath))
  259. // copy systemd file
  260. runPrint("cp", "-p", options.systemdFileSrc, filepath.Join(packageRoot, options.systemdServiceFilePath))
  261. // copy release files
  262. runPrint("cp", "-a", filepath.Join(workingDir, "tmp")+"/.", filepath.Join(packageRoot, options.homeDir))
  263. // remove bin path
  264. runPrint("rm", "-rf", filepath.Join(packageRoot, options.homeDir, "bin"))
  265. args := []string{
  266. "-s", "dir",
  267. "--description", "Grafana",
  268. "-C", packageRoot,
  269. "--url", "https://grafana.com",
  270. "--maintainer", "contact@grafana.com",
  271. "--config-files", options.initdScriptFilePath,
  272. "--config-files", options.etcDefaultFilePath,
  273. "--config-files", options.systemdServiceFilePath,
  274. "--after-install", options.postinstSrc,
  275. "--version", linuxPackageVersion,
  276. "-p", "./dist",
  277. }
  278. name := "grafana"
  279. if enterprise {
  280. name += "-enterprise"
  281. args = append(args, "--replaces", "grafana")
  282. }
  283. args = append(args, "--name", name)
  284. description := "Grafana"
  285. if enterprise {
  286. description += " Enterprise"
  287. }
  288. args = append(args, "--vendor", description)
  289. if !enterprise {
  290. args = append(args, "--license", "\"Apache 2.0\"")
  291. }
  292. if options.packageType == "rpm" {
  293. args = append(args, "--rpm-posttrans", "packaging/rpm/control/posttrans")
  294. }
  295. if options.packageType == "deb" {
  296. args = append(args, "--deb-no-default-config-files")
  297. }
  298. if pkgArch != "" {
  299. args = append(args, "-a", pkgArch)
  300. }
  301. if linuxPackageIteration != "" {
  302. args = append(args, "--iteration", linuxPackageIteration)
  303. }
  304. // add dependenciesj
  305. for _, dep := range options.depends {
  306. args = append(args, "--depends", dep)
  307. }
  308. args = append(args, ".")
  309. fmt.Println("Creating package: ", options.packageType)
  310. runPrint("fpm", append([]string{"-t", options.packageType}, args...)...)
  311. }
  312. func ensureGoPath() {
  313. if os.Getenv("GOPATH") == "" {
  314. cwd, err := os.Getwd()
  315. if err != nil {
  316. log.Fatal(err)
  317. }
  318. gopath := filepath.Clean(filepath.Join(cwd, "../../../../"))
  319. log.Println("GOPATH is", gopath)
  320. os.Setenv("GOPATH", gopath)
  321. }
  322. }
  323. func grunt(params ...string) {
  324. if runtime.GOOS == windows {
  325. runPrint(`.\node_modules\.bin\grunt`, params...)
  326. } else {
  327. runPrint("./node_modules/.bin/grunt", params...)
  328. }
  329. }
  330. func gruntBuildArg(task string) []string {
  331. args := []string{task}
  332. if includeBuildId {
  333. args = append(args, fmt.Sprintf("--pkgVer=%v-%v", linuxPackageVersion, linuxPackageIteration))
  334. } else {
  335. args = append(args, fmt.Sprintf("--pkgVer=%v", version))
  336. }
  337. if pkgArch != "" {
  338. args = append(args, fmt.Sprintf("--arch=%v", pkgArch))
  339. }
  340. if phjsToRelease != "" {
  341. args = append(args, fmt.Sprintf("--phjsToRelease=%v", phjsToRelease))
  342. }
  343. if enterprise {
  344. args = append(args, "--enterprise")
  345. }
  346. args = append(args, fmt.Sprintf("--platform=%v", goos))
  347. return args
  348. }
  349. func setup() {
  350. runPrint("go", "get", "-v", "github.com/golang/dep")
  351. runPrint("go", "install", "-v", "./pkg/cmd/grafana-server")
  352. }
  353. func test(pkg string) {
  354. setBuildEnv()
  355. runPrint("go", "test", "-short", "-timeout", "60s", pkg)
  356. }
  357. func build(binaryName, pkg string, tags []string) {
  358. binary := fmt.Sprintf("./bin/%s-%s/%s", goos, goarch, binaryName)
  359. if isDev {
  360. //don't include os and arch in output path in dev environment
  361. binary = fmt.Sprintf("./bin/%s", binaryName)
  362. }
  363. if goos == windows {
  364. binary += ".exe"
  365. }
  366. if !isDev {
  367. rmr(binary, binary+".md5")
  368. }
  369. args := []string{"build", "-ldflags", ldflags()}
  370. if len(tags) > 0 {
  371. args = append(args, "-tags", strings.Join(tags, ","))
  372. }
  373. if race {
  374. args = append(args, "-race")
  375. }
  376. args = append(args, "-o", binary)
  377. args = append(args, pkg)
  378. if !isDev {
  379. setBuildEnv()
  380. runPrint("go", "version")
  381. fmt.Printf("Targeting %s/%s\n", goos, goarch)
  382. }
  383. runPrint("go", args...)
  384. if !isDev {
  385. // Create an md5 checksum of the binary, to be included in the archive for
  386. // automatic upgrades.
  387. err := md5File(binary)
  388. if err != nil {
  389. log.Fatal(err)
  390. }
  391. }
  392. }
  393. func ldflags() string {
  394. var b bytes.Buffer
  395. b.WriteString("-w")
  396. b.WriteString(fmt.Sprintf(" -X main.version=%s", version))
  397. b.WriteString(fmt.Sprintf(" -X main.commit=%s", getGitSha()))
  398. b.WriteString(fmt.Sprintf(" -X main.buildstamp=%d", buildStamp()))
  399. b.WriteString(fmt.Sprintf(" -X main.buildBranch=%s", getGitBranch()))
  400. return b.String()
  401. }
  402. func rmr(paths ...string) {
  403. for _, path := range paths {
  404. log.Println("rm -r", path)
  405. os.RemoveAll(path)
  406. }
  407. }
  408. func clean() {
  409. if isDev {
  410. return
  411. }
  412. rmr("dist")
  413. rmr("tmp")
  414. rmr(filepath.Join(os.Getenv("GOPATH"), fmt.Sprintf("pkg/%s_%s/github.com/grafana", goos, goarch)))
  415. }
  416. func setBuildEnv() {
  417. os.Setenv("GOOS", goos)
  418. if goos == windows {
  419. // require windows >=7
  420. os.Setenv("CGO_CFLAGS", "-D_WIN32_WINNT=0x0601")
  421. }
  422. if goarch != "amd64" || goos != linux {
  423. // needed for all other archs
  424. cgo = true
  425. }
  426. if strings.HasPrefix(goarch, "armv") {
  427. os.Setenv("GOARCH", "arm")
  428. os.Setenv("GOARM", goarch[4:])
  429. } else {
  430. os.Setenv("GOARCH", goarch)
  431. }
  432. if goarch == "386" {
  433. os.Setenv("GO386", "387")
  434. }
  435. if cgo {
  436. os.Setenv("CGO_ENABLED", "1")
  437. }
  438. if gocc != "" {
  439. os.Setenv("CC", gocc)
  440. }
  441. }
  442. func getGitBranch() string {
  443. v, err := runError("git", "rev-parse", "--abbrev-ref", "HEAD")
  444. if err != nil {
  445. return "master"
  446. }
  447. return string(v)
  448. }
  449. func getGitSha() string {
  450. v, err := runError("git", "rev-parse", "--short", "HEAD")
  451. if err != nil {
  452. return "unknown-dev"
  453. }
  454. return string(v)
  455. }
  456. func buildStamp() int64 {
  457. bs, err := runError("git", "show", "-s", "--format=%ct")
  458. if err != nil {
  459. return time.Now().Unix()
  460. }
  461. s, _ := strconv.ParseInt(string(bs), 10, 64)
  462. return s
  463. }
  464. func runError(cmd string, args ...string) ([]byte, error) {
  465. ecmd := exec.Command(cmd, args...)
  466. bs, err := ecmd.CombinedOutput()
  467. if err != nil {
  468. return nil, err
  469. }
  470. return bytes.TrimSpace(bs), nil
  471. }
  472. func runPrint(cmd string, args ...string) {
  473. log.Println(cmd, strings.Join(args, " "))
  474. ecmd := exec.Command(cmd, args...)
  475. ecmd.Stdout = os.Stdout
  476. ecmd.Stderr = os.Stderr
  477. err := ecmd.Run()
  478. if err != nil {
  479. log.Fatal(err)
  480. }
  481. }
  482. func md5File(file string) error {
  483. fd, err := os.Open(file)
  484. if err != nil {
  485. return err
  486. }
  487. defer fd.Close()
  488. h := md5.New()
  489. _, err = io.Copy(h, fd)
  490. if err != nil {
  491. return err
  492. }
  493. out, err := os.Create(file + ".md5")
  494. if err != nil {
  495. return err
  496. }
  497. _, err = fmt.Fprintf(out, "%x\n", h.Sum(nil))
  498. if err != nil {
  499. return err
  500. }
  501. return out.Close()
  502. }
  503. func shaFilesInDist() {
  504. filepath.Walk("./dist", func(path string, f os.FileInfo, err error) error {
  505. if path == "./dist" {
  506. return nil
  507. }
  508. if !strings.Contains(path, ".sha256") {
  509. err := shaFile(path)
  510. if err != nil {
  511. log.Printf("Failed to create sha file. error: %v\n", err)
  512. }
  513. }
  514. return nil
  515. })
  516. }
  517. func shaFile(file string) error {
  518. fd, err := os.Open(file)
  519. if err != nil {
  520. return err
  521. }
  522. defer fd.Close()
  523. h := sha256.New()
  524. _, err = io.Copy(h, fd)
  525. if err != nil {
  526. return err
  527. }
  528. out, err := os.Create(file + ".sha256")
  529. if err != nil {
  530. return err
  531. }
  532. _, err = fmt.Fprintf(out, "%x\n", h.Sum(nil))
  533. if err != nil {
  534. return err
  535. }
  536. return out.Close()
  537. }
  538. func shortenBuildId(buildId string) string {
  539. buildId = strings.Replace(buildId, "-", "", -1)
  540. if len(buildId) < 9 {
  541. return buildId
  542. }
  543. return buildId[0:8]
  544. }