2023-01-09 11:05:56 +02:00
// Copyright 2023 The Prometheus Authors
// 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.
2023-01-09 10:14:37 +02:00
package rules
2023-01-09 10:53:49 +02:00
import (
"context"
2023-01-20 10:27:50 +02:00
"fmt"
2023-01-09 10:53:49 +02:00
"github.com/prometheus/prometheus/model/labels"
)
2023-01-09 10:14:37 +02:00
type ruleOrigin struct { }
2023-01-09 10:53:49 +02:00
// RuleDetail contains information about the rule that is being evaluated.
2023-01-09 10:14:37 +02:00
type RuleDetail struct {
2023-01-09 10:53:49 +02:00
Name string
Query string
Labels labels . Labels
Kind string
2023-01-09 10:14:37 +02:00
}
2023-01-09 10:42:13 +02:00
const (
KindAlerting = "alerting"
KindRecording = "recording"
)
2023-01-09 10:14:37 +02:00
2023-01-09 10:53:49 +02:00
// NewRuleDetail creates a RuleDetail from a given Rule.
func NewRuleDetail ( r Rule ) RuleDetail {
var kind string
switch r . ( type ) {
case * AlertingRule :
kind = KindAlerting
case * RecordingRule :
kind = KindRecording
default :
2023-01-20 10:27:50 +02:00
panic ( fmt . Sprintf ( ` unknown rule type "%T" ` , r ) )
2023-01-09 10:53:49 +02:00
}
2023-01-09 10:14:37 +02:00
return RuleDetail {
2023-01-09 10:53:49 +02:00
Name : r . Name ( ) ,
Query : r . Query ( ) . String ( ) ,
Labels : r . Labels ( ) ,
Kind : kind ,
2023-01-09 10:14:37 +02:00
}
}
// NewOriginContext returns a new context with data about the origin attached.
func NewOriginContext ( ctx context . Context , rule RuleDetail ) context . Context {
return context . WithValue ( ctx , ruleOrigin { } , rule )
}
2023-01-09 10:53:49 +02:00
// FromOriginContext returns the RuleDetail origin data from the context.
2023-01-09 10:14:37 +02:00
func FromOriginContext ( ctx context . Context ) RuleDetail {
if rule , ok := ctx . Value ( ruleOrigin { } ) . ( RuleDetail ) ; ok {
return rule
}
return RuleDetail { }
}