server.go 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232
  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. "github.com/grafana/grafana/pkg/services/notifications"
  19. "github.com/grafana/grafana/pkg/services/provisioning"
  20. "golang.org/x/sync/errgroup"
  21. "github.com/grafana/grafana/pkg/api"
  22. "github.com/grafana/grafana/pkg/log"
  23. "github.com/grafana/grafana/pkg/login"
  24. "github.com/grafana/grafana/pkg/metrics"
  25. "github.com/grafana/grafana/pkg/services/sqlstore"
  26. "github.com/grafana/grafana/pkg/setting"
  27. "github.com/grafana/grafana/pkg/social"
  28. "github.com/grafana/grafana/pkg/tracing"
  29. _ "github.com/grafana/grafana/pkg/extensions"
  30. _ "github.com/grafana/grafana/pkg/plugins"
  31. _ "github.com/grafana/grafana/pkg/services/alerting"
  32. _ "github.com/grafana/grafana/pkg/services/cleanup"
  33. _ "github.com/grafana/grafana/pkg/services/search"
  34. )
  35. func NewGrafanaServer() *GrafanaServerImpl {
  36. rootCtx, shutdownFn := context.WithCancel(context.Background())
  37. childRoutines, childCtx := errgroup.WithContext(rootCtx)
  38. return &GrafanaServerImpl{
  39. context: childCtx,
  40. shutdownFn: shutdownFn,
  41. childRoutines: childRoutines,
  42. log: log.New("server"),
  43. }
  44. }
  45. type GrafanaServerImpl struct {
  46. context context.Context
  47. shutdownFn context.CancelFunc
  48. childRoutines *errgroup.Group
  49. log log.Logger
  50. RouteRegister api.RouteRegister `inject:""`
  51. HttpServer *api.HTTPServer `inject:""`
  52. }
  53. func (g *GrafanaServerImpl) Start() error {
  54. g.initLogging()
  55. g.writePIDFile()
  56. // initSql
  57. sqlstore.NewEngine() // TODO: this should return an error
  58. sqlstore.EnsureAdminUser()
  59. metrics.Init(setting.Cfg)
  60. login.Init()
  61. social.NewOAuthService()
  62. if err := provisioning.Init(g.context, setting.HomePath, setting.Cfg); err != nil {
  63. return fmt.Errorf("Failed to provision Grafana from config. error: %v", err)
  64. }
  65. tracingCloser, err := tracing.Init(setting.Cfg)
  66. if err != nil {
  67. return fmt.Errorf("Tracing settings is not valid. error: %v", err)
  68. }
  69. defer tracingCloser.Close()
  70. if err = notifications.Init(); err != nil {
  71. return fmt.Errorf("Notification service failed to initialize. error: %v", err)
  72. }
  73. serviceGraph := inject.Graph{}
  74. serviceGraph.Provide(&inject.Object{Value: bus.GetBus()})
  75. serviceGraph.Provide(&inject.Object{Value: dashboards.NewProvisioningService()})
  76. serviceGraph.Provide(&inject.Object{Value: api.NewRouteRegister(middleware.RequestMetrics, middleware.RequestTracing)})
  77. serviceGraph.Provide(&inject.Object{Value: api.HTTPServer{}})
  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. err := service.Run(g.context)
  109. g.log.Info("Stopped "+reflect.TypeOf(service).Elem().Name(), "reason", err)
  110. return err
  111. })
  112. }
  113. sendSystemdNotification("READY=1")
  114. return g.startHttpServer()
  115. }
  116. func (g *GrafanaServerImpl) initLogging() {
  117. err := setting.NewConfigContext(&setting.CommandLineArgs{
  118. Config: *configFile,
  119. HomePath: *homePath,
  120. Args: flag.Args(),
  121. })
  122. if err != nil {
  123. fmt.Fprintf(os.Stderr, "Failed to start grafana. error: %s\n", err.Error())
  124. os.Exit(1)
  125. }
  126. g.log.Info("Starting "+setting.ApplicationName, "version", version, "commit", commit, "compiled", time.Unix(setting.BuildStamp, 0))
  127. setting.LogConfigurationInfo()
  128. }
  129. func (g *GrafanaServerImpl) startHttpServer() error {
  130. g.HttpServer.Init()
  131. err := g.HttpServer.Start(g.context)
  132. if err != nil {
  133. return fmt.Errorf("Fail to start server. error: %v", err)
  134. }
  135. return nil
  136. }
  137. func (g *GrafanaServerImpl) Shutdown(code int, reason string) {
  138. g.log.Info("Shutdown started", "code", code, "reason", reason)
  139. err := g.HttpServer.Shutdown(g.context)
  140. if err != nil {
  141. g.log.Error("Failed to shutdown server", "error", err)
  142. }
  143. g.shutdownFn()
  144. err = g.childRoutines.Wait()
  145. if err != nil && err != context.Canceled {
  146. g.log.Error("Server shutdown completed with an error", "error", err)
  147. }
  148. }
  149. func (g *GrafanaServerImpl) writePIDFile() {
  150. if *pidFile == "" {
  151. return
  152. }
  153. // Ensure the required directory structure exists.
  154. err := os.MkdirAll(filepath.Dir(*pidFile), 0700)
  155. if err != nil {
  156. g.log.Error("Failed to verify pid directory", "error", err)
  157. os.Exit(1)
  158. }
  159. // Retrieve the PID and write it.
  160. pid := strconv.Itoa(os.Getpid())
  161. if err := ioutil.WriteFile(*pidFile, []byte(pid), 0644); err != nil {
  162. g.log.Error("Failed to write pidfile", "error", err)
  163. os.Exit(1)
  164. }
  165. g.log.Info("Writing PID file", "path", *pidFile, "pid", pid)
  166. }
  167. func sendSystemdNotification(state string) error {
  168. notifySocket := os.Getenv("NOTIFY_SOCKET")
  169. if notifySocket == "" {
  170. return fmt.Errorf("NOTIFY_SOCKET environment variable empty or unset.")
  171. }
  172. socketAddr := &net.UnixAddr{
  173. Name: notifySocket,
  174. Net: "unixgram",
  175. }
  176. conn, err := net.DialUnix(socketAddr.Net, nil, socketAddr)
  177. if err != nil {
  178. return err
  179. }
  180. _, err = conn.Write([]byte(state))
  181. conn.Close()
  182. return err
  183. }