build.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470
  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", args...)
  279. // Create an md5 checksum of the binary, to be included in the archive for
  280. // automatic upgrades.
  281. err := md5File(binary)
  282. if err != nil {
  283. log.Fatal(err)
  284. }
  285. }
  286. func ldflags() string {
  287. var b bytes.Buffer
  288. b.WriteString("-w")
  289. b.WriteString(fmt.Sprintf(" -X main.version=%s", version))
  290. b.WriteString(fmt.Sprintf(" -X main.commit=%s", getGitSha()))
  291. b.WriteString(fmt.Sprintf(" -X main.buildstamp=%d", buildStamp()))
  292. return b.String()
  293. }
  294. func rmr(paths ...string) {
  295. for _, path := range paths {
  296. log.Println("rm -r", path)
  297. os.RemoveAll(path)
  298. }
  299. }
  300. func clean() {
  301. rmr("bin", "Godeps/_workspace/pkg", "Godeps/_workspace/bin")
  302. rmr("dist")
  303. rmr("tmp")
  304. rmr(filepath.Join(os.Getenv("GOPATH"), fmt.Sprintf("pkg/%s_%s/github.com/grafana", goos, goarch)))
  305. }
  306. func setBuildEnv() {
  307. os.Setenv("GOOS", goos)
  308. if strings.HasPrefix(goarch, "armv") {
  309. os.Setenv("GOARCH", "arm")
  310. os.Setenv("GOARM", goarch[4:])
  311. } else {
  312. os.Setenv("GOARCH", goarch)
  313. }
  314. if goarch == "386" {
  315. os.Setenv("GO386", "387")
  316. }
  317. wd, err := os.Getwd()
  318. if err != nil {
  319. log.Println("Warning: can't determine current dir:", err)
  320. log.Println("Build might not work as expected")
  321. }
  322. os.Setenv("GOPATH", fmt.Sprintf("%s%c%s", filepath.Join(wd, "Godeps", "_workspace"), os.PathListSeparator, os.Getenv("GOPATH")))
  323. log.Println("GOPATH=" + os.Getenv("GOPATH"))
  324. }
  325. func getGitSha() string {
  326. v, err := runError("git", "describe", "--always", "--dirty")
  327. if err != nil {
  328. return "unknown-dev"
  329. }
  330. v = versionRe.ReplaceAllFunc(v, func(s []byte) []byte {
  331. s[0] = '+'
  332. return s
  333. })
  334. return string(v)
  335. }
  336. func buildStamp() int64 {
  337. bs, err := runError("git", "show", "-s", "--format=%ct")
  338. if err != nil {
  339. return time.Now().Unix()
  340. }
  341. s, _ := strconv.ParseInt(string(bs), 10, 64)
  342. return s
  343. }
  344. func buildArch() string {
  345. os := goos
  346. if os == "darwin" {
  347. os = "macosx"
  348. }
  349. return fmt.Sprintf("%s-%s", os, goarch)
  350. }
  351. func run(cmd string, args ...string) []byte {
  352. bs, err := runError(cmd, args...)
  353. if err != nil {
  354. log.Println(cmd, strings.Join(args, " "))
  355. log.Println(string(bs))
  356. log.Fatal(err)
  357. }
  358. return bytes.TrimSpace(bs)
  359. }
  360. func runError(cmd string, args ...string) ([]byte, error) {
  361. ecmd := exec.Command(cmd, args...)
  362. bs, err := ecmd.CombinedOutput()
  363. if err != nil {
  364. return nil, err
  365. }
  366. return bytes.TrimSpace(bs), nil
  367. }
  368. func runPrint(cmd string, args ...string) {
  369. log.Println(cmd, strings.Join(args, " "))
  370. ecmd := exec.Command(cmd, args...)
  371. ecmd.Stdout = os.Stdout
  372. ecmd.Stderr = os.Stderr
  373. err := ecmd.Run()
  374. if err != nil {
  375. log.Fatal(err)
  376. }
  377. }
  378. func md5File(file string) error {
  379. fd, err := os.Open(file)
  380. if err != nil {
  381. return err
  382. }
  383. defer fd.Close()
  384. h := md5.New()
  385. _, err = io.Copy(h, fd)
  386. if err != nil {
  387. return err
  388. }
  389. out, err := os.Create(file + ".md5")
  390. if err != nil {
  391. return err
  392. }
  393. _, err = fmt.Fprintf(out, "%x\n", h.Sum(nil))
  394. if err != nil {
  395. return err
  396. }
  397. return out.Close()
  398. }