server.go 5.5 KB

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