api_test.go 16.1 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 17 18 19
package v1

import (
	"encoding/json"
	"errors"
	"fmt"
20
	"io/ioutil"
21 22 23 24 25 26 27
	"net/http"
	"net/http/httptest"
	"net/url"
	"reflect"
	"testing"
	"time"

28
	"github.com/prometheus/common/model"
F
Fabian Reinartz 已提交
29
	"github.com/prometheus/common/route"
F
Fabian Reinartz 已提交
30
	"golang.org/x/net/context"
31 32

	"github.com/prometheus/prometheus/promql"
F
Frederic Branczyk 已提交
33
	"github.com/prometheus/prometheus/retrieval"
34 35
)

B
beorn7 已提交
36
type targetRetrieverFunc func() []*retrieval.Target
F
Frederic Branczyk 已提交
37

B
beorn7 已提交
38
func (f targetRetrieverFunc) Targets() []*retrieval.Target {
F
Frederic Branczyk 已提交
39 40 41
	return f()
}

42
type alertmanagerRetrieverFunc func() []*url.URL
43

44
func (f alertmanagerRetrieverFunc) Alertmanagers() []*url.URL {
45 46 47
	return f()
}

48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
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)
	}

64
	now := model.Now()
F
Frederic Branczyk 已提交
65

B
beorn7 已提交
66 67 68
	tr := targetRetrieverFunc(func() []*retrieval.Target {
		return []*retrieval.Target{
			retrieval.NewTarget(
F
Frederic Branczyk 已提交
69 70 71 72 73 74 75 76 77 78 79
				model.LabelSet{
					model.SchemeLabel:      "http",
					model.AddressLabel:     "example.com:8080",
					model.MetricsPathLabel: "/metrics",
				},
				model.LabelSet{},
				url.Values{},
			),
		}
	})

80 81 82 83 84 85
	ar := alertmanagerRetrieverFunc(func() []*url.URL {
		return []*url.URL{{
			Scheme: "http",
			Host:   "alertmanager.example.com:8080",
			Path:   "/api/v1/alerts",
		}}
86 87
	})

88
	api := &API{
89 90 91 92 93
		Storage:               suite.Storage(),
		QueryEngine:           suite.QueryEngine(),
		targetRetriever:       tr,
		alertmanagerRetriever: ar,
		now: func() model.Time { return now },
94 95
	}

96
	start := model.Time(0)
97 98
	var tests = []struct {
		endpoint apiFunc
99
		params   map[string]string
100 101 102 103 104 105 106 107 108 109 110
		query    url.Values
		response interface{}
		errType  errorType
	}{
		{
			endpoint: api.query,
			query: url.Values{
				"query": []string{"2"},
				"time":  []string{"123.3"},
			},
			response: &queryData{
111 112
				ResultType: model.ValScalar,
				Result: &model.Scalar{
113 114 115 116 117 118 119 120 121 122 123 124
					Value:     2,
					Timestamp: start.Add(123*time.Second + 300*time.Millisecond),
				},
			},
		},
		{
			endpoint: api.query,
			query: url.Values{
				"query": []string{"0.333"},
				"time":  []string{"1970-01-01T00:02:03Z"},
			},
			response: &queryData{
125 126
				ResultType: model.ValScalar,
				Result: &model.Scalar{
127 128 129 130 131 132 133 134 135 136 137 138
					Value:     0.333,
					Timestamp: start.Add(123 * time.Second),
				},
			},
		},
		{
			endpoint: api.query,
			query: url.Values{
				"query": []string{"0.333"},
				"time":  []string{"1970-01-01T01:02:03+01:00"},
			},
			response: &queryData{
139 140
				ResultType: model.ValScalar,
				Result: &model.Scalar{
141 142 143 144 145
					Value:     0.333,
					Timestamp: start.Add(123 * time.Second),
				},
			},
		},
146 147 148 149 150 151 152 153 154 155 156 157 158
		{
			endpoint: api.query,
			query: url.Values{
				"query": []string{"0.333"},
			},
			response: &queryData{
				ResultType: model.ValScalar,
				Result: &model.Scalar{
					Value:     0.333,
					Timestamp: now,
				},
			},
		},
159 160 161 162 163 164 165 166 167
		{
			endpoint: api.queryRange,
			query: url.Values{
				"query": []string{"time()"},
				"start": []string{"0"},
				"end":   []string{"2"},
				"step":  []string{"1"},
			},
			response: &queryData{
168 169 170
				ResultType: model.ValMatrix,
				Result: model.Matrix{
					&model.SampleStream{
171
						Values: []model.SamplePair{
172 173 174 175
							{Value: 0, Timestamp: start},
							{Value: 1, Timestamp: start.Add(1 * time.Second)},
							{Value: 2, Timestamp: start.Add(2 * time.Second)},
						},
176
						Metric: model.Metric{},
177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227
					},
				},
			},
		},
		// 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,
		},
228
		// Invalid step.
