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