server.go 4.3 KB

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