github.com/thanos-io/thanos@v0.32.5/pkg/targets/prometheus_test.go (about)

     1  // Copyright (c) The Thanos Authors.
     2  // Licensed under the Apache License 2.0.
     3  
     4  package targets
     5  
     6  import (
     7  	"context"
     8  	"fmt"
     9  	"net/http"
    10  	"net/url"
    11  	"testing"
    12  	"time"
    13  
    14  	"github.com/go-kit/log"
    15  	"github.com/gogo/protobuf/proto"
    16  	"github.com/pkg/errors"
    17  	"github.com/prometheus/prometheus/model/labels"
    18  	"github.com/prometheus/prometheus/storage"
    19  
    20  	"github.com/efficientgo/core/testutil"
    21  	"github.com/thanos-io/thanos/pkg/promclient"
    22  	"github.com/thanos-io/thanos/pkg/runutil"
    23  	"github.com/thanos-io/thanos/pkg/store/labelpb"
    24  	"github.com/thanos-io/thanos/pkg/targets/targetspb"
    25  	"github.com/thanos-io/thanos/pkg/testutil/e2eutil"
    26  )
    27  
    28  func TestPrometheus_Targets_e2e(t *testing.T) {
    29  	p, err := e2eutil.NewPrometheus()
    30  	testutil.Ok(t, err)
    31  	defer func() { testutil.Ok(t, p.Stop()) }()
    32  
    33  	p.SetConfig(fmt.Sprintf(`
    34  global:
    35    external_labels:
    36      region: eu-west
    37  scrape_configs:
    38  - job_name: 'myself'
    39    # Quick scrapes for test purposes.
    40    scrape_interval: 1s
    41    scrape_timeout: 1s
    42    static_configs:
    43    - targets: ['%s','localhost:80']
    44    relabel_configs:
    45    - source_labels: ['__address__']
    46      regex: '^.+:80$'
    47      action: drop
    48  `, e2eutil.PromAddrPlaceHolder))
    49  	testutil.Ok(t, p.Start())
    50  
    51  	ctx, cancel := context.WithCancel(context.Background())
    52  	defer cancel()
    53  
    54  	upctx, upcancel := context.WithTimeout(ctx, 10*time.Second)
    55  	defer upcancel()
    56  
    57  	logger := log.NewNopLogger()
    58  	err = p.WaitPrometheusUp(upctx, logger)
    59  	testutil.Ok(t, err)
    60  
    61  	u, err := url.Parse("http://" + p.Addr())
    62  	testutil.Ok(t, err)
    63  
    64  	c := promclient.NewClient(http.DefaultClient, logger, "")
    65  
    66  	// Wait targets response to be ready as Prometheus scrapes targets.
    67  	testutil.Ok(t, runutil.Retry(3*time.Second, ctx.Done(), func() error {
    68  		targets, err := c.TargetsInGRPC(ctx, u, "")
    69  		testutil.Ok(t, err)
    70  		if len(targets.ActiveTargets) > 0 {
    71  			return nil
    72  		}
    73  		return errors.New("empty targets response from Prometheus")
    74  	}))
    75  
    76  	promTargets := NewPrometheus(u, promclient.NewDefaultClient(), func() labels.Labels {
    77  		return labels.FromStrings("replica", "test1")
    78  	})
    79  
    80  	expected := &targetspb.TargetDiscovery{
    81  		ActiveTargets: []*targetspb.ActiveTarget{
    82  			{
    83  				DiscoveredLabels: labelpb.ZLabelSet{Labels: []labelpb.ZLabel{
    84  					{Name: "__address__", Value: p.Addr()},
    85  					{Name: "__metrics_path__", Value: "/metrics"},
    86  					{Name: "__scheme__", Value: "http"},
    87  					{Name: "__scrape_interval__", Value: "1s"},
    88  					{Name: "__scrape_timeout__", Value: "1s"},
    89  					{Name: "job", Value: "myself"},
    90  					{Name: "replica", Value: "test1"},
    91  				}},
    92  				Labels: labelpb.ZLabelSet{Labels: []labelpb.ZLabel{
    93  					{Name: "instance", Value: p.Addr()},
    94  					{Name: "job", Value: "myself"},
    95  					{Name: "replica", Value: "test1"},
    96  				}},
    97  				ScrapePool:         "myself",
    98  				ScrapeUrl:          fmt.Sprintf("http://%s/metrics", p.Addr()),
    99  				GlobalUrl:          "",
   100  				Health:             targetspb.TargetHealth_UP,
   101  				LastScrape:         time.Time{},
   102  				LastScrapeDuration: 0,
   103  			},
   104  		},
   105  		DroppedTargets: []*targetspb.DroppedTarget{
   106  			{
   107  				DiscoveredLabels: labelpb.ZLabelSet{Labels: []labelpb.ZLabel{
   108  					{Name: "__address__", Value: "localhost:80"},
   109  					{Name: "__metrics_path__", Value: "/metrics"},
   110  					{Name: "__scheme__", Value: "http"},
   111  					{Name: "__scrape_interval__", Value: "1s"},
   112  					{Name: "__scrape_timeout__", Value: "1s"},
   113  					{Name: "job", Value: "myself"},
   114  					{Name: "replica", Value: "test1"},
   115  				}},
   116  			},
   117  		},
   118  	}
   119  
   120  	grpcClient := NewGRPCClientWithDedup(promTargets, nil)
   121  	for _, tcase := range []struct {
   122  		requestedState targetspb.TargetsRequest_State
   123  		expectedErr    error
   124  	}{
   125  		{
   126  			requestedState: targetspb.TargetsRequest_ANY,
   127  		},
   128  		{
   129  			requestedState: targetspb.TargetsRequest_ACTIVE,
   130  		},
   131  		{
   132  			requestedState: targetspb.TargetsRequest_DROPPED,
   133  		},
   134  	} {
   135  		t.Run(tcase.requestedState.String(), func(t *testing.T) {
   136  			targets, w, err := grpcClient.Targets(context.Background(), &targetspb.TargetsRequest{
   137  				State: tcase.requestedState,
   138  			})
   139  			testutil.Equals(t, storage.Warnings(nil), w)
   140  			if tcase.expectedErr != nil {
   141  				testutil.NotOk(t, err)
   142  				testutil.Equals(t, tcase.expectedErr.Error(), err.Error())
   143  				return
   144  			}
   145  			testutil.Ok(t, err)
   146  
   147  			expectedTargets := proto.Clone(expected).(*targetspb.TargetDiscovery)
   148  
   149  			switch tcase.requestedState {
   150  			case targetspb.TargetsRequest_ACTIVE:
   151  				expectedTargets.DroppedTargets = expectedTargets.DroppedTargets[:0]
   152  			case targetspb.TargetsRequest_DROPPED:
   153  				expectedTargets.ActiveTargets = expectedTargets.ActiveTargets[:0]
   154  			}
   155  
   156  			for i := range targets.ActiveTargets {
   157  				targets.ActiveTargets[i].LastScrapeDuration = 0
   158  				targets.ActiveTargets[i].LastScrape = time.Time{}
   159  				targets.ActiveTargets[i].LastError = ""
   160  				targets.ActiveTargets[i].GlobalUrl = ""
   161  			}
   162  
   163  			testutil.Equals(t, expectedTargets.ActiveTargets, targets.ActiveTargets)
   164  			testutil.Equals(t, expectedTargets.DroppedTargets, targets.DroppedTargets)
   165  		})
   166  	}
   167  }