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

Define evaluation metrics #3688

Merged
merged 3 commits into from
Jun 24, 2024
Merged
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
2 changes: 2 additions & 0 deletions cmd/dev/app/testserver/testserver.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ import (
"github.com/stacklok/minder/internal/controlplane/metrics"
"github.com/stacklok/minder/internal/db/embedded"
"github.com/stacklok/minder/internal/logger"
"github.com/stacklok/minder/internal/metrics/meters"
"github.com/stacklok/minder/internal/providers/ratecache"
provtelemetry "github.com/stacklok/minder/internal/providers/telemetry"
"github.com/stacklok/minder/internal/service"
Expand Down Expand Up @@ -102,5 +103,6 @@ func runTestServer(cmd *cobra.Command, _ []string) error {
metrics.NewNoopMetrics(),
provtelemetry.NewNoopMetrics(),
[]message.HandlerMiddleware{},
&meters.NoopMeterFactory{},
)
}
2 changes: 2 additions & 0 deletions cmd/server/app/serve.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ import (
cpmetrics "github.com/stacklok/minder/internal/controlplane/metrics"
"github.com/stacklok/minder/internal/db"
"github.com/stacklok/minder/internal/logger"
"github.com/stacklok/minder/internal/metrics/meters"
"github.com/stacklok/minder/internal/providers/ratecache"
provtelemetry "github.com/stacklok/minder/internal/providers/telemetry"
"github.com/stacklok/minder/internal/service"
Expand Down Expand Up @@ -138,6 +139,7 @@ var serveCmd = &cobra.Command{
cpmetrics.NewMetrics(),
providerMetrics,
[]message.HandlerMiddleware{telemetryMiddleware.TelemetryStoreMiddleware},
&meters.ExportingMeterFactory{},
)
},
}
Expand Down
11 changes: 11 additions & 0 deletions internal/engine/eval_status.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ import (
"github.com/stacklok/minder/internal/engine/entities"
evalerrors "github.com/stacklok/minder/internal/engine/errors"
engif "github.com/stacklok/minder/internal/engine/interfaces"
ent "github.com/stacklok/minder/internal/entities"
pb "github.com/stacklok/minder/pkg/api/protobuf/go/minder/v1"
)

Expand All @@ -52,6 +53,7 @@ func (e *Executor) createEvalStatusParams(
RepoID: repoID,
ArtifactID: artID,
PullRequestID: prID,
ProjectID: inf.ProjectID,
}

// Prepare params for fetching the current rule evaluation from the database
Expand Down Expand Up @@ -141,6 +143,12 @@ func (e *Executor) createOrUpdateEvalStatus(
}

