api_test.go 49.4 KB
Newer Older
J
Jonathan Boulle 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13
// Copyright 2016 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.

14 15 16
package v1

import (
T
Tom Wilkie 已提交
17
	"bytes"
18
	"context"
19 20 21
	"encoding/json"
	"errors"
	"fmt"
22
	"io"
23
	"io/ioutil"
24
	"math"
25 26 27
	"net/http"
	"net/http/httptest"
	"net/url"
28
	"os"
29
	"reflect"
30
	"strings"
31 32 33
	"testing"
	"time"

34
	"github.com/go-kit/kit/log"
T
Tom Wilkie 已提交
35 36
	"github.com/gogo/protobuf/proto"
	"github.com/golang/snappy"
37
	"github.com/prometheus/client_golang/prometheus"
38
	config_util "github.com/prometheus/common/config"
39
	"github.com/prometheus/common/model"
40
	"github.com/prometheus/common/promlog"
F
Fabian Reinartz 已提交
41
	"github.com/prometheus/common/route"
42

43
	"github.com/prometheus/prometheus/config"
44
	"github.com/prometheus/prometheus/pkg/gate"
45 46
	"github.com/prometheus/prometheus/pkg/labels"
	"github.com/prometheus/prometheus/pkg/timestamp"
T
Tom Wilkie 已提交
47
	"github.com/prometheus/prometheus/prompb"
48
	"github.com/prometheus/prometheus/promql"
M
mg03 已提交
49
	"github.com/prometheus/prometheus/rules"
50
	"github.com/prometheus/prometheus/scrape"
51
	"github.com/prometheus/prometheus/storage"
T
Tom Wilkie 已提交
52
	"github.com/prometheus/prometheus/storage/remote"
T
Tom Wilkie 已提交
53
	"github.com/prometheus/prometheus/tsdb"
54
	"github.com/prometheus/prometheus/util/teststorage"
M
mg03 已提交
55
	"github.com/prometheus/prometheus/util/testutil"
56 57
)

58
type testTargetRetriever struct{}
F
Frederic Branczyk 已提交
59

60 61 62 63
var (
	scrapeStart = time.Now().Add(-11 * time.Second)
)

64
func (t testTargetRetriever) TargetsActive() map[string][]*scrape.Target {
65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86
	testTarget := scrape.NewTarget(
		labels.FromMap(map[string]string{
			model.SchemeLabel:      "http",
			model.AddressLabel:     "example.com:8080",
			model.MetricsPathLabel: "/metrics",
			model.JobLabel:         "test",
		}),
		nil,
		url.Values{},
	)
	testTarget.Report(scrapeStart, 70*time.Millisecond, nil)
	blackboxTarget := scrape.NewTarget(
		labels.FromMap(map[string]string{
			model.SchemeLabel:      "http",
			model.AddressLabel:     "localhost:9115",
			model.MetricsPathLabel: "/probe",
			model.JobLabel:         "blackbox",
		}),
		nil,
		url.Values{"target": []string{"example.com"}},
	)
	blackboxTarget.Report(scrapeStart, 100*time.Millisecond, errors.New("failed"))
87
	return map[string][]*scrape.Target{
88 89
		"test":     {testTarget},
		"blackbox": {blackboxTarget},
90 91
	}
}
92 93
func (t testTargetRetriever) TargetsDropped() map[string][]*scrape.Target {
	return map[string][]*scrape.Target{
S
Simon Pasquier 已提交
94
		"blackbox": {
95 96 97 98 99 100 101 102 103 104 105
			scrape.NewTarget(
				nil,
				labels.FromMap(map[string]string{
					model.AddressLabel:     "http://dropped.example.com:9115",
					model.MetricsPathLabel: "/probe",
					model.SchemeLabel:      "http",
					model.JobLabel:         "blackbox",
				}),
				url.Values{},
			),
		},
106
	}
F
Frederic Branczyk 已提交
107 108
}

109
type testAlertmanagerRetriever struct{}
110

111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128
func (t testAlertmanagerRetriever) Alertmanagers() []*url.URL {
	return []*url.URL{
		{
			Scheme: "http",
			Host:   "alertmanager.example.com:8080",
			Path:   "/api/v1/alerts",
		},
	}
}

func (t testAlertmanagerRetriever) DroppedAlertmanagers() []*url.URL {
	return []*url.URL{
		{
			Scheme: "http",
			Host:   "dropped.alertmanager.example.com:8080",
			Path:   "/api/v1/alerts",
		},
	}
F
Frederic Branczyk 已提交
129 130
}

131 132
type rulesRetrieverMock struct {
	testing *testing.T
M
mg03 已提交
133 134
}

135
func (m rulesRetrieverMock) AlertingRules() []*rules.AlertingRule {
M
mg03 已提交
136 137
	expr1, err := promql.ParseExpr(`absent(test_metric3) != 1`)
	if err != nil {
138
		m.testing.Fatalf("unable to parse alert expression: %s", err)
M
mg03 已提交
139 140 141
	}
	expr2, err := promql.ParseExpr(`up == 1`)
	if err != nil {
142
		m.testing.Fatalf("Unable to parse alert expression: %s", err)
M
mg03 已提交
143 144 145 146 147 148 149 150
	}

	rule1 := rules.NewAlertingRule(
		"test_metric3",
		expr1,
		time.Second,
		labels.Labels{},
		labels.Labels{},
B
Bjoern Rabenstein 已提交
151
		labels.Labels{},
152
		true,
M
mg03 已提交
153 154 155 156 157 158 159 160
		log.NewNopLogger(),
	)
	rule2 := rules.NewAlertingRule(
		"test_metric4",
		expr2,
		time.Second,
		labels.Labels{},
		labels.Labels{},
B
Bjoern Rabenstein 已提交
161
		labels.Labels{},
162
		true,
M
mg03 已提交
163 164 165 166 167 168 169 170
		log.NewNopLogger(),
	)
	var r []*rules.AlertingRule
	r = append(r, rule1)
	r = append(r, rule2)
	return r
}

171 172
func (m rulesRetrieverMock) RuleGroups() []*rules.Group {
	var ar rulesRetrieverMock
M
mg03 已提交
173
	arules := ar.AlertingRules()
174
	storage := teststorage.New(m.testing)
M
mg03 已提交
175 176
	defer storage.Close()

177 178 179 180 181 182 183 184 185
	engineOpts := promql.EngineOpts{
		Logger:        nil,
		Reg:           nil,
		MaxConcurrent: 10,
		MaxSamples:    10,
		Timeout:       100 * time.Second,
	}

	engine := promql.NewEngine(engineOpts)
M
mg03 已提交
186 187 188 189 190 191 192 193 194 195 196 197 198
	opts := &rules.ManagerOptions{
		QueryFunc:  rules.EngineQueryFunc(engine, storage),
		Appendable: storage,
		Context:    context.Background(),
		Logger:     log.NewNopLogger(),
	}

	var r []rules.Rule

	for _, alertrule := range arules {
		r = append(r, alertrule)
	}

199 200 201 202 203 204 205
	recordingExpr, err := promql.ParseExpr(`vector(1)`)
	if err != nil {
		m.testing.Fatalf("unable to parse alert expression: %s", err)
	}
	recordingRule := rules.NewRecordingRule("recording-rule-1", recordingExpr, labels.Labels{})
	r = append(r, recordingRule)

206
	group := rules.NewGroup("grp", "/path/to/file", time.Second, r, false, opts)
M
mg03 已提交
207 208 209
	return []*rules.Group{group}
}

210 211 212 213 214 215 216 217 218
var samplePrometheusCfg = config.Config{
	GlobalConfig:       config.GlobalConfig{},
	AlertingConfig:     config.AlertingConfig{},
	RuleFiles:          []string{},
	ScrapeConfigs:      []*config.ScrapeConfig{},
	RemoteWriteConfigs: []*config.RemoteWriteConfig{},
	RemoteReadConfigs:  []*config.RemoteReadConfig{},
}

219 220 221 222 223
var sampleFlagMap = map[string]string{
	"flag1": "value1",
	"flag2": "value2",
}

