server.go 6.0 KB

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