// Upsert evaluation details
entityID, entityType, err := ent.EntityFromIDs(params.RepoID.UUID, params.ArtifactID.UUID, params.PullRequestID.UUID)
if err != nil {
return err
}
status := evalerrors.ErrorAsEvalStatus(params.GetEvalErr())
e.metrics.CountEvalStatus(ctx, status, params.ProfileID, params.ProjectID, entityID, entityType)
_, err = e.querier.UpsertRuleDetailsEval(ctx, db.UpsertRuleDetailsEvalParams{
RuleEvalID: id,
Status: evalerrors.ErrorAsEvalStatus(params.GetEvalErr()),
Expand All @@ -151,6 +159,7 @@ func (e *Executor) createOrUpdateEvalStatus(
logger.Err(err).Msg("error upserting rule evaluation details")
return err
}

// Upsert remediation details
_, err = e.querier.UpsertRuleDetailsRemediate(ctx, db.UpsertRuleDetailsRemediateParams{
RuleEvalID: id,
Expand All @@ -161,6 +170,7 @@ func (e *Executor) createOrUpdateEvalStatus(
if err != nil {
logger.Err(err).Msg("error upserting rule remediation details")
}

// Upsert alert details
_, err = e.querier.UpsertRuleDetailsAlert(ctx, db.UpsertRuleDetailsAlertParams{
RuleEvalID: id,
Expand All @@ -171,6 +181,7 @@ func (e *Executor) createOrUpdateEvalStatus(
if err != nil {
logger.Err(err).Msg("error upserting rule alert details")
}

return err
}

Expand Down
3 changes: 3 additions & 0 deletions internal/engine/executor.go
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,7 @@ type Executor struct {
// when the server is shutting down.
terminationcontext context.Context
providerManager manager.ProviderManager
metrics *ExecutorMetrics
}

// NewExecutor creates a new executor
Expand All @@ -69,6 +70,7 @@ func NewExecutor(
evt events.Publisher,
providerManager manager.ProviderManager,
handlerMiddleware []message.HandlerMiddleware,
metrics *ExecutorMetrics,
) *Executor {
return &Executor{
querier: querier,
Expand All @@ -77,6 +79,7 @@ func NewExecutor(
terminationcontext: ctx,
handlerMiddleware: handlerMiddleware,
providerManager: providerManager,
metrics: metrics,
}
}

Expand Down
5 changes: 5 additions & 0 deletions internal/engine/executor_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ import (
"github.com/stacklok/minder/internal/engine/entities"
"github.com/stacklok/minder/internal/events"
"github.com/stacklok/minder/internal/logger"
"github.com/stacklok/minder/internal/metrics/meters"
"github.com/stacklok/minder/internal/providers"
"github.com/stacklok/minder/internal/providers/github/clients"
ghmanager "github.com/stacklok/minder/internal/providers/github/manager"
Expand Down Expand Up @@ -347,12 +348,16 @@ default allow = true`,
providerManager, err := manager.NewProviderManager(providerStore, githubProviderManager)
require.NoError(t, err)

execMetrics, err := engine.NewExecutorMetrics(&meters.NoopMeterFactory{})
require.NoError(t, err)

e := engine.NewExecutor(
ctx,
mockStore,
evt,
providerManager,
[]message.HandlerMiddleware{},
execMetrics,
)
require.NoError(t, err, "expected no error")

Expand Down
1 change: 1 addition & 0 deletions internal/engine/interfaces/interface.go
Original file line number Diff line number Diff line change
Expand Up @@ -136,6 +136,7 @@ type EvalStatusParams struct {
RepoID uuid.NullUUID
ArtifactID uuid.NullUUID
PullRequestID uuid.NullUUID
ProjectID uuid.UUID
EntityType db.Entities
RuleTypeID uuid.UUID
EvalStatusFromDb *db.ListRuleEvaluationsByProfileIdRow
Expand Down
111 changes: 111 additions & 0 deletions internal/engine/metrics.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,111 @@
// Copyright 2023 Stacklok, Inc.
//
// 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.

package engine

import (
"context"
"fmt"

"github.com/google/uuid"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/metric"

"github.com/stacklok/minder/internal/db"
"github.com/stacklok/minder/internal/metrics/meters"
)

// ExecutorMetrics encapsulates metrics operations for the executor
type ExecutorMetrics struct {
evalCounter metric.Int64Counter
remediationCounter metric.Int64Counter
alertCounter metric.Int64Counter
}

// NewExecutorMetrics instantiates the ExecutorMetrics struct.
func NewExecutorMetrics(meterFactory meters.MeterFactory) (*ExecutorMetrics, error) {
meter := meterFactory.Build("executor")
evalCounter, err := meter.Int64Counter("eval.status",
metric.WithDescription("Number of rule evaluation statuses"),
metric.WithUnit("evaluations"))
if err != nil {
return nil, fmt.Errorf("failed to create eval counter: %w", err)
}

remediationCounter, err := meter.Int64Counter("eval.remediation",
metric.WithDescription("Number of remediation statuses"),
metric.WithUnit("evaluations"))
if err != nil {
return nil, fmt.Errorf("failed to create remediation counter: %w", err)
}

alertCounter, err := meter.Int64Counter("eval.alert",
metric.WithDescription("Number of alert statuses"),
metric.WithUnit("evaluations"))
if err != nil {
return nil, fmt.Errorf("failed to create alert counter: %w", err)
}

return &ExecutorMetrics{
evalCounter: evalCounter,
remediationCounter: remediationCounter,
alertCounter: alertCounter,
}, nil
}

// CountEvalStatus counts evaluation events by status.
func (e *ExecutorMetrics) CountEvalStatus(
ctx context.Context,
status db.EvalStatusTypes,
profileID uuid.UUID,
projectID uuid.UUID,
entityID uuid.UUID,
entityType db.Entities,
) {
e.evalCounter.Add(ctx, 1, metric.WithAttributes(
attribute.String("profile_id", profileID.String()),
attribute.String("project_id", projectID.String()),
attribute.String("entity_id", entityID.String()),
attribute.String("entity_type", string(entityType)),
attribute.String("status", string(status)),
))
}

// CountRemediationStatus counts remediation events by status.
func (e *ExecutorMetrics) CountRemediationStatus(
ctx context.Context,
status string,
evalID uuid.UUID,
projectID uuid.UUID,
) {
e.evalCounter.Add(ctx, 1, metric.WithAttributes(
attribute.String("profile_id", evalID.String()),
attribute.String("project_id", projectID.String()),
attribute.String("status", status),
))
}

// CountAlertStatus counts alert events by status.
func (e *ExecutorMetrics) CountAlertStatus(
ctx context.Context,
status string,
evalID uuid.UUID,
projectID uuid.UUID,
) {
e.evalCounter.Add(ctx, 1, metric.WithAttributes(
attribute.String("profile_id", evalID.String()),
attribute.String("project_id", projectID.String()),
attribute.String("status", status),
))
}
1 change: 0 additions & 1 deletion internal/engine/rule_type_engine.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@
// 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.
// Package rule provides the CLI subcommand for managing rules

package engine

Expand Down
44 changes: 44 additions & 0 deletions internal/entities/utils.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
// Copyright 2024 Stacklok, Inc.
//
// 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.

// Package entities contains logic relating to entity management
package entities

import (
"fmt"

"github.com/google/uuid"

"github.com/stacklok/minder/internal/db"
)

// EntityFromIDs takes the IDs of the three known entity types and
// returns a single ID along with the type of the entity.
// This assumes that exactly one of the IDs is not equal to uuid.Nil
func EntityFromIDs(
Copy link
Contributor

Choose a reason for hiding this comment

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

This is smart, but I worry that the code might get fragile in the future. Since the caller already passes attributes of interfaces.EvalStatusParams, why not pass its EntityType attribute directly?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

The problem is that the way we refer to entities right now requires us to pass around a UUID field for each type of entity, so if another entity gets added we will need to add another parameter anyway.

I would love to come up with a more elegant way of managing entities in the codebase, but it's definitely a future problem.

repositoryID uuid.UUID,
artifactID uuid.UUID,
pullRequestID uuid.UUID,
) (uuid.UUID, db.Entities, error) {
if repositoryID != uuid.Nil && artifactID == uuid.Nil && pullRequestID == uuid.Nil {
return repositoryID, db.EntitiesRepository, nil
}
if repositoryID == uuid.Nil && artifactID != uuid.Nil && pullRequestID == uuid.Nil {
return artifactID, db.EntitiesArtifact, nil
}
if repositoryID == uuid.Nil && artifactID == uuid.Nil && pullRequestID != uuid.Nil {
return pullRequestID, db.EntitiesPullRequest, nil
}
return uuid.Nil, "", fmt.Errorf("unexpected combination of IDs: %s %s %s", repositoryID, artifactID, pullRequestID)
}
46 changes: 46 additions & 0 deletions internal/metrics/meters/factory.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
// Copyright 2024 Stacklok, Inc.
//
// 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.

// Package meters contains the OpenTelemetry meter factories.
package meters

import (
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/metric"
"go.opentelemetry.io/otel/metric/noop"
)

// MeterFactory is an interface which hides the details of creating an
// OpenTelemetry metrics meter. This is used to select between a real exporter
// or noop for testing.
type MeterFactory interface {
// Build creates a meter with the specified name.
Build(name string) metric.Meter
}

// ExportingMeterFactory uses the "real" OpenTelemetry metric meter
type ExportingMeterFactory struct{}

// Build creates a meter with the specified name.
func (_ *ExportingMeterFactory) Build(name string) metric.Meter {
return otel.Meter(name)
}

// NoopMeterFactory returns a noop metrics meter
type NoopMeterFactory struct{}

// Build returns a noop meter implementation.
func (_ *NoopMeterFactory) Build(_ string) metric.Meter {
return noop.Meter{}
}
7 changes: 7 additions & 0 deletions internal/service/service.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ import (
"github.com/stacklok/minder/internal/events"
"github.com/stacklok/minder/internal/flags"
"github.com/stacklok/minder/internal/marketplaces"
"github.com/stacklok/minder/internal/metrics/meters"
"github.com/stacklok/minder/internal/profiles"
"github.com/stacklok/minder/internal/projects"
"github.com/stacklok/minder/internal/providers"
Expand Down Expand Up @@ -67,6 +68,7 @@ func AllInOneServerService(
serverMetrics metrics.Metrics,
providerMetrics provtelemetry.ProviderMetrics,
executorMiddleware []message.HandlerMiddleware,
meterFactory meters.MeterFactory,
) error {
errg, ctx := errgroup.WithContext(ctx)

Expand Down Expand Up @@ -167,13 +169,18 @@ func AllInOneServerService(

// prepend the aggregator to the executor options
executorMiddleware = append([]message.HandlerMiddleware{aggr.AggregateMiddleware}, executorMiddleware...)
executorMetrics, err := engine.NewExecutorMetrics(meterFactory)
if err != nil {
return fmt.Errorf("unable to create metrics for executor: %w", err)
}

exec := engine.NewExecutor(
ctx,
store,
evt,
providerManager,
executorMiddleware,
executorMetrics,
)

evt.ConsumeEvents(exec)
Expand Down