224 225 226 227 228 229 230
func TestEndpoints(t *testing.T) {
	suite, err := promql.NewTest(t, `
		load 1m
			test_metric1{foo="bar"} 0+100x100
			test_metric1{foo="boo"} 1+0x100
			test_metric2{foo="boo"} 1+0x100
	`)
231
	testutil.Ok(t, err)
232 233
	defer suite.Close()

234
	testutil.Ok(t, suite.Run())
235

236
	now := time.Now()
F
Frederic Branczyk 已提交
237

238 239 240
	t.Run("local", func(t *testing.T) {
		var algr rulesRetrieverMock
		algr.testing = t
M
mg03 已提交
241 242 243 244 245

		algr.AlertingRules()

		algr.RuleGroups()

246 247 248 249 250
		api := &API{
			Queryable:             suite.Storage(),
			QueryEngine:           suite.QueryEngine(),
			targetRetriever:       testTargetRetriever{},
			alertmanagerRetriever: testAlertmanagerRetriever{},
251
			flagsMap:              sampleFlagMap,
S
Simon Pasquier 已提交
252 253 254 255
			now:                   func() time.Time { return now },
			config:                func() config.Config { return samplePrometheusCfg },
			ready:                 func(f http.HandlerFunc) http.HandlerFunc { return f },
			rulesRetriever:        algr,
256
		}
F
Frederic Branczyk 已提交
257

258 259
		testEndpoints(t, api, true)
	})
260

261 262
	// Run all the API tests against a API that is wired to forward queries via
	// the remote read client to a test server, which in turn sends them to the
T
Tom Wilkie 已提交
263
	// data from the test suite.
264 265 266 267 268
	t.Run("remote", func(t *testing.T) {
		server := setupRemote(suite.Storage())
		defer server.Close()

		u, err := url.Parse(server.URL)
269
		testutil.Ok(t, err)
270 271

		al := promlog.AllowedLevel{}
272
		testutil.Ok(t, al.Set("debug"))
@
@aifsair 已提交
273

A
Alex Yu 已提交
274
		af := promlog.AllowedFormat{}
275
		testutil.Ok(t, af.Set("logfmt"))
@
@aifsair 已提交
276

A
Alex Yu 已提交
277 278 279 280 281
		promlogConfig := promlog.Config{
			Level:  &al,
			Format: &af,
		}

282 283 284 285 286
		dbDir, err := ioutil.TempDir("", "tsdb-api-ready")
		testutil.Ok(t, err)
		defer os.RemoveAll(dbDir)

		remote := remote.NewStorage(promlog.New(&promlogConfig), prometheus.DefaultRegisterer, func() (int64, error) {
287
			return 0, nil
288
		}, dbDir, 1*time.Second)
289 290 291 292 293 294 295 296 297 298

		err = remote.ApplyConfig(&config.Config{
			RemoteReadConfigs: []*config.RemoteReadConfig{
				{
					URL:           &config_util.URL{URL: u},
					RemoteTimeout: model.Duration(1 * time.Second),
					ReadRecent:    true,
				},
			},
		})
299
		testutil.Ok(t, err)
300

301 302
		var algr rulesRetrieverMock
		algr.testing = t
M
mg03 已提交
303 304 305 306 307

		algr.AlertingRules()

		algr.RuleGroups()

308 309 310 311 312
		api := &API{
			Queryable:             remote,
			QueryEngine:           suite.QueryEngine(),
			targetRetriever:       testTargetRetriever{},
			alertmanagerRetriever: testAlertmanagerRetriever{},
313
			flagsMap:              sampleFlagMap,
S
Simon Pasquier 已提交
314 315 316 317
			now:                   func() time.Time { return now },
			config:                func() config.Config { return samplePrometheusCfg },
			ready:                 func(f http.HandlerFunc) http.HandlerFunc { return f },
			rulesRetriever:        algr,
318 319 320 321
		}

		testEndpoints(t, api, false)
	})
322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353

}

func TestLabelNames(t *testing.T) {
	// TestEndpoints doesn't have enough label names to test api.labelNames
	// endpoint properly. Hence we test it separately.
	suite, err := promql.NewTest(t, `
		load 1m
			test_metric1{foo1="bar", baz="abc"} 0+100x100
			test_metric1{foo2="boo"} 1+0x100
			test_metric2{foo="boo"} 1+0x100
			test_metric2{foo="boo", xyz="qwerty"} 1+0x100
	`)
	testutil.Ok(t, err)
	defer suite.Close()
	testutil.Ok(t, suite.Run())

	api := &API{
		Queryable: suite.Storage(),
	}
	request := func(m string) (*http.Request, error) {
		if m == http.MethodPost {
			r, err := http.NewRequest(m, "http://example.com", nil)
			r.Header.Set("Content-Type", "application/x-www-form-urlencoded")
			return r, err
		}
		return http.NewRequest(m, "http://example.com", nil)
	}
	for _, method := range []string{http.MethodGet, http.MethodPost} {
		ctx := context.Background()
		req, err := request(method)
		testutil.Ok(t, err)
354 355 356
		res := api.labelNames(req.WithContext(ctx))
		assertAPIError(t, res.err, "")
		assertAPIResponse(t, res.data, []string{"__name__", "baz", "foo", "foo1", "foo2", "xyz"})
357
	}
358 359 360 361 362 363 364 365 366 367 368 369 370
}

func setupRemote(s storage.Storage) *httptest.Server {
	handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		req, err := remote.DecodeReadRequest(r)
		if err != nil {
			http.Error(w, err.Error(), http.StatusBadRequest)
			return
		}
		resp := prompb.ReadResponse{
			Results: make([]*prompb.QueryResult, len(req.Queries)),
		}
		for i, query := range req.Queries {
371
			matchers, err := remote.FromLabelMatchers(query.Matchers)
372 373 374 375 376
			if err != nil {
				http.Error(w, err.Error(), http.StatusBadRequest)
				return
			}

377 378 379 380 381 382 383 384 385 386 387
			var selectParams *storage.SelectParams
			if query.Hints != nil {
				selectParams = &storage.SelectParams{
					Start: query.Hints.StartMs,
					End:   query.Hints.EndMs,
					Step:  query.Hints.StepMs,
					Func:  query.Hints.Func,
				}
			}

			querier, err := s.Querier(r.Context(), query.StartTimestampMs, query.EndTimestampMs)
388 389 390 391 392 393
			if err != nil {
				http.Error(w, err.Error(), http.StatusInternalServerError)
				return
			}
			defer querier.Close()

394
			set, _, err := querier.Select(selectParams, matchers...)
395 396 397 398
			if err != nil {
				http.Error(w, err.Error(), http.StatusInternalServerError)
				return
			}
399
			resp.Results[i], err = remote.ToQueryResult(set, 1e6)
400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415
			if err != nil {
				http.Error(w, err.Error(), http.StatusInternalServerError)
				return
			}
		}

		if err := remote.EncodeReadResponse(&resp, w); err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
	})

	return httptest.NewServer(handler)
}

