Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Split label names queries in the frontend. #2441

Merged
merged 2 commits into from
Jul 29, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
140 changes: 117 additions & 23 deletions pkg/querier/queryrange/codec.go
Original file line number Diff line number Diff line change
Expand Up @@ -108,12 +108,47 @@ func (r *LokiSeriesRequest) LogToSpan(sp opentracing.Span) {
)
}

func (r *LokiLabelNamesRequest) GetEnd() int64 {
return r.EndTs.UnixNano() / (int64(time.Millisecond) / int64(time.Nanosecond))
}

func (r *LokiLabelNamesRequest) GetStart() int64 {
return r.StartTs.UnixNano() / (int64(time.Millisecond) / int64(time.Nanosecond))
}

func (r *LokiLabelNamesRequest) WithStartEnd(s int64, e int64) queryrange.Request {
new := *r
new.StartTs = time.Unix(0, s*int64(time.Millisecond))
new.EndTs = time.Unix(0, e*int64(time.Millisecond))
return &new
}

func (r *LokiLabelNamesRequest) WithQuery(query string) queryrange.Request {
new := *r
return &new
}

func (r *LokiLabelNamesRequest) GetQuery() string {
return ""
}

func (r *LokiLabelNamesRequest) GetStep() int64 {
return 0
}

func (r *LokiLabelNamesRequest) LogToSpan(sp opentracing.Span) {
sp.LogFields(
otlog.String("start", timestamp.Time(r.GetStart()).String()),
otlog.String("end", timestamp.Time(r.GetEnd()).String()),
)
}