229 230 231 232 233 234 235 236 237 238
		{
			endpoint: api.queryRange,
			query: url.Values{
				"query": []string{"time()"},
				"start": []string{"1"},
				"end":   []string{"2"},
				"step":  []string{"0"},
			},
			errType: errorBadData,
		},
239
		// Start after end.
240 241 242 243 244 245 246 247 248 249
		{
			endpoint: api.queryRange,
			query: url.Values{
				"query": []string{"time()"},
				"start": []string{"2"},
				"end":   []string{"1"},
				"step":  []string{"1"},
			},
			errType: errorBadData,
		},
250 251 252 253 254 255 256 257 258 259 260
		// 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,
		},
261
		{
262 263 264 265
			endpoint: api.labelValues,
			params: map[string]string{
				"name": "__name__",
			},
266
			response: model.LabelValues{
267 268 269 270
				"test_metric1",
				"test_metric2",
			},
		},
271 272 273 274 275
		{
			endpoint: api.labelValues,
			params: map[string]string{
				"name": "foo",
			},
276
			response: model.LabelValues{
277 278 279 280
				"bar",
				"boo",
			},
		},
281 282 283 284 285 286 287 288
		// Bad name parameter.
		{
			endpoint: api.labelValues,
			params: map[string]string{
				"name": "not!!!allowed",
			},
			errType: errorBadData,
		},
289 290 291 292 293
		{
			endpoint: api.series,
			query: url.Values{
				"match[]": []string{`test_metric2`},
			},
294
			response: []model.Metric{
295 296 297 298 299 300 301 302 303
				{
					"__name__": "test_metric2",
					"foo":      "boo",
				},
			},
		},
		{
			endpoint: api.series,
			query: url.Values{
304
				"match[]": []string{`test_metric1{foo=~".+o"}`},
305
			},
306
			response: []model.Metric{
307 308 309 310 311 312 313 314 315
				{
					"__name__": "test_metric1",
					"foo":      "boo",
				},
			},
		},
		{
			endpoint: api.series,
			query: url.Values{
316
				"match[]": []string{`test_metric1{foo=~"o$"}`, `test_metric1{foo=~".+o"}`},
317
			},
318
			response: []model.Metric{
319 320 321 322 323 324 325 326 327
				{
					"__name__": "test_metric1",
					"foo":      "boo",
				},
			},
		},
		{
			endpoint: api.series,
			query: url.Values{
328
				"match[]": []string{`test_metric1{foo=~".+o"}`, `none`},
329
			},
330
			response: []model.Metric{
331 332 333 334 335 336
				{
					"__name__": "test_metric1",
					"foo":      "boo",
				},
			},
		},
337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 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
		// Start and end before series starts.
		{
			endpoint: api.series,
			query: url.Values{
				"match[]": []string{`test_metric2`},
				"start":   []string{"-2"},
				"end":     []string{"-1"},
			},
			response: []model.Metric{},
		},
		// Start and end after series ends.
		{
			endpoint: api.series,
			query: url.Values{
				"match[]": []string{`test_metric2`},
				"start":   []string{"100000"},
				"end":     []string{"100001"},
			},
			response: []model.Metric{},
		},
		// Start before series starts, end after series ends.
		{
			endpoint: api.series,
			query: url.Values{
				"match[]": []string{`test_metric2`},
				"start":   []string{"-1"},
				"end":     []string{"100000"},
			},
			response: []model.Metric{
				{
					"__name__": "test_metric2",
					"foo":      "boo",
				},
			},
		},
		// Start and end within series.
		{
			endpoint: api.series,
			query: url.Values{
				"match[]": []string{`test_metric2`},
				"start":   []string{"1"},
				"end":     []string{"100"},
			},
			response: []model.Metric{
				{
					"__name__": "test_metric2",
					"foo":      "boo",
				},
			},
		},
		// Start within series, end after.
		{
			endpoint: api.series,
			query: url.Values{
				"match[]": []string{`test_metric2`},
				"start":   []string{"1"},
				"end":     []string{"100000"},
			},
			response: []model.Metric{
				{
					"__name__": "test_metric2",
					"foo":      "boo",
				},
			},
		},
		// Start before series, end within series.
		{
			endpoint: api.series,
			query: url.Values{
				"match[]": []string{`test_metric2`},
				"start":   []string{"-1"},
				"end":     []string{"1"},
			},
			response: []model.Metric{
				{
					"__name__": "test_metric2",
					"foo":      "boo",
				},
			},
		},