func testEndpoints(t *testing.T, api *API, testLabelAPI bool) {
416 417
	start := time.Unix(0, 0)

418
	type test struct {
419
		endpoint apiFunc
420
		params   map[string]string
421 422 423
		query    url.Values
		response interface{}
		errType  errorType
424 425 426
	}

	var tests = []test{
427 428 429 430
		{
			endpoint: api.query,
			query: url.Values{
				"query": []string{"2"},
431
				"time":  []string{"123.4"},
432 433
			},
			response: &queryData{
434 435 436 437
				ResultType: promql.ValueTypeScalar,
				Result: promql.Scalar{
					V: 2,
					T: timestamp.FromTime(start.Add(123*time.Second + 400*time.Millisecond)),
438 439 440 441 442 443 444 445 446 447
				},
			},
		},
		{
			endpoint: api.query,
			query: url.Values{
				"query": []string{"0.333"},
				"time":  []string{"1970-01-01T00:02:03Z"},
			},
			response: &queryData{
448 449 450 451
				ResultType: promql.ValueTypeScalar,
				Result: promql.Scalar{
					V: 0.333,
					T: timestamp.FromTime(start.Add(123 * time.Second)),
452 453 454 455 456 457 458 459 460 461
				},
			},
		},
		{
			endpoint: api.query,
			query: url.Values{
				"query": []string{"0.333"},
				"time":  []string{"1970-01-01T01:02:03+01:00"},
			},
			response: &queryData{
462 463 464 465
				ResultType: promql.ValueTypeScalar,
				Result: promql.Scalar{
					V: 0.333,
					T: timestamp.FromTime(start.Add(123 * time.Second)),
466 467 468
				},
			},
		},
469 470 471 472 473 474
		{
			endpoint: api.query,
			query: url.Values{
				"query": []string{"0.333"},
			},
			response: &queryData{
475 476 477
				ResultType: promql.ValueTypeScalar,
				Result: promql.Scalar{
					V: 0.333,
478
					T: timestamp.FromTime(api.now()),
479 480 481
				},
			},
		},
482 483 484 485 486 487 488 489 490
		{
			endpoint: api.queryRange,
			query: url.Values{
				"query": []string{"time()"},
				"start": []string{"0"},
				"end":   []string{"2"},
				"step":  []string{"1"},
			},
			response: &queryData{
491 492 493 494 495 496 497
				ResultType: promql.ValueTypeMatrix,
				Result: promql.Matrix{
					promql.Series{
						Points: []promql.Point{
							{V: 0, T: timestamp.FromTime(start)},
							{V: 1, T: timestamp.FromTime(start.Add(1 * time.Second))},
							{V: 2, T: timestamp.FromTime(start.Add(2 * time.Second))},
498
						},
499
						Metric: nil,
500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550
					},
				},
			},
		},
		// Missing query params in range queries.
		{
			endpoint: api.queryRange,
			query: url.Values{
				"query": []string{"time()"},
				"end":   []string{"2"},
				"step":  []string{"1"},
			},
			errType: errorBadData,
		},
		{
			endpoint: api.queryRange,
			query: url.Values{
				"query": []string{"time()"},
				"start": []string{"0"},
				"step":  []string{"1"},
			},
			errType: errorBadData,
		},
		{
			endpoint: api.queryRange,
			query: url.Values{
				"query": []string{"time()"},
				"start": []string{"0"},
				"end":   []string{"2"},
			},
			errType: errorBadData,
		},
		// Bad query expression.
		{
			endpoint: api.query,
			query: url.Values{
				"query": []string{"invalid][query"},
				"time":  []string{"1970-01-01T01:02:03+01:00"},
			},
			errType: errorBadData,
		},
		{
			endpoint: api.queryRange,
			query: url.Values{
				"query": []string{"invalid][query"},
				"start": []string{"0"},
				"end":   []string{"100"},
				"step":  []string{"1"},
			},
			errType: errorBadData,
		},
551
		// Invalid step.
552 553 554 555 556 557 558 559 560 561
		{
			endpoint: api.queryRange,
			query: url.Values{
				"query": []string{"time()"},
				"start": []string{"1"},
				"end":   []string{"2"},
				"step":  []string{"0"},
			},
			errType: errorBadData,
		},
562
		// Start after end.
563 564 565 566 567 568 569 570 571 572
		{
			endpoint: api.queryRange,
			query: url.Values{
				"query": []string{"time()"},
				"start": []string{"2"},
				"end":   []string{"1"},
				"step":  []string{"1"},
			},
			errType: errorBadData,
		},
573 574 575 576 577 578 579 580 581 582 583
		// Start overflows int64 internally.
		{
			endpoint: api.queryRange,
			query: url.Values{
				"query": []string{"time()"},
				"start": []string{"148966367200.372"},
				"end":   []string{"1489667272.372"},
				"step":  []string{"1"},
			},
			errType: errorBadData,
		},
584 585 586 587 588
		{
			endpoint: api.series,
			query: url.Values{
				"match[]": []string{`test_metric2`},
			},
589 590
			response: []labels.Labels{
				labels.FromStrings("__name__", "test_metric2", "foo", "boo"),
591 592 593 594 595
			},
		},
		{
			endpoint: api.series,
			query: url.Values{
596
				"match[]": []string{`test_metric1{foo=~".+o"}`},
597
			},
598 599
			response: []labels.Labels{
				labels.FromStrings("__name__", "test_metric1", "foo", "boo"),
600 601 602 603 604
			},
		},
		{
			endpoint: api.series,
			query: url.Values{
605
				"match[]": []string{`test_metric1{foo=~".+o$"}`, `test_metric1{foo=~".+o"}`},
606
			},
607 608
			response: []labels.Labels{
				labels.FromStrings("__name__", "test_metric1", "foo", "boo"),
609 610 611 612 613
			},
		},
		{
			endpoint: api.series,
			query: url.Values{
614
				"match[]": []string{`test_metric1{foo=~".+o"}`, `none`},
615
			},
616 617
			response: []labels.Labels{
				labels.FromStrings("__name__", "test_metric1", "foo", "boo"),
618 619
			},
		},
620 621 622 623 624 625 626 627
		// Start and end before series starts.
		{
			endpoint: api.series,
			query: url.Values{
				"match[]": []string{`test_metric2`},
				"start":   []string{"-2"},
				"end":     []string{"-1"},
			},
628
			response: []labels.Labels{},
629 630 631 632 633 634 635 636 637
		},
		// Start and end after series ends.
		{
			endpoint: api.series,
			query: url.Values{
				"match[]": []string{`test_metric2`},
				"start":   []string{"100000"},
				"end":     []string{"100001"},
			},
638
			response: []labels.Labels{},
639 640 641 642 643 644 645 646 647
		},
		// Start before series starts, end after series ends.
		{
			endpoint: api.series,
			query: url.Values{
				"match[]": []string{`test_metric2`},
				"start":   []string{"-1"},
				"end":     []string{"100000"},
			},
648 649
			response: []labels.Labels{
				labels.FromStrings("__name__", "test_metric2", "foo", "boo"),
650 651 652 653 654 655 656 657 658 659
			},
		},
		// Start and end within series.
		{
			endpoint: api.series,
			query: url.Values{
				"match[]": []string{`test_metric2`},
				"start":   []string{"1"},
				"end":     []string{"100"},
			},
660 661
			response: []labels.Labels{
				labels.FromStrings("__name__", "test_metric2", "foo", "boo"),
662 663 664 665 666 667 668 669 670 671
			},
		},
		// Start within series, end after.
		{
			endpoint: api.series,
			query: url.Values{
				"match[]": []string{`test_metric2`},
				"start":   []string{"1"},
				"end":     []string{"100000"},
			},
672 673
			response: []labels.Labels{
				labels.FromStrings("__name__", "test_metric2", "foo", "boo"),
674 675 676 677 678 679 680 681 682 683
			},
		},
		// Start before series, end within series.
		{
			endpoint: api.series,
			query: url.Values{
				"match[]": []string{`test_metric2`},
				"start":   []string{"-1"},
				"end":     []string{"1"},
			},
684 685
			response: []labels.Labels{
				labels.FromStrings("__name__", "test_metric2", "foo", "boo"),
686 687
			},
		},
688 689 690 691 692 693 694
		// Missing match[] query params in series requests.
		{
			endpoint: api.series,
			errType:  errorBadData,
		},
		{
			endpoint: api.dropSeries,
F
Fabian Reinartz 已提交
695
			errType:  errorInternal,
696
		},
697
		{
F
Frederic Branczyk 已提交
698
			endpoint: api.targets,
699
			response: &TargetDiscovery{
S
Simon Pasquier 已提交
700 701 702 703 704
				ActiveTargets: []*Target{
					{
						DiscoveredLabels: map[string]string{},
						Labels: map[string]string{
							"job": "blackbox",
705
						},
706 707 708 709 710 711
						ScrapePool:         "blackbox",
						ScrapeURL:          "http://localhost:9115/probe?target=example.com",
						Health:             "down",
						LastError:          "failed",
						LastScrape:         scrapeStart,
						LastScrapeDuration: 0.1,
S
Simon Pasquier 已提交
712 713 714 715 716 717
					},
					{
						DiscoveredLabels: map[string]string{},
						Labels: map[string]string{
							"job": "test",
						},
718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733
						ScrapePool:         "test",
						ScrapeURL:          "http://example.com:8080/metrics",
						Health:             "up",
						LastError:          "",
						LastScrape:         scrapeStart,
						LastScrapeDuration: 0.07,
					},
				},
				DroppedTargets: []*DroppedTarget{
					{
						DiscoveredLabels: map[string]string{
							"__address__":      "http://dropped.example.com:9115",
							"__metrics_path__": "/probe",
							"__scheme__":       "http",
							"job":              "blackbox",
						},
734
					},
F
Frederic Branczyk 已提交
735
				},
736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823
			},
		},
		{
			endpoint: api.targets,
			query: url.Values{
				"state": []string{"any"},
			},
			response: &TargetDiscovery{
				ActiveTargets: []*Target{
					{
						DiscoveredLabels: map[string]string{},
						Labels: map[string]string{
							"job": "blackbox",
						},
						ScrapePool:         "blackbox",
						ScrapeURL:          "http://localhost:9115/probe?target=example.com",
						Health:             "down",
						LastError:          "failed",
						LastScrape:         scrapeStart,
						LastScrapeDuration: 0.1,
					},
					{
						DiscoveredLabels: map[string]string{},
						Labels: map[string]string{
							"job": "test",
						},
						ScrapePool:         "test",
						ScrapeURL:          "http://example.com:8080/metrics",
						Health:             "up",
						LastError:          "",
						LastScrape:         scrapeStart,
						LastScrapeDuration: 0.07,
					},
				},
				DroppedTargets: []*DroppedTarget{
					{
						DiscoveredLabels: map[string]string{
							"__address__":      "http://dropped.example.com:9115",
							"__metrics_path__": "/probe",
							"__scheme__":       "http",
							"job":              "blackbox",
						},
					},
				},
			},
		},
		{
			endpoint: api.targets,
			query: url.Values{
				"state": []string{"active"},
			},
			response: &TargetDiscovery{
				ActiveTargets: []*Target{
					{
						DiscoveredLabels: map[string]string{},
						Labels: map[string]string{
							"job": "blackbox",
						},
						ScrapePool:         "blackbox",
						ScrapeURL:          "http://localhost:9115/probe?target=example.com",
						Health:             "down",
						LastError:          "failed",
						LastScrape:         scrapeStart,
						LastScrapeDuration: 0.1,
					},
					{
						DiscoveredLabels: map[string]string{},
						Labels: map[string]string{
							"job": "test",
						},
						ScrapePool:         "test",
						ScrapeURL:          "http://example.com:8080/metrics",
						Health:             "up",
						LastError:          "",
						LastScrape:         scrapeStart,
						LastScrapeDuration: 0.07,
					},
				},
				DroppedTargets: []*DroppedTarget{},
			},
		},
		{
			endpoint: api.targets,
			query: url.Values{
				"state": []string{"Dropped"},
			},
			response: &TargetDiscovery{
				ActiveTargets: []*Target{},
S
Simon Pasquier 已提交
824 825 826 827 828 829 830
				DroppedTargets: []*DroppedTarget{
					{
						DiscoveredLabels: map[string]string{
							"__address__":      "http://dropped.example.com:9115",
							"__metrics_path__": "/probe",
							"__scheme__":       "http",
							"job":              "blackbox",
831 832 833
						},
					},
				},
F
Frederic Branczyk 已提交
834
			},
835
		},
836
		{
837 838 839
			endpoint: api.alertmanagers,
			response: &AlertmanagerDiscovery{
				ActiveAlertmanagers: []*AlertmanagerTarget{
A
Alexey Palazhchenko 已提交
840
					{
841 842 843
						URL: "http://alertmanager.example.com:8080/api/v1/alerts",
					},
				},
844 845 846 847 848
				DroppedAlertmanagers: []*AlertmanagerTarget{
					{
						URL: "http://dropped.alertmanager.example.com:8080/api/v1/alerts",
					},
				},
849
			},
850
		},
851 852 853 854 855 856
		{
			endpoint: api.serveConfig,
			response: &prometheusConfig{
				YAML: samplePrometheusCfg.String(),
			},
		},
857 858 859 860
		{
			endpoint: api.serveFlags,
			response: sampleFlagMap,
		},
M
mg03 已提交
861 862 863
		{
			endpoint: api.alerts,
			response: &AlertDiscovery{
864
				Alerts: []*Alert{},
M
mg03 已提交
865 866 867 868
			},
		},
		{
			endpoint: api.rules,
869 870
			response: &RuleDiscovery{
				RuleGroups: []*RuleGroup{
M
mg03 已提交
871
					{
872 873 874 875 876 877 878 879 880 881 882
						Name:     "grp",
						File:     "/path/to/file",
						Interval: 1,
						Rules: []rule{
							alertingRule{
								Name:        "test_metric3",
								Query:       "absent(test_metric3) != 1",
								Duration:    1,
								Labels:      labels.Labels{},
								Annotations: labels.Labels{},
								Alerts:      []*Alert{},
883
								Health:      "unknown",
884 885 886 887 888 889 890 891 892
								Type:        "alerting",
							},
							alertingRule{
								Name:        "test_metric4",
								Query:       "up == 1",
								Duration:    1,
								Labels:      labels.Labels{},
								Annotations: labels.Labels{},
								Alerts:      []*Alert{},
893
								Health:      "unknown",
894
								Type:        "alerting",
M
mg03 已提交
895
							},
896 897 898 899
							recordingRule{
								Name:   "recording-rule-1",
								Query:  "vector(1)",
								Labels: labels.Labels{},
900
								Health: "unknown",
901
								Type:   "recording",
M
mg03 已提交
902 903 904 905 906 907
							},
						},
					},
				},
			},
		},
908 909
	}

910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939
	if testLabelAPI {
		tests = append(tests, []test{
			{
				endpoint: api.labelValues,
				params: map[string]string{
					"name": "__name__",
				},
				response: []string{
					"test_metric1",
					"test_metric2",
				},
			},
			{
				endpoint: api.labelValues,
				params: map[string]string{
					"name": "foo",
				},
				response: []string{
					"bar",
					"boo",
				},
			},
			// Bad name parameter.
			{
				endpoint: api.labelValues,
				params: map[string]string{
					"name": "not!!!allowed",
				},
				errType: errorBadData,
			},
940 941 942 943 944
			// Label names.
			{
				endpoint: api.labelNames,
				response: []string{"__name__", "foo"},
			},
945 946 947
		}...)
	}

948 949
	methods := func(f apiFunc) []string {
		fp := reflect.ValueOf(f).Pointer()
950
		if fp == reflect.ValueOf(api.query).Pointer() || fp == reflect.ValueOf(api.queryRange).Pointer() || fp == reflect.ValueOf(api.series).Pointer() {
951
			return []string{http.MethodGet, http.MethodPost}
952
		}
953 954
		return []string{http.MethodGet}
	}
955

956 957 958 959 960
	request := func(m string, q url.Values) (*http.Request, error) {
		if m == http.MethodPost {
			r, err := http.NewRequest(m, "http://example.com", strings.NewReader(q.Encode()))
			r.Header.Set("Content-Type", "application/x-www-form-urlencoded")
			return r, err
961
		}
962 963 964
		return http.NewRequest(m, fmt.Sprintf("http://example.com?%s", q.Encode()), nil)
	}

965
	for i, test := range tests {
966 967 968 969 970
		for _, method := range methods(test.endpoint) {
			// Build a context with the correct request params.
			ctx := context.Background()
			for p, v := range test.params {
				ctx = route.WithParam(ctx, p, v)
971
			}
972
			t.Logf("run %d\t%s\t%q", i, method, test.query.Encode())
973 974 975 976 977

			req, err := request(method, test.query)
			if err != nil {
				t.Fatal(err)
			}
978 979 980
			res := test.endpoint(req.WithContext(ctx))
			assertAPIError(t, res.err, test.errType)
			assertAPIResponse(t, res.data, test.response)
981 982 983
		}
	}
}
984

