Exemple #1
0
func timeGraphiteRequest(e *State, T miniprofiler.Timer, req *graphite.Request) (resp graphite.Response, err error) {
	e.graphiteQueries = append(e.graphiteQueries, *req)
	b, _ := json.MarshalIndent(req, "", "  ")
	T.StepCustomTiming("graphite", "query", string(b), func() {
		key := req.CacheKey()
		getFn := func() (interface{}, error) {
			return e.graphiteContext.Query(req)
		}
		var val interface{}
		val, err = e.cache.Get(key, getFn)
		resp = val.(graphite.Response)
	})
	return
}
Exemple #2
0
// Query performs a request to Graphite at the given host. host specifies
// a hostname with optional port, and may optionally begin with a scheme
// (http, https) to specify the protocol (http is the default). header is
// the headers to send.
func Query(r *bgraphite.Request, host string, header http.Header) ([]byte, bgraphite.Response, error) {
	v := url.Values{
		"format": []string{"json"},
		"target": r.Targets,
	}
	if r.Start != nil {
		v.Add("from", fmt.Sprint(r.Start.Unix()))
	}
	if r.End != nil {
		v.Add("until", fmt.Sprint(r.End.Unix()))
	}
	r.URL = &url.URL{
		Scheme:   "http",
		Host:     host,
		Path:     "/render/",
		RawQuery: v.Encode(),
	}
	if u, _ := url.Parse(host); u.Scheme != "" && u.Host != "" {
		r.URL.Scheme = u.Scheme
		r.URL.Host = u.Host
		if u.Path != "" {
			r.URL.Path = u.Path
		}
	}
	req, err := http.NewRequest("GET", r.URL.String(), nil)
	if err != nil {
		return nil, nil, fmt.Errorf(requestErrFmt, r.URL, "NewRequest failed: "+err.Error())
	}
	if header != nil {
		req.Header = header
	}
	resp, err := DefaultClient.Do(req)
	if err != nil {
		return nil, nil, fmt.Errorf(requestErrFmt, r.URL, "Get failed: "+err.Error())
	}
	defer resp.Body.Close()
	if resp.StatusCode != http.StatusOK {
		tb, err := readTraceback(resp)
		if err != nil {
			tb = &[]string{"<Could not read traceback: " + err.Error() + ">"}
		}
		return nil, nil, fmt.Errorf(requestErrFmt, r.URL, fmt.Sprintf("Get failed: %s\n%s", resp.Status, strings.Join(*tb, "\n")))
	}
	var series bgraphite.Response
	dump, err := httputil.DumpResponse(resp, true)
	if err != nil {
		e := fmt.Errorf(requestErrFmt, r.URL, "Reading HTTP response failed: "+err.Error())
		return nil, series, e
	}

	err = json.NewDecoder(resp.Body).Decode(&series)

	if err != nil {
		e := fmt.Errorf(requestErrFmt, r.URL, "Json decode failed: "+err.Error())
		return dump, series, e
	}
	return dump, series, nil
}