github.com/thanos-io/thanos@v0.32.5/pkg/rules/prometheus.go (about)

     1  // Copyright (c) The Thanos Authors.
     2  // Licensed under the Apache License 2.0.
     3  
     4  package rules
     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/rules/rulespb"
    14  	"github.com/thanos-io/thanos/pkg/store/labelpb"
    15  )
    16  
    17  // Prometheus implements rulespb.Rules gRPC that allows to fetch rules from Prometheus HTTP api/v1/rules 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 rules.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  // Rules returns all specified rules from Prometheus.
    35  func (p *Prometheus) Rules(r *rulespb.RulesRequest, s rulespb.Rules_RulesServer) error {
    36  	var typeRules string
    37  	if r.Type != rulespb.RulesRequest_ALL {
    38  		typeRules = strings.ToLower(r.Type.String())
    39  	}
    40  	groups, err := p.client.RulesInGRPC(s.Context(), p.base, typeRules)
    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  	enrichRulesWithExtLabels(groups, p.extLabels())
    47  
    48  	for _, g := range groups {
    49  		if err := s.Send(&rulespb.RulesResponse{Result: &rulespb.RulesResponse_Group{Group: g}}); err != nil {
    50  			return err
    51  		}
    52  	}
    53  	return nil
    54  }
    55  
    56  // extLset has to be sorted.
    57  func enrichRulesWithExtLabels(groups []*rulespb.RuleGroup, extLset labels.Labels) {
    58  	for _, g := range groups {
    59  		for _, r := range g.Rules {
    60  			r.SetLabels(labelpb.ExtendSortedLabels(r.GetLabels(), extLset))
    61  		}
    62  	}
    63  }