985 986
func assertAPIError(t *testing.T, got *apiError, exp errorType) {
	t.Helper()
987

988 989 990 991 992 993
	if got != nil {
		if exp == errorNone {
			t.Fatalf("Unexpected error: %s", got)
		}
		if exp != got.typ {
			t.Fatalf("Expected error of type %q but got type %q (%q)", exp, got.typ, got)
994
		}
995 996
		return
	}
997
	if exp != errorNone {
998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018
		t.Fatalf("Expected error of type %q but got none", exp)
	}
}

func assertAPIResponse(t *testing.T, got interface{}, exp interface{}) {
	if !reflect.DeepEqual(exp, got) {
		respJSON, err := json.Marshal(got)
		if err != nil {
			t.Fatalf("failed to marshal response as JSON: %v", err.Error())
		}

		expectedRespJSON, err := json.Marshal(exp)
		if err != nil {
			t.Fatalf("failed to marshal expected response as JSON: %v", err.Error())
		}

		t.Fatalf(
			"Response does not match, expected:\n%+v\ngot:\n%+v",
			string(expectedRespJSON),
			string(respJSON),
		)
1019 1020 1021
	}
}

1022
func TestSampledReadEndpoint(t *testing.T) {
T
Tom Wilkie 已提交
1023 1024 1025 1026
	suite, err := promql.NewTest(t, `
		load 1m
			test_metric1{foo="bar",baz="qux"} 1
	`)
1027 1028
	testutil.Ok(t, err)

T
Tom Wilkie 已提交
1029 1030
	defer suite.Close()

1031 1032
	err = suite.Run()
	testutil.Ok(t, err)
T
Tom Wilkie 已提交
1033 1034 1035 1036 1037 1038 1039

	api := &API{
		Queryable:   suite.Storage(),
		QueryEngine: suite.QueryEngine(),
		config: func() config.Config {
			return config.Config{
				GlobalConfig: config.GlobalConfig{
1040
					ExternalLabels: labels.Labels{
1041
						// We expect external labels to be added, with the source labels honored.
1042 1043 1044
						{Name: "baz", Value: "a"},
						{Name: "b", Value: "c"},
						{Name: "d", Value: "e"},
T
Tom Wilkie 已提交
1045 1046 1047 1048
					},
				},
			}
		},
1049 1050
		remoteReadSampleLimit: 1e6,
		remoteReadGate:        gate.New(1),
T
Tom Wilkie 已提交
1051 1052 1053 1054
	}

	// Encode the request.
	matcher1, err := labels.NewMatcher(labels.MatchEqual, "__name__", "test_metric1")
1055 1056
	testutil.Ok(t, err)

T
Tom Wilkie 已提交
1057
	matcher2, err := labels.NewMatcher(labels.MatchEqual, "d", "e")
1058 1059
	testutil.Ok(t, err)

1060
	query, err := remote.ToQuery(0, 1, []*labels.Matcher{matcher1, matcher2}, &storage.SelectParams{Step: 0, Func: "avg"})
1061 1062
	testutil.Ok(t, err)

T
Tom Wilkie 已提交
1063 1064
	req := &prompb.ReadRequest{Queries: []*prompb.Query{query}}
	data, err := proto.Marshal(req)
1065 1066
	testutil.Ok(t, err)

T
Tom Wilkie 已提交
1067 1068
	compressed := snappy.Encode(nil, data)
	request, err := http.NewRequest("POST", "", bytes.NewBuffer(compressed))
1069 1070
	testutil.Ok(t, err)

T
Tom Wilkie 已提交
1071 1072 1073
	recorder := httptest.NewRecorder()
	api.remoteRead(recorder, request)

1074 1075 1076 1077
	if recorder.Code/100 != 2 {
		t.Fatal(recorder.Code)
	}

1078 1079 1080
	testutil.Equals(t, "application/x-protobuf", recorder.Result().Header.Get("Content-Type"))
	testutil.Equals(t, "snappy", recorder.Result().Header.Get("Content-Encoding"))

T
Tom Wilkie 已提交
1081 1082
	// Decode the response.
	compressed, err = ioutil.ReadAll(recorder.Result().Body)
1083 1084
	testutil.Ok(t, err)

T
Tom Wilkie 已提交
1085
	uncompressed, err := snappy.Decode(nil, compressed)
1086
	testutil.Ok(t, err)
T
Tom Wilkie 已提交
1087 1088 1089

	var resp prompb.ReadResponse
	err = proto.Unmarshal(uncompressed, &resp)
1090
	testutil.Ok(t, err)
T
Tom Wilkie 已提交
1091 1092 1093 1094 1095

	if len(resp.Results) != 1 {
		t.Fatalf("Expected 1 result, got %d", len(resp.Results))
	}

1096
	testutil.Equals(t, &prompb.QueryResult{
T
Tom Wilkie 已提交
1097 1098
		Timeseries: []*prompb.TimeSeries{
			{
1099
				Labels: []prompb.Label{
T
Tom Wilkie 已提交
1100 1101
					{Name: "__name__", Value: "test_metric1"},
					{Name: "b", Value: "c"},
T
Tom Wilkie 已提交
1102
					{Name: "baz", Value: "qux"},
T
Tom Wilkie 已提交
1103
					{Name: "d", Value: "e"},
T
Tom Wilkie 已提交
1104
					{Name: "foo", Value: "bar"},
T
Tom Wilkie 已提交
1105
				},
1106
				Samples: []prompb.Sample{{Value: 1, Timestamp: 0}},
T
Tom Wilkie 已提交
1107 1108
			},
		},
1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155
	}, resp.Results[0])
}

