server.go 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229
  1. package main
  2. import (
  3. "context"
  4. "flag"
  5. "fmt"
  6. "io/ioutil"
  7. "net"
  8. "os"
  9. "path/filepath"
  10. "reflect"
  11. "strconv"
  12. "time"
  13. "github.com/facebookgo/inject"
  14. "github.com/grafana/grafana/pkg/bus"
  15. "github.com/grafana/grafana/pkg/middleware"
  16. "github.com/grafana/grafana/pkg/registry"
  17. "github.com/grafana/grafana/pkg/services/dashboards"
  18. "github.com/grafana/grafana/pkg/services/provisioning"
  19. "golang.org/x/sync/errgroup"
  20. "github.com/grafana/grafana/pkg/api"
  21. "github.com/grafana/grafana/pkg/log"
  22. "github.com/grafana/grafana/pkg/login"
  23. "github.com/grafana/grafana/pkg/metrics"
  24. "github.com/grafana/grafana/pkg/services/sqlstore"
  25. "github.com/grafana/grafana/pkg/setting"
  26. "github.com/grafana/grafana/pkg/social"
  27. "github.com/grafana/grafana/pkg/tracing"
  28. // self registering services
  29. _ "github.com/grafana/grafana/pkg/extensions"
  30. _ "github.com/grafana/grafana/pkg/plugins"
  31. _ "github.com/grafana/grafana/pkg/services/alerting"
  32. _ "github.com/grafana/grafana/pkg/services/cleanup"
  33. _ "github.com/grafana/grafana/pkg/services/notifications"
  34. _ "github.com/grafana/grafana/pkg/services/search"
  35. )
  36. func NewGrafanaServer() *GrafanaServerImpl {
  37. rootCtx, shutdownFn := context.WithCancel(context.Background())
  38. childRoutines, childCtx := errgroup.WithContext(rootCtx)
  39. return &GrafanaServerImpl{
  40. context: childCtx,
  41. shutdownFn: shutdownFn,
  42. childRoutines: childRoutines,
  43. log: log.New("server"),
  44. }
  45. }
  46. type GrafanaServerImpl struct {
  47. context context.Context
  48. shutdownFn context.CancelFunc
  49. childRoutines *errgroup.Group
  50. log log.Logger
  51. RouteRegister api.RouteRegister `inject:""`
  52. HttpServer *api.HTTPServer `inject:""`
  53. }
  54. func (g *GrafanaServerImpl) Start() error {
  55. g.initLogging()
  56. g.writePIDFile()
  57. // initSql
  58. sqlstore.NewEngine() // TODO: this should return an error
  59. sqlstore.EnsureAdminUser()
  60. metrics.Init(setting.Cfg)
  61. login.Init()
  62. social.NewOAuthService()
  63. if err := provisioning.Init(g.context, setting.HomePath, setting.Cfg); err != nil {
  64. return fmt.Errorf("Failed to provision Grafana from config. error: %v", err)
  65. }
  66. tracingCloser, err := tracing.Init(setting.Cfg)
  67. if err != nil {
  68. return fmt.Errorf("Tracing settings is not valid. error: %v", err)
  69. }
  70. defer tracingCloser.Close()
  71. serviceGraph := inject.Graph{}
  72. serviceGraph.Provide(&inject.Object{Value: bus.GetBus()})
  73. serviceGraph.Provide(&inject.Object{Value: dashboards.NewProvisioningService()})
  74. serviceGraph.Provide(&inject.Object{Value: api.NewRouteRegister(middleware.RequestMetrics, middleware.RequestTracing)})
  75. serviceGraph.Provide(&inject.Object{Value: api.HTTPServer{}})
  76. services := registry.GetServices()
  77. // Add all services to dependency graph
  78. for _, service := range services {
  79. serviceGraph.Provide(&inject.Object{Value: service})
  80. }
  81. serviceGraph.Provide(&inject.Object{Value: g})
  82. // Inject dependencies to services
  83. if err := serviceGraph.Populate(); err != nil {
  84. return fmt.Errorf("Failed to populate service dependency: %v", err)
  85. }
  86. // Init & start services
  87. for _, service := range services {
  88. if registry.IsDisabled(service) {
  89. continue
  90. }
  91. g.log.Info("Initializing " + reflect.TypeOf(service).Elem().Name())
  92. if err := service.Init(); err != nil {
  93. return fmt.Errorf("Service init failed %v", err)
  94. }
  95. }
  96. // Start background services
  97. for index := range services {
  98. service, ok := services[index].(registry.BackgroundService)
  99. if !ok {
  100. continue
  101. }
  102. if registry.IsDisabled(services[index]) {
  103. continue
  104. }
  105. g.childRoutines.Go(func() error {
  106. err := service.Run(g.context)
  107. g.log.Info("Stopped "+reflect.TypeOf(service).Elem().Name(), "reason", err)
  108. return err
  109. })
  110. }
  111. sendSystemdNotification("READY=1")
  112. return g.startHttpServer()
  113. }
  114. func (g *GrafanaServerImpl) initLogging() {
  115. err := setting.NewConfigContext(&setting.CommandLineArgs{
  116. Config: *configFile,
  117. HomePath: *homePath,
  118. Args: flag.Args(),
  119. })
  120. if err != nil {
  121. fmt.Fprintf(os.Stderr, "Failed to start grafana. error: %s\n", err.Error())
  122. os.Exit(1)
  123. }
  124. g.log.Info("Starting "+setting.ApplicationName, "version", version, "commit", commit, "compiled", time.Unix(setting.BuildStamp, 0))
  125. setting.LogConfigurationInfo()
  126. }
  127. func (g *GrafanaServerImpl) startHttpServer() error {
  128. g.HttpServer.Init()
  129. err := g.HttpServer.Start(g.context)
  130. if err != nil {
  131. return fmt.Errorf("Fail to start server. error: %v", err)
  132. }
  133. return nil
  134. }
  135. func (g *GrafanaServerImpl) Shutdown(code int, reason string) {
  136. g.log.Info("Shutdown started", "code", code, "reason", reason)
  137. err := g.HttpServer.Shutdown(g.context)
  138. if err != nil {
  139. g.log.Error("Failed to shutdown server", "error", err)
  140. }
  141. g.shutdownFn()
  142. err = g.childRoutines.Wait()
  143. if err != nil && err != context.Canceled {
  144. g.log.Error("Server shutdown completed with an error", "error", err)
  145. }
  146. }
  147. func (g *GrafanaServerImpl) writePIDFile() {
  148. if *pidFile == "" {
  149. return
  150. }
  151. // Ensure the required directory structure exists.
  152. err := os.MkdirAll(filepath.Dir(*pidFile), 0700)
  153. if err != nil {
  154. g.log.Error("Failed to verify pid directory", "error", err)
  155. os.Exit(1)
  156. }
  157. // Retrieve the PID and write it.
  158. pid := strconv.Itoa(os.Getpid())
  159. if err := ioutil.WriteFile(*pidFile, []byte(pid), 0644); err != nil {
  160. g.log.Error("Failed to write pidfile", "error", err)
  161. os.Exit(1)
  162. }
  163. g.log.Info("Writing PID file", "path", *pidFile, "pid", pid)
  164. }
  165. func sendSystemdNotification(state string) error {
  166. notifySocket := os.Getenv("NOTIFY_SOCKET")
  167. if notifySocket == "" {
  168. return fmt.Errorf("NOTIFY_SOCKET environment variable empty or unset.")
  169. }
  170. socketAddr := &net.UnixAddr{
  171. Name: notifySocket,
  172. Net: "unixgram",
  173. }
  174. conn, err := net.DialUnix(socketAddr.Net, nil, socketAddr)
  175. if err != nil {
  176. return err
  177. }
  178. _, err = conn.Write([]byte(state))
  179. conn.Close()
  180. return err
  181. }