rendering.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. package rendering
  2. import (
  3. "context"
  4. "fmt"
  5. "path/filepath"
  6. plugin "github.com/hashicorp/go-plugin"
  7. pluginModel "github.com/grafana/grafana-plugin-model/go/renderer"
  8. "github.com/grafana/grafana/pkg/log"
  9. "github.com/grafana/grafana/pkg/middleware"
  10. "github.com/grafana/grafana/pkg/models"
  11. "github.com/grafana/grafana/pkg/plugins"
  12. "github.com/grafana/grafana/pkg/registry"
  13. "github.com/grafana/grafana/pkg/setting"
  14. "github.com/grafana/grafana/pkg/util"
  15. )
  16. func init() {
  17. registry.RegisterService(&RenderingService{})
  18. }
  19. type RenderingService struct {
  20. log log.Logger
  21. pluginClient *plugin.Client
  22. grpcPlugin pluginModel.RendererPlugin
  23. pluginInfo *plugins.RendererPlugin
  24. renderAction renderFunc
  25. Cfg *setting.Cfg `inject:""`
  26. }
  27. func (rs *RenderingService) Init() error {
  28. rs.log = log.New("rendering")
  29. return nil
  30. }
  31. func (rs *RenderingService) Run(ctx context.Context) error {
  32. if rs.Cfg.RendererUrl != "" {
  33. rs.log.Info("Backend rendering via external http server")
  34. rs.renderAction = rs.renderViaHttp
  35. <-ctx.Done()
  36. return nil
  37. }
  38. if plugins.Renderer == nil {
  39. rs.renderAction = rs.renderViaPhantomJS
  40. <-ctx.Done()
  41. return nil
  42. }
  43. rs.pluginInfo = plugins.Renderer
  44. if err := rs.startPlugin(ctx); err != nil {
  45. return err
  46. }
  47. rs.renderAction = rs.renderViaPlugin
  48. err := rs.watchAndRestartPlugin(ctx)
  49. if rs.pluginClient != nil {
  50. rs.log.Debug("Killing renderer plugin process")
  51. rs.pluginClient.Kill()
  52. }
  53. return err
  54. }
  55. func (rs *RenderingService) Render(ctx context.Context, opts Opts) (*RenderResult, error) {
  56. if rs.renderAction != nil {
  57. return rs.renderAction(ctx, opts)
  58. } else {
  59. return nil, fmt.Errorf("No renderer found")
  60. }
  61. }
  62. func (rs *RenderingService) getFilePathForNewImage() string {
  63. pngPath, _ := filepath.Abs(filepath.Join(rs.Cfg.ImagesDir, util.GetRandomString(20)))
  64. return pngPath + ".png"
  65. }
  66. func (rs *RenderingService) getURL(path string) string {
  67. // &render=1 signals to the legacy redirect layer to
  68. return fmt.Sprintf("%s://%s:%s/%s&render=1", setting.Protocol, rs.getLocalDomain(), setting.HttpPort, path)
  69. }
  70. func (rs *RenderingService) getLocalDomain() string {
  71. if setting.HttpAddr != setting.DEFAULT_HTTP_ADDR {
  72. return setting.HttpAddr
  73. }
  74. return "localhost"
  75. }
  76. func (rs *RenderingService) getRenderKey(orgId, userId int64, orgRole models.RoleType) string {
  77. return middleware.AddRenderAuthKey(orgId, userId, orgRole)
  78. }