Merge pull request #872 from prometheus/fabxc/vecfix

promql: marshal sample pairs to JSON tuples.
This commit is contained in:
Fabian Reinartz 2015-07-06 13:46:10 +02:00
commit f515559a96
5 changed files with 182 additions and 115 deletions

View file

@ -14,10 +14,12 @@
package promql
import (
"encoding/json"
"fmt"
"math"
"runtime"
"sort"
"strconv"
"time"
"golang.org/x/net/context"
@ -42,6 +44,22 @@ type Sample struct {
Timestamp clientmodel.Timestamp `json:"timestamp"`
}
// MarshalJSON implements json.Marshaler.
func (s *Sample) MarshalJSON() ([]byte, error) {
v := struct {
Metric clientmodel.COWMetric `json:"metric"`
Value metric.SamplePair `json:"value"`
}{
Metric: s.Metric,
Value: metric.SamplePair{
Timestamp: s.Timestamp,
Value: s.Value,
},
}
return json.Marshal(&v)
}
// Scalar is a scalar value evaluated at the set timestamp.
type Scalar struct {
Value clientmodel.SampleValue `json:"value"`
@ -52,12 +70,23 @@ func (s *Scalar) String() string {
return fmt.Sprintf("scalar: %v @[%v]", s.Value, s.Timestamp)
}
// MarshalJSON implements json.Marshaler.
func (s *Scalar) MarshalJSON() ([]byte, error) {
v := strconv.FormatFloat(float64(s.Value), 'f', -1, 64)
return json.Marshal([]interface{}{s.Timestamp, string(v)})
}
// String is a string value evaluated at the set timestamp.
type String struct {
Value string `json:"value"`
Timestamp clientmodel.Timestamp `json:"timestamp"`
}
// MarshalJSON implements json.Marshaler.
func (s *String) MarshalJSON() ([]byte, error) {
return json.Marshal([]interface{}{s.Timestamp, s.Value})
}
func (s *String) String() string {
return s.Value
}

View file

@ -1,65 +0,0 @@
// Copyright 2013 The Prometheus Authors
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package httputil
import (
"encoding/json"
"io"
"net/http"
"net/url"
"github.com/prometheus/prometheus/promql"
)
// GetQueryParams calls r.ParseForm and returns r.Form.
func GetQueryParams(r *http.Request) url.Values {
r.ParseForm()
return r.Form
}
var jsonFormatVersion = 1
// ErrorJSON writes the given error JSON-formatted to w.
func ErrorJSON(w io.Writer, err error) error {
data := struct {
Type string `json:"type"`
Value string `json:"value"`
Version int `json:"version"`
}{
Type: "error",
Value: err.Error(),
Version: jsonFormatVersion,
}
enc := json.NewEncoder(w)
return enc.Encode(data)
}
// RespondJSON converts the given data value to JSON and writes it to w.
func RespondJSON(w io.Writer, val promql.Value) error {
data := struct {
Type string `json:"type"`
Value interface{} `json:"value"`
Version int `json:"version"`
}{
Type: val.Type().String(),
Value: val,
Version: jsonFormatVersion,
}
// TODO(fabxc): Adding MarshalJSON to promql.Values might be a good idea.
if sc, ok := val.(*promql.Scalar); ok {
data.Value = sc.Value
}
enc := json.NewEncoder(w)
return enc.Encode(data)
}

View file

@ -17,7 +17,9 @@ import (
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"sort"
"strconv"
"time"
@ -26,7 +28,7 @@ import (
clientmodel "github.com/prometheus/client_golang/model"
"github.com/prometheus/prometheus/util/httputil"
"github.com/prometheus/prometheus/promql"
)
// Enables cross-site script calls.
@ -39,7 +41,7 @@ func setAccessControlHeaders(w http.ResponseWriter) {
func httpJSONError(w http.ResponseWriter, err error, code int) {
w.WriteHeader(code)
httputil.ErrorJSON(w, err)
errorJSON(w, err)
}
func parseTimestampOrNow(t string, now clientmodel.Timestamp) (clientmodel.Timestamp, error) {
@ -67,7 +69,7 @@ func (api *API) Query(w http.ResponseWriter, r *http.Request) {
setAccessControlHeaders(w)
w.Header().Set("Content-Type", "application/json")
params := httputil.GetQueryParams(r)
params := getQueryParams(r)
expr := params.Get("expr")
timestamp, err := parseTimestampOrNow(params.Get("timestamp"), api.Now())
@ -88,7 +90,67 @@ func (api *API) Query(w http.ResponseWriter, r *http.Request) {
}
log.Debugf("Instant query: %s\nQuery stats:\n%s\n", expr, query.Stats())
httputil.RespondJSON(w, res.Value)
if vec, ok := res.Value.(promql.Vector); ok {
respondJSON(w, plainVec(vec))
return
}
if sca, ok := res.Value.(*promql.Scalar); ok {
respondJSON(w, (*plainScalar)(sca))
return
}
if str, ok := res.Value.(*promql.String); ok {
respondJSON(w, (*plainString)(str))
return
}
respondJSON(w, res.Value)
}
// plainVec is an indirection that hides the original MarshalJSON method
// which does not fit the response format for the legacy API.
type plainVec promql.Vector
func (pv plainVec) MarshalJSON() ([]byte, error) {
type plainSmpl promql.Sample
v := make([]*plainSmpl, len(pv))
for i, sv := range pv {
v[i] = (*plainSmpl)(sv)
}
return json.Marshal(&v)
}
func (pv plainVec) Type() promql.ExprType {
return promql.ExprVector
}
func (pv plainVec) String() string {
return ""
}
// plainScalar is an indirection that hides the original MarshalJSON method
// which does not fit the response format for the legacy API.
type plainScalar promql.Scalar
func (pv plainScalar) Type() promql.ExprType {
return promql.ExprScalar
}
func (pv plainScalar) String() string {
return ""
}
// plainString is an indirection that hides the original MarshalJSON method
// which does not fit the response format for the legacy API.
type plainString promql.String
func (pv plainString) Type() promql.ExprType {
return promql.ExprString
}
func (pv plainString) String() string {
return ""
}
// QueryRange handles the /api/query_range endpoint.
@ -96,7 +158,7 @@ func (api *API) QueryRange(w http.ResponseWriter, r *http.Request) {
setAccessControlHeaders(w)
w.Header().Set("Content-Type", "application/json")
params := httputil.GetQueryParams(r)
params := getQueryParams(r)
expr := params.Get("expr")
duration, err := parseDuration(params.Get("range"))
@ -148,7 +210,7 @@ func (api *API) QueryRange(w http.ResponseWriter, r *http.Request) {
}
log.Debugf("Range query: %s\nQuery stats:\n%s\n", expr, query.Stats())
httputil.RespondJSON(w, matrix)
respondJSON(w, matrix)
}
// Metrics handles the /api/metrics endpoint.
@ -166,3 +228,45 @@ func (api *API) Metrics(w http.ResponseWriter, r *http.Request) {
}
w.Write(resultBytes)
}
// GetQueryParams calls r.ParseForm and returns r.Form.
func getQueryParams(r *http.Request) url.Values {
r.ParseForm()
return r.Form
}
var jsonFormatVersion = 1
// ErrorJSON writes the given error JSON-formatted to w.
func errorJSON(w io.Writer, err error) error {
data := struct {
Type string `json:"type"`
Value string `json:"value"`
Version int `json:"version"`
}{
Type: "error",
Value: err.Error(),
Version: jsonFormatVersion,
}
enc := json.NewEncoder(w)
return enc.Encode(data)
}
// RespondJSON converts the given data value to JSON and writes it to w.
func respondJSON(w io.Writer, val promql.Value) error {
data := struct {
Type string `json:"type"`
Value interface{} `json:"value"`
Version int `json:"version"`
}{
Type: val.Type().String(),
Value: val,
Version: jsonFormatVersion,
}
// TODO(fabxc): Adding MarshalJSON to promql.Values might be a good idea.
if sc, ok := val.(*promql.Scalar); ok {
data.Value = sc.Value
}
enc := json.NewEncoder(w)
return enc.Encode(data)
}

File diff suppressed because one or more lines are too long

View file

@ -579,7 +579,7 @@ Prometheus.Graph.prototype.handleConsoleResponse = function(data, textStatus) {
for (var i = 0; i < data.result.length; i++) {
var s = data.result[i];
var tsName = self.metricToTsName(s.metric);
tBody.append("<tr><td>" + escapeHTML(tsName) + "</td><td>" + s.value + "</td></tr>");
tBody.append("<tr><td>" + escapeHTML(tsName) + "</td><td>" + s[1] + "</td></tr>");
}
break;
case "matrix":
@ -598,10 +598,10 @@ Prometheus.Graph.prototype.handleConsoleResponse = function(data, textStatus) {
}
break;
case "scalar":
tBody.append("<tr><td>scalar</td><td>" + data.result.value + "</td></tr>");
tBody.append("<tr><td>scalar</td><td>" + data.result[1] + "</td></tr>");
break;
case "string":
tBody.append("<tr><td>string</td><td>" + data.result.value + "</td></tr>");
tBody.append("<tr><td>string</td><td>" + data.result[1] + "</td></tr>");
break;
default:
self.showError("Unsupported value type!");