server.go 4.5 KB

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