server.go 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231
  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/facebookgo/inject"
  13. "github.com/grafana/grafana/pkg/api"
  14. "github.com/grafana/grafana/pkg/api/routing"
  15. "github.com/grafana/grafana/pkg/bus"
  16. _ "github.com/grafana/grafana/pkg/extensions"
  17. "github.com/grafana/grafana/pkg/log"
  18. "github.com/grafana/grafana/pkg/login"
  19. _ "github.com/grafana/grafana/pkg/metrics"
  20. "github.com/grafana/grafana/pkg/middleware"
  21. _ "github.com/grafana/grafana/pkg/plugins"
  22. "github.com/grafana/grafana/pkg/registry"
  23. _ "github.com/grafana/grafana/pkg/services/alerting"
  24. _ "github.com/grafana/grafana/pkg/services/cleanup"
  25. _ "github.com/grafana/grafana/pkg/services/notifications"
  26. _ "github.com/grafana/grafana/pkg/services/provisioning"
  27. _ "github.com/grafana/grafana/pkg/services/rendering"
  28. _ "github.com/grafana/grafana/pkg/services/search"
  29. _ "github.com/grafana/grafana/pkg/services/sqlstore"
  30. "github.com/grafana/grafana/pkg/setting"
  31. "github.com/grafana/grafana/pkg/social" // self registering services
  32. _ "github.com/grafana/grafana/pkg/tracing"
  33. "golang.org/x/sync/errgroup"
  34. )
  35. func NewGrafanaServer() *GrafanaServerImpl {
  36. rootCtx, shutdownFn := context.WithCancel(context.Background())
  37. childRoutines, childCtx := errgroup.WithContext(rootCtx)
  38. return &GrafanaServerImpl{
  39. context: childCtx,
  40. shutdownFn: shutdownFn,
  41. childRoutines: childRoutines,
  42. log: log.New("server"),
  43. cfg: setting.NewCfg(),
  44. }
  45. }
  46. type GrafanaServerImpl struct {
  47. context context.Context
  48. shutdownFn context.CancelFunc
  49. childRoutines *errgroup.Group
  50. log log.Logger
  51. cfg *setting.Cfg
  52. shutdownReason string
  53. shutdownInProgress bool
  54. RouteRegister routing.RouteRegister `inject:""`
  55. HttpServer *api.HTTPServer `inject:""`
  56. }
  57. func (g *GrafanaServerImpl) Run() error {
  58. g.loadConfiguration()
  59. g.writePIDFile()
  60. login.Init()
  61. social.NewOAuthService()
  62. serviceGraph := inject.Graph{}
  63. serviceGraph.Provide(&inject.Object{Value: bus.GetBus()})
  64. serviceGraph.Provide(&inject.Object{Value: g.cfg})
  65. serviceGraph.Provide(&inject.Object{Value: routing.NewRouteRegister(middleware.RequestMetrics, middleware.RequestTracing)})
  66. // self registered services
  67. services := registry.GetServices()
  68. // Add all services to dependency graph
  69. for _, service := range services {
  70. serviceGraph.Provide(&inject.Object{Value: service.Instance})
  71. }
  72. serviceGraph.Provide(&inject.Object{Value: g})
  73. // Inject dependencies to services
  74. if err := serviceGraph.Populate(); err != nil {
  75. return fmt.Errorf("Failed to populate service dependency: %v", err)
  76. }
  77. // Init & start services
  78. for _, service := range services {
  79. if registry.IsDisabled(service.Instance) {
  80. continue
  81. }
  82. g.log.Info("Initializing " + service.Name)
  83. if err := service.Instance.Init(); err != nil {
  84. return fmt.Errorf("Service init failed: %v", err)
  85. }
  86. }
  87. // Start background services
  88. for _, srv := range services {
  89. // variable needed for accessing loop variable in function callback
  90. descriptor := srv
  91. service, ok := srv.Instance.(registry.BackgroundService)
  92. if !ok {
  93. continue
  94. }
  95. if registry.IsDisabled(descriptor.Instance) {
  96. continue
  97. }
  98. g.childRoutines.Go(func() error {
  99. // Skip starting new service when shutting down
  100. // Can happen when service stop/return during startup
  101. if g.shutdownInProgress {
  102. return nil
  103. }
  104. err := service.Run(g.context)
  105. // If error is not canceled then the service crashed
  106. if err != context.Canceled && err != nil {
  107. g.log.Error("Stopped "+descriptor.Name, "reason", err)
  108. } else {
  109. g.log.Info("Stopped "+descriptor.Name, "reason", err)
  110. }
  111. // Mark that we are in shutdown mode
  112. // So more services are not started
  113. g.shutdownInProgress = true
  114. return err
  115. })
  116. }
  117. sendSystemdNotification("READY=1")
  118. return g.childRoutines.Wait()
  119. }
  120. func (g *GrafanaServerImpl) loadConfiguration() {
  121. err := g.cfg.Load(&setting.CommandLineArgs{
  122. Config: *configFile,
  123. HomePath: *homePath,
  124. Args: flag.Args(),
  125. })
  126. if err != nil {
  127. fmt.Fprintf(os.Stderr, "Failed to start grafana. error: %s\n", err.Error())
  128. os.Exit(1)
  129. }
  130. g.log.Info("Starting "+setting.ApplicationName, "version", version, "commit", commit, "branch", buildBranch, "compiled", time.Unix(setting.BuildStamp, 0))
  131. g.cfg.LogConfigSources()
  132. }
  133. func (g *GrafanaServerImpl) Shutdown(reason string) {
  134. g.log.Info("Shutdown started", "reason", reason)
  135. g.shutdownReason = reason
  136. g.shutdownInProgress = true
  137. // call cancel func on root context
  138. g.shutdownFn()
  139. // wait for child routines
  140. g.childRoutines.Wait()
  141. }
  142. func (g *GrafanaServerImpl) Exit(reason error) int {
  143. // default exit code is 1
  144. code := 1
  145. if reason == context.Canceled && g.shutdownReason != "" {
  146. reason = fmt.Errorf(g.shutdownReason)
  147. code = 0
  148. }
  149. g.log.Error("Server shutdown", "reason", reason)
  150. return code
  151. }
  152. func (g *GrafanaServerImpl) writePIDFile() {
  153. if *pidFile == "" {
  154. return
  155. }
  156. // Ensure the required directory structure exists.
  157. err := os.MkdirAll(filepath.Dir(*pidFile), 0700)
  158. if err != nil {
  159. g.log.Error("Failed to verify pid directory", "error", err)
  160. os.Exit(1)
  161. }
  162. // Retrieve the PID and write it.
  163. pid := strconv.Itoa(os.Getpid())
  164. if err := ioutil.WriteFile(*pidFile, []byte(pid), 0644); err != nil {
  165. g.log.Error("Failed to write pidfile", "error", err)
  166. os.Exit(1)
  167. }
  168. g.log.Info("Writing PID file", "path", *pidFile, "pid", pid)
  169. }
  170. func sendSystemdNotification(state string) error {
  171. notifySocket := os.Getenv("NOTIFY_SOCKET")
  172. if notifySocket == "" {
  173. return fmt.Errorf("NOTIFY_SOCKET environment variable empty or unset.")
  174. }
  175. socketAddr := &net.UnixAddr{
  176. Name: notifySocket,
  177. Net: "unixgram",
  178. }
  179. conn, err := net.DialUnix(socketAddr.Net, nil, socketAddr)
  180. if err != nil {
  181. return err
  182. }
  183. _, err = conn.Write([]byte(state))
  184. conn.Close()
  185. return err
  186. }