func (r *AlertingRule) ActiveAlerts() []*Alert {
	var res []*Alert
	for _, a := range r.currentAlerts() {
		if a.ResolvedAt.IsZero() {
			res = append(res, a)
		}
	}
	return res
}
ActiveAlerts returns a slice of active alerts.
package rules
import (
	"context"
	"fmt"
	"net/url"
	"sync"
	"time"
	html_template "html/template"
	yaml "gopkg.in/yaml.v2"
	"github.com/go-kit/kit/log"
	"github.com/go-kit/kit/log/level"
	"github.com/prometheus/common/model"
	"github.com/prometheus/prometheus/pkg/labels"
	"github.com/prometheus/prometheus/pkg/rulefmt"
	"github.com/prometheus/prometheus/pkg/timestamp"
	"github.com/prometheus/prometheus/promql"
	"github.com/prometheus/prometheus/template"
	"github.com/prometheus/prometheus/util/strutil"
)
const (
	alertMetricName = "ALERTS"
	alertNameLabel = "alertname"
	alertStateLabel = "alertstate"
)
type AlertState int
const (
	StateInactive AlertState = iota
	StatePending
	StateFiring
)
func (s AlertState) String() string {
	switch s {
	case StateInactive:
		return "inactive"
	case StatePending:
		return "pending"
	case StateFiring:
		return "firing"
	}
	panic(fmt.Errorf("unknown alert state: %v", s.String()))
}
type Alert struct {
	State AlertState
	Labels      labels.Labels
	Annotations labels.Labels
	Value float64
	ActiveAt   time.Time
	FiredAt    time.Time
	ResolvedAt time.Time
}
type AlertingRule struct {
	name string
	vector promql.Expr
	holdDuration time.Duration
	labels labels.Labels
	annotations labels.Labels
	evaluationTime time.Duration
	mtx sync.Mutex
	active map[uint64]*Alert
	logger log.Logger
}
func NewAlertingRule(name string, vec promql.Expr, hold time.Duration, lbls, anns labels.Labels, logger log.Logger) *AlertingRule {
	return &AlertingRule{
		name:         name,
		vector:       vec,
		holdDuration: hold,
		labels:       lbls,
		annotations:  anns,
		active:       map[uint64]*Alert{},
		logger:       logger,
	}
}
func (r *AlertingRule) Name() string {
	return r.name
}
func (r *AlertingRule) equal(o *AlertingRule) bool {
	return r.name == o.name && labels.Equal(r.labels, o.labels)
}
func (r *AlertingRule) sample(alert *Alert, ts time.Time) promql.Sample {
	lb := labels.NewBuilder(r.labels)
	for _, l := range alert.Labels {
		lb.Set(l.Name, l.Value)
	}
	lb.Set(labels.MetricName, alertMetricName)
	lb.Set(labels.AlertName, r.name)
	lb.Set(alertStateLabel, alert.State.String())
	s := promql.Sample{
		Metric: lb.Labels(),
		Point:  promql.Point{T: timestamp.FromTime(ts), V: 1},
	}
	return s
}
func (r *AlertingRule) SetEvaluationTime(dur time.Duration) {
	r.mtx.Lock()
	defer r.mtx.Unlock()
	r.evaluationTime = dur
}
func (r *AlertingRule) GetEvaluationTime() time.Duration {
	r.mtx.Lock()
	defer r.mtx.Unlock()
	return r.evaluationTime
}
const resolvedRetention = 15 * time.Minute
func (r *AlertingRule) Eval(ctx context.Context, ts time.Time, query QueryFunc, externalURL *url.URL) (promql.Vector, error) {
	res, err := query(ctx, r.vector.String(), ts)
	if err != nil {
		return nil, err
	}
	r.mtx.Lock()
	defer r.mtx.Unlock()
	resultFPs := map[uint64]struct{}{}
	for _, smpl := range res {
		l := make(map[string]string, len(smpl.Metric))
		for _, lbl := range smpl.Metric {
			l[lbl.Name] = lbl.Value
		}
		tmplData := struct {
			Labels map[string]string
			Value  float64
		}{
			Labels: l,
			Value:  smpl.V,
		}
		defs := "{{$labels := .Labels}}{{$value := .Value}}"
		expand := func(text string) string {
			tmpl := template.NewTemplateExpander(
				ctx,
				defs+text,
				"__alert_"+r.Name(),
				tmplData,
				model.Time(timestamp.FromTime(ts)),
				template.QueryFunc(query),
				externalURL,
			)
			result, err := tmpl.Expand()
			if err != nil {
				result = fmt.Sprintf("<error expanding template: %s>", err)
				level.Warn(r.logger).Log("msg", "Expanding alert template failed", "err", err, "data", tmplData)
			}
			return result
		}
		lb := labels.NewBuilder(smpl.Metric).Del(labels.MetricName)
		for _, l := range r.labels {
			lb.Set(l.Name, expand(l.Value))
		}
		lb.Set(labels.AlertName, r.Name())
		annotations := make(labels.Labels, 0, len(r.annotations))
		for _, a := range r.annotations {
			annotations = append(annotations, labels.Label{Name: a.Name, Value: expand(a.Value)})
		}
		h := smpl.Metric.Hash()
		resultFPs[h] = struct{}{}
		if alert, ok := r.active[h]; ok && alert.State != StateInactive {
			alert.Value = smpl.V
			alert.Annotations = annotations
			continue
		}
		r.active[h] = &Alert{
			Labels:      lb.Labels(),
			Annotations: annotations,
			ActiveAt:    ts,
			State:       StatePending,
			Value:       smpl.V,
		}
	}
	var vec promql.Vector
	for fp, a := range r.active {
		if _, ok := resultFPs[fp]; !ok {
			if a.State == StatePending || (!a.ResolvedAt.IsZero() && ts.Sub(a.ResolvedAt) > resolvedRetention) {
				delete(r.active, fp)
			}
			if a.State != StateInactive {
				a.State = StateInactive
				a.ResolvedAt = ts
			}
			continue
		}
		if a.State == StatePending && ts.Sub(a.ActiveAt) >= r.holdDuration {
			a.State = StateFiring
			a.FiredAt = ts
		}
		vec = append(vec, r.sample(a, ts))
	}
	return vec, nil
}
func (r *AlertingRule) State() AlertState {
	r.mtx.Lock()
	defer r.mtx.Unlock()
	maxState := StateInactive
	for _, a := range r.active {
		if a.State > maxState {
			maxState = a.State
		}
	}
	return maxState
}