server.go 6.5 KB

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