renderer.go 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. package renderer
  2. import (
  3. "io"
  4. "os"
  5. "os/exec"
  6. "path/filepath"
  7. "time"
  8. "github.com/grafana/grafana/pkg/log"
  9. "github.com/grafana/grafana/pkg/setting"
  10. "github.com/grafana/grafana/pkg/util"
  11. )
  12. type RenderOpts struct {
  13. Url string
  14. Width string
  15. Height string
  16. SessionId string
  17. }
  18. func RenderToPng(params *RenderOpts) (string, error) {
  19. log.Info("PhantomRenderer::renderToPng url %v", params.Url)
  20. binPath, _ := filepath.Abs(filepath.Join(setting.PhantomDir, "phantomjs"))
  21. scriptPath, _ := filepath.Abs(filepath.Join(setting.PhantomDir, "render.js"))
  22. pngPath, _ := filepath.Abs(filepath.Join(setting.ImagesDir, util.GetRandomString(20)))
  23. pngPath = pngPath + ".png"
  24. cmd := exec.Command(binPath, scriptPath, "url="+params.Url, "width="+params.Width,
  25. "height="+params.Height, "png="+pngPath, "cookiename="+setting.SessionOptions.CookieName,
  26. "domain="+setting.Domain, "sessionid="+params.SessionId)
  27. stdout, err := cmd.StdoutPipe()
  28. if err != nil {
  29. return "", err
  30. }
  31. stderr, err := cmd.StderrPipe()
  32. if err != nil {
  33. return "", err
  34. }
  35. err = cmd.Start()
  36. if err != nil {
  37. return "", err
  38. }
  39. go io.Copy(os.Stdout, stdout)
  40. go io.Copy(os.Stdout, stderr)
  41. done := make(chan error)
  42. go func() {
  43. cmd.Wait()
  44. close(done)
  45. }()
  46. select {
  47. case <-time.After(10 * time.Second):
  48. if err := cmd.Process.Kill(); err != nil {
  49. log.Error(4, "failed to kill: %v", err)
  50. }
  51. case <-done:
  52. }
  53. return pngPath, nil
  54. }