github.com/thanos-io/thanos@v0.32.5/pkg/targets/prometheus.go (about) 1 // Copyright (c) The Thanos Authors. 2 // Licensed under the Apache License 2.0. 3 4 package targets 5 6 import ( 7 "net/url" 8 "strings" 9 10 "github.com/prometheus/prometheus/model/labels" 11 12 "github.com/thanos-io/thanos/pkg/promclient" 13 "github.com/thanos-io/thanos/pkg/store/labelpb" 14 "github.com/thanos-io/thanos/pkg/targets/targetspb" 15 ) 16 17 // Prometheus implements targetspb.Targets gRPC that allows to fetch targets from Prometheus HTTP api/v1/targets endpoint. 18 type Prometheus struct { 19 base *url.URL 20 client *promclient.Client 21 22 extLabels func() labels.Labels 23 } 24 25 // NewPrometheus creates new targets.Prometheus. 26 func NewPrometheus(base *url.URL, client *promclient.Client, extLabels func() labels.Labels) *Prometheus { 27 return &Prometheus{ 28 base: base, 29 client: client, 30 extLabels: extLabels, 31 } 32 } 33 34 // Targets returns all specified targets from Prometheus. 35 func (p *Prometheus) Targets(r *targetspb.TargetsRequest, s targetspb.Targets_TargetsServer) error { 36 var stateTargets string 37 if r.State != targetspb.TargetsRequest_ANY { 38 stateTargets = strings.ToLower(r.State.String()) 39 } 40 targets, err := p.client.TargetsInGRPC(s.Context(), p.base, stateTargets) 41 if err != nil { 42 return err 43 } 44 45 // Prometheus does not add external labels, so we need to add on our own. 46 enrichTargetsWithExtLabels(targets, p.extLabels()) 47 48 if err := s.Send(&targetspb.TargetsResponse{Result: &targetspb.TargetsResponse_Targets{Targets: targets}}); err != nil { 49 return err 50 } 51 52 return nil 53 } 54 55 func enrichTargetsWithExtLabels(targets *targetspb.TargetDiscovery, extLset labels.Labels) { 56 for i, target := range targets.ActiveTargets { 57 target.SetDiscoveredLabels(labelpb.ExtendSortedLabels(target.DiscoveredLabels.PromLabels(), extLset)) 58 target.SetLabels(labelpb.ExtendSortedLabels(target.Labels.PromLabels(), extLset)) 59 60 targets.ActiveTargets[i] = target 61 } 62 63 for i, target := range targets.DroppedTargets { 64 target.SetDiscoveredLabels(labelpb.ExtendSortedLabels(target.DiscoveredLabels.PromLabels(), extLset)) 65 66 targets.DroppedTargets[i] = target 67 } 68 }