api_test.go 63.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
	"sort"
31
	"strings"
32 33 34
	"testing"
	"time"

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

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

60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79
// testMetaStore satisfies the scrape.MetricMetadataStore interface.
// It is used to inject specific metadata as part of a test case.
type testMetaStore struct {
	Metadata []scrape.MetricMetadata
}

func (s *testMetaStore) ListMetadata() []scrape.MetricMetadata {
	return s.Metadata
}

func (s *testMetaStore) GetMetadata(metric string) (scrape.MetricMetadata, bool) {
	for _, m := range s.Metadata {
		if metric == m.Metric {
			return m, true
		}
	}

	return scrape.MetricMetadata{}, false
}

80 81 82
func (s *testMetaStore) SizeMetadata() int   { return 0 }
func (s *testMetaStore) LengthMetadata() int { return 0 }

83 84
// testTargetRetriever represents a list of targets to scrape.
// It is used to represent targets as part of test cases.
85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129
type testTargetRetriever struct {
	activeTargets  map[string][]*scrape.Target
	droppedTargets map[string][]*scrape.Target
}

type testTargetParams struct {
	Identifier       string
	Labels           []labels.Label
	DiscoveredLabels []labels.Label
	Params           url.Values
	Reports          []*testReport
	Active           bool
}

type testReport struct {
	Start    time.Time
	Duration time.Duration
	Error    error
}

func newTestTargetRetriever(targetsInfo []*testTargetParams) *testTargetRetriever {
	var activeTargets map[string][]*scrape.Target
	var droppedTargets map[string][]*scrape.Target
	activeTargets = make(map[string][]*scrape.Target)
	droppedTargets = make(map[string][]*scrape.Target)

	for _, t := range targetsInfo {
		nt := scrape.NewTarget(t.Labels, t.DiscoveredLabels, t.Params)

		for _, r := range t.Reports {
			nt.Report(r.Start, r.Duration, r.Error)
		}

		if t.Active {
			activeTargets[t.Identifier] = []*scrape.Target{nt}
		} else {
			droppedTargets[t.Identifier] = []*scrape.Target{nt}
		}
	}

	return &testTargetRetriever{
		activeTargets:  activeTargets,
		droppedTargets: droppedTargets,
	}
}
F
Frederic Branczyk 已提交
130

131 132 133 134
var (
	scrapeStart = time.Now().Add(-11 * time.Second)
)

135
func (t testTargetRetriever) TargetsActive() map[string][]*scrape.Target {
136
	return t.activeTargets
137
}
138

139
func (t testTargetRetriever) TargetsDropped() map[string][]*scrape.Target {
140
	return t.droppedTargets
F
Frederic Branczyk 已提交
141 142
}

G
gotjosh 已提交
143
func (t *testTargetRetriever) SetMetadataStoreForTargets(identifier string, metadata scrape.MetricMetadataStore) error {
144 145 146 147 148 149 150 151 152 153 154 155 156
	targets, ok := t.activeTargets[identifier]

	if !ok {
		return errors.New("targets not found")
	}

	for _, at := range targets {
		at.SetMetadataStore(metadata)
	}

	return nil
}

G
gotjosh 已提交
157 158 159 160 161 162 163 164
func (t *testTargetRetriever) ResetMetadataStore() {
	for _, at := range t.activeTargets {
		for _, tt := range at {
			tt.SetMetadataStore(&testMetaStore{})
		}
	}
}

165
type testAlertmanagerRetriever struct{}
166

167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184
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 已提交
185 186
}

187 188
type rulesRetrieverMock struct {
	testing *testing.T
M
mg03 已提交
189 190
}

191
func (m rulesRetrieverMock) AlertingRules() []*rules.AlertingRule {
M
mg03 已提交
192 193
	expr1, err := promql.ParseExpr(`absent(test_metric3) != 1`)
	if err != nil {
194
		m.testing.Fatalf("unable to parse alert expression: %s", err)
M
mg03 已提交
195 196 197
	}
	expr2, err := promql.ParseExpr(`up == 1`)
	if err != nil {
198
		m.testing.Fatalf("Unable to parse alert expression: %s", err)
M
mg03 已提交
199 200 201 202 203 204 205 206
	}

	rule1 := rules.NewAlertingRule(
		"test_metric3",
		expr1,
		time.Second,
		labels.Labels{},
		labels.Labels{},
B
Bjoern Rabenstein 已提交
207
		labels.Labels{},
208
		true,
M
mg03 已提交
209 210 211 212 213 214 215 216
		log.NewNopLogger(),
	)
	rule2 := rules.NewAlertingRule(
		"test_metric4",
		expr2,
		time.Second,
		labels.Labels{},
		labels.Labels{},
B
Bjoern Rabenstein 已提交
217
		labels.Labels{},
218
		true,
M
mg03 已提交
219 220 221 222 223 224 225 226
		log.NewNopLogger(),
	)
	var r []*rules.AlertingRule
	r = append(r, rule1)
	r = append(r, rule2)
	return r
}

227 228
func (m rulesRetrieverMock) RuleGroups() []*rules.Group {
	var ar rulesRetrieverMock
M
mg03 已提交
229
	arules := ar.AlertingRules()
230
	storage := teststorage.New(m.testing)
M
mg03 已提交
231 232
	defer storage.Close()

233
	engineOpts := promql.EngineOpts{
234 235 236 237
		Logger:     nil,
		Reg:        nil,
		MaxSamples: 10,
		Timeout:    100 * time.Second,
238 239 240
	}

	engine := promql.NewEngine(engineOpts)
M
mg03 已提交
241 242 243 244 245 246 247 248 249 250 251 252 253
	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)
	}

254 255 256 257 258 259 260
	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)

261 262 263 264 265 266 267 268
	group := rules.NewGroup(rules.GroupOptions{
		Name:          "grp",
		File:          "/path/to/file",
		Interval:      time.Second,
		Rules:         r,
		ShouldRestore: false,
		Opts:          opts,
	})
M
mg03 已提交
269 270 271
	return []*rules.Group{group}
}

272 273 274 275 276 277 278 279 280
var samplePrometheusCfg = config.Config{
	GlobalConfig:       config.GlobalConfig{},
	AlertingConfig:     config.AlertingConfig{},
	RuleFiles:          []string{},
	ScrapeConfigs:      []*config.ScrapeConfig{},
	RemoteWriteConfigs: []*config.RemoteWriteConfig{},
	RemoteReadConfigs:  []*config.RemoteReadConfig{},
}

