Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: fetch recording rules from tenant-settings #3874

Open
wants to merge 2 commits into
base: alsoba13/metrics-from-profiles-record-and-export
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 2 additions & 8 deletions pkg/experiment/metrics/recorder.go
Original file line number Diff line number Diff line change
Expand Up @@ -114,13 +114,7 @@ func generateExportedLabels(labelsMap map[string]string, rec *Recording, pyrosco
Value: pyroscopeInstance,
},
}
// Add filters as exported labels
for _, matcher := range rec.rule.matchers {
exportedLabels = append(exportedLabels, labels.Label{
Name: matcher.Name,
Value: matcher.Value,
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this was in fact a bug. I was appending name value pair, when the label value may not be the label filter value (for exmaple vehicle!="car")-

Anyway, considering removing this part as the code comment argues

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I finally removed.

})
}

// Keep the expected labels
for _, label := range rec.rule.keepLabels {
labelValue, ok := labelsMap[label]
Expand All @@ -135,7 +129,7 @@ func generateExportedLabels(labelsMap map[string]string, rec *Recording, pyrosco
}

func (r *Recording) matches(labelsMap map[string]string) bool {
if r.rule.profileType != labelsMap["__profile_type__"] {
if r.rule.profileType != labelsMap["__type__"] {
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

TODO: solve ambiguities: __type__ is not enough! block/contentions and block/delays can't be distinguish from mutex/contentions and mutex/delays

return false
}
for _, matcher := range r.rule.matchers {
Expand Down
139 changes: 137 additions & 2 deletions pkg/experiment/metrics/rules.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,23 @@
package metrics

import (
"context"
"encoding/json"
"fmt"
"os"
"regexp"
"strings"

"connectrpc.com/connect"
"github.com/go-kit/log"
"github.com/go-kit/log/level"
"github.com/prometheus/prometheus/model/labels"

settingsv1 "github.com/grafana/pyroscope/api/gen/proto/go/settings/v1"
"github.com/grafana/pyroscope/api/gen/proto/go/settings/v1/settingsv1connect"
connectapi "github.com/grafana/pyroscope/pkg/api/connect"
"github.com/grafana/pyroscope/pkg/tenant"
"github.com/grafana/pyroscope/pkg/util"
)

type RecordingRule struct {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It would be better if this is a protobuf defined type.

Expand All @@ -11,8 +27,31 @@ type RecordingRule struct {
keepLabels []string
}

func recordingRulesFromTenant(tenant string) []*RecordingRule {
// TODO
func recordingRulesFromTenant(tenantId string) []*RecordingRule {
// TODO err handling in general
ctx := tenant.InjectTenantID(context.Background(), "1218") // TODO, tenantId here is empty. This is normal at compaction level 0 as we took this tenant from the block (L0 blocs mix data of different tenants), while we should take it from the dataset.
client := SettingsClient()
response, err := client.Get(ctx, connect.NewRequest(
&settingsv1.GetSettingsRequest{}))

if err != nil {
level.Error(log.NewLogfmtLogger(os.Stderr)).Log("msg", "failed to get settings", "err", err)
return nil // this will probably cause a panic in the caller
}
rules := []*RecordingRule{}
for _, rule := range response.Msg.Settings {
if !strings.HasPrefix(rule.Name, "metric.") {
continue
}
rules = append(rules, parseRule(rule))
}
for _, rule := range rules {
level.Debug(log.NewLogfmtLogger(os.Stderr)).Log("rule", rule.metricName)
}
return rules
}

func recordingRulesFromTenantStatic(tenant2 string) []*RecordingRule {
return []*RecordingRule{
{
profileType: "process_cpu:samples:count:cpu:nanoseconds",
Expand Down Expand Up @@ -48,5 +87,101 @@ func recordingRulesFromTenant(tenant string) []*RecordingRule {
},
keepLabels: []string{},
},
{
profileType: "process_cpu:cpu:nanoseconds:cpu:nanoseconds",
metricName: "pyroscope_exported_metrics_mimir_dev_10_ingester",
matchers: []*labels.Matcher{
{
Type: labels.MatchEqual,
Name: "service_name",
Value: "mimir-dev-10/ingester",
},
},
keepLabels: []string{"controller_revision_hash"},
},
{
profileType: "process_cpu:cpu:nanoseconds:cpu:nanoseconds",
metricName: "pyroscope_exported_metrics_mimir_dev_10_ingester_with_span_names",
matchers: []*labels.Matcher{
{
Type: labels.MatchEqual,
Name: "service_name",
Value: "mimir-dev-10/ingester",
},
},
keepLabels: []string{"controller_revision_hash", "span_name"},
},
}
}

func SettingsClient() settingsv1connect.SettingsServiceClient {
// TODO: refactor this. Very rudimentary, only intended for experimental
httpClient := util.InstrumentedDefaultHTTPClient()
opts := connectapi.DefaultClientOptions()
opts = append(opts, connect.WithInterceptors(tenant.NewAuthInterceptor(true)))
return settingsv1connect.NewSettingsServiceClient(
httpClient,
"http://fire-tenant-settings-headless.fire-dev-001.svc.cluster.local:4100", // TODO: get it from config (set it in deployment tools) use "http://localhost:4040" for local
opts...,
)
}

func parseRule(rule *settingsv1.Setting) *RecordingRule {
var parsed RecordingRuleSetting
err := json.Unmarshal([]byte(rule.Value), &parsed)
if err != nil {
// TODO
fmt.Println("Error parsing JSON:", err)
}

return &RecordingRule{
profileType: parsed.ProfileType,
metricName: "pyroscope_exported_metrics_" + parsed.Name, // TODO sanitize
matchers: parseMatchers(parsed.Matcher, parsed.ServiceName),
keepLabels: parsed.Labels, // [] != All
}
}

func parseMatchers(matchersString string, serviceName string) []*labels.Matcher {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

github.com/prometheus/prometheus/promql/parser.ParseMetricSelector should be used

matchers := []*labels.Matcher{
{Type: labels.MatchEqual, Name: "service_name", Value: serviceName}, // TODO __service_name__ or service_name?
}
// TODO: can't believe there's not a reversed labels.Matcher map.
matcherRegex := regexp.MustCompile(`([a-zA-Z0-9_]+)(=|!=|=~|!~)"([^"]+)"`) // TODO: let's store this statically so we don't need to compile every time
matches := matcherRegex.FindAllStringSubmatch(matchersString, -1)

if matches == nil {
return matchers
}

for _, match := range matches {
matcher, _ := labels.NewMatcher(parseType(match[2]), match[1], match[3]) // TODO err
matchers = append(matchers, matcher)
}

return matchers
}

func parseType(t string) labels.MatchType {
switch t {
case "=":
return labels.MatchEqual
case "!=":
return labels.MatchNotEqual
case "=~":
return labels.MatchRegexp
case "!~":
return labels.MatchNotRegexp
}
return labels.MatchEqual // TODO
}

type RecordingRuleSetting struct {
Version int `json:"version"`
Name string `json:"name"`
ServiceName string `json:"serviceName"`
ProfileType string `json:"profileType"`
Matcher string `json:"matcher"`
PrometheusDataSource string `json:"prometheusDataSource"`
Labels []string `json:"labels"`
}
Loading