web.go 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. // Copyright 2014 Unknwon
  2. // Copyright 2014 Torkel Ödegaard
  3. package cmd
  4. import (
  5. "fmt"
  6. "net/http"
  7. "path"
  8. "github.com/Unknwon/macaron"
  9. "github.com/codegangsta/cli"
  10. "github.com/macaron-contrib/session"
  11. "github.com/torkelo/grafana-pro/pkg/log"
  12. "github.com/torkelo/grafana-pro/pkg/middleware"
  13. "github.com/torkelo/grafana-pro/pkg/routes"
  14. "github.com/torkelo/grafana-pro/pkg/setting"
  15. "github.com/torkelo/grafana-pro/pkg/social"
  16. "github.com/torkelo/grafana-pro/pkg/stores/rethink"
  17. "github.com/torkelo/grafana-pro/pkg/stores/sqlstore"
  18. )
  19. var CmdWeb = cli.Command{
  20. Name: "web",
  21. Usage: "Start Grafana Pro web server",
  22. Description: `Start Grafana Pro server`,
  23. Action: runWeb,
  24. Flags: []cli.Flag{},
  25. }
  26. func newMacaron() *macaron.Macaron {
  27. m := macaron.New()
  28. m.Use(middleware.Logger())
  29. m.Use(macaron.Recovery())
  30. mapStatic(m, "public", "public")
  31. mapStatic(m, "public/app", "app")
  32. mapStatic(m, "public/img", "img")
  33. m.Use(session.Sessioner(session.Options{
  34. Provider: setting.SessionProvider,
  35. Config: *setting.SessionConfig,
  36. }))
  37. m.Use(macaron.Renderer(macaron.RenderOptions{
  38. Directory: path.Join(setting.StaticRootPath, "views"),
  39. IndentJSON: macaron.Env != macaron.PROD,
  40. Delims: macaron.Delims{Left: "[[", Right: "]]"},
  41. }))
  42. m.Use(middleware.GetContextHandler())
  43. return m
  44. }
  45. func mapStatic(m *macaron.Macaron, dir string, prefix string) {
  46. m.Use(macaron.Static(
  47. path.Join(setting.StaticRootPath, dir),
  48. macaron.StaticOptions{
  49. SkipLogging: true,
  50. Prefix: prefix,
  51. },
  52. ))
  53. }
  54. func runWeb(*cli.Context) {
  55. setting.NewConfigContext()
  56. setting.InitServices()
  57. rethink.Init()
  58. social.NewOAuthService()
  59. // init database
  60. sqlstore.LoadModelsConfig()
  61. if err := sqlstore.NewEngine(); err != nil {
  62. log.Fatal(4, "fail to initialize orm engine: %v", err)
  63. }
  64. log.Info("Starting Grafana-Pro v.1-alpha")
  65. m := newMacaron()
  66. routes.Register(m)
  67. var err error
  68. listenAddr := fmt.Sprintf("%s:%s", setting.HttpAddr, setting.HttpPort)
  69. log.Info("Listen: %v://%s%s", setting.Protocol, listenAddr, setting.AppSubUrl)
  70. switch setting.Protocol {
  71. case setting.HTTP:
  72. err = http.ListenAndServe(listenAddr, m)
  73. case setting.HTTPS:
  74. err = http.ListenAndServeTLS(listenAddr, setting.CertFile, setting.KeyFile, m)
  75. default:
  76. log.Fatal(4, "Invalid protocol: %s", setting.Protocol)
  77. }
  78. if err != nil {
  79. log.Fatal(4, "Fail to start server: %v", err)
  80. }
  81. }