server.go 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226
  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. "golang.org/x/sync/errgroup"
  19. "github.com/grafana/grafana/pkg/api"
  20. "github.com/grafana/grafana/pkg/log"
  21. "github.com/grafana/grafana/pkg/login"
  22. "github.com/grafana/grafana/pkg/services/sqlstore"
  23. "github.com/grafana/grafana/pkg/setting"
  24. "github.com/grafana/grafana/pkg/social"
  25. "github.com/grafana/grafana/pkg/tracing"
  26. // self registering services
  27. _ "github.com/grafana/grafana/pkg/extensions"
  28. _ "github.com/grafana/grafana/pkg/metrics"
  29. _ "github.com/grafana/grafana/pkg/plugins"
  30. _ "github.com/grafana/grafana/pkg/services/alerting"
  31. _ "github.com/grafana/grafana/pkg/services/cleanup"
  32. _ "github.com/grafana/grafana/pkg/services/notifications"
  33. _ "github.com/grafana/grafana/pkg/services/provisioning"
  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. cfg: setting.NewCfg(),
  45. }
  46. }
  47. type GrafanaServerImpl struct {
  48. context context.Context
  49. shutdownFn context.CancelFunc
  50. childRoutines *errgroup.Group
  51. log log.Logger
  52. cfg *setting.Cfg
  53. RouteRegister api.RouteRegister `inject:""`
  54. HttpServer *api.HTTPServer `inject:""`
  55. }
  56. func (g *GrafanaServerImpl) Start() error {
  57. g.loadConfiguration()
  58. g.writePIDFile()
  59. // initSql
  60. sqlstore.NewEngine() // TODO: this should return an error
  61. sqlstore.EnsureAdminUser()
  62. login.Init()
  63. social.NewOAuthService()
  64. tracingCloser, err := tracing.Init(g.cfg.Raw)
  65. if err != nil {
  66. return fmt.Errorf("Tracing settings is not valid. error: %v", err)
  67. }
  68. defer tracingCloser.Close()
  69. serviceGraph := inject.Graph{}
  70. serviceGraph.Provide(&inject.Object{Value: bus.GetBus()})
  71. serviceGraph.Provide(&inject.Object{Value: g.cfg})
  72. serviceGraph.Provide(&inject.Object{Value: dashboards.NewProvisioningService()})
  73. serviceGraph.Provide(&inject.Object{Value: api.NewRouteRegister(middleware.RequestMetrics, middleware.RequestTracing)})
  74. serviceGraph.Provide(&inject.Object{Value: api.HTTPServer{}})
  75. // self registered services
  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) loadConfiguration() {
  115. err := g.cfg.Load(&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. g.cfg.LogConfigSources()
  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. // call cancel func on root context
  138. g.shutdownFn()
  139. // wait for child routines
  140. if err := g.childRoutines.Wait(); err != nil && err != context.Canceled {
  141. g.log.Error("Server shutdown completed", "error", err)
  142. }
  143. }
  144. func (g *GrafanaServerImpl) writePIDFile() {
  145. if *pidFile == "" {
  146. return
  147. }
  148. // Ensure the required directory structure exists.
  149. err := os.MkdirAll(filepath.Dir(*pidFile), 0700)
  150. if err != nil {
  151. g.log.Error("Failed to verify pid directory", "error", err)
  152. os.Exit(1)
  153. }
  154. // Retrieve the PID and write it.
  155. pid := strconv.Itoa(os.Getpid())
  156. if err := ioutil.WriteFile(*pidFile, []byte(pid), 0644); err != nil {
  157. g.log.Error("Failed to write pidfile", "error", err)
  158. os.Exit(1)
  159. }
  160. g.log.Info("Writing PID file", "path", *pidFile, "pid", pid)
  161. }
  162. func sendSystemdNotification(state string) error {
  163. notifySocket := os.Getenv("NOTIFY_SOCKET")
  164. if notifySocket == "" {
  165. return fmt.Errorf("NOTIFY_SOCKET environment variable empty or unset.")
  166. }
  167. socketAddr := &net.UnixAddr{
  168. Name: notifySocket,
  169. Net: "unixgram",
  170. }
  171. conn, err := net.DialUnix(socketAddr.Net, nil, socketAddr)
  172. if err != nil {
  173. return err
  174. }
  175. _, err = conn.Write([]byte(state))
  176. conn.Close()
  177. return err
  178. }