server.go 4.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171
  1. package main
  2. import (
  3. "context"
  4. "flag"
  5. "io/ioutil"
  6. "os"
  7. "path/filepath"
  8. "strconv"
  9. "time"
  10. "github.com/grafana/grafana/pkg/cmd/grafana-cli/logger"
  11. "github.com/grafana/grafana/pkg/services/provisioning"
  12. "golang.org/x/sync/errgroup"
  13. "github.com/grafana/grafana/pkg/api"
  14. "github.com/grafana/grafana/pkg/log"
  15. "github.com/grafana/grafana/pkg/login"
  16. "github.com/grafana/grafana/pkg/metrics"
  17. "github.com/grafana/grafana/pkg/models"
  18. "github.com/grafana/grafana/pkg/plugins"
  19. "github.com/grafana/grafana/pkg/services/alerting"
  20. "github.com/grafana/grafana/pkg/services/cleanup"
  21. "github.com/grafana/grafana/pkg/services/notifications"
  22. "github.com/grafana/grafana/pkg/services/search"
  23. "github.com/grafana/grafana/pkg/services/sqlstore"
  24. "github.com/grafana/grafana/pkg/setting"
  25. "github.com/grafana/grafana/pkg/social"
  26. "github.com/grafana/grafana/pkg/tracing"
  27. )
  28. func NewGrafanaServer() models.GrafanaServer {
  29. rootCtx, shutdownFn := context.WithCancel(context.Background())
  30. childRoutines, childCtx := errgroup.WithContext(rootCtx)
  31. return &GrafanaServerImpl{
  32. context: childCtx,
  33. shutdownFn: shutdownFn,
  34. childRoutines: childRoutines,
  35. log: log.New("server"),
  36. }
  37. }
  38. type GrafanaServerImpl struct {
  39. context context.Context
  40. shutdownFn context.CancelFunc
  41. childRoutines *errgroup.Group
  42. log log.Logger
  43. httpServer *api.HttpServer
  44. }
  45. func (g *GrafanaServerImpl) Start() {
  46. go listenToSystemSignals(g)
  47. g.initLogging()
  48. g.writePIDFile()
  49. initSql()
  50. metrics.Init(setting.Cfg)
  51. search.Init()
  52. login.Init()
  53. social.NewOAuthService()
  54. plugins.Init()
  55. if err := provisioning.StartUp(setting.DatasourcesPath); err != nil {
  56. logger.Error("Failed to provision Grafana from config", "error", err)
  57. g.Shutdown(1, "Startup failed")
  58. return
  59. }
  60. closer, err := tracing.Init(setting.Cfg)
  61. if err != nil {
  62. g.log.Error("Tracing settings is not valid", "error", err)
  63. g.Shutdown(1, "Startup failed")
  64. return
  65. }
  66. defer closer.Close()
  67. // init alerting
  68. if setting.AlertingEnabled && setting.ExecuteAlerts {
  69. engine := alerting.NewEngine()
  70. g.childRoutines.Go(func() error { return engine.Run(g.context) })
  71. }
  72. // cleanup service
  73. cleanUpService := cleanup.NewCleanUpService()
  74. g.childRoutines.Go(func() error { return cleanUpService.Run(g.context) })
  75. if err = notifications.Init(); err != nil {
  76. g.log.Error("Notification service failed to initialize", "error", err)
  77. g.Shutdown(1, "Startup failed")
  78. return
  79. }
  80. g.startHttpServer()
  81. }
  82. func initSql() {
  83. sqlstore.NewEngine()
  84. sqlstore.EnsureAdminUser()
  85. }
  86. func (g *GrafanaServerImpl) initLogging() {
  87. err := setting.NewConfigContext(&setting.CommandLineArgs{
  88. Config: *configFile,
  89. HomePath: *homePath,
  90. Args: flag.Args(),
  91. })
  92. if err != nil {
  93. g.log.Error(err.Error())
  94. os.Exit(1)
  95. }
  96. g.log.Info("Starting Grafana", "version", version, "commit", commit, "compiled", time.Unix(setting.BuildStamp, 0))
  97. setting.LogConfigurationInfo()
  98. }
  99. func (g *GrafanaServerImpl) startHttpServer() {
  100. g.httpServer = api.NewHttpServer()
  101. err := g.httpServer.Start(g.context)
  102. if err != nil {
  103. g.log.Error("Fail to start server", "error", err)
  104. g.Shutdown(1, "Startup failed")
  105. return
  106. }
  107. }
  108. func (g *GrafanaServerImpl) Shutdown(code int, reason string) {
  109. g.log.Info("Shutdown started", "code", code, "reason", reason)
  110. err := g.httpServer.Shutdown(g.context)
  111. if err != nil {
  112. g.log.Error("Failed to shutdown server", "error", err)
  113. }
  114. g.shutdownFn()
  115. err = g.childRoutines.Wait()
  116. g.log.Info("Shutdown completed", "reason", err)
  117. log.Close()
  118. os.Exit(code)
  119. }
  120. func (g *GrafanaServerImpl) writePIDFile() {
  121. if *pidFile == "" {
  122. return
  123. }
  124. // Ensure the required directory structure exists.
  125. err := os.MkdirAll(filepath.Dir(*pidFile), 0700)
  126. if err != nil {
  127. g.log.Error("Failed to verify pid directory", "error", err)
  128. os.Exit(1)
  129. }
  130. // Retrieve the PID and write it.
  131. pid := strconv.Itoa(os.Getpid())
  132. if err := ioutil.WriteFile(*pidFile, []byte(pid), 0644); err != nil {
  133. g.log.Error("Failed to write pidfile", "error", err)
  134. os.Exit(1)
  135. }
  136. g.log.Info("Writing PID file", "path", *pidFile, "pid", pid)
  137. }