func (codec) DecodeRequest(_ context.Context, r *http.Request) (queryrange.Request, error) {
if err := r.ParseForm(); err != nil {
return nil, httpgrpc.Errorf(http.StatusBadRequest, err.Error())
}

switch op := getOperation(r); op {
switch op := getOperation(r.URL.Path); op {
case QueryRangeOp:
req, err := loghttp.ParseRangeQuery(r)
if err != nil {
Expand Down Expand Up @@ -141,6 +176,16 @@ func (codec) DecodeRequest(_ context.Context, r *http.Request) (queryrange.Reque
EndTs: req.End.UTC(),
Path: r.URL.Path,
}, nil
case LabelNamesOp:
req, err := loghttp.ParseLabelQuery(r)
if err != nil {
return nil, httpgrpc.Errorf(http.StatusBadRequest, err.Error())
}
return &LokiLabelNamesRequest{
StartTs: *req.Start,
EndTs: *req.End,
Path: r.URL.Path,
}, nil
default:
return nil, httpgrpc.Errorf(http.StatusBadRequest, fmt.Sprintf("unknown request path: %s", r.URL.Path))
}
Expand Down Expand Up @@ -196,6 +241,24 @@ func (codec) EncodeRequest(ctx context.Context, r queryrange.Request) (*http.Req
Header: http.Header{},
}
return req.WithContext(ctx), nil
case *LokiLabelNamesRequest:
params := url.Values{
"start": []string{fmt.Sprintf("%d", request.StartTs.UnixNano())},
"end": []string{fmt.Sprintf("%d", request.EndTs.UnixNano())},
}

u := &url.URL{
Path: "/loki/api/v1/labels",
RawQuery: params.Encode(),
}
req := &http.Request{
Method: "GET",
RequestURI: u.String(), // This is what the httpgrpc code looks at.
URL: u,
Body: http.NoBody,
Header: http.Header{},
}
return req.WithContext(ctx), nil
default:
return nil, httpgrpc.Errorf(http.StatusInternalServerError, "invalid request format")
}
Expand Down Expand Up @@ -238,6 +301,16 @@ func (codec) DecodeResponse(ctx context.Context, r *http.Response, req queryrang
Version: uint32(loghttp.GetVersion(req.Path)),
Data: data,
}, nil
case *LokiLabelNamesRequest:
var resp loghttp.LabelResponse
if err := json.Unmarshal(buf, &resp); err != nil {
return nil, httpgrpc.Errorf(http.StatusInternalServerError, "error decoding response: %v", err)
}
return &LokiLabelNamesResponse{
Status: resp.Status,
Version: uint32(loghttp.GetVersion(req.Path)),
Data: resp.Data,
}, nil
default:
var resp loghttp.QueryResponse
if err := json.Unmarshal(buf, &resp); err != nil {
Expand Down Expand Up @@ -277,6 +350,7 @@ func (codec) DecodeResponse(ctx context.Context, r *http.Response, req queryrang
func (codec) EncodeResponse(ctx context.Context, res queryrange.Response) (*http.Response, error) {
sp, _ := opentracing.StartSpanFromContext(ctx, "codec.EncodeResponse")
defer sp.Finish()
var buf bytes.Buffer

switch response := res.(type) {
case *LokiPromResponse:
Expand All @@ -294,7 +368,6 @@ func (codec) EncodeResponse(ctx context.Context, res queryrange.Response) (*http
Data: logql.Streams(streams),
Statistics: response.Statistics,
}
var buf bytes.Buffer
if loghttp.Version(response.Version) == loghttp.VersionLegacy {
if err := marshal_legacy.WriteQueryResponseJSON(result, &buf); err != nil {
return nil, err
Expand All @@ -305,38 +378,37 @@ func (codec) EncodeResponse(ctx context.Context, res queryrange.Response) (*http
}
}

sp.LogFields(otlog.Int("bytes", buf.Len()))

resp := http.Response{
Header: http.Header{
"Content-Type": []string{"application/json"},
},
Body: ioutil.NopCloser(&buf),
StatusCode: http.StatusOK,
}
return &resp, nil
case *LokiSeriesResponse:
result := logproto.SeriesResponse{
Series: response.Data,
}
var buf bytes.Buffer
if err := marshal.WriteSeriesResponseJSON(result, &buf); err != nil {
return nil, err
}

sp.LogFields(otlog.Int("bytes", buf.Len()))

resp := http.Response{
Header: http.Header{
"Content-Type": []string{"application/json"},
},
Body: ioutil.NopCloser(&buf),
StatusCode: http.StatusOK,
case *LokiLabelNamesResponse:
if loghttp.Version(response.Version) == loghttp.VersionLegacy {
if err := marshal_legacy.WriteLabelResponseJSON(logproto.LabelResponse{Values: response.Data}, &buf); err != nil {
return nil, err
}
} else {
if err := marshal.WriteLabelResponseJSON(logproto.LabelResponse{Values: response.Data}, &buf); err != nil {
return nil, err
}
}
return &resp, nil
default:
return nil, httpgrpc.Errorf(http.StatusInternalServerError, "invalid response format")
}

sp.LogFields(otlog.Int("bytes", buf.Len()))

resp := http.Response{
Header: http.Header{
"Content-Type": []string{"application/json"},
},
Body: ioutil.NopCloser(&buf),
StatusCode: http.StatusOK,
}
return &resp, nil
}

func (codec) MergeResponse(responses ...queryrange.Response) (queryrange.Response, error) {
Expand Down Expand Up @@ -406,6 +478,28 @@ func (codec) MergeResponse(responses ...queryrange.Response) (queryrange.Respons
Version: lokiSeriesRes.Version,
Data: lokiSeriesData,
}, nil
case *LokiLabelNamesResponse:
labelNameRes := responses[0].(*LokiLabelNamesResponse)
uniqueNames := make(map[string]struct{})
names := []string{}

// only unique name should be merged
for _, res := range responses {
lokiResult := res.(*LokiLabelNamesResponse)
for _, labelName := range lokiResult.Data {
if _, ok := uniqueNames[labelName]; !ok {
names = append(names, labelName)
uniqueNames[labelName] = struct{}{}
}

}
}

return &LokiLabelNamesResponse{
Status: labelNameRes.Status,
Version: labelNameRes.Version,
Data: names,
}, nil
default:
return nil, errors.New("unknown response in merging responses")
}
Expand Down
90 changes: 90 additions & 0 deletions pkg/querier/queryrange/codec_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,14 @@ func Test_codec_DecodeRequest(t *testing.T) {
StartTs: start,
EndTs: end,
}, false},
{"labels", func() (*http.Request, error) {
return http.NewRequest(http.MethodGet,
fmt.Sprintf(`/label?start=%d&end=%d`, start.UnixNano(), end.UnixNano()), nil)
}, &LokiLabelNamesRequest{
Path: "/label",
StartTs: start,
EndTs: end,
}, false},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
Expand Down Expand Up @@ -131,6 +139,13 @@ func Test_codec_DecodeResponse(t *testing.T) {
Version: uint32(loghttp.VersionV1),
Data: seriesData,
}, false},
{"labels legacy", &http.Response{StatusCode: 200, Body: ioutil.NopCloser(strings.NewReader(labelsString))},
&LokiLabelNamesRequest{Path: "/api/prom/label"},
&LokiLabelNamesResponse{
Status: "success",
Version: uint32(loghttp.VersionLegacy),
Data: labelsData,
}, false},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
Expand Down Expand Up @@ -213,6 +228,29 @@ func Test_codec_series_EncodeRequest(t *testing.T) {
require.Equal(t, "/loki/api/v1/series", req.(*LokiSeriesRequest).Path)
}

func Test_codec_labels_EncodeRequest(t *testing.T) {

ctx := context.Background()
toEncode := &LokiLabelNamesRequest{
Path: "/loki/api/v1/labels",
StartTs: start,
EndTs: end,
}
got, err := lokiCodec.EncodeRequest(ctx, toEncode)
require.NoError(t, err)
require.Equal(t, ctx, got.Context())
require.Equal(t, "/loki/api/v1/labels", got.URL.Path)
require.Equal(t, fmt.Sprintf("%d", start.UnixNano()), got.URL.Query().Get("start"))
require.Equal(t, fmt.Sprintf("%d", end.UnixNano()), got.URL.Query().Get("end"))

// testing a full roundtrip
req, err := lokiCodec.DecodeRequest(context.TODO(), got)
require.NoError(t, err)
require.Equal(t, toEncode.StartTs, req.(*LokiLabelNamesRequest).StartTs)
require.Equal(t, toEncode.EndTs, req.(*LokiLabelNamesRequest).EndTs)
require.Equal(t, "/loki/api/v1/labels", req.(*LokiLabelNamesRequest).Path)
}

func Test_codec_EncodeResponse(t *testing.T) {

tests := []struct {
Expand Down Expand Up @@ -262,6 +300,18 @@ func Test_codec_EncodeResponse(t *testing.T) {
Version: uint32(loghttp.VersionV1),
Data: seriesData,
}, seriesString, false},
{"loki labels",
&LokiLabelNamesResponse{
Status: "success",
Version: uint32(loghttp.VersionV1),
Data: labelsData,
}, labelsString, false},
{"loki labels legacy",
&LokiLabelNamesResponse{
Status: "success",
Version: uint32(loghttp.VersionLegacy),
Data: labelsData,
}, labelsLegacyString, false},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
Expand Down Expand Up @@ -700,6 +750,32 @@ func Test_codec_MergeResponse(t *testing.T) {
},
false,
},
{
"loki labels",
[]queryrange.Response{
&LokiLabelNamesResponse{
Status: "success",
Version: 1,
Data: []string{"foo", "bar", "buzz"},
},
&LokiLabelNamesResponse{
Status: "success",
Version: 1,
Data: []string{"foo", "bar", "buzz"},
},
&LokiLabelNamesResponse{
Status: "success",
Version: 1,
Data: []string{"foo", "blip", "blop"},
},
},
&LokiLabelNamesResponse{
Status: "success",
Version: 1,
Data: []string{"foo", "bar", "buzz", "blip", "blop"},
},
false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
Expand Down Expand Up @@ -867,6 +943,20 @@ var (
Labels: map[string]string{"filename": "/var/hostlog/test.log", "job": "varlogs"},
},
}
labelsString = `{
"status": "success",
"data": [
"foo",
"bar"
]
}`
labelsLegacyString = `{
"values": [
"foo",
"bar"
]
}`
labelsData = []string{"foo", "bar"}
statsResult = stats.Result{
Summary: stats.Summary{
BytesProcessedPerSecond: 20,
Expand Down
15 changes: 14 additions & 1 deletion pkg/querier/queryrange/limits.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,13 @@ type Limits interface {
type limits struct {
Limits
splitDuration time.Duration
overrides bool
}

func (l limits) QuerySplitDuration(user string) time.Duration {
if !l.overrides {
return l.splitDuration
}
dur := l.Limits.QuerySplitDuration(user)
if dur == 0 {
return l.splitDuration
Expand All @@ -30,7 +34,8 @@ func (l limits) QuerySplitDuration(user string) time.Duration {
// WithDefaults will construct a Limits with a default value for QuerySplitDuration when no overrides are present.
func WithDefaultLimits(l Limits, conf queryrange.Config) Limits {
res := limits{
Limits: l,
Limits: l,
overrides: true,
}

if conf.SplitQueriesByDay {
Expand All @@ -44,6 +49,14 @@ func WithDefaultLimits(l Limits, conf queryrange.Config) Limits {
return res
}

// WithSplitByLimits will construct a Limits with a static split by duration.
func WithSplitByLimits(l Limits, splitBy time.Duration) Limits {
return limits{
Limits: l,
splitDuration: splitBy,
}
}

// cacheKeyLimits intersects Limits and CacheSplitter
type cacheKeyLimits struct {
Limits
Expand Down
Loading