api_test.go 28.6 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"
M
mg03 已提交
22
	"github.com/go-kit/kit/log"
23
	"io/ioutil"
M
mg03 已提交
24
	stdlog "log"
25
	"math"
26 27 28 29
	"net/http"
	"net/http/httptest"
	"net/url"
	"reflect"
30
	"strings"
31 32 33
	"testing"
	"time"

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

41
	"github.com/prometheus/prometheus/config"
42 43
	"github.com/prometheus/prometheus/pkg/labels"
	"github.com/prometheus/prometheus/pkg/timestamp"
T
Tom Wilkie 已提交
44
	"github.com/prometheus/prometheus/prompb"
45
	"github.com/prometheus/prometheus/promql"
M
mg03 已提交
46
	"github.com/prometheus/prometheus/rules"
47
	"github.com/prometheus/prometheus/scrape"
48
	"github.com/prometheus/prometheus/storage"
T
Tom Wilkie 已提交
49
	"github.com/prometheus/prometheus/storage/remote"
M
mg03 已提交
50
	"github.com/prometheus/prometheus/util/testutil"
51 52
)

53
type testTargetRetriever struct{}
F
Frederic Branczyk 已提交
54

K
Krasi Georgiev 已提交
55
func (t testTargetRetriever) TargetsActive() []*scrape.Target {
56 57 58 59 60 61 62 63 64 65 66 67
	return []*scrape.Target{
		scrape.NewTarget(
			labels.FromMap(map[string]string{
				model.SchemeLabel:      "http",
				model.AddressLabel:     "example.com:8080",
				model.MetricsPathLabel: "/metrics",
			}),
			nil,
			url.Values{},
		),
	}
}
K
Krasi Georgiev 已提交
68
func (t testTargetRetriever) TargetsDropped() []*scrape.Target {
69 70 71 72 73 74 75 76 77 78 79 80
	return []*scrape.Target{
		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{},
		),
	}
F
Frederic Branczyk 已提交
81 82
}

83
type testAlertmanagerRetriever struct{}
84

85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102
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 已提交
103 104
}

M
mg03 已提交
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 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166
type testalertsrulesfunc struct {
	test *testing.T
}

func (t testalertsrulesfunc) AlertingRules() []*rules.AlertingRule {
	expr1, err := promql.ParseExpr(`absent(test_metric3) != 1`)
	if err != nil {
		stdlog.Fatalf("Unable to parse alert expression: %s", err)
	}
	expr2, err := promql.ParseExpr(`up == 1`)
	if err != nil {
		stdlog.Fatalf("Unable to parse alert expression: %s", err)
	}

	rule1 := rules.NewAlertingRule(
		"test_metric3",
		expr1,
		time.Second,
		labels.Labels{},
		labels.Labels{},
		log.NewNopLogger(),
	)
	rule2 := rules.NewAlertingRule(
		"test_metric4",
		expr2,
		time.Second,
		labels.Labels{},
		labels.Labels{},
		log.NewNopLogger(),
	)
	var r []*rules.AlertingRule
	r = append(r, rule1)
	r = append(r, rule2)
	return r
}

func (t testalertsrulesfunc) RuleGroups() []*rules.Group {
	var ar testalertsrulesfunc
	arules := ar.AlertingRules()
	storage := testutil.NewStorage(t.test)
	defer storage.Close()

	engine := promql.NewEngine(nil, nil, 10, 10*time.Second)
	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)
	}

	group := rules.NewGroup("grp", "/path/to/file", time.Second, r, opts)
	fmt.Println(group)
	return []*rules.Group{group}

}

167 168 169 170 171 172 173 174 175
var samplePrometheusCfg = config.Config{
	GlobalConfig:       config.GlobalConfig{},
	AlertingConfig:     config.AlertingConfig{},
	RuleFiles:          []string{},
	ScrapeConfigs:      []*config.ScrapeConfig{},
	RemoteWriteConfigs: []*config.RemoteWriteConfig{},
	RemoteReadConfigs:  []*config.RemoteReadConfig{},
}

176 177 178 179 180
var sampleFlagMap = map[string]string{
	"flag1": "value1",
	"flag2": "value2",
}

