server.go 5.8 KB

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