server.go 6.1 KB

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