server.go 6.6 KB

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