grafana/pkg/api/render.go
Agnès Toulet ec71919e7b
Rendering: add CSV support (#33729)
* Rendering: add CSV rendering support

* Rendering: save csv files into a separate folder

* add missing field

* Renderer: get filename from renderer plugin

* apply PR suggestions

* Rendering: remove old PhantomJS error

* Rendering: separate RenderCSV and Render functions

* fix alerting test

* Rendering: fix handling error in HTTP mode

* apply PR feedback

* Update pkg/services/rendering/http_mode.go

Co-authored-by: Joan López de la Franca Beltran <joanjan14@gmail.com>

* apply PR feedback

* Update rendering metrics with type label

* Rendering: return error if not able to parse header

* Rendering: update grpc generated file

* Rendering: use context.WithTimeout to render CSV too

Co-authored-by: Joan López de la Franca Beltran <joanjan14@gmail.com>
2021-05-12 17:16:57 +02:00

81 lines
2.2 KiB
Go

package api
import (
"errors"
"fmt"
"net/http"
"strconv"
"time"
"github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/services/rendering"
"github.com/grafana/grafana/pkg/util"
)
func (hs *HTTPServer) RenderToPng(c *models.ReqContext) {
queryReader, err := util.NewURLQueryReader(c.Req.URL)
if err != nil {
c.Handle(hs.Cfg, 400, "Render parameters error", err)
return
}
queryParams := fmt.Sprintf("?%s", c.Req.URL.RawQuery)
width, err := strconv.Atoi(queryReader.Get("width", "800"))
if err != nil {
c.Handle(hs.Cfg, 400, "Render parameters error", fmt.Errorf("cannot parse width as int: %s", err))
return
}
height, err := strconv.Atoi(queryReader.Get("height", "400"))
if err != nil {
c.Handle(hs.Cfg, 400, "Render parameters error", fmt.Errorf("cannot parse height as int: %s", err))
return
}
timeout, err := strconv.Atoi(queryReader.Get("timeout", "60"))
if err != nil {
c.Handle(hs.Cfg, 400, "Render parameters error", fmt.Errorf("cannot parse timeout as int: %s", err))
return
}
scale, err := strconv.ParseFloat(queryReader.Get("scale", "1"), 64)
if err != nil {
c.Handle(hs.Cfg, 400, "Render parameters error", fmt.Errorf("cannot parse scale as float: %s", err))
return
}
headers := http.Header{}
acceptLanguageHeader := c.Req.Header.Values("Accept-Language")
if len(acceptLanguageHeader) > 0 {
headers["Accept-Language"] = acceptLanguageHeader
}
result, err := hs.RenderService.Render(c.Req.Context(), rendering.Opts{
Width: width,
Height: height,
Timeout: time.Duration(timeout) * time.Second,
OrgID: c.OrgId,
UserID: c.UserId,
OrgRole: c.OrgRole,
Path: c.Params("*") + queryParams,
Timezone: queryReader.Get("tz", ""),
Encoding: queryReader.Get("encoding", ""),
ConcurrentLimit: hs.Cfg.RendererConcurrentRequestLimit,
DeviceScaleFactor: scale,
Headers: headers,
})
if err != nil {
if errors.Is(err, rendering.ErrTimeout) {
c.Handle(hs.Cfg, 500, err.Error(), err)
return
}
c.Handle(hs.Cfg, 500, "Rendering failed.", err)
return
}
c.Resp.Header().Set("Content-Type", "image/png")
http.ServeFile(c.Resp, c.Req.Request, result.FilePath)
}