grafana/pkg/services/alerting/graphite/graphite.go
2016-05-30 18:52:38 +02:00

66 lines
1.4 KiB
Go

package graphite
import (
"fmt"
"github.com/franela/goreq"
"github.com/grafana/grafana/pkg/cmd/grafana-cli/log"
"github.com/grafana/grafana/pkg/components/simplejson"
m "github.com/grafana/grafana/pkg/models"
"net/http"
"net/url"
"strconv"
"time"
)
type GraphiteClient struct{}
type GraphiteSerie struct {
Datapoints [][2]float64
Target string
}
type GraphiteResponse []GraphiteSerie
func (this GraphiteClient) GetSeries(rule *m.AlertJob) (m.TimeSeriesSlice, error) {
v := url.Values{
"format": []string{"json"},
"target": []string{getTargetFromRule(rule.Rule)},
"until": []string{"now"},
"from": []string{"-" + strconv.Itoa(rule.Rule.QueryRange) + "s"},
}
log.Debug("Graphite: sending request with querystring: ", v.Encode())
res, err := goreq.Request{
Method: "POST",
Uri: rule.Datasource.Url + "/render",
Body: v.Encode(),
Timeout: 5 * time.Second,
}.Do()
response := GraphiteResponse{}
res.Body.FromJsonTo(&response)
if err != nil {
return nil, err
}
if res.StatusCode != http.StatusOK {
return nil, fmt.Errorf("expected httpstatus 200, found %d", res.StatusCode)
}
timeSeries := make([]*m.TimeSeries, 0)
for _, v := range response {
timeSeries = append(timeSeries, m.NewTimeSeries(v.Target, v.Datapoints))
}
return timeSeries, nil
}
func getTargetFromRule(rule m.AlertRule) string {
json, _ := simplejson.NewJson([]byte(rule.Query))
return json.Get("target").MustString()
}