server.go 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195
  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/services/provisioning"
  13. "golang.org/x/sync/errgroup"
  14. "github.com/grafana/grafana/pkg/api"
  15. "github.com/grafana/grafana/pkg/log"
  16. "github.com/grafana/grafana/pkg/login"
  17. "github.com/grafana/grafana/pkg/metrics"
  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() *GrafanaServerImpl {
  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() error {
  46. g.initLogging()
  47. g.writePIDFile()
  48. initSql()
  49. metrics.Init(setting.Cfg)
  50. search.Init()
  51. login.Init()
  52. social.NewOAuthService()
  53. pluginCloser, err := plugins.Init()
  54. if err != nil {
  55. g.log.Error("failed to start plugins", "error", err)
  56. g.Shutdown(1, "Startup failed")
  57. }
  58. defer pluginCloser()
  59. if err := provisioning.Init(g.context, setting.HomePath, setting.Cfg); err != nil {
  60. return fmt.Errorf("Failed to provision Grafana from config. error: %v", err)
  61. }
  62. tracingCloser, err := tracing.Init(setting.Cfg)
  63. if err != nil {
  64. return fmt.Errorf("Tracing settings is not valid. error: %v", err)
  65. }
  66. defer tracingCloser.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. return fmt.Errorf("Notification service failed to initialize. error: %v", err)
  77. }
  78. sendSystemdNotification("READY=1")
  79. return g.startHttpServer()
  80. }
  81. func initSql() {
  82. sqlstore.NewEngine()
  83. sqlstore.EnsureAdminUser()
  84. }
  85. func (g *GrafanaServerImpl) initLogging() {
  86. err := setting.NewConfigContext(&setting.CommandLineArgs{
  87. Config: *configFile,
  88. HomePath: *homePath,
  89. Args: flag.Args(),
  90. })
  91. if err != nil {
  92. g.log.Error(err.Error())
  93. os.Exit(1)
  94. }
  95. g.log.Info("Starting Grafana", "version", version, "commit", commit, "compiled", time.Unix(setting.BuildStamp, 0))
  96. setting.LogConfigurationInfo()
  97. }
  98. func (g *GrafanaServerImpl) startHttpServer() error {
  99. g.httpServer = api.NewHttpServer()
  100. err := g.httpServer.Start(g.context)
  101. if err != nil {
  102. return fmt.Errorf("Fail to start server. error: %v", err)
  103. }
  104. return nil
  105. }
  106. func (g *GrafanaServerImpl) Shutdown(code int, reason string) {
  107. g.log.Info("Shutdown started", "code", code, "reason", reason)
  108. err := g.httpServer.Shutdown(g.context)
  109. if err != nil {
  110. g.log.Error("Failed to shutdown server", "error", err)
  111. }
  112. g.shutdownFn()
  113. err = g.childRoutines.Wait()
  114. if err != nil && err != context.Canceled {
  115. g.log.Error("Server shutdown completed with an error", "error", err)
  116. }
  117. }
  118. func (g *GrafanaServerImpl) writePIDFile() {
  119. if *pidFile == "" {
  120. return
  121. }
  122. // Ensure the required directory structure exists.
  123. err := os.MkdirAll(filepath.Dir(*pidFile), 0700)
  124. if err != nil {
  125. g.log.Error("Failed to verify pid directory", "error", err)
  126. os.Exit(1)
  127. }
  128. // Retrieve the PID and write it.
  129. pid := strconv.Itoa(os.Getpid())
  130. if err := ioutil.WriteFile(*pidFile, []byte(pid), 0644); err != nil {
  131. g.log.Error("Failed to write pidfile", "error", err)
  132. os.Exit(1)
  133. }
  134. g.log.Info("Writing PID file", "path", *pidFile, "pid", pid)
  135. }
  136. func sendSystemdNotification(state string) error {
  137. notifySocket := os.Getenv("NOTIFY_SOCKET")
  138. if notifySocket == "" {
  139. return fmt.Errorf("NOTIFY_SOCKET environment variable empty or unset.")
  140. }
  141. socketAddr := &net.UnixAddr{
  142. Name: notifySocket,
  143. Net: "unixgram",
  144. }
  145. conn, err := net.DialUnix(socketAddr.Net, nil, socketAddr)
  146. if err != nil {
  147. return err
  148. }
  149. _, err = conn.Write([]byte(state))
  150. conn.Close()
  151. return err
  152. }