build.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472
  1. // +build ignore
  2. package main
  3. import (
  4. "bytes"
  5. "crypto/md5"
  6. "encoding/json"
  7. "flag"
  8. "fmt"
  9. "io"
  10. "io/ioutil"
  11. "log"
  12. "os"
  13. "os/exec"
  14. "path/filepath"
  15. "regexp"
  16. "runtime"
  17. "strconv"
  18. "strings"
  19. "time"
  20. )
  21. var (
  22. versionRe = regexp.MustCompile(`-[0-9]{1,3}-g[0-9a-f]{5,10}`)
  23. goarch string
  24. goos string
  25. version string = "v1"
  26. // deb & rpm does not support semver so have to handle their version a little differently
  27. linuxPackageVersion string = "v1"
  28. linuxPackageIteration string = ""
  29. race bool
  30. workingDir string
  31. serverBinaryName string = "grafana-server"
  32. )
  33. const minGoVersion = 1.3
  34. func main() {
  35. log.SetOutput(os.Stdout)
  36. log.SetFlags(0)
  37. ensureGoPath()
  38. readVersionFromPackageJson()
  39. log.Printf("Version: %s, Linux Version: %s, Package Iteration: %s\n", version, linuxPackageVersion, linuxPackageIteration)
  40. flag.StringVar(&goarch, "goarch", runtime.GOARCH, "GOARCH")
  41. flag.StringVar(&goos, "goos", runtime.GOOS, "GOOS")
  42. flag.BoolVar(&race, "race", race, "Use race detector")
  43. flag.Parse()
  44. if flag.NArg() == 0 {
  45. log.Println("Usage: go run build.go build")
  46. return
  47. }
  48. workingDir, _ = os.Getwd()
  49. for _, cmd := range flag.Args() {
  50. switch cmd {
  51. case "setup":
  52. setup()
  53. case "build":
  54. pkg := "."
  55. clean()
  56. build(pkg, []string{})
  57. case "test":
  58. test("./pkg/...")
  59. grunt("test")
  60. case "package":
  61. //verifyGitRepoIsClean()
  62. grunt("release")
  63. createLinuxPackages()
  64. case "pkg-rpm":
  65. grunt("release")
  66. createRpmPackages()
  67. case "pkg-deb":
  68. grunt("release")
  69. createDebPackages()
  70. case "latest":
  71. makeLatestDistCopies()
  72. case "clean":
  73. clean()
  74. default:
  75. log.Fatalf("Unknown command %q", cmd)
  76. }
  77. }
  78. }
  79. func makeLatestDistCopies() {
  80. rpmIteration := "-1"
  81. if linuxPackageIteration != "" {
  82. rpmIteration = "-" + linuxPackageIteration
  83. }
  84. runError("cp", "dist/grafana_"+version+"_amd64.deb", "dist/grafana_latest_amd64.deb")
  85. runError("cp", "dist/grafana-"+linuxPackageVersion+rpmIteration+".x86_64.rpm", "dist/grafana-latest-1.x86_64.rpm")
  86. runError("cp", "dist/grafana-"+version+".linux-x64.tar.gz", "dist/grafana-latest.linux-x64.tar.gz")
  87. }
  88. func readVersionFromPackageJson() {
  89. reader, err := os.Open("package.json")
  90. if err != nil {
  91. log.Fatal("Failed to open package.json")
  92. return
  93. }
  94. defer reader.Close()
  95. jsonObj := map[string]interface{}{}
  96. jsonParser := json.NewDecoder(reader)
  97. if err := jsonParser.Decode(&jsonObj); err != nil {
  98. log.Fatal("Failed to decode package.json")
  99. }
  100. version = jsonObj["version"].(string)
  101. linuxPackageVersion = version
  102. linuxPackageIteration = ""
  103. // handle pre version stuff (deb / rpm does not support semver)
  104. parts := strings.Split(version, "-")
  105. if len(parts) > 1 {
  106. linuxPackageVersion = parts[0]
  107. linuxPackageIteration = parts[1]
  108. }
  109. }
  110. type linuxPackageOptions struct {
  111. packageType string
  112. homeDir string
  113. binPath string
  114. configDir string
  115. configFilePath string
  116. ldapFilePath string
  117. etcDefaultPath string
  118. etcDefaultFilePath string
  119. initdScriptFilePath string
  120. systemdServiceFilePath string
  121. postinstSrc string
  122. initdScriptSrc string
  123. defaultFileSrc string
  124. systemdFileSrc string
  125. depends []string
  126. }
  127. func createDebPackages() {
  128. createPackage(linuxPackageOptions{
  129. packageType: "deb",
  130. homeDir: "/usr/share/grafana",
  131. binPath: "/usr/sbin/grafana-server",
  132. configDir: "/etc/grafana",
  133. configFilePath: "/etc/grafana/grafana.ini",
  134. ldapFilePath: "/etc/grafana/ldap.toml",
  135. etcDefaultPath: "/etc/default",
  136. etcDefaultFilePath: "/etc/default/grafana-server",
  137. initdScriptFilePath: "/etc/init.d/grafana-server",
  138. systemdServiceFilePath: "/usr/lib/systemd/system/grafana-server.service",
  139. postinstSrc: "packaging/deb/control/postinst",
  140. initdScriptSrc: "packaging/deb/init.d/grafana-server",
  141. defaultFileSrc: "packaging/deb/default/grafana-server",
  142. systemdFileSrc: "packaging/deb/systemd/grafana-server.service",
  143. depends: []string{"adduser", "libfontconfig"},
  144. })
  145. }
  146. func createRpmPackages() {
  147. createPackage(linuxPackageOptions{
  148. packageType: "rpm",
  149. homeDir: "/usr/share/grafana",
  150. binPath: "/usr/sbin/grafana-server",
  151. configDir: "/etc/grafana",
  152. configFilePath: "/etc/grafana/grafana.ini",
  153. ldapFilePath: "/etc/grafana/ldap.toml",
  154. etcDefaultPath: "/etc/sysconfig",
  155. etcDefaultFilePath: "/etc/sysconfig/grafana-server",
  156. initdScriptFilePath: "/etc/init.d/grafana-server",
  157. systemdServiceFilePath: "/usr/lib/systemd/system/grafana-server.service",
  158. postinstSrc: "packaging/rpm/control/postinst",
  159. initdScriptSrc: "packaging/rpm/init.d/grafana-server",
  160. defaultFileSrc: "packaging/rpm/sysconfig/grafana-server",
  161. systemdFileSrc: "packaging/rpm/systemd/grafana-server.service",
  162. depends: []string{"initscripts", "fontconfig"},
  163. })
  164. }
  165. func createLinuxPackages() {
  166. createDebPackages()
  167. createRpmPackages()
  168. }
  169. func createPackage(options linuxPackageOptions) {
  170. packageRoot, _ := ioutil.TempDir("", "grafana-linux-pack")
  171. // create directories
  172. runPrint("mkdir", "-p", filepath.Join(packageRoot, options.homeDir))
  173. runPrint("mkdir", "-p", filepath.Join(packageRoot, options.configDir))
  174. runPrint("mkdir", "-p", filepath.Join(packageRoot, "/etc/init.d"))
  175. runPrint("mkdir", "-p", filepath.Join(packageRoot, options.etcDefaultPath))
  176. runPrint("mkdir", "-p", filepath.Join(packageRoot, "/usr/lib/systemd/system"))
  177. runPrint("mkdir", "-p", filepath.Join(packageRoot, "/usr/sbin"))
  178. // copy binary
  179. runPrint("cp", "-p", filepath.Join(workingDir, "tmp/bin/"+serverBinaryName), filepath.Join(packageRoot, options.binPath))
  180. // copy init.d script
  181. runPrint("cp", "-p", options.initdScriptSrc, filepath.Join(packageRoot, options.initdScriptFilePath))
  182. // copy environment var file
  183. runPrint("cp", "-p", options.defaultFileSrc, filepath.Join(packageRoot, options.etcDefaultFilePath))
  184. // copy systemd file
  185. runPrint("cp", "-p", options.systemdFileSrc, filepath.Join(packageRoot, options.systemdServiceFilePath))
  186. // copy release files
  187. runPrint("cp", "-a", filepath.Join(workingDir, "tmp")+"/.", filepath.Join(packageRoot, options.homeDir))
  188. // remove bin path
  189. runPrint("rm", "-rf", filepath.Join(packageRoot, options.homeDir, "bin"))
  190. // copy sample ini file to /etc/grafana
  191. runPrint("cp", "conf/sample.ini", filepath.Join(packageRoot, options.configFilePath))
  192. // copy sample ldap toml config file to /etc/grafana/ldap.toml
  193. runPrint("cp", "conf/ldap.toml", filepath.Join(packageRoot, options.ldapFilePath))
  194. args := []string{
  195. "-s", "dir",
  196. "--description", "Grafana",
  197. "-C", packageRoot,
  198. "--vendor", "Grafana",
  199. "--url", "http://grafana.org",
  200. "--license", "Apache 2.0",
  201. "--maintainer", "contact@grafana.org",
  202. "--config-files", options.configFilePath,
  203. "--config-files", options.ldapFilePath,
  204. "--config-files", options.initdScriptFilePath,
  205. "--config-files", options.etcDefaultFilePath,
  206. "--config-files", options.systemdServiceFilePath,
  207. "--after-install", options.postinstSrc,
  208. "--name", "grafana",
  209. "--version", linuxPackageVersion,
  210. "-p", "./dist",
  211. }
  212. if linuxPackageIteration != "" {
  213. args = append(args, "--iteration", linuxPackageIteration)
  214. }
  215. // add dependenciesj
  216. for _, dep := range options.depends {
  217. args = append(args, "--depends", dep)
  218. }
  219. args = append(args, ".")
  220. fmt.Println("Creating package: ", options.packageType)
  221. runPrint("fpm", append([]string{"-t", options.packageType}, args...)...)
  222. }
  223. func verifyGitRepoIsClean() {
  224. rs, err := runError("git", "ls-files", "--modified")
  225. if err != nil {
  226. log.Fatalf("Failed to check if git tree was clean, %v, %v\n", string(rs), err)
  227. return
  228. }
  229. count := len(string(rs))
  230. if count > 0 {
  231. log.Fatalf("Git repository has modified files, aborting")
  232. }
  233. log.Println("Git repository is clean")
  234. }
  235. func ensureGoPath() {
  236. if os.Getenv("GOPATH") == "" {
  237. cwd, err := os.Getwd()
  238. if err != nil {
  239. log.Fatal(err)
  240. }
  241. gopath := filepath.Clean(filepath.Join(cwd, "../../../../"))
  242. log.Println("GOPATH is", gopath)
  243. os.Setenv("GOPATH", gopath)
  244. }
  245. }
  246. func ChangeWorkingDir(dir string) {
  247. os.Chdir(dir)
  248. }
  249. func grunt(params ...string) {
  250. runPrint("./node_modules/grunt-cli/bin/grunt", params...)
  251. }
  252. func setup() {
  253. runPrint("go", "get", "-v", "github.com/tools/godep")
  254. runPrint("go", "get", "-v", "github.com/blang/semver")
  255. runPrint("go", "get", "-v", "github.com/mattn/go-sqlite3")
  256. runPrint("go", "install", "-v", "github.com/mattn/go-sqlite3")
  257. }
  258. func test(pkg string) {
  259. setBuildEnv()
  260. runPrint("go", "test", "-short", "-timeout", "60s", pkg)
  261. }
  262. func build(pkg string, tags []string) {
  263. binary := "./bin/" + serverBinaryName
  264. if goos == "windows" {
  265. binary += ".exe"
  266. }
  267. rmr(binary, binary+".md5")
  268. args := []string{"build", "-ldflags", ldflags()}
  269. if len(tags) > 0 {
  270. args = append(args, "-tags", strings.Join(tags, ","))
  271. }
  272. if race {
  273. args = append(args, "-race")
  274. }
  275. args = append(args, "-o", binary)
  276. args = append(args, pkg)
  277. setBuildEnv()
  278. runPrint("go", "version")
  279. runPrint("go", args...)
  280. // Create an md5 checksum of the binary, to be included in the archive for
  281. // automatic upgrades.
  282. err := md5File(binary)
  283. if err != nil {
  284. log.Fatal(err)
  285. }
  286. }
  287. func ldflags() string {
  288. var b bytes.Buffer
  289. b.WriteString("-w")
  290. b.WriteString(fmt.Sprintf(" -X main.version=%s", version))
  291. b.WriteString(fmt.Sprintf(" -X main.commit=%s", getGitSha()))
  292. b.WriteString(fmt.Sprintf(" -X main.buildstamp=%d", buildStamp()))
  293. return b.String()
  294. }
  295. func rmr(paths ...string) {
  296. for _, path := range paths {
  297. log.Println("rm -r", path)
  298. os.RemoveAll(path)
  299. }
  300. }
  301. func clean() {
  302. rmr("bin", "Godeps/_workspace/pkg", "Godeps/_workspace/bin")
  303. rmr("dist")
  304. rmr("tmp")
  305. rmr(filepath.Join(os.Getenv("GOPATH"), fmt.Sprintf("pkg/%s_%s/github.com/grafana", goos, goarch)))
  306. }
  307. func setBuildEnv() {
  308. os.Setenv("GOOS", goos)
  309. if strings.HasPrefix(goarch, "armv") {
  310. os.Setenv("GOARCH", "arm")
  311. os.Setenv("GOARM", goarch[4:])
  312. } else {
  313. os.Setenv("GOARCH", goarch)
  314. }
  315. if goarch == "386" {
  316. os.Setenv("GO386", "387")
  317. }
  318. wd, err := os.Getwd()
  319. if err != nil {
  320. log.Println("Warning: can't determine current dir:", err)
  321. log.Println("Build might not work as expected")
  322. }
  323. os.Setenv("GOPATH", fmt.Sprintf("%s%c%s", filepath.Join(wd, "Godeps", "_workspace"), os.PathListSeparator, os.Getenv("GOPATH")))
  324. log.Println("GOPATH=" + os.Getenv("GOPATH"))
  325. }
  326. func getGitSha() string {
  327. v, err := runError("git", "describe", "--always", "--dirty")
  328. if err != nil {
  329. return "unknown-dev"
  330. }
  331. v = versionRe.ReplaceAllFunc(v, func(s []byte) []byte {
  332. s[0] = '+'
  333. return s
  334. })
  335. return string(v)
  336. }
  337. func buildStamp() int64 {
  338. bs, err := runError("git", "show", "-s", "--format=%ct")
  339. if err != nil {
  340. return time.Now().Unix()
  341. }
  342. s, _ := strconv.ParseInt(string(bs), 10, 64)
  343. return s
  344. }
  345. func buildArch() string {
  346. os := goos
  347. if os == "darwin" {
  348. os = "macosx"
  349. }
  350. return fmt.Sprintf("%s-%s", os, goarch)
  351. }
  352. func run(cmd string, args ...string) []byte {
  353. bs, err := runError(cmd, args...)
  354. if err != nil {
  355. log.Println(cmd, strings.Join(args, " "))
  356. log.Println(string(bs))
  357. log.Fatal(err)
  358. }
  359. return bytes.TrimSpace(bs)
  360. }
  361. func runError(cmd string, args ...string) ([]byte, error) {
  362. ecmd := exec.Command(cmd, args...)
  363. bs, err := ecmd.CombinedOutput()
  364. if err != nil {
  365. return nil, err
  366. }
  367. return bytes.TrimSpace(bs), nil
  368. }
  369. func runPrint(cmd string, args ...string) {
  370. log.Println(cmd, strings.Join(args, " "))
  371. ecmd := exec.Command(cmd, args...)
  372. ecmd.Stdout = os.Stdout
  373. ecmd.Stderr = os.Stderr
  374. err := ecmd.Run()
  375. if err != nil {
  376. log.Fatal(err)
  377. }
  378. }
  379. func md5File(file string) error {
  380. fd, err := os.Open(file)
  381. if err != nil {
  382. return err
  383. }
  384. defer fd.Close()
  385. h := md5.New()
  386. _, err = io.Copy(h, fd)
  387. if err != nil {
  388. return err
  389. }
  390. out, err := os.Create(file + ".md5")
  391. if err != nil {
  392. return err
  393. }
  394. _, err = fmt.Fprintf(out, "%x\n", h.Sum(nil))
  395. if err != nil {
  396. return err
  397. }
  398. return out.Close()
  399. }