func TestStreamReadEndpoint(t *testing.T) {
	// First with 120 samples. We expect 1 frame with 1 chunk.
	// Second with 121 samples, We expect 1 frame with 2 chunks.
	// Third with 241 samples. We expect 1 frame with 2 chunks, and 1 frame with 1 chunk for the same series due to bytes limit.
	suite, err := promql.NewTest(t, `
		load 1m
			test_metric1{foo="bar1",baz="qux"} 0+100x119
            test_metric1{foo="bar2",baz="qux"} 0+100x120
            test_metric1{foo="bar3",baz="qux"} 0+100x240
	`)
	testutil.Ok(t, err)

	defer suite.Close()

	testutil.Ok(t, suite.Run())

	api := &API{
		Queryable:   suite.Storage(),
		QueryEngine: suite.QueryEngine(),
		config: func() config.Config {
			return config.Config{
				GlobalConfig: config.GlobalConfig{
					ExternalLabels: labels.Labels{
						// We expect external labels to be added, with the source labels honored.
						{Name: "baz", Value: "a"},
						{Name: "b", Value: "c"},
						{Name: "d", Value: "e"},
					},
				},
			}
		},
		remoteReadSampleLimit: 1e6,
		remoteReadGate:        gate.New(1),
		// Labelset has 57 bytes. Full chunk in test data has roughly 240 bytes. This allows us to have at max 2 chunks in this test.
		remoteReadMaxBytesInFrame: 57 + 480,
	}

	// Encode the request.
	matcher1, err := labels.NewMatcher(labels.MatchEqual, "__name__", "test_metric1")
	testutil.Ok(t, err)

	matcher2, err := labels.NewMatcher(labels.MatchEqual, "d", "e")
	testutil.Ok(t, err)

1156 1157 1158 1159 1160 1161 1162
	matcher3, err := labels.NewMatcher(labels.MatchEqual, "foo", "bar1")
	testutil.Ok(t, err)

	query1, err := remote.ToQuery(0, 14400001, []*labels.Matcher{matcher1, matcher2}, &storage.SelectParams{Step: 0, Func: "avg"})
	testutil.Ok(t, err)

	query2, err := remote.ToQuery(0, 14400001, []*labels.Matcher{matcher1, matcher3}, &storage.SelectParams{Step: 0, Func: "avg"})
1163 1164 1165
	testutil.Ok(t, err)

	req := &prompb.ReadRequest{
1166
		Queries:               []*prompb.Query{query1, query2},
1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180
		AcceptedResponseTypes: []prompb.ReadRequest_ResponseType{prompb.ReadRequest_STREAMED_XOR_CHUNKS},
	}
	data, err := proto.Marshal(req)
	testutil.Ok(t, err)

	compressed := snappy.Encode(nil, data)
	request, err := http.NewRequest("POST", "", bytes.NewBuffer(compressed))
	testutil.Ok(t, err)

	recorder := httptest.NewRecorder()
	api.remoteRead(recorder, request)

	if recorder.Code/100 != 2 {
		t.Fatal(recorder.Code)
T
Tom Wilkie 已提交
1181
	}
1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197

	testutil.Equals(t, "application/x-streamed-protobuf; proto=prometheus.ChunkedReadResponse", recorder.Result().Header.Get("Content-Type"))
	testutil.Equals(t, "", recorder.Result().Header.Get("Content-Encoding"))

	var results []*prompb.ChunkedReadResponse
	stream := remote.NewChunkedReader(recorder.Result().Body, remote.DefaultChunkedReadLimit, nil)
	for {
		res := &prompb.ChunkedReadResponse{}
		err := stream.NextProto(res)
		if err == io.EOF {
			break
		}
		testutil.Ok(t, err)
		results = append(results, res)
	}

1198 1199
	if len(results) != 5 {
		t.Fatalf("Expected 5 result, got %d", len(results))
T
Tom Wilkie 已提交
1200
	}
1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295

	testutil.Equals(t, []*prompb.ChunkedReadResponse{
		{
			ChunkedSeries: []*prompb.ChunkedSeries{
				{
					Labels: []prompb.Label{
						{Name: "__name__", Value: "test_metric1"},
						{Name: "b", Value: "c"},
						{Name: "baz", Value: "qux"},
						{Name: "d", Value: "e"},
						{Name: "foo", Value: "bar1"},
					},
					Chunks: []prompb.Chunk{
						{
							Type:      prompb.Chunk_XOR,
							MaxTimeMs: 7140000,
							Data:      []byte("\000x\000\000\000\000\000\000\000\000\000\340\324\003\302|\005\224\000\301\254}\351z2\320O\355\264n[\007\316\224\243md\371\320\375\032Pm\nS\235\016Q\255\006P\275\250\277\312\201Z\003(3\240R\207\332\005(\017\240\322\201\332=(\023\2402\203Z\007(w\2402\201Z\017(\023\265\227\364P\033@\245\007\364\nP\033C\245\002t\036P+@e\036\364\016Pk@e\002t:P;A\245\001\364\nS\373@\245\006t\006P+C\345\002\364\006Pk@\345\036t\nP\033A\245\003\364:P\033@\245\006t\016ZJ\377\\\205\313\210\327\270\017\345+F[\310\347E)\355\024\241\366\342}(v\215(N\203)\326\207(\336\203(V\332W\362\202t4\240m\005(\377AJ\006\320\322\202t\374\240\255\003(oA\312:\3202"),
						},
					},
				},
			},
		},
		{
			ChunkedSeries: []*prompb.ChunkedSeries{
				{
					Labels: []prompb.Label{
						{Name: "__name__", Value: "test_metric1"},
						{Name: "b", Value: "c"},
						{Name: "baz", Value: "qux"},
						{Name: "d", Value: "e"},
						{Name: "foo", Value: "bar2"},
					},
					Chunks: []prompb.Chunk{
						{
							Type:      prompb.Chunk_XOR,
							MaxTimeMs: 7140000,
							Data:      []byte("\000x\000\000\000\000\000\000\000\000\000\340\324\003\302|\005\224\000\301\254}\351z2\320O\355\264n[\007\316\224\243md\371\320\375\032Pm\nS\235\016Q\255\006P\275\250\277\312\201Z\003(3\240R\207\332\005(\017\240\322\201\332=(\023\2402\203Z\007(w\2402\201Z\017(\023\265\227\364P\033@\245\007\364\nP\033C\245\002t\036P+@e\036\364\016Pk@e\002t:P;A\245\001\364\nS\373@\245\006t\006P+C\345\002\364\006Pk@\345\036t\nP\033A\245\003\364:P\033@\245\006t\016ZJ\377\\\205\313\210\327\270\017\345+F[\310\347E)\355\024\241\366\342}(v\215(N\203)\326\207(\336\203(V\332W\362\202t4\240m\005(\377AJ\006\320\322\202t\374\240\255\003(oA\312:\3202"),
						},
						{
							Type:      prompb.Chunk_XOR,
							MinTimeMs: 7200000,
							MaxTimeMs: 7200000,
							Data:      []byte("\000\001\200\364\356\006@\307p\000\000\000\000\000\000"),
						},
					},
				},
			},
		},
		{
			ChunkedSeries: []*prompb.ChunkedSeries{
				{
					Labels: []prompb.Label{
						{Name: "__name__", Value: "test_metric1"},
						{Name: "b", Value: "c"},
						{Name: "baz", Value: "qux"},
						{Name: "d", Value: "e"},
						{Name: "foo", Value: "bar3"},
					},
					Chunks: []prompb.Chunk{
						{
							Type:      prompb.Chunk_XOR,
							MaxTimeMs: 7140000,
							Data:      []byte("\000x\000\000\000\000\000\000\000\000\000\340\324\003\302|\005\224\000\301\254}\351z2\320O\355\264n[\007\316\224\243md\371\320\375\032Pm\nS\235\016Q\255\006P\275\250\277\312\201Z\003(3\240R\207\332\005(\017\240\322\201\332=(\023\2402\203Z\007(w\2402\201Z\017(\023\265\227\364P\033@\245\007\364\nP\033C\245\002t\036P+@e\036\364\016Pk@e\002t:P;A\245\001\364\nS\373@\245\006t\006P+C\345\002\364\006Pk@\345\036t\nP\033A\245\003\364:P\033@\245\006t\016ZJ\377\\\205\313\210\327\270\017\345+F[\310\347E)\355\024\241\366\342}(v\215(N\203)\326\207(\336\203(V\332W\362\202t4\240m\005(\377AJ\006\320\322\202t\374\240\255\003(oA\312:\3202"),
						},
						{
							Type:      prompb.Chunk_XOR,
							MinTimeMs: 7200000,
							MaxTimeMs: 14340000,
							Data:      []byte("\000x\200\364\356\006@\307p\000\000\000\000\000\340\324\003\340>\224\355\260\277\322\200\372\005(=\240R\207:\003(\025\240\362\201z\003(\365\240r\203:\005(\r\241\322\201\372\r(\r\240R\237:\007(5\2402\201z\037(\025\2402\203:\005(\375\240R\200\372\r(\035\241\322\201:\003(5\240r\326g\364\271\213\227!\253q\037\312N\340GJ\033E)\375\024\241\266\362}(N\217(V\203)\336\207(\326\203(N\334W\322\203\2644\240}\005(\373AJ\031\3202\202\264\374\240\275\003(kA\3129\320R\201\2644\240\375\264\277\322\200\332\005(3\240r\207Z\003(\027\240\362\201Z\003(\363\240R\203\332\005(\017\241\322\201\332\r(\023\2402\237Z\007(7\2402\201Z\037(\023\240\322\200\332\005(\377\240R\200\332\r "),
						},
					},
				},
			},
		},
		{
			ChunkedSeries: []*prompb.ChunkedSeries{
				{
					Labels: []prompb.Label{
						{Name: "__name__", Value: "test_metric1"},
						{Name: "b", Value: "c"},
						{Name: "baz", Value: "qux"},
						{Name: "d", Value: "e"},
						{Name: "foo", Value: "bar3"},
					},
					Chunks: []prompb.Chunk{
						{
							Type:      prompb.Chunk_XOR,
							MinTimeMs: 14400000,
							MaxTimeMs: 14400000,
							Data:      []byte("\000\001\200\350\335\r@\327p\000\000\000\000\000\000"),
						},
					},
				},
			},
		},
1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316
		{
			ChunkedSeries: []*prompb.ChunkedSeries{
				{
					Labels: []prompb.Label{
						{Name: "__name__", Value: "test_metric1"},
						{Name: "b", Value: "c"},
						{Name: "baz", Value: "qux"},
						{Name: "d", Value: "e"},
						{Name: "foo", Value: "bar1"},
					},
					Chunks: []prompb.Chunk{
						{
							Type:      prompb.Chunk_XOR,
							MaxTimeMs: 7140000,
							Data:      []byte("\000x\000\000\000\000\000\000\000\000\000\340\324\003\302|\005\224\000\301\254}\351z2\320O\355\264n[\007\316\224\243md\371\320\375\032Pm\nS\235\016Q\255\006P\275\250\277\312\201Z\003(3\240R\207\332\005(\017\240\322\201\332=(\023\2402\203Z\007(w\2402\201Z\017(\023\265\227\364P\033@\245\007\364\nP\033C\245\002t\036P+@e\036\364\016Pk@e\002t:P;A\245\001\364\nS\373@\245\006t\006P+C\345\002\364\006Pk@\345\036t\nP\033A\245\003\364:P\033@\245\006t\016ZJ\377\\\205\313\210\327\270\017\345+F[\310\347E)\355\024\241\366\342}(v\215(N\203)\326\207(\336\203(V\332W\362\202t4\240m\005(\377AJ\006\320\322\202t\374\240\255\003(oA\312:\3202"),
						},
					},
				},
			},
			QueryIndex: 1,
		},
1317
	}, results)
T
Tom Wilkie 已提交
1318 1319
}

