server.go 6.2 KB

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