server.go 5.8 KB

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