1320 1321 1322 1323 1324
type fakeDB struct {
	err    error
	closer func()
}

T
Tom Wilkie 已提交
1325 1326
func (f *fakeDB) CleanTombstones() error                               { return f.err }
func (f *fakeDB) Delete(mint, maxt int64, ms ...*labels.Matcher) error { return f.err }
1327 1328 1329 1330 1331 1332 1333 1334
func (f *fakeDB) Dir() string {
	dir, _ := ioutil.TempDir("", "fakeDB")
	f.closer = func() {
		os.RemoveAll(dir)
	}
	return dir
}
func (f *fakeDB) Snapshot(dir string, withHead bool) error { return f.err }
1335 1336 1337 1338
func (f *fakeDB) Head() *tsdb.Head {
	h, _ := tsdb.NewHead(nil, nil, nil, 1000)
	return h
}
1339 1340

func TestAdminEndpoints(t *testing.T) {
1341
	tsdb, tsdbWithError := &fakeDB{}, &fakeDB{err: errors.New("some error")}
1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373
	snapshotAPI := func(api *API) apiFunc { return api.snapshot }
	cleanAPI := func(api *API) apiFunc { return api.cleanTombstones }
	deleteAPI := func(api *API) apiFunc { return api.deleteSeries }

	for i, tc := range []struct {
		db          *fakeDB
		enableAdmin bool
		endpoint    func(api *API) apiFunc
		method      string
		values      url.Values

		errType errorType
	}{
		// Tests for the snapshot endpoint.
		{
			db:          tsdb,
			enableAdmin: false,
			endpoint:    snapshotAPI,

			errType: errorUnavailable,
		},
		{
			db:          tsdb,
			enableAdmin: true,
			endpoint:    snapshotAPI,

			errType: errorNone,
		},
		{
			db:          tsdb,
			enableAdmin: true,
			endpoint:    snapshotAPI,
M
Matt Layher 已提交
1374
			values:      map[string][]string{"skip_head": {"true"}},
1375 1376 1377 1378 1379 1380 1381

			errType: errorNone,
		},
		{
			db:          tsdb,
			enableAdmin: true,
			endpoint:    snapshotAPI,
M
Matt Layher 已提交
1382
			values:      map[string][]string{"skip_head": {"xxx"}},
1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447

			errType: errorBadData,
		},
		{
			db:          tsdbWithError,
			enableAdmin: true,
			endpoint:    snapshotAPI,

			errType: errorInternal,
		},
		{
			db:          nil,
			enableAdmin: true,
			endpoint:    snapshotAPI,

			errType: errorUnavailable,
		},
		// Tests for the cleanTombstones endpoint.
		{
			db:          tsdb,
			enableAdmin: false,
			endpoint:    cleanAPI,

			errType: errorUnavailable,
		},
		{
			db:          tsdb,
			enableAdmin: true,
			endpoint:    cleanAPI,

			errType: errorNone,
		},
		{
			db:          tsdbWithError,
			enableAdmin: true,
			endpoint:    cleanAPI,

			errType: errorInternal,
		},
		{
			db:          nil,
			enableAdmin: true,
			endpoint:    cleanAPI,

			errType: errorUnavailable,
		},
		// Tests for the deleteSeries endpoint.
		{
			db:          tsdb,
			enableAdmin: false,
			endpoint:    deleteAPI,

			errType: errorUnavailable,
		},
		{
			db:          tsdb,
			enableAdmin: true,
			endpoint:    deleteAPI,

			errType: errorBadData,
		},
		{
			db:          tsdb,
			enableAdmin: true,
			endpoint:    deleteAPI,
M
Matt Layher 已提交
1448
			values:      map[string][]string{"match[]": {"123"}},
1449 1450 1451 1452 1453 1454 1455

			errType: errorBadData,
		},
		{
			db:          tsdb,
			enableAdmin: true,
			endpoint:    deleteAPI,
M
Matt Layher 已提交
1456
			values:      map[string][]string{"match[]": {"up"}, "start": {"xxx"}},
1457 1458 1459 1460 1461 1462 1463

			errType: errorBadData,
		},
		{
			db:          tsdb,
			enableAdmin: true,
			endpoint:    deleteAPI,
M
Matt Layher 已提交
1464
			values:      map[string][]string{"match[]": {"up"}, "end": {"xxx"}},
1465 1466 1467 1468 1469 1470 1471

			errType: errorBadData,
		},
		{
			db:          tsdb,
			enableAdmin: true,
			endpoint:    deleteAPI,
M
Matt Layher 已提交
1472
			values:      map[string][]string{"match[]": {"up"}},
1473 1474 1475 1476 1477 1478 1479

			errType: errorNone,
		},
		{
			db:          tsdb,
			enableAdmin: true,
			endpoint:    deleteAPI,
M
Matt Layher 已提交
1480
			values:      map[string][]string{"match[]": {"up{job!=\"foo\"}", "{job=~\"bar.+\"}", "up{instance!~\"fred.+\"}"}},
1481 1482 1483 1484 1485 1486 1487

			errType: errorNone,
		},
		{
			db:          tsdbWithError,
			enableAdmin: true,
			endpoint:    deleteAPI,
M
Matt Layher 已提交
1488
			values:      map[string][]string{"match[]": {"up"}},
1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522

			errType: errorInternal,
		},
		{
			db:          nil,
			enableAdmin: true,
			endpoint:    deleteAPI,

			errType: errorUnavailable,
		},
	} {
		tc := tc
		t.Run(fmt.Sprintf("%d", i), func(t *testing.T) {
			api := &API{
				db: func() TSDBAdmin {
					if tc.db != nil {
						return tc.db
					}
					return nil
				},
				ready:       func(f http.HandlerFunc) http.HandlerFunc { return f },
				enableAdmin: tc.enableAdmin,
			}
			defer func() {
				if tc.db != nil && tc.db.closer != nil {
					tc.db.closer()
				}
			}()

			endpoint := tc.endpoint(api)
			req, err := http.NewRequest(tc.method, fmt.Sprintf("?%s", tc.values.Encode()), nil)
			if err != nil {
				t.Fatalf("Error when creating test request: %s", err)
			}
1523 1524
			res := endpoint(req)
			assertAPIError(t, res.err, tc.errType)
1525 1526 1527 1528
		})
	}
}