181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196
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
	`)
	if err != nil {
		t.Fatal(err)
	}
	defer suite.Close()

	if err := suite.Run(); err != nil {
		t.Fatal(err)
	}

197
	now := time.Now()
F
Frederic Branczyk 已提交
198

199
	t.Run("local", func(t *testing.T) {
M
mg03 已提交
200 201 202 203 204 205 206 207

		var algr testalertsrulesfunc
		algr.test = t

		algr.AlertingRules()

		algr.RuleGroups()

208 209 210 211 212
		api := &API{
			Queryable:             suite.Storage(),
			QueryEngine:           suite.QueryEngine(),
			targetRetriever:       testTargetRetriever{},
			alertmanagerRetriever: testAlertmanagerRetriever{},
M
mg03 已提交
213 214 215 216 217
			now:                  func() time.Time { return now },
			config:               func() config.Config { return samplePrometheusCfg },
			flagsMap:             sampleFlagMap,
			ready:                func(f http.HandlerFunc) http.HandlerFunc { return f },
			alertsrulesRetreiver: algr,
218
		}
F
Frederic Branczyk 已提交
219

220 221
		testEndpoints(t, api, true)
	})
222

223 224
	// 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 已提交
225
	// data from the test suite.
226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253
	t.Run("remote", func(t *testing.T) {
		server := setupRemote(suite.Storage())
		defer server.Close()

		u, err := url.Parse(server.URL)
		if err != nil {
			t.Fatal(err)
		}

		al := promlog.AllowedLevel{}
		al.Set("debug")
		remote := remote.NewStorage(promlog.New(al), func() (int64, error) {
			return 0, nil
		}, 1*time.Second)

		err = remote.ApplyConfig(&config.Config{
			RemoteReadConfigs: []*config.RemoteReadConfig{
				{
					URL:           &config_util.URL{URL: u},
					RemoteTimeout: model.Duration(1 * time.Second),
					ReadRecent:    true,
				},
			},
		})
		if err != nil {
			t.Fatal(err)
		}

M
mg03 已提交
254 255 256 257 258 259 260
		var algr testalertsrulesfunc
		algr.test = t

		algr.AlertingRules()

		algr.RuleGroups()

261 262 263 264 265
		api := &API{
			Queryable:             remote,
			QueryEngine:           suite.QueryEngine(),
			targetRetriever:       testTargetRetriever{},
			alertmanagerRetriever: testAlertmanagerRetriever{},
M
mg03 已提交
266 267 268 269 270
			now:                  func() time.Time { return now },
			config:               func() config.Config { return samplePrometheusCfg },
			flagsMap:             sampleFlagMap,
			ready:                func(f http.HandlerFunc) http.HandlerFunc { return f },
			alertsrulesRetreiver: algr,
271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287
		}

		testEndpoints(t, api, false)
	})
}

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 {
288
			from, through, matchers, selectParams, err := remote.FromQuery(query)
289 290 291 292 293 294 295 296 297 298 299 300
			if err != nil {
				http.Error(w, err.Error(), http.StatusBadRequest)
				return
			}

			querier, err := s.Querier(r.Context(), from, through)
			if err != nil {
				http.Error(w, err.Error(), http.StatusInternalServerError)
				return
			}
			defer querier.Close()

301
			set, err := querier.Select(selectParams, matchers...)
302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322
			if err != nil {
				http.Error(w, err.Error(), http.StatusInternalServerError)
				return
			}
			resp.Results[i], err = remote.ToQueryResult(set)
			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) {
323 324
	start := time.Unix(0, 0)

325
	type test struct {
326
		endpoint apiFunc
327
		params   map[string]string
328 329 330
		query    url.Values
		response interface{}
		errType  errorType
331 332 333
	}

	var tests = []test{
334 335 336 337
		{
			endpoint: api.query,
			query: url.Values{
				"query": []string{"2"},
338
				"time":  []string{"123.4"},
339 340
			},
			response: &queryData{
341 342 343 344
				ResultType: promql.ValueTypeScalar,
				Result: promql.Scalar{
					V: 2,
					T: timestamp.FromTime(start.Add(123*time.Second + 400*time.Millisecond)),
345 346 347 348 349 350 351 352 353 354
				},
			},
		},
		{
			endpoint: api.query,
			query: url.Values{
				"query": []string{"0.333"},
				"time":  []string{"1970-01-01T00:02:03Z"},
			},
			response: &queryData{
355 356 357 358
				ResultType: promql.ValueTypeScalar,
				Result: promql.Scalar{
					V: 0.333,
					T: timestamp.FromTime(start.Add(123 * time.Second)),
359 360 361 362 363 364 365 366 367 368
				},
			},
		},
		{
			endpoint: api.query,
			query: url.Values{
				"query": []string{"0.333"},
				"time":  []string{"1970-01-01T01:02:03+01:00"},
			},
			response: &queryData{
369 370 371 372
				ResultType: promql.ValueTypeScalar,
				Result: promql.Scalar{
					V: 0.333,
					T: timestamp.FromTime(start.Add(123 * time.Second)),
373 374 375
				},
			},
		},
376 377 378 379 380 381
		{
			endpoint: api.query,
			query: url.Values{
				"query": []string{"0.333"},
			},
			response: &queryData{
382 383 384
				ResultType: promql.ValueTypeScalar,
				Result: promql.Scalar{
					V: 0.333,
385
					T: timestamp.FromTime(api.now()),
386 387 388
				},
			},
		},
389 390 391 392 393 394 395 396 397
		{
			endpoint: api.queryRange,
			query: url.Values{
				"query": []string{"time()"},
				"start": []string{"0"},
				"end":   []string{"2"},
				"step":  []string{"1"},
			},
			response: &queryData{
398 399 400 401 402 403 404
				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))},
405
						},
406
						Metric: nil,
407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 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
					},
				},
			},
		},
		// 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,
		},
458
		// Invalid step.
459 460 461 462 463 464 465 466 467 468
		{
			endpoint: api.queryRange,
			query: url.Values{
				"query": []string{"time()"},
				"start": []string{"1"},
				"end":   []string{"2"},
				"step":  []string{"0"},
			},
			errType: errorBadData,
		},
469
		// Start after end.
470 471 472 473 474 475 476 477 478 479
		{
			endpoint: api.queryRange,
			query: url.Values{
				"query": []string{"time()"},
				"start": []string{"2"},
				"end":   []string{"1"},
				"step":  []string{"1"},
			},
			errType: errorBadData,
		},
480 481 482 483 484 485 486 487 488 489 490
		// 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,
		},
491 492 493 494 495
		{
			endpoint: api.series,
			query: url.Values{
				"match[]": []string{`test_metric2`},
			},
496 497
			response: []labels.Labels{
				labels.FromStrings("__name__", "test_metric2", "foo", "boo"),
498 499 500 501 502
			},
		},
		{
			endpoint: api.series,
			query: url.Values{
503
				"match[]": []string{`test_metric1{foo=~".+o"}`},
504
			},
505 506
			response: []labels.Labels{
				labels.FromStrings("__name__", "test_metric1", "foo", "boo"),
507 508 509 510 511
			},
		},
		{
			endpoint: api.series,
			query: url.Values{
512
				"match[]": []string{`test_metric1{foo=~".+o$"}`, `test_metric1{foo=~".+o"}`},
513
			},
514 515
			response: []labels.Labels{
				labels.FromStrings("__name__", "test_metric1", "foo", "boo"),
516 517 518 519 520
			},
		},
		{
			endpoint: api.series,
			query: url.Values{
521
				"match[]": []string{`test_metric1{foo=~".+o"}`, `none`},
522
			},
523 524
			response: []labels.Labels{
				labels.FromStrings("__name__", "test_metric1", "foo", "boo"),
525 526
			},
		},
527 528 529 530 531 532 533 534
		// Start and end before series starts.
		{
			endpoint: api.series,
			query: url.Values{
				"match[]": []string{`test_metric2`},
				"start":   []string{"-2"},
				"end":     []string{"-1"},
			},
535
			response: []labels.Labels{},
536 537 538 539 540 541 542 543 544
		},
		// Start and end after series ends.
		{
			endpoint: api.series,
			query: url.Values{
				"match[]": []string{`test_metric2`},
				"start":   []string{"100000"},
				"end":     []string{"100001"},
			},
545
			response: []labels.Labels{},
546 547 548 549 550 551 552 553 554
		},
		// Start before series starts, end after series ends.
		{
			endpoint: api.series,
			query: url.Values{
				"match[]": []string{`test_metric2`},
				"start":   []string{"-1"},
				"end":     []string{"100000"},
			},
555 556
			response: []labels.Labels{
				labels.FromStrings("__name__", "test_metric2", "foo", "boo"),
557 558 559 560 561 562 563 564 565 566
			},
		},
		// Start and end within series.
		{
			endpoint: api.series,
			query: url.Values{
				"match[]": []string{`test_metric2`},
				"start":   []string{"1"},
				"end":     []string{"100"},
			},
567 568
			response: []labels.Labels{
				labels.FromStrings("__name__", "test_metric2", "foo", "boo"),
569 570 571 572 573 574 575 576 577 578
			},
		},
		// Start within series, end after.
		{
			endpoint: api.series,
			query: url.Values{
				"match[]": []string{`test_metric2`},
				"start":   []string{"1"},
				"end":     []string{"100000"},
			},
579 580
			response: []labels.Labels{
				labels.FromStrings("__name__", "test_metric2", "foo", "boo"),
581 582 583 584 585 586 587 588 589 590
			},
		},
		// Start before series, end within series.
		{
			endpoint: api.series,
			query: url.Values{
				"match[]": []string{`test_metric2`},
				"start":   []string{"-1"},
				"end":     []string{"1"},
			},
591 592
			response: []labels.Labels{
				labels.FromStrings("__name__", "test_metric2", "foo", "boo"),
593 594
			},
		},
595 596 597 598 599 600 601
		// Missing match[] query params in series requests.
		{
			endpoint: api.series,
			errType:  errorBadData,
		},
		{
			endpoint: api.dropSeries,
F
Fabian Reinartz 已提交
602
			errType:  errorInternal,
603
		},
604
		{
F
Frederic Branczyk 已提交
605
			endpoint: api.targets,
606 607
			response: &TargetDiscovery{
				ActiveTargets: []*Target{
A
Alexey Palazhchenko 已提交
608
					{
609 610
						DiscoveredLabels: map[string]string{},
						Labels:           map[string]string{},
611 612 613
						ScrapeURL:        "http://example.com:8080/metrics",
						Health:           "unknown",
					},
F
Frederic Branczyk 已提交
614
				},
615 616 617 618 619 620 621 622 623 624
				DroppedTargets: []*DroppedTarget{
					{
						DiscoveredLabels: map[string]string{
							"__address__":      "http://dropped.example.com:9115",
							"__metrics_path__": "/probe",
							"__scheme__":       "http",
							"job":              "blackbox",
						},
					},
				},
F
Frederic Branczyk 已提交
625
			},
626
		},
627
		{
628 629 630
			endpoint: api.alertmanagers,
			response: &AlertmanagerDiscovery{
				ActiveAlertmanagers: []*AlertmanagerTarget{
A
Alexey Palazhchenko 已提交
631
					{
632 633 634
						URL: "http://alertmanager.example.com:8080/api/v1/alerts",
					},
				},
635 636 637 638 639
				DroppedAlertmanagers: []*AlertmanagerTarget{
					{
						URL: "http://dropped.alertmanager.example.com:8080/api/v1/alerts",
					},
				},
640
			},
641
		},
642 643 644 645 646 647
		{
			endpoint: api.serveConfig,
			response: &prometheusConfig{
				YAML: samplePrometheusCfg.String(),
			},
		},
648 649 650 651
		{
			endpoint: api.serveFlags,
			response: sampleFlagMap,
		},
M
mg03 已提交
652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691
		{
			endpoint: api.alerts,
			response: &AlertDiscovery{
				Alertgrps: []*Alertgrp{
					{
						Name:        "test_metric3",
						Query:       "absent(test_metric3) != 1",
						Duration:    "1s",
						Alerts:      nil,
						Annotations: labels.Labels{},
					},
					{
						Name:        "test_metric4",
						Query:       "up == 1",
						Duration:    "1s",
						Alerts:      nil,
						Annotations: labels.Labels{},
					},
				},
			},
		},
		{
			endpoint: api.rules,
			response: &GroupDiscovery{
				Rulegrps: []*Rulegrp{
					{
						Name: "grp",
						File: "/path/to/file",
						Rules: []*Ruleinfo{
							{
								Rule: "alert: test_metric3\nexpr: absent(test_metric3) != 1\nfor: 1s\n",
							},
							{
								Rule: "alert: test_metric4\nexpr: up == 1\nfor: 1s\n",
							},
						},
					},
				},
			},
		},
692 693
	}

694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726
	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,
			},
		}...)
	}

727 728 729 730
	methods := func(f apiFunc) []string {
		fp := reflect.ValueOf(f).Pointer()
		if fp == reflect.ValueOf(api.query).Pointer() || fp == reflect.ValueOf(api.queryRange).Pointer() {
			return []string{http.MethodGet, http.MethodPost}
731
		}
732 733
		return []string{http.MethodGet}
	}
734

735 736 737 738 739
	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
740
		}
741 742 743
		return http.NewRequest(m, fmt.Sprintf("http://example.com?%s", q.Encode()), nil)
	}

744
	for i, test := range tests {
745 746 747 748 749
		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)
750
			}
751
			t.Logf("run %d\t%s\t%q", i, method, test.query.Encode())
752 753 754 755 756

			req, err := request(method, test.query)
			if err != nil {
				t.Fatal(err)
			}
B
Brian Brazil 已提交
757
			resp, apiErr, _ := test.endpoint(req.WithContext(ctx))
758 759 760 761 762 763 764 765 766 767 768 769 770 771
			if apiErr != nil {
				if test.errType == errorNone {
					t.Fatalf("Unexpected error: %s", apiErr)
				}
				if test.errType != apiErr.typ {
					t.Fatalf("Expected error of type %q but got type %q", test.errType, apiErr.typ)
				}
				continue
			}
			if apiErr == nil && test.errType != errorNone {
				t.Fatalf("Expected error of type %q but got none", test.errType)
			}
			if !reflect.DeepEqual(resp, test.response) {
				t.Fatalf("Response does not match, expected:\n%+v\ngot:\n%+v", test.response, resp)
772 773 774 775 776
			}
		}
	}
}

T
Tom Wilkie 已提交
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
func TestReadEndpoint(t *testing.T) {
	suite, err := promql.NewTest(t, `
		load 1m
			test_metric1{foo="bar",baz="qux"} 1
	`)
	if err != nil {
		t.Fatal(err)
	}
	defer suite.Close()

	if err := suite.Run(); err != nil {
		t.Fatal(err)
	}

	api := &API{
		Queryable:   suite.Storage(),
		QueryEngine: suite.QueryEngine(),
		config: func() config.Config {
			return config.Config{
				GlobalConfig: config.GlobalConfig{
					ExternalLabels: model.LabelSet{
						"baz": "a",
						"b":   "c",
						"d":   "e",
					},
				},
			}
		},
	}

	// Encode the request.
	matcher1, err := labels.NewMatcher(labels.MatchEqual, "__name__", "test_metric1")
	if err != nil {
		t.Fatal(err)
	}
	matcher2, err := labels.NewMatcher(labels.MatchEqual, "d", "e")
	if err != nil {
		t.Fatal(err)
	}
816
	query, err := remote.ToQuery(0, 1, []*labels.Matcher{matcher1, matcher2}, &storage.SelectParams{Step: 0, Func: "avg"})
T
Tom Wilkie 已提交
817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859
	if err != nil {
		t.Fatal(err)
	}
	req := &prompb.ReadRequest{Queries: []*prompb.Query{query}}
	data, err := proto.Marshal(req)
	if err != nil {
		t.Fatal(err)
	}
	compressed := snappy.Encode(nil, data)
	request, err := http.NewRequest("POST", "", bytes.NewBuffer(compressed))
	if err != nil {
		t.Fatal(err)
	}
	recorder := httptest.NewRecorder()
	api.remoteRead(recorder, request)

	// Decode the response.
	compressed, err = ioutil.ReadAll(recorder.Result().Body)
	if err != nil {
		t.Fatal(err)
	}
	uncompressed, err := snappy.Decode(nil, compressed)
	if err != nil {
		t.Fatal(err)
	}

	var resp prompb.ReadResponse
	err = proto.Unmarshal(uncompressed, &resp)
	if err != nil {
		t.Fatal(err)
	}

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

	result := resp.Results[0]
	expected := &prompb.QueryResult{
		Timeseries: []*prompb.TimeSeries{
			{
				Labels: []*prompb.Label{
					{Name: "__name__", Value: "test_metric1"},
					{Name: "b", Value: "c"},
T
Tom Wilkie 已提交
860
					{Name: "baz", Value: "qux"},
T
Tom Wilkie 已提交
861
					{Name: "d", Value: "e"},
T
Tom Wilkie 已提交
862
					{Name: "foo", Value: "bar"},
T
Tom Wilkie 已提交
863 864 865 866 867 868 869 870 871 872
				},
				Samples: []*prompb.Sample{{Value: 1, Timestamp: 0}},
			},
		},
	}
	if !reflect.DeepEqual(result, expected) {
		t.Fatalf("Expected response \n%v\n but got \n%v\n", result, expected)
	}
}

873
func TestRespondSuccess(t *testing.T) {
874
	s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
875 876
		api := API{}
		api.respond(w, "test")
877 878
	}))
	defer s.Close()
879

880 881 882
	resp, err := http.Get(s.URL)
	if err != nil {
		t.Fatalf("Error on test request: %s", err)
883
	}
884 885
	body, err := ioutil.ReadAll(resp.Body)
	defer resp.Body.Close()
886
	if err != nil {
887
		t.Fatalf("Error reading response body: %s", err)
888 889
	}

890 891 892 893 894 895 896 897 898 899
	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)
900 901 902 903 904 905 906 907 908 909 910 911
	}

	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) {
912
	s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
913 914
		api := API{}
		api.respondError(w, &apiError{errorTimeout, errors.New("message")}, "test")
915 916
	}))
	defer s.Close()
917

918 919 920
	resp, err := http.Get(s.URL)
	if err != nil {
		t.Fatalf("Error on test request: %s", err)
921
	}
922 923
	body, err := ioutil.ReadAll(resp.Body)
	defer resp.Body.Close()
924
	if err != nil {
925
		t.Fatalf("Error reading response body: %s", err)
926 927
	}

928 929
	if want, have := http.StatusServiceUnavailable, resp.StatusCode; want != have {
		t.Fatalf("Return code %d expected in error response but got %d", want, have)
930 931 932 933 934 935 936 937
	}
	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)
938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995
	}

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

	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
		}
996 997
		if !test.fail && !ts.Equal(test.result) {
			t.Errorf("Expected time %v for input %q but got %v", test.result, test.input, ts)
998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016
		}
	}
}

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,
1017 1018 1019 1020 1021 1022 1023 1024
		}, {
			// Internal int64 overflow.
			input: "-148966367200.372",
			fail:  true,
		}, {
			// Internal int64 overflow.
			input: "148966367200.372",
			fail:  true,
1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054
		}, {
			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)
		}
	}
}
1055 1056

func TestOptionsMethod(t *testing.T) {
1057
	r := route.New()
1058
	api := &API{ready: func(f http.HandlerFunc) http.HandlerFunc { return f }}
1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083
	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)
	}

	for h, v := range corsHeaders {
		if resp.Header.Get(h) != v {
			t.Fatalf("Expected %q for header %q, got %q", v, h, resp.Header.Get(h))
		}
	}
}
B
Brian Brazil 已提交
1084

1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111
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},
1112
			expected: `{"status":"success","data":[0.010,"20"]}`,
1113 1114 1115
		},
		{
			response: promql.Point{V: 20, T: 100},
1116
			expected: `{"status":"success","data":[0.100,"20"]}`,
1117 1118 1119 1120 1121 1122 1123
		},
		{
			response: promql.Point{V: 20, T: 1001},
			expected: `{"status":"success","data":[1.001,"20"]}`,
		},
		{
			response: promql.Point{V: 20, T: 1010},
1124
			expected: `{"status":"success","data":[1.010,"20"]}`,
1125 1126 1127
		},
		{
			response: promql.Point{V: 20, T: 1100},
1128
			expected: `{"status":"success","data":[1.100,"20"]}`,
1129 1130 1131
		},
		{
			response: promql.Point{V: 20, T: 12345678123456555},
1132
			expected: `{"status":"success","data":[12345678123456.555,"20"]}`,
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
		},
		{
			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) {
1166 1167
			api := API{}
			api.respond(w, c.response)
1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186
		}))
		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))
		}
	}
}

B
Brian Brazil 已提交
1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204
// 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,
			},
		},
	}
1205
	b.ResetTimer()
1206
	api := API{}
B
Brian Brazil 已提交
1207
	for n := 0; n < b.N; n++ {
1208
		api.respond(&testResponseWriter, response)
B
Brian Brazil 已提交
1209 1210
	}
}