build.go 12 KB

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