1529
func TestRespondSuccess(t *testing.T) {
1530
	s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
1531
		api := API{}
1532
		api.respond(w, "test", nil)
1533 1534
	}))
	defer s.Close()
1535

1536 1537 1538
	resp, err := http.Get(s.URL)
	if err != nil {
		t.Fatalf("Error on test request: %s", err)
1539
	}
1540 1541
	body, err := ioutil.ReadAll(resp.Body)
	defer resp.Body.Close()
1542
	if err != nil {
1543
		t.Fatalf("Error reading response body: %s", err)
1544 1545
	}

1546 1547 1548 1549 1550 1551 1552 1553 1554 1555
	if resp.StatusCode != 200 {
		t.Fatalf("Return code %d expected in success response but got %d", 200, resp.StatusCode)
	}
	if h := resp.Header.Get("Content-Type"); h != "application/json" {
		t.Fatalf("Expected Content-Type %q but got %q", "application/json", h)
	}

	var res response
	if err = json.Unmarshal([]byte(body), &res); err != nil {
		t.Fatalf("Error unmarshaling JSON body: %s", err)
1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567
	}

	exp := &response{
		Status: statusSuccess,
		Data:   "test",
	}
	if !reflect.DeepEqual(&res, exp) {
		t.Fatalf("Expected response \n%v\n but got \n%v\n", res, exp)
	}
}

func TestRespondError(t *testing.T) {
1568
	s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
1569 1570
		api := API{}
		api.respondError(w, &apiError{errorTimeout, errors.New("message")}, "test")
1571 1572
	}))
	defer s.Close()
1573

1574 1575 1576
	resp, err := http.Get(s.URL)
	if err != nil {
		t.Fatalf("Error on test request: %s", err)
1577
	}
1578 1579
	body, err := ioutil.ReadAll(resp.Body)
	defer resp.Body.Close()
1580
	if err != nil {
1581
		t.Fatalf("Error reading response body: %s", err)
1582 1583
	}

1584 1585
	if want, have := http.StatusServiceUnavailable, resp.StatusCode; want != have {
		t.Fatalf("Return code %d expected in error response but got %d", want, have)
1586 1587 1588 1589 1590 1591 1592 1593
	}
	if h := resp.Header.Get("Content-Type"); h != "application/json" {
		t.Fatalf("Expected Content-Type %q but got %q", "application/json", h)
	}

	var res response
	if err = json.Unmarshal([]byte(body), &res); err != nil {
		t.Fatalf("Error unmarshaling JSON body: %s", err)
1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638
	}

	exp := &response{
		Status:    statusError,
		Data:      "test",
		ErrorType: errorTimeout,
		Error:     "message",
	}
	if !reflect.DeepEqual(&res, exp) {
		t.Fatalf("Expected response \n%v\n but got \n%v\n", res, exp)
	}
}

func TestParseTime(t *testing.T) {
	ts, err := time.Parse(time.RFC3339Nano, "2015-06-03T13:21:58.555Z")
	if err != nil {
		panic(err)
	}

	var tests = []struct {
		input  string
		fail   bool
		result time.Time
	}{
		{
			input: "",
			fail:  true,
		}, {
			input: "abc",
			fail:  true,
		}, {
			input: "30s",
			fail:  true,
		}, {
			input:  "123",
			result: time.Unix(123, 0),
		}, {
			input:  "123.123",
			result: time.Unix(123, 123000000),
		}, {
			input:  "2015-06-03T13:21:58.555Z",
			result: ts,
		}, {
			input:  "2015-06-03T14:21:58.555+01:00",
			result: ts,
1639 1640 1641 1642
		}, {
			// Test float rounding.
			input:  "1543578564.705",
			result: time.Unix(1543578564, 705*1e6),
1643
		},
1644 1645 1646 1647 1648 1649 1650 1651
		{
			input:  minTime.Format(time.RFC3339Nano),
			result: minTime,
		},
		{
			input:  maxTime.Format(time.RFC3339Nano),
			result: maxTime,
		},
1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663
	}

	for _, test := range tests {
		ts, err := parseTime(test.input)
		if err != nil && !test.fail {
			t.Errorf("Unexpected error for %q: %s", test.input, err)
			continue
		}
		if err == nil && test.fail {
			t.Errorf("Expected error for %q but got none", test.input)
			continue
		}
1664 1665
		if !test.fail && !ts.Equal(test.result) {
			t.Errorf("Expected time %v for input %q but got %v", test.result, test.input, ts)
1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684
		}
	}
}

func TestParseDuration(t *testing.T) {
	var tests = []struct {
		input  string
		fail   bool
		result time.Duration
	}{
		{
			input: "",
			fail:  true,
		}, {
			input: "abc",
			fail:  true,
		}, {
			input: "2015-06-03T13:21:58.555Z",
			fail:  true,
1685 1686 1687 1688 1689 1690 1691 1692
		}, {
			// Internal int64 overflow.
			input: "-148966367200.372",
			fail:  true,
		}, {
			// Internal int64 overflow.
			input: "148966367200.372",
			fail:  true,
1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722
		}, {
			input:  "123",
			result: 123 * time.Second,
		}, {
			input:  "123.333",
			result: 123*time.Second + 333*time.Millisecond,
		}, {
			input:  "15s",
			result: 15 * time.Second,
		}, {
			input:  "5m",
			result: 5 * time.Minute,
		},
	}

	for _, test := range tests {
		d, err := parseDuration(test.input)
		if err != nil && !test.fail {
			t.Errorf("Unexpected error for %q: %s", test.input, err)
			continue
		}
		if err == nil && test.fail {
			t.Errorf("Expected error for %q but got none", test.input)
			continue
		}
		if !test.fail && d != test.result {
			t.Errorf("Expected duration %v for input %q but got %v", test.result, test.input, d)
		}
	}
}
1723 1724

func TestOptionsMethod(t *testing.T) {
1725
	r := route.New()
1726
	api := &API{ready: func(f http.HandlerFunc) http.HandlerFunc { return f }}
1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745
	api.Register(r)

	s := httptest.NewServer(r)
	defer s.Close()

	req, err := http.NewRequest("OPTIONS", s.URL+"/any_path", nil)
	if err != nil {
		t.Fatalf("Error creating OPTIONS request: %s", err)
	}
	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		t.Fatalf("Error executing OPTIONS request: %s", err)
	}

	if resp.StatusCode != http.StatusNoContent {
		t.Fatalf("Expected status %d, got %d", http.StatusNoContent, resp.StatusCode)
	}
}
B
Brian Brazil 已提交
1746

1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773
func TestRespond(t *testing.T) {
	cases := []struct {
		response interface{}
		expected string
	}{
		{
			response: &queryData{
				ResultType: promql.ValueTypeMatrix,
				Result: promql.Matrix{
					promql.Series{
						Points: []promql.Point{{V: 1, T: 1000}},
						Metric: labels.FromStrings("__name__", "foo"),
					},
				},
			},
			expected: `{"status":"success","data":{"resultType":"matrix","result":[{"metric":{"__name__":"foo"},"values":[[1,"1"]]}]}}`,
		},
		{
			response: promql.Point{V: 0, T: 0},
			expected: `{"status":"success","data":[0,"0"]}`,
		},
		{
			response: promql.Point{V: 20, T: 1},
			expected: `{"status":"success","data":[0.001,"20"]}`,
		},
		{
			response: promql.Point{V: 20, T: 10},
1774
			expected: `{"status":"success","data":[0.010,"20"]}`,
1775 1776 1777
		},
		{
			response: promql.Point{V: 20, T: 100},
1778
			expected: `{"status":"success","data":[0.100,"20"]}`,
1779 1780 1781 1782 1783 1784 1785
		},
		{
			response: promql.Point{V: 20, T: 1001},
			expected: `{"status":"success","data":[1.001,"20"]}`,
		},
		{
			response: promql.Point{V: 20, T: 1010},
1786
			expected: `{"status":"success","data":[1.010,"20"]}`,
1787 1788 1789
		},
		{
			response: promql.Point{V: 20, T: 1100},
1790
			expected: `{"status":"success","data":[1.100,"20"]}`,
1791 1792 1793
		},
		{
			response: promql.Point{V: 20, T: 12345678123456555},
1794
			expected: `{"status":"success","data":[12345678123456.555,"20"]}`,
1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827
		},
		{
			response: promql.Point{V: 20, T: -1},
			expected: `{"status":"success","data":[-0.001,"20"]}`,
		},
		{
			response: promql.Point{V: math.NaN(), T: 0},
			expected: `{"status":"success","data":[0,"NaN"]}`,
		},
		{
			response: promql.Point{V: math.Inf(1), T: 0},
			expected: `{"status":"success","data":[0,"+Inf"]}`,
		},
		{
			response: promql.Point{V: math.Inf(-1), T: 0},
			expected: `{"status":"success","data":[0,"-Inf"]}`,
		},
		{
			response: promql.Point{V: 1.2345678e6, T: 0},
			expected: `{"status":"success","data":[0,"1234567.8"]}`,
		},
		{
			response: promql.Point{V: 1.2345678e-6, T: 0},
			expected: `{"status":"success","data":[0,"0.0000012345678"]}`,
		},
		{
			response: promql.Point{V: 1.2345678e-67, T: 0},
			expected: `{"status":"success","data":[0,"1.2345678e-67"]}`,
		},
	}

	for _, c := range cases {
		s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
1828
			api := API{}
1829
			api.respond(w, c.response, nil)
1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848
		}))
		defer s.Close()

		resp, err := http.Get(s.URL)
		if err != nil {
			t.Fatalf("Error on test request: %s", err)
		}
		body, err := ioutil.ReadAll(resp.Body)
		defer resp.Body.Close()
		if err != nil {
			t.Fatalf("Error reading response body: %s", err)
		}

		if string(body) != c.expected {
			t.Fatalf("Expected response \n%v\n but got \n%v\n", c.expected, string(body))
		}
	}
}

1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889
func TestTSDBStatus(t *testing.T) {
	tsdb := &fakeDB{}
	tsdbStatusAPI := func(api *API) apiFunc { return api.serveTSDBStatus }

	for i, tc := range []struct {
		db       *fakeDB
		endpoint func(api *API) apiFunc
		method   string
		values   url.Values

		errType errorType
	}{
		// Tests for the TSDB Status endpoint.
		{
			db:       tsdb,
			endpoint: tsdbStatusAPI,

			errType: errorNone,
		},
	} {
		tc := tc
		t.Run(fmt.Sprintf("%d", i), func(t *testing.T) {
			api := &API{
				db: func() TSDBAdmin {
					if tc.db != nil {
						return tc.db
					}
					return nil
				},
			}
			endpoint := tc.endpoint(api)
			req, err := http.NewRequest(tc.method, fmt.Sprintf("?%s", tc.values.Encode()), nil)
			if err != nil {
				t.Fatalf("Error when creating test request: %s", err)
			}
			res := endpoint(req)
			assertAPIError(t, res.err, tc.errType)
		})
	}
}

B
Brian Brazil 已提交
1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907
// This is a global to avoid the benchmark being optimized away.
var testResponseWriter = httptest.ResponseRecorder{}

func BenchmarkRespond(b *testing.B) {
	b.ReportAllocs()
	points := []promql.Point{}
	for i := 0; i < 10000; i++ {
		points = append(points, promql.Point{V: float64(i * 1000000), T: int64(i)})
	}
	response := &queryData{
		ResultType: promql.ValueTypeMatrix,
		Result: promql.Matrix{
			promql.Series{
				Points: points,
				Metric: nil,
			},
		},
	}
1908
	b.ResetTimer()
1909
	api := API{}
B
Brian Brazil 已提交
1910
	for n := 0; n < b.N; n++ {
1911
		api.respond(&testResponseWriter, response, nil)
B
Brian Brazil 已提交
1912 1913
	}
}