417 418 419 420 421 422 423 424 425 426 427 428 429 430
		// Missing match[] query params in series requests.
		{
			endpoint: api.series,
			errType:  errorBadData,
		},
		{
			endpoint: api.dropSeries,
			errType:  errorBadData,
		},
		// The following tests delete time series from the test storage. They
		// must remain at the end and are fixed in their order.
		{
			endpoint: api.dropSeries,
			query: url.Values{
431
				"match[]": []string{`test_metric1{foo=~".+o"}`},
432 433 434 435 436 437 438 439 440 441
			},
			response: struct {
				NumDeleted int `json:"numDeleted"`
			}{1},
		},
		{
			endpoint: api.series,
			query: url.Values{
				"match[]": []string{`test_metric1`},
			},
442
			response: []model.Metric{
443 444 445 446 447 448 449 450
				{
					"__name__": "test_metric1",
					"foo":      "bar",
				},
			},
		}, {
			endpoint: api.dropSeries,
			query: url.Values{
451
				"match[]": []string{`{__name__=~".+"}`},
452 453 454 455
			},
			response: struct {
				NumDeleted int `json:"numDeleted"`
			}{2},
F
Frederic Branczyk 已提交
456 457
		}, {
			endpoint: api.targets,
458 459
			response: &TargetDiscovery{
				ActiveTargets: []*Target{
A
Alexey Palazhchenko 已提交
460
					{
461 462 463 464 465
						DiscoveredLabels: model.LabelSet{},
						Labels:           model.LabelSet{},
						ScrapeURL:        "http://example.com:8080/metrics",
						Health:           "unknown",
					},
F
Frederic Branczyk 已提交
466 467
				},
			},
468 469 470 471
		}, {
			endpoint: api.alertmanagers,
			response: &AlertmanagerDiscovery{
				ActiveAlertmanagers: []*AlertmanagerTarget{
A
Alexey Palazhchenko 已提交
472
					{
473 474 475 476
						URL: "http://alertmanager.example.com:8080/api/v1/alerts",
					},
				},
			},
477
		},
478 479 480
	}

	for _, test := range tests {
481 482 483 484 485 486 487 488 489
		// Build a context with the correct request params.
		ctx := context.Background()
		for p, v := range test.params {
			ctx = route.WithParam(ctx, p, v)
		}
		api.context = func(r *http.Request) context.Context {
			return ctx
		}

490 491 492 493
		req, err := http.NewRequest("ANY", fmt.Sprintf("http://example.com?%s", test.query.Encode()), nil)
		if err != nil {
			t.Fatal(err)
		}
494 495 496 497
		resp, apiErr := test.endpoint(req)
		if apiErr != nil {
			if test.errType == errorNone {
				t.Fatalf("Unexpected error: %s", apiErr)
498
			}
499 500
			if test.errType != apiErr.typ {
				t.Fatalf("Expected error of type %q but got type %q", test.errType, apiErr.typ)
501 502 503
			}
			continue
		}
504
		if apiErr == nil && test.errType != errorNone {
505 506 507
			t.Fatalf("Expected error of type %q but got none", test.errType)
		}
		if !reflect.DeepEqual(resp, test.response) {
508
			t.Fatalf("Response does not match, expected:\n%+v\ngot:\n%+v", test.response, resp)
509
		}
510 511
		// Ensure that removed metrics are unindexed before the next request.
		suite.Storage().WaitForIndexing()
512 513 514 515
	}
}

func TestRespondSuccess(t *testing.T) {
516 517 518 519
	s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		respond(w, "test")
	}))
	defer s.Close()
520

521 522 523
	resp, err := http.Get(s.URL)
	if err != nil {
		t.Fatalf("Error on test request: %s", err)
524
	}
525 526
	body, err := ioutil.ReadAll(resp.Body)
	defer resp.Body.Close()
527
	if err != nil {
528
		t.Fatalf("Error reading response body: %s", err)
529 530
	}

531 532 533 534 535 536 537 538 539 540
	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)
541 542 543 544 545 546 547 548 549 550 551 552
	}

	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) {
553 554 555 556
	s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		respondError(w, &apiError{errorTimeout, errors.New("message")}, "test")
	}))
	defer s.Close()
557

558 559 560
	resp, err := http.Get(s.URL)
	if err != nil {
		t.Fatalf("Error on test request: %s", err)
561
	}
562 563
	body, err := ioutil.ReadAll(resp.Body)
	defer resp.Body.Close()
564
	if err != nil {
565
		t.Fatalf("Error reading response body: %s", err)
566 567
	}

568 569
	if want, have := http.StatusServiceUnavailable, resp.StatusCode; want != have {
		t.Fatalf("Return code %d expected in error response but got %d", want, have)
570 571 572 573 574 575 576 577
	}
	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)
578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610
	}

	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,
611 612 613 614 615 616 617 618
		}, {
			// Internal int64 overflow.
			input: "-148966367200.372",
			fail:  true,
		}, {
			// Internal int64 overflow.
			input: "148966367200.372",
			fail:  true,
619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643
		}, {
			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
		}
644
		res := model.TimeFromUnixNano(test.result.UnixNano())
645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665
		if !test.fail && ts != res {
			t.Errorf("Expected time %v for input %q but got %v", res, test.input, ts)
		}
	}
}

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,
666 667 668 669 670 671 672 673
		}, {
			// Internal int64 overflow.
			input: "-148966367200.372",
			fail:  true,
		}, {
			// Internal int64 overflow.
			input: "148966367200.372",
			fail:  true,
674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703
		}, {
			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)
		}
	}
}
704 705

func TestOptionsMethod(t *testing.T) {
J
Julius Volz 已提交
706
	r := route.New(nil)
707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732
	api := &API{}
	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))
		}
	}
}