server.go 4.8 KB

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