server.go 6.6 KB

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