prometheus.go 1.27 KB
Newer Older
Adam Harrison's avatar
Adam Harrison committed
1
2
3
4
5
6
package alerts

import (
	"context"
	"fmt"
	"regexp"
7
	"sort"
Adam Harrison's avatar
Adam Harrison committed
8
9
10
11
12
13
	"time"

	"github.com/prometheus/client_golang/api/prometheus"
	"github.com/prometheus/common/model"
)

14
15
16
// Returns a list of names of active (e.g. pending or firing) alerts, filtered
// by the supplied regexp.
func PrometheusActiveAlerts(prometheusURL string, filter *regexp.Regexp) ([]string, error) {
Adam Harrison's avatar
Adam Harrison committed
17
18
	client, err := prometheus.New(prometheus.Config{Address: prometheusURL})
	if err != nil {
19
		return nil, err
Adam Harrison's avatar
Adam Harrison committed
20
21
22
23
24
25
	}

	queryAPI := prometheus.NewQueryAPI(client)

	value, err := queryAPI.Query(context.Background(), "ALERTS", time.Now())
	if err != nil {
26
		return nil, err
Adam Harrison's avatar
Adam Harrison committed
27
28
29
30
	}

	if value.Type() == model.ValVector {
		if vector, ok := value.(model.Vector); ok {
31
			activeAlertSet := make(map[string]bool)
Adam Harrison's avatar
Adam Harrison committed
32
			for _, sample := range vector {
33
				if alertName, isAlert := sample.Metric[model.AlertNameLabel]; isAlert && sample.Value != 0 {
Adam Harrison's avatar
Adam Harrison committed
34
					if filter == nil || !filter.MatchString(string(alertName)) {
35
						activeAlertSet[string(alertName)] = true
Adam Harrison's avatar
Adam Harrison committed
36
37
38
					}
				}
			}
39
40
41
42
43
44
45

			var activeAlerts []string
			for activeAlert, _ := range activeAlertSet {
				activeAlerts = append(activeAlerts, activeAlert)
			}
			sort.Sort(sort.StringSlice(activeAlerts))

46
			return activeAlerts, nil
Adam Harrison's avatar
Adam Harrison committed
47
48
49
		}
	}

50
	return nil, fmt.Errorf("Unexpected value type: %v", value)
Adam Harrison's avatar
Adam Harrison committed
51
}