281 282 283 284 285
var sampleFlagMap = map[string]string{
	"flag1": "value1",
	"flag2": "value2",
}

286 287 288 289 290 291 292
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
	`)
293
	testutil.Ok(t, err)
294 295
	defer suite.Close()

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

298
	now := time.Now()
F
Frederic Branczyk 已提交
299

300 301 302
	t.Run("local", func(t *testing.T) {
		var algr rulesRetrieverMock
		algr.testing = t
M
mg03 已提交
303 304 305 306 307

		algr.AlertingRules()

		algr.RuleGroups()

308
		testTargetRetriever := setupTestTargetRetriever(t)
309

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

G
gotjosh 已提交
322
		testEndpoints(t, api, testTargetRetriever, true)
323
	})
324

325 326
	// 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 已提交
327
	// data from the test suite.
328 329 330 331 332
	t.Run("remote", func(t *testing.T) {
		server := setupRemote(suite.Storage())
		defer server.Close()

		u, err := url.Parse(server.URL)
333
		testutil.Ok(t, err)
334 335

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

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

A
Alex Yu 已提交
341 342 343 344 345
		promlogConfig := promlog.Config{
			Level:  &al,
			Format: &af,
		}

346 347 348 349 350
		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) {
351
			return 0, nil
352
		}, dbDir, 1*time.Second)
353 354 355 356 357 358 359 360 361 362

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

365 366
		var algr rulesRetrieverMock
		algr.testing = t
M
mg03 已提交
367 368 369 370 371

		algr.AlertingRules()

		algr.RuleGroups()

372
		testTargetRetriever := setupTestTargetRetriever(t)
373

374 375 376
		api := &API{
			Queryable:             remote,
			QueryEngine:           suite.QueryEngine(),
377
			targetRetriever:       testTargetRetriever,
378
			alertmanagerRetriever: testAlertmanagerRetriever{},
379
			flagsMap:              sampleFlagMap,
S
Simon Pasquier 已提交
380 381 382 383
			now:                   func() time.Time { return now },
			config:                func() config.Config { return samplePrometheusCfg },
			ready:                 func(f http.HandlerFunc) http.HandlerFunc { return f },
			rulesRetriever:        algr,
384 385
		}

G
gotjosh 已提交
386
		testEndpoints(t, api, testTargetRetriever, false)
387
	})
388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419

}

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)
420 421 422
		res := api.labelNames(req.WithContext(ctx))
		assertAPIError(t, res.err, "")
		assertAPIResponse(t, res.data, []string{"__name__", "baz", "foo", "foo1", "foo2", "xyz"})
423
	}
424 425
}

426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469
func setupTestTargetRetriever(t *testing.T) *testTargetRetriever {
	t.Helper()

	targets := []*testTargetParams{
		{
			Identifier: "test",
			Labels: labels.FromMap(map[string]string{
				model.SchemeLabel:      "http",
				model.AddressLabel:     "example.com:8080",
				model.MetricsPathLabel: "/metrics",
				model.JobLabel:         "test",
			}),
			DiscoveredLabels: nil,
			Params:           url.Values{},
			Reports:          []*testReport{{scrapeStart, 70 * time.Millisecond, nil}},
			Active:           true,
		},
		{
			Identifier: "blackbox",
			Labels: labels.FromMap(map[string]string{
				model.SchemeLabel:      "http",
				model.AddressLabel:     "localhost:9115",
				model.MetricsPathLabel: "/probe",
				model.JobLabel:         "blackbox",
			}),
			DiscoveredLabels: nil,
			Params:           url.Values{"target": []string{"example.com"}},
			Reports:          []*testReport{{scrapeStart, 100 * time.Millisecond, errors.New("failed")}},
			Active:           true,
		},
		{
			Identifier: "blackbox",
			Labels:     nil,
			DiscoveredLabels: labels.FromMap(map[string]string{
				model.SchemeLabel:      "http",
				model.AddressLabel:     "http://dropped.example.com:9115",
				model.MetricsPathLabel: "/probe",
				model.JobLabel:         "blackbox",
			}),
			Params: url.Values{},
			Active: false,
		},
	}

G
gotjosh 已提交
470
	return newTestTargetRetriever(targets)
471 472
}

473 474 475 476 477 478 479 480 481 482 483
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 {
484
			matchers, err := remote.FromLabelMatchers(query.Matchers)
485 486 487 488 489
			if err != nil {
				http.Error(w, err.Error(), http.StatusBadRequest)
				return
			}

490 491 492 493 494 495 496 497 498 499 500
			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)
501 502 503 504 505 506
			if err != nil {
				http.Error(w, err.Error(), http.StatusInternalServerError)
				return
			}
			defer querier.Close()

507
			set, _, err := querier.Select(selectParams, matchers...)
508 509 510 511
			if err != nil {
				http.Error(w, err.Error(), http.StatusInternalServerError)
				return
			}
512
			resp.Results[i], err = remote.ToQueryResult(set, 1e6)
513 514 515 516 517 518 519 520 521 522 523 524 525 526 527
			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)
}

G
gotjosh 已提交
528
func testEndpoints(t *testing.T, api *API, tr *testTargetRetriever, testLabelAPI bool) {
529 530
	start := time.Unix(0, 0)

G
gotjosh 已提交
531 532 533 534 535
	type targetMetadata struct {
		identifier string
		metadata   []scrape.MetricMetadata
	}

536
	type test struct {
G
gotjosh 已提交
537 538 539 540 541 542 543 544
		endpoint    apiFunc
		params      map[string]string
		query       url.Values
		response    interface{}
		responseLen int
		errType     errorType
		sorter      func(interface{})
		metadata    []targetMetadata
545 546 547
	}

	var tests = []test{
548 549 550 551
		{
			endpoint: api.query,
			query: url.Values{
				"query": []string{"2"},
552
				"time":  []string{"123.4"},
553 554
			},
			response: &queryData{
555 556 557 558
				ResultType: promql.ValueTypeScalar,
				Result: promql.Scalar{
					V: 2,
					T: timestamp.FromTime(start.Add(123*time.Second + 400*time.Millisecond)),
559 560 561 562 563 564 565 566 567 568
				},
			},
		},
		{
			endpoint: api.query,
			query: url.Values{
				"query": []string{"0.333"},
				"time":  []string{"1970-01-01T00:02:03Z"},
			},
			response: &queryData{
569 570 571 572
				ResultType: promql.ValueTypeScalar,
				Result: promql.Scalar{
					V: 0.333,
					T: timestamp.FromTime(start.Add(123 * time.Second)),
573 574 575 576 577 578 579 580 581 582
				},
			},
		},
		{
			endpoint: api.query,
			query: url.Values{
				"query": []string{"0.333"},
				"time":  []string{"1970-01-01T01:02:03+01:00"},
			},
			response: &queryData{
583 584 585 586
				ResultType: promql.ValueTypeScalar,
				Result: promql.Scalar{
					V: 0.333,
					T: timestamp.FromTime(start.Add(123 * time.Second)),
587 588 589
				},
			},
		},
590 591 592 593 594 595
		{
			endpoint: api.query,
			query: url.Values{
				"query": []string{"0.333"},
			},
			response: &queryData{
596 597 598
				ResultType: promql.ValueTypeScalar,
				Result: promql.Scalar{
					V: 0.333,
599
					T: timestamp.FromTime(api.now()),
600 601 602
				},
			},
		},
603 604 605 606 607 608 609 610 611
		{
			endpoint: api.queryRange,
			query: url.Values{
				"query": []string{"time()"},
				"start": []string{"0"},
				"end":   []string{"2"},
				"step":  []string{"1"},
			},
			response: &queryData{
612 613 614 615 616 617 618
				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))},
619
						},
620
						Metric: nil,
621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671
					},
				},
			},
		},
		// 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,
		},
672
		// Invalid step.
673 674 675 676 677 678 679 680 681 682
		{
			endpoint: api.queryRange,
			query: url.Values{
				"query": []string{"time()"},
				"start": []string{"1"},
				"end":   []string{"2"},
				"step":  []string{"0"},
			},
			errType: errorBadData,
		},
683
		// Start after end.
684 685 686 687 688 689 690 691 692 693
		{
			endpoint: api.queryRange,
			query: url.Values{
				"query": []string{"time()"},
				"start": []string{"2"},
				"end":   []string{"1"},
				"step":  []string{"1"},
			},
			errType: errorBadData,
		},
694 695 696 697 698 699 700 701 702 703 704
		// 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,
		},
705 706 707 708 709
		{
			endpoint: api.series,
			query: url.Values{
				"match[]": []string{`test_metric2`},
			},
710 711
			response: []labels.Labels{
				labels.FromStrings("__name__", "test_metric2", "foo", "boo"),
712 713 714 715 716
			},
		},
		{
			endpoint: api.series,
			query: url.Values{
717
				"match[]": []string{`test_metric1{foo=~".+o"}`},
718
			},
719 720
			response: []labels.Labels{
				labels.FromStrings("__name__", "test_metric1", "foo", "boo"),
721 722 723 724 725
			},
		},
		{
			endpoint: api.series,
			query: url.Values{
726
				"match[]": []string{`test_metric1{foo=~".+o$"}`, `test_metric1{foo=~".+o"}`},
727
			},
728 729
			response: []labels.Labels{
				labels.FromStrings("__name__", "test_metric1", "foo", "boo"),
730 731 732 733 734
			},
		},
		{
			endpoint: api.series,
			query: url.Values{
735
				"match[]": []string{`test_metric1{foo=~".+o"}`, `none`},
736
			},
737 738
			response: []labels.Labels{
				labels.FromStrings("__name__", "test_metric1", "foo", "boo"),
739 740
			},
		},
741 742 743 744 745 746 747 748
		// Start and end before series starts.
		{
			endpoint: api.series,
			query: url.Values{
				"match[]": []string{`test_metric2`},
				"start":   []string{"-2"},
				"end":     []string{"-1"},
			},
749
			response: []labels.Labels{},
750 751 752 753 754 755 756 757 758
		},
		// Start and end after series ends.
		{
			endpoint: api.series,
			query: url.Values{
				"match[]": []string{`test_metric2`},
				"start":   []string{"100000"},
				"end":     []string{"100001"},
			},
759
			response: []labels.Labels{},
760 761 762 763 764 765 766 767 768
		},
		// Start before series starts, end after series ends.
		{
			endpoint: api.series,
			query: url.Values{
				"match[]": []string{`test_metric2`},
				"start":   []string{"-1"},
				"end":     []string{"100000"},
			},
769 770
			response: []labels.Labels{
				labels.FromStrings("__name__", "test_metric2", "foo", "boo"),
771 772 773 774 775 776 777 778 779 780
			},
		},
		// Start and end within series.
		{
			endpoint: api.series,
			query: url.Values{
				"match[]": []string{`test_metric2`},
				"start":   []string{"1"},
				"end":     []string{"100"},
			},
781 782
			response: []labels.Labels{
				labels.FromStrings("__name__", "test_metric2", "foo", "boo"),
783 784 785 786 787 788 789 790 791 792
			},
		},
		// Start within series, end after.
		{
			endpoint: api.series,
			query: url.Values{
				"match[]": []string{`test_metric2`},
				"start":   []string{"1"},
				"end":     []string{"100000"},
			},
793 794
			response: []labels.Labels{
				labels.FromStrings("__name__", "test_metric2", "foo", "boo"),
795 796 797 798 799 800 801 802 803 804
			},
		},
		// Start before series, end within series.
		{
			endpoint: api.series,
			query: url.Values{
				"match[]": []string{`test_metric2`},
				"start":   []string{"-1"},
				"end":     []string{"1"},
			},
805 806
			response: []labels.Labels{
				labels.FromStrings("__name__", "test_metric2", "foo", "boo"),
807 808
			},
		},
809 810 811 812 813 814 815
		// Missing match[] query params in series requests.
		{
			endpoint: api.series,
			errType:  errorBadData,
		},
		{
			endpoint: api.dropSeries,
F
Fabian Reinartz 已提交
816
			errType:  errorInternal,
817
		},
818
		{
F
Frederic Branczyk 已提交
819
			endpoint: api.targets,
820
			response: &TargetDiscovery{
S
Simon Pasquier 已提交
821 822 823 824 825
				ActiveTargets: []*Target{
					{
						DiscoveredLabels: map[string]string{},
						Labels: map[string]string{
							"job": "blackbox",
826
						},
827 828
						ScrapePool:         "blackbox",
						ScrapeURL:          "http://localhost:9115/probe?target=example.com",
829
						GlobalURL:          "http://localhost:9115/probe?target=example.com",
830
						Health:             "down",
831
						LastError:          "failed: missing port in address",
832 833
						LastScrape:         scrapeStart,
						LastScrapeDuration: 0.1,
S
Simon Pasquier 已提交
834 835 836 837 838 839
					},
					{
						DiscoveredLabels: map[string]string{},
						Labels: map[string]string{
							"job": "test",
						},
840 841
						ScrapePool:         "test",
						ScrapeURL:          "http://example.com:8080/metrics",
842
						GlobalURL:          "http://example.com:8080/metrics",
843 844 845 846 847 848 849 850 851 852 853 854 855 856
						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",
						},
857
					},
F
Frederic Branczyk 已提交
858
				},
859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874
			},
		},
		{
			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",
875
						GlobalURL:          "http://localhost:9115/probe?target=example.com",
876
						Health:             "down",
877
						LastError:          "failed: missing port in address",
878 879 880 881 882 883 884 885 886 887
						LastScrape:         scrapeStart,
						LastScrapeDuration: 0.1,
					},
					{
						DiscoveredLabels: map[string]string{},
						Labels: map[string]string{
							"job": "test",
						},
						ScrapePool:         "test",
						ScrapeURL:          "http://example.com:8080/metrics",
888
						GlobalURL:          "http://example.com:8080/metrics",
889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920
						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",
921
						GlobalURL:          "http://localhost:9115/probe?target=example.com",
922
						Health:             "down",
923
						LastError:          "failed: missing port in address",
924 925 926 927 928 929 930 931 932 933
						LastScrape:         scrapeStart,
						LastScrapeDuration: 0.1,
					},
					{
						DiscoveredLabels: map[string]string{},
						Labels: map[string]string{
							"job": "test",
						},
						ScrapePool:         "test",
						ScrapeURL:          "http://example.com:8080/metrics",
934
						GlobalURL:          "http://example.com:8080/metrics",
935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950
						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 已提交
951 952 953 954 955 956 957
				DroppedTargets: []*DroppedTarget{
					{
						DiscoveredLabels: map[string]string{
							"__address__":      "http://dropped.example.com:9115",
							"__metrics_path__": "/probe",
							"__scheme__":       "http",
							"job":              "blackbox",
958 959 960
						},
					},
				},
F
Frederic Branczyk 已提交
961
			},
962
		},
963 964 965 966 967 968
		// With a matching metric.
		{
			endpoint: api.targetMetadata,
			query: url.Values{
				"metric": []string{"go_threads"},
			},
G
gotjosh 已提交
969 970 971 972 973 974 975 976 977 978 979 980 981
			metadata: []targetMetadata{
				{
					identifier: "test",
					metadata: []scrape.MetricMetadata{
						{
							Metric: "go_threads",
							Type:   textparse.MetricTypeGauge,
							Help:   "Number of OS threads created.",
							Unit:   "",
						},
					},
				},
			},
982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998
			response: []metricMetadata{
				{
					Target: labels.FromMap(map[string]string{
						"job": "test",
					}),
					Help: "Number of OS threads created.",
					Type: textparse.MetricTypeGauge,
					Unit: "",
				},
			},
		},
		// With a matching target.
		{
			endpoint: api.targetMetadata,
			query: url.Values{
				"match_target": []string{"{job=\"blackbox\"}"},
			},
G
gotjosh 已提交
999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011
			metadata: []targetMetadata{
				{
					identifier: "blackbox",
					metadata: []scrape.MetricMetadata{
						{
							Metric: "prometheus_tsdb_storage_blocks_bytes",
							Type:   textparse.MetricTypeGauge,
							Help:   "The number of bytes that are currently used for local storage by all blocks.",
							Unit:   "",
						},
					},
				},
			},
1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026
			response: []metricMetadata{
				{
					Target: labels.FromMap(map[string]string{
						"job": "blackbox",
					}),
					Metric: "prometheus_tsdb_storage_blocks_bytes",
					Help:   "The number of bytes that are currently used for local storage by all blocks.",
					Type:   textparse.MetricTypeGauge,
					Unit:   "",
				},
			},
		},
		// Without a target or metric.
		{
			endpoint: api.targetMetadata,
G
gotjosh 已提交
1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050
			metadata: []targetMetadata{
				{
					identifier: "test",
					metadata: []scrape.MetricMetadata{
						{
							Metric: "go_threads",
							Type:   textparse.MetricTypeGauge,
							Help:   "Number of OS threads created.",
							Unit:   "",
						},
					},
				},
				{
					identifier: "blackbox",
					metadata: []scrape.MetricMetadata{
						{
							Metric: "prometheus_tsdb_storage_blocks_bytes",
							Type:   textparse.MetricTypeGauge,
							Help:   "The number of bytes that are currently used for local storage by all blocks.",
							Unit:   "",
						},
					},
				},
			},
1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070
			response: []metricMetadata{
				{
					Target: labels.FromMap(map[string]string{
						"job": "test",
					}),
					Metric: "go_threads",
					Help:   "Number of OS threads created.",
					Type:   textparse.MetricTypeGauge,
					Unit:   "",
				},
				{
					Target: labels.FromMap(map[string]string{
						"job": "blackbox",
					}),
					Metric: "prometheus_tsdb_storage_blocks_bytes",
					Help:   "The number of bytes that are currently used for local storage by all blocks.",
					Type:   textparse.MetricTypeGauge,
					Unit:   "",
				},
			},
1071 1072 1073 1074 1075 1076
			sorter: func(m interface{}) {
				sort.Slice(m.([]metricMetadata), func(i, j int) bool {
					s := m.([]metricMetadata)
					return s[i].Metric < s[j].Metric
				})
			},
1077 1078 1079 1080 1081 1082 1083
		},
		// Without a matching metric.
		{
			endpoint: api.targetMetadata,
			query: url.Values{
				"match_target": []string{"{job=\"non-existentblackbox\"}"},
			},
G
gotjosh 已提交
1084
			response: []metricMetadata{},
1085
		},
1086
		{
1087 1088 1089
			endpoint: api.alertmanagers,
			response: &AlertmanagerDiscovery{
				ActiveAlertmanagers: []*AlertmanagerTarget{
A
Alexey Palazhchenko 已提交
1090
					{
1091 1092 1093
						URL: "http://alertmanager.example.com:8080/api/v1/alerts",
					},
				},
1094 1095 1096 1097 1098
				DroppedAlertmanagers: []*AlertmanagerTarget{
					{
						URL: "http://dropped.alertmanager.example.com:8080/api/v1/alerts",
					},
				},
1099
			},
1100
		},
G
gotjosh 已提交
1101 1102 1103 1104 1105 1106 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 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199
		// With metadata available.
		{
			endpoint: api.metricMetadata,
			metadata: []targetMetadata{
				{
					identifier: "test",
					metadata: []scrape.MetricMetadata{
						{
							Metric: "prometheus_engine_query_duration_seconds",
							Type:   textparse.MetricTypeSummary,
							Help:   "Query timings",
							Unit:   "",
						},
						{
							Metric: "go_info",
							Type:   textparse.MetricTypeGauge,
							Help:   "Information about the Go environment.",
							Unit:   "",
						},
					},
				},
			},
			response: map[string][]metadata{
				"prometheus_engine_query_duration_seconds": {{textparse.MetricTypeSummary, "Query timings", ""}},
				"go_info": {{textparse.MetricTypeGauge, "Information about the Go environment.", ""}},
			},
		},
		// With duplicate metadata for a metric that comes from different targets.
		{
			endpoint: api.metricMetadata,
			metadata: []targetMetadata{
				{
					identifier: "test",
					metadata: []scrape.MetricMetadata{
						{
							Metric: "go_threads",
							Type:   textparse.MetricTypeGauge,
							Help:   "Number of OS threads created",
							Unit:   "",
						},
					},
				},
				{
					identifier: "blackbox",
					metadata: []scrape.MetricMetadata{
						{
							Metric: "go_threads",
							Type:   textparse.MetricTypeGauge,
							Help:   "Number of OS threads created",
							Unit:   "",
						},
					},
				},
			},
			response: map[string][]metadata{
				"go_threads": {{textparse.MetricTypeGauge, "Number of OS threads created", ""}},
			},
		},
		// With non-duplicate metadata for the same metric from different targets.
		{
			endpoint: api.metricMetadata,
			metadata: []targetMetadata{
				{
					identifier: "test",
					metadata: []scrape.MetricMetadata{
						{
							Metric: "go_threads",
							Type:   textparse.MetricTypeGauge,
							Help:   "Number of OS threads created",
							Unit:   "",
						},
					},
				},
				{
					identifier: "blackbox",
					metadata: []scrape.MetricMetadata{
						{
							Metric: "go_threads",
							Type:   textparse.MetricTypeGauge,
							Help:   "Number of OS threads that were created.",
							Unit:   "",
						},
					},
				},
			},
			response: map[string][]metadata{
				"go_threads": []metadata{
					{textparse.MetricTypeGauge, "Number of OS threads created", ""},
					{textparse.MetricTypeGauge, "Number of OS threads that were created.", ""},
				},
			},
			sorter: func(m interface{}) {
				v := m.(map[string][]metadata)["go_threads"]

				sort.Slice(v, func(i, j int) bool {
					return v[i].Help < v[j].Help
				})
			},
		},
G
gotjosh 已提交
1200
		// With a limit for the number of metrics returned.
G
gotjosh 已提交
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
		{
			endpoint: api.metricMetadata,
			query: url.Values{
				"limit": []string{"2"},
			},
			metadata: []targetMetadata{
				{
					identifier: "test",
					metadata: []scrape.MetricMetadata{
						{
							Metric: "go_threads",
							Type:   textparse.MetricTypeGauge,
							Help:   "Number of OS threads created",
							Unit:   "",
						},
						{
							Metric: "prometheus_engine_query_duration_seconds",
							Type:   textparse.MetricTypeSummary,
							Help:   "Query Timmings.",
							Unit:   "",
						},
					},
				},
				{
					identifier: "blackbox",
					metadata: []scrape.MetricMetadata{
						{
							Metric: "go_gc_duration_seconds",
							Type:   textparse.MetricTypeSummary,
							Help:   "A summary of the GC invocation durations.",
							Unit:   "",
						},
					},
				},
			},
			responseLen: 2,
		},
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 1296 1297 1298 1299 1300 1301 1302 1303 1304
		// When requesting a specific metric that is present.
		{
			endpoint: api.metricMetadata,
			query:    url.Values{"metric": []string{"go_threads"}},
			metadata: []targetMetadata{
				{
					identifier: "test",
					metadata: []scrape.MetricMetadata{
						{
							Metric: "go_threads",
							Type:   textparse.MetricTypeGauge,
							Help:   "Number of OS threads created",
							Unit:   "",
						},
					},
				},
				{
					identifier: "blackbox",
					metadata: []scrape.MetricMetadata{
						{
							Metric: "go_gc_duration_seconds",
							Type:   textparse.MetricTypeSummary,
							Help:   "A summary of the GC invocation durations.",
							Unit:   "",
						},
						{
							Metric: "go_threads",
							Type:   textparse.MetricTypeGauge,
							Help:   "Number of OS threads that were created.",
							Unit:   "",
						},
					},
				},
			},
			response: map[string][]metadata{
				"go_threads": []metadata{
					{textparse.MetricTypeGauge, "Number of OS threads created", ""},
					{textparse.MetricTypeGauge, "Number of OS threads that were created.", ""},
				},
			},
			sorter: func(m interface{}) {
				v := m.(map[string][]metadata)["go_threads"]

				sort.Slice(v, func(i, j int) bool {
					return v[i].Help < v[j].Help
				})
			},
		},
		// With a specific metric that is not present.
		{
			endpoint: api.metricMetadata,
			query:    url.Values{"metric": []string{"go_gc_duration_seconds"}},
			metadata: []targetMetadata{
				{
					identifier: "test",
					metadata: []scrape.MetricMetadata{
						{
							Metric: "go_threads",
							Type:   textparse.MetricTypeGauge,
							Help:   "Number of OS threads created",
							Unit:   "",
						},
					},
				},
			},
			response: map[string][]metadata{},
		},
G
gotjosh 已提交
1305
		// With no available metadata.
G
gotjosh 已提交
1306 1307 1308 1309
		{
			endpoint: api.metricMetadata,
			response: map[string][]metadata{},
		},
1310 1311 1312 1313 1314 1315
		{
			endpoint: api.serveConfig,
			response: &prometheusConfig{
				YAML: samplePrometheusCfg.String(),
			},
		},
1316 1317 1318 1319
		{
			endpoint: api.serveFlags,
			response: sampleFlagMap,
		},
M
mg03 已提交
1320 1321 1322
		{
			endpoint: api.alerts,
			response: &AlertDiscovery{
1323
				Alerts: []*Alert{},
M
mg03 已提交
1324 1325 1326 1327
			},
		},
		{
			endpoint: api.rules,
1328 1329
			response: &RuleDiscovery{
				RuleGroups: []*RuleGroup{
M
mg03 已提交
1330
					{
1331 1332 1333 1334 1335
						Name:     "grp",
						File:     "/path/to/file",
						Interval: 1,
						Rules: []rule{
							alertingRule{
B
Boyko 已提交
1336
								State:       "inactive",
1337 1338 1339 1340 1341 1342
								Name:        "test_metric3",
								Query:       "absent(test_metric3) != 1",
								Duration:    1,
								Labels:      labels.Labels{},
								Annotations: labels.Labels{},
								Alerts:      []*Alert{},
1343
								Health:      "unknown",
1344 1345 1346
								Type:        "alerting",
							},
							alertingRule{
B
Boyko 已提交
1347
								State:       "inactive",
1348 1349 1350 1351 1352 1353
								Name:        "test_metric4",
								Query:       "up == 1",
								Duration:    1,
								Labels:      labels.Labels{},
								Annotations: labels.Labels{},
								Alerts:      []*Alert{},
1354
								Health:      "unknown",
1355
								Type:        "alerting",
M
mg03 已提交
1356
							},
1357 1358 1359 1360
							recordingRule{
								Name:   "recording-rule-1",
								Query:  "vector(1)",
								Labels: labels.Labels{},
1361
								Health: "unknown",
1362
								Type:   "recording",
M
mg03 已提交
1363 1364 1365 1366 1367 1368
							},
						},
					},
				},
			},
		},
B
Boyko 已提交
1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 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
		{
			endpoint: api.rules,
			query: url.Values{
				"type": []string{"alert"},
			},
			response: &RuleDiscovery{
				RuleGroups: []*RuleGroup{
					{
						Name:     "grp",
						File:     "/path/to/file",
						Interval: 1,
						Rules: []rule{
							alertingRule{
								State:       "inactive",
								Name:        "test_metric3",
								Query:       "absent(test_metric3) != 1",
								Duration:    1,
								Labels:      labels.Labels{},
								Annotations: labels.Labels{},
								Alerts:      []*Alert{},
								Health:      "unknown",
								Type:        "alerting",
							},
							alertingRule{
								State:       "inactive",
								Name:        "test_metric4",
								Query:       "up == 1",
								Duration:    1,
								Labels:      labels.Labels{},
								Annotations: labels.Labels{},
								Alerts:      []*Alert{},
								Health:      "unknown",
								Type:        "alerting",
							},
						},
					},
				},
			},
		},
		{
			endpoint: api.rules,
			query: url.Values{
				"type": []string{"record"},
			},
			response: &RuleDiscovery{
				RuleGroups: []*RuleGroup{
					{
						Name:     "grp",
						File:     "/path/to/file",
						Interval: 1,
						Rules: []rule{
							recordingRule{
								Name:   "recording-rule-1",
								Query:  "vector(1)",
								Labels: labels.Labels{},
								Health: "unknown",
								Type:   "recording",
							},
						},
					},
				},
			},
		},
1432 1433
	}

1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463
	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,
			},
1464 1465 1466 1467 1468
			// Label names.
			{
				endpoint: api.labelNames,
				response: []string{"__name__", "foo"},
			},
1469 1470 1471
		}...)
	}

1472 1473
	methods := func(f apiFunc) []string {
		fp := reflect.ValueOf(f).Pointer()
1474
		if fp == reflect.ValueOf(api.query).Pointer() || fp == reflect.ValueOf(api.queryRange).Pointer() || fp == reflect.ValueOf(api.series).Pointer() {
1475
			return []string{http.MethodGet, http.MethodPost}
1476
		}
1477 1478
		return []string{http.MethodGet}
	}
1479

1480 1481 1482 1483
	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")
J
Julien Pivotto 已提交
1484
			r.RemoteAddr = "127.0.0.1:20201"
1485
			return r, err
1486
		}
J
Julien Pivotto 已提交
1487 1488 1489
		r, err := http.NewRequest(m, fmt.Sprintf("http://example.com?%s", q.Encode()), nil)
		r.RemoteAddr = "127.0.0.1:20201"
		return r, err
1490 1491
	}

1492
	for i, test := range tests {
1493 1494 1495 1496 1497
		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)
1498
			}
1499
			t.Logf("run %d\t%s\t%q", i, method, test.query.Encode())
1500 1501 1502 1503 1504

			req, err := request(method, test.query)
			if err != nil {
				t.Fatal(err)
			}
G
gotjosh 已提交
1505 1506 1507 1508 1509 1510

			tr.ResetMetadataStore()
			for _, tm := range test.metadata {
				tr.SetMetadataStoreForTargets(tm.identifier, &testMetaStore{Metadata: tm.metadata})
			}

1511 1512
			res := test.endpoint(req.WithContext(ctx))
			assertAPIError(t, res.err, test.errType)
1513 1514 1515 1516 1517

			if test.sorter != nil {
				test.sorter(res.data)
			}

G
gotjosh 已提交
1518 1519 1520 1521 1522
			if test.responseLen != 0 {
				assertAPIResponseLength(t, res.data, test.responseLen)
			} else {
				assertAPIResponse(t, res.data, test.response)
			}
1523 1524 1525
		}
	}
}
1526

1527 1528
func assertAPIError(t *testing.T, got *apiError, exp errorType) {
	t.Helper()
1529

1530 1531 1532 1533 1534 1535
	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)
1536
		}
1537 1538
		return
	}
1539
	if exp != errorNone {
1540 1541 1542 1543 1544
		t.Fatalf("Expected error of type %q but got none", exp)
	}
}

func assertAPIResponse(t *testing.T, got interface{}, exp interface{}) {
1545 1546
	t.Helper()

1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562
	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),
		)
1563 1564 1565
	}
}

G
gotjosh 已提交
1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578
func assertAPIResponseLength(t *testing.T, got interface{}, expLen int) {
	t.Helper()

	gotLen := reflect.ValueOf(got).Len()
	if gotLen != expLen {
		t.Fatalf(
			"Response length does not match, expected:\n%d\ngot:\n%d",
			expLen,
			gotLen,
		)
	}
}

1579
func TestSampledReadEndpoint(t *testing.T) {
T
Tom Wilkie 已提交
1580 1581 1582 1583
	suite, err := promql.NewTest(t, `
		load 1m
			test_metric1{foo="bar",baz="qux"} 1
	`)
1584 1585
	testutil.Ok(t, err)

T
Tom Wilkie 已提交
1586 1587
	defer suite.Close()

1588 1589
	err = suite.Run()
	testutil.Ok(t, err)
T
Tom Wilkie 已提交
1590 1591 1592 1593 1594 1595 1596

	api := &API{
		Queryable:   suite.Storage(),
		QueryEngine: suite.QueryEngine(),
		config: func() config.Config {
			return config.Config{
				GlobalConfig: config.GlobalConfig{
1597
					ExternalLabels: labels.Labels{
1598
						// We expect external labels to be added, with the source labels honored.
1599 1600 1601
						{Name: "baz", Value: "a"},
						{Name: "b", Value: "c"},
						{Name: "d", Value: "e"},
T
Tom Wilkie 已提交
1602 1603 1604 1605
					},
				},
			}
		},
1606 1607
		remoteReadSampleLimit: 1e6,
		remoteReadGate:        gate.New(1),
T
Tom Wilkie 已提交
1608 1609 1610 1611
	}

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

T
Tom Wilkie 已提交
1614
	matcher2, err := labels.NewMatcher(labels.MatchEqual, "d", "e")
1615 1616
	testutil.Ok(t, err)

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

T
Tom Wilkie 已提交
1620 1621
	req := &prompb.ReadRequest{Queries: []*prompb.Query{query}}
	data, err := proto.Marshal(req)
1622 1623
	testutil.Ok(t, err)

T
Tom Wilkie 已提交
1624 1625
	compressed := snappy.Encode(nil, data)
	request, err := http.NewRequest("POST", "", bytes.NewBuffer(compressed))
1626 1627
	testutil.Ok(t, err)

T
Tom Wilkie 已提交
1628 1629 1630
	recorder := httptest.NewRecorder()
	api.remoteRead(recorder, request)

1631 1632 1633 1634
	if recorder.Code/100 != 2 {
		t.Fatal(recorder.Code)
	}

1635 1636 1637
	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 已提交
1638 1639
	// Decode the response.
	compressed, err = ioutil.ReadAll(recorder.Result().Body)
1640 1641
	testutil.Ok(t, err)

T
Tom Wilkie 已提交
1642
	uncompressed, err := snappy.Decode(nil, compressed)
1643
	testutil.Ok(t, err)
T
Tom Wilkie 已提交
1644 1645 1646

	var resp prompb.ReadResponse
	err = proto.Unmarshal(uncompressed, &resp)
1647
	testutil.Ok(t, err)
T
Tom Wilkie 已提交
1648 1649 1650 1651 1652

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

1653
	testutil.Equals(t, &prompb.QueryResult{
T
Tom Wilkie 已提交
1654 1655
		Timeseries: []*prompb.TimeSeries{
			{
1656
				Labels: []prompb.Label{
T
Tom Wilkie 已提交
1657 1658
					{Name: "__name__", Value: "test_metric1"},
					{Name: "b", Value: "c"},
T
Tom Wilkie 已提交
1659
					{Name: "baz", Value: "qux"},
T
Tom Wilkie 已提交
1660
					{Name: "d", Value: "e"},
T
Tom Wilkie 已提交
1661
					{Name: "foo", Value: "bar"},
T
Tom Wilkie 已提交
1662
				},
1663
				Samples: []prompb.Sample{{Value: 1, Timestamp: 0}},
T
Tom Wilkie 已提交
1664 1665
			},
		},
1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712
	}, 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)

1713 1714 1715
	matcher3, err := labels.NewMatcher(labels.MatchEqual, "foo", "bar1")
	testutil.Ok(t, err)

B
Bartlomiej Plotka 已提交
1716 1717 1718 1719 1720 1721
	query1, err := remote.ToQuery(0, 14400001, []*labels.Matcher{matcher1, matcher2}, &storage.SelectParams{
		Step:  1,
		Func:  "avg",
		Start: 0,
		End:   14400001,
	})
1722 1723
	testutil.Ok(t, err)

B
Bartlomiej Plotka 已提交
1724 1725 1726 1727 1728 1729
	query2, err := remote.ToQuery(0, 14400001, []*labels.Matcher{matcher1, matcher3}, &storage.SelectParams{
		Step:  1,
		Func:  "avg",
		Start: 0,
		End:   14400001,
	})
1730 1731 1732
	testutil.Ok(t, err)

	req := &prompb.ReadRequest{
1733
		Queries:               []*prompb.Query{query1, query2},
1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747
		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 已提交
1748
	}
1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764

	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)
	}

1765 1766
	if len(results) != 5 {
		t.Fatalf("Expected 5 result, got %d", len(results))
T
Tom Wilkie 已提交
1767
	}
1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 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 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862

	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"),
						},
					},
				},
			},
		},
1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883
		{
			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,
		},
1884
	}, results)
T
Tom Wilkie 已提交
1885 1886
}

1887 1888 1889 1890 1891
type fakeDB struct {
	err    error
	closer func()
}

T
Tom Wilkie 已提交
1892 1893
func (f *fakeDB) CleanTombstones() error                               { return f.err }
func (f *fakeDB) Delete(mint, maxt int64, ms ...*labels.Matcher) error { return f.err }
1894 1895 1896 1897 1898 1899 1900 1901
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 }
1902
func (f *fakeDB) Head() *tsdb.Head {
T
Thor 已提交
1903
	h, _ := tsdb.NewHead(nil, nil, nil, 1000, tsdb.DefaultStripeSize)
1904 1905
	return h
}
1906 1907

func TestAdminEndpoints(t *testing.T) {
1908
	tsdb, tsdbWithError := &fakeDB{}, &fakeDB{err: errors.New("some error")}
1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940
	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 已提交
1941
			values:      map[string][]string{"skip_head": {"true"}},
1942 1943 1944 1945 1946 1947 1948

			errType: errorNone,
		},
		{
			db:          tsdb,
			enableAdmin: true,
			endpoint:    snapshotAPI,
M
Matt Layher 已提交
1949
			values:      map[string][]string{"skip_head": {"xxx"}},
1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014

			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 已提交
2015
			values:      map[string][]string{"match[]": {"123"}},
2016 2017 2018 2019 2020 2021 2022

			errType: errorBadData,
		},
		{
			db:          tsdb,
			enableAdmin: true,
			endpoint:    deleteAPI,
M
Matt Layher 已提交
2023
			values:      map[string][]string{"match[]": {"up"}, "start": {"xxx"}},
2024 2025 2026 2027 2028 2029 2030

			errType: errorBadData,
		},
		{
			db:          tsdb,
			enableAdmin: true,
			endpoint:    deleteAPI,
M
Matt Layher 已提交
2031
			values:      map[string][]string{"match[]": {"up"}, "end": {"xxx"}},
2032 2033 2034 2035 2036 2037 2038

			errType: errorBadData,
		},
		{
			db:          tsdb,
			enableAdmin: true,
			endpoint:    deleteAPI,
M
Matt Layher 已提交
2039
			values:      map[string][]string{"match[]": {"up"}},
2040 2041 2042 2043 2044 2045 2046

			errType: errorNone,
		},
		{
			db:          tsdb,
			enableAdmin: true,
			endpoint:    deleteAPI,
M
Matt Layher 已提交
2047
			values:      map[string][]string{"match[]": {"up{job!=\"foo\"}", "{job=~\"bar.+\"}", "up{instance!~\"fred.+\"}"}},
2048 2049 2050 2051 2052 2053 2054

			errType: errorNone,
		},
		{
			db:          tsdbWithError,
			enableAdmin: true,
			endpoint:    deleteAPI,
M
Matt Layher 已提交
2055
			values:      map[string][]string{"match[]": {"up"}},
2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089

			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)
			}
2090 2091
			res := endpoint(req)
			assertAPIError(t, res.err, tc.errType)
2092 2093 2094 2095
		})
	}
}

2096
func TestRespondSuccess(t *testing.T) {
2097
	s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
2098
		api := API{}
2099
		api.respond(w, "test", nil)
2100 2101
	}))
	defer s.Close()
2102

2103 2104 2105
	resp, err := http.Get(s.URL)
	if err != nil {
		t.Fatalf("Error on test request: %s", err)
2106
	}
2107 2108
	body, err := ioutil.ReadAll(resp.Body)
	defer resp.Body.Close()
2109
	if err != nil {
2110
		t.Fatalf("Error reading response body: %s", err)
2111 2112
	}

2113 2114 2115 2116 2117 2118 2119 2120 2121 2122
	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)
2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134
	}

	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) {
2135
	s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
2136 2137
		api := API{}
		api.respondError(w, &apiError{errorTimeout, errors.New("message")}, "test")
2138 2139
	}))
	defer s.Close()
2140

2141 2142 2143
	resp, err := http.Get(s.URL)
	if err != nil {
		t.Fatalf("Error on test request: %s", err)
2144
	}
2145 2146
	body, err := ioutil.ReadAll(resp.Body)
	defer resp.Body.Close()
2147
	if err != nil {
2148
		t.Fatalf("Error reading response body: %s", err)
2149 2150
	}

2151 2152
	if want, have := http.StatusServiceUnavailable, resp.StatusCode; want != have {
		t.Fatalf("Return code %d expected in error response but got %d", want, have)
2153 2154 2155 2156 2157 2158 2159 2160
	}
	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)
2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205
	}

	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,
2206 2207 2208 2209
		}, {
			// Test float rounding.
			input:  "1543578564.705",
			result: time.Unix(1543578564, 705*1e6),
2210
		},
2211 2212 2213 2214 2215 2216 2217 2218
		{
			input:  minTime.Format(time.RFC3339Nano),
			result: minTime,
		},
		{
			input:  maxTime.Format(time.RFC3339Nano),
			result: maxTime,
		},
2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230
	}

	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
		}
2231 2232
		if !test.fail && !ts.Equal(test.result) {
			t.Errorf("Expected time %v for input %q but got %v", test.result, test.input, ts)
2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251
		}
	}
}

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,
2252 2253 2254 2255 2256 2257 2258 2259
		}, {
			// Internal int64 overflow.
			input: "-148966367200.372",
			fail:  true,
		}, {
			// Internal int64 overflow.
			input: "148966367200.372",
			fail:  true,
2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289
		}, {
			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)
		}
	}
}
2290 2291

func TestOptionsMethod(t *testing.T) {
2292
	r := route.New()
2293
	api := &API{ready: func(f http.HandlerFunc) http.HandlerFunc { return f }}
2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312
	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 已提交
2313

2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340
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},
2341
			expected: `{"status":"success","data":[0.010,"20"]}`,
2342 2343 2344
		},
		{
			response: promql.Point{V: 20, T: 100},
2345
			expected: `{"status":"success","data":[0.100,"20"]}`,
2346 2347 2348 2349 2350 2351 2352
		},
		{
			response: promql.Point{V: 20, T: 1001},
			expected: `{"status":"success","data":[1.001,"20"]}`,
		},
		{
			response: promql.Point{V: 20, T: 1010},
2353
			expected: `{"status":"success","data":[1.010,"20"]}`,
2354 2355 2356
		},
		{
			response: promql.Point{V: 20, T: 1100},
2357
			expected: `{"status":"success","data":[1.100,"20"]}`,
2358 2359 2360
		},
		{
			response: promql.Point{V: 20, T: 12345678123456555},
2361
			expected: `{"status":"success","data":[12345678123456.555,"20"]}`,
2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394
		},
		{
			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) {
2395
			api := API{}
2396
			api.respond(w, c.response, nil)
2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415
		}))
		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))
		}
	}
}

2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456
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 已提交
2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474
// 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,
			},
		},
	}
2475
	b.ResetTimer()
2476
	api := API{}
B
Brian Brazil 已提交
2477
	for n := 0; n < b.N; n++ {
2478
		api.respond(&testResponseWriter, response, nil)
B
Brian Brazil 已提交
2479 2480
	}
}