Files
grafana/pkg/tsdb/mqe/token_client.go

102 lines
2.1 KiB
Go
Raw Normal View History

2016-11-14 14:00:35 +01:00
package mqe
import (
"context"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"net/url"
"path"
2016-12-13 13:47:37 +01:00
"time"
2016-11-14 14:00:35 +01:00
"golang.org/x/net/context/ctxhttp"
2016-12-13 13:47:37 +01:00
"strconv"
2016-11-14 14:00:35 +01:00
"github.com/grafana/grafana/pkg/log"
"github.com/grafana/grafana/pkg/models"
2016-12-13 13:47:37 +01:00
"github.com/patrickmn/go-cache"
2016-11-14 14:00:35 +01:00
)
2016-12-13 13:47:37 +01:00
var tokenCache *cache.Cache
func init() {
tokenCache = cache.New(5*time.Minute, 30*time.Second)
}
2016-11-14 14:00:35 +01:00
type TokenClient struct {
2016-12-13 13:47:37 +01:00
log log.Logger
Datasource *models.DataSource
HttpClient *http.Client
2016-11-14 14:00:35 +01:00
}
func NewTokenClient(datasource *models.DataSource) *TokenClient {
httpClient, _ := datasource.GetHttpClient()
2016-11-14 14:00:35 +01:00
return &TokenClient{
2016-12-13 13:47:37 +01:00
log: log.New("tsdb.mqe.tokenclient"),
Datasource: datasource,
HttpClient: httpClient,
2016-11-14 14:00:35 +01:00
}
}
func (client *TokenClient) GetTokenData(ctx context.Context) (*TokenBody, error) {
2016-12-13 13:47:37 +01:00
key := strconv.FormatInt(client.Datasource.Id, 10)
item, found := tokenCache.Get(key)
if found {
if result, ok := item.(*TokenBody); ok {
return result, nil
2016-11-14 14:49:58 +01:00
}
2016-12-13 13:47:37 +01:00
}
2016-11-14 14:49:58 +01:00
2016-12-13 13:47:37 +01:00
b, err := client.RequestTokenData(ctx)
if err != nil {
return nil, err
2016-11-14 14:49:58 +01:00
}
2016-12-13 13:47:37 +01:00
tokenCache.Set(key, b, cache.DefaultExpiration)
return b, nil
2016-11-14 14:49:58 +01:00
}
func (client *TokenClient) RequestTokenData(ctx context.Context) (*TokenBody, error) {
u, _ := url.Parse(client.Datasource.Url)
2016-11-14 14:00:35 +01:00
u.Path = path.Join(u.Path, "token")
req, err := http.NewRequest(http.MethodGet, u.String(), nil)
if err != nil {
2016-12-13 13:47:37 +01:00
client.log.Info("Failed to create request", "error", err)
2016-11-14 14:00:35 +01:00
}
res, err := ctxhttp.Do(ctx, client.HttpClient, req)
2016-11-14 14:00:35 +01:00
if err != nil {
return nil, err
}
body, err := ioutil.ReadAll(res.Body)
defer res.Body.Close()
if err != nil {
return nil, err
}
if res.StatusCode/100 != 2 {
2016-12-13 13:47:37 +01:00
client.log.Info("Request failed", "status", res.Status, "body", string(body))
2016-11-14 14:00:35 +01:00
return nil, fmt.Errorf("Request failed status: %v", res.Status)
}
var result *TokenResponse
err = json.Unmarshal(body, &result)
if err != nil {
2016-12-13 13:47:37 +01:00
client.log.Info("Failed to unmarshal response", "error", err, "status", res.Status, "body", string(body))
2016-11-14 14:00:35 +01:00
return nil, err
}
2016-11-14 14:49:58 +01:00
if !result.Success {
return nil, fmt.Errorf("Request failed for unknown reason.")
}
return &result.Body, nil
2016-11-14 14:00:35 +01:00
}