Elasticsearch: Run version check thorugh backend if enableElasticsearchBackendQuerying enabled (#67679)

* Elasticsearch: Run getDBversion trough resource calls

* Update

* Update

* Fix lint

* Close response body

* Fix lint

* Refactor
This commit is contained in:
Ivana Huckova
2023-05-03 18:09:18 +02:00
committed by GitHub
parent 681925fb63
commit 4d7c0904ef
3 changed files with 111 additions and 3 deletions

View File

@@ -1,10 +1,15 @@
package elasticsearch
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"path"
"strconv"
"github.com/grafana/grafana-plugin-sdk-go/backend"
@@ -172,3 +177,66 @@ func (s *Service) getDSInfo(pluginCtx backend.PluginContext) (*es.DatasourceInfo
return &instance, nil
}
func (s *Service) CallResource(ctx context.Context, req *backend.CallResourceRequest, sender backend.CallResourceResponseSender) error {
logger := eslog.FromContext(ctx)
// allowed paths for resource calls:
// - empty string for fetching db version
if req.Path != "" {
return fmt.Errorf("invalid resource URL: %s", req.Path)
}
ds, err := s.getDSInfo(req.PluginContext)
if err != nil {
return err
}
esUrl, err := url.Parse(ds.URL)
if err != nil {
return err
}
resourcePath, err := url.Parse(req.Path)
if err != nil {
return err
}
// We take the path and the query-string only
esUrl.RawQuery = resourcePath.RawQuery
esUrl.Path = path.Join(esUrl.Path, resourcePath.Path)
request, err := http.NewRequestWithContext(ctx, req.Method, esUrl.String(), bytes.NewBuffer(req.Body))
if err != nil {
return err
}
response, err := ds.HTTPClient.Do(request)
if err != nil {
return err
}
defer func() {
if err := response.Body.Close(); err != nil {
logger.Warn("Failed to close response body", "err", err)
}
}()
body, err := io.ReadAll(response.Body)
if err != nil {
return err
}
responseHeaders := map[string][]string{
"content-type": {"application/json"},
}
if response.Header.Get("Content-Encoding") != "" {
responseHeaders["content-encoding"] = []string{response.Header.Get("Content-Encoding")}
}
return sender.Send(&backend.CallResourceResponse{
Status: response.StatusCode,
Headers: responseHeaders,
Body: body,
})
}