server.go 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232
  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. 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. metrics.Init(g.cfg.Raw)
  63. login.Init()
  64. social.NewOAuthService()
  65. if err := provisioning.Init(g.context, setting.HomePath, g.cfg.Raw); err != nil {
  66. return fmt.Errorf("Failed to provision Grafana from config. error: %v", err)
  67. }
  68. tracingCloser, err := tracing.Init(g.cfg.Raw)
  69. if err != nil {
  70. return fmt.Errorf("Tracing settings is not valid. error: %v", err)
  71. }
  72. defer tracingCloser.Close()
  73. serviceGraph := inject.Graph{}
  74. serviceGraph.Provide(&inject.Object{Value: bus.GetBus()})
  75. serviceGraph.Provide(&inject.Object{Value: g.cfg})
  76. serviceGraph.Provide(&inject.Object{Value: dashboards.NewProvisioningService()})
  77. serviceGraph.Provide(&inject.Object{Value: api.NewRouteRegister(middleware.RequestMetrics, middleware.RequestTracing)})
  78. serviceGraph.Provide(&inject.Object{Value: api.HTTPServer{}})
  79. services := registry.GetServices()
  80. // Add all services to dependency graph
  81. for _, service := range services {
  82. serviceGraph.Provide(&inject.Object{Value: service})
  83. }
  84. serviceGraph.Provide(&inject.Object{Value: g})
  85. // Inject dependencies to services
  86. if err := serviceGraph.Populate(); err != nil {
  87. return fmt.Errorf("Failed to populate service dependency: %v", err)
  88. }
  89. // Init & start services
  90. for _, service := range services {
  91. if registry.IsDisabled(service) {
  92. continue
  93. }
  94. g.log.Info("Initializing " + reflect.TypeOf(service).Elem().Name())
  95. if err := service.Init(); err != nil {
  96. return fmt.Errorf("Service init failed %v", err)
  97. }
  98. }
  99. // Start background services
  100. for index := range services {
  101. service, ok := services[index].(registry.BackgroundService)
  102. if !ok {
  103. continue
  104. }
  105. if registry.IsDisabled(services[index]) {
  106. continue
  107. }
  108. g.childRoutines.Go(func() error {
  109. err := service.Run(g.context)
  110. g.log.Info("Stopped "+reflect.TypeOf(service).Elem().Name(), "reason", err)
  111. return err
  112. })
  113. }
  114. sendSystemdNotification("READY=1")
  115. return g.startHttpServer()
  116. }
  117. func (g *GrafanaServerImpl) loadConfiguration() {
  118. err := g.cfg.Load(&setting.CommandLineArgs{
  119. Config: *configFile,
  120. HomePath: *homePath,
  121. Args: flag.Args(),
  122. })
  123. if err != nil {
  124. fmt.Fprintf(os.Stderr, "Failed to start grafana. error: %s\n", err.Error())
  125. os.Exit(1)
  126. }
  127. g.log.Info("Starting "+setting.ApplicationName, "version", version, "commit", commit, "compiled", time.Unix(setting.BuildStamp, 0))
  128. g.cfg.LogConfigSources()
  129. }
  130. func (g *GrafanaServerImpl) startHttpServer() error {
  131. g.HttpServer.Init()
  132. err := g.HttpServer.Start(g.context)
  133. if err != nil {
  134. return fmt.Errorf("Fail to start server. error: %v", err)
  135. }
  136. return nil
  137. }
  138. func (g *GrafanaServerImpl) Shutdown(code int, reason string) {
  139. g.log.Info("Shutdown started", "code", code, "reason", reason)
  140. err := g.HttpServer.Shutdown(g.context)
  141. if err != nil {
  142. g.log.Error("Failed to shutdown server", "error", err)
  143. }
  144. g.shutdownFn()
  145. err = g.childRoutines.Wait()
  146. if err != nil && err != context.Canceled {
  147. g.log.Error("Server shutdown completed with an error", "error", err)
  148. }
  149. }
  150. func (g *GrafanaServerImpl) writePIDFile() {
  151. if *pidFile == "" {
  152. return
  153. }
  154. // Ensure the required directory structure exists.
  155. err := os.MkdirAll(filepath.Dir(*pidFile), 0700)
  156. if err != nil {
  157. g.log.Error("Failed to verify pid directory", "error", err)
  158. os.Exit(1)
  159. }
  160. // Retrieve the PID and write it.
  161. pid := strconv.Itoa(os.Getpid())
  162. if err := ioutil.WriteFile(*pidFile, []byte(pid), 0644); err != nil {
  163. g.log.Error("Failed to write pidfile", "error", err)
  164. os.Exit(1)
  165. }
  166. g.log.Info("Writing PID file", "path", *pidFile, "pid", pid)
  167. }
  168. func sendSystemdNotification(state string) error {
  169. notifySocket := os.Getenv("NOTIFY_SOCKET")
  170. if notifySocket == "" {
  171. return fmt.Errorf("NOTIFY_SOCKET environment variable empty or unset.")
  172. }
  173. socketAddr := &net.UnixAddr{
  174. Name: notifySocket,
  175. Net: "unixgram",
  176. }
  177. conn, err := net.DialUnix(socketAddr.Net, nil, socketAddr)
  178. if err != nil {
  179. return err
  180. }
  181. _, err = conn.Write([]byte(state))
  182. conn.Close()
  183. return err
  184. }