|
| 1 | +package promql |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "fmt" |
| 6 | + "sync" |
| 7 | + |
| 8 | + "github.com/prometheus/client_golang/api" |
| 9 | + prometheusv1 "github.com/prometheus/client_golang/api/prometheus/v1" |
| 10 | + "github.com/prometheus/common/config" |
| 11 | + |
| 12 | + "k8s.io/klog/v2" |
| 13 | + |
| 14 | + "github.com/openshift/cluster-version-operator/pkg/clusterconditions" |
| 15 | +) |
| 16 | + |
| 17 | +type Getter interface { |
| 18 | + Get(ctx context.Context) prometheusv1.AlertsResult |
| 19 | +} |
| 20 | + |
| 21 | +func NewAlertGetter(promQLTarget clusterconditions.PromQLTarget) Getter { |
| 22 | + p := NewPromQL(promQLTarget) |
| 23 | + condition := p.Condition |
| 24 | + v, ok := condition.(*PromQL) |
| 25 | + if !ok { |
| 26 | + panic("invalid condition type") |
| 27 | + } |
| 28 | + return &ocAlertGetter{promQL: v} |
| 29 | +} |
| 30 | + |
| 31 | +type ocAlertGetter struct { |
| 32 | + promQL *PromQL |
| 33 | + |
| 34 | + mutex sync.Mutex |
| 35 | + cached prometheusv1.AlertsResult |
| 36 | +} |
| 37 | + |
| 38 | +func (o *ocAlertGetter) Get(ctx context.Context) prometheusv1.AlertsResult { |
| 39 | + if err := o.refresh(ctx); err != nil { |
| 40 | + klog.Errorf("Failed to refresh alerts, using stale cache instead: %v", err) |
| 41 | + } |
| 42 | + return o.cached |
| 43 | +} |
| 44 | + |
| 45 | +func (o *ocAlertGetter) refresh(ctx context.Context) error { |
| 46 | + o.mutex.Lock() |
| 47 | + defer o.mutex.Unlock() |
| 48 | + |
| 49 | + klog.Info("refresh alerts ...") |
| 50 | + p := o.promQL |
| 51 | + host, err := p.Host(ctx) |
| 52 | + if err != nil { |
| 53 | + return fmt.Errorf("failure determine thanos IP: %w", err) |
| 54 | + } |
| 55 | + p.url.Host = host |
| 56 | + clientConfig := api.Config{Address: p.url.String()} |
| 57 | + |
| 58 | + if roundTripper, err := config.NewRoundTripperFromConfig(p.HTTPClientConfig, "cluster-conditions"); err == nil { |
| 59 | + clientConfig.RoundTripper = roundTripper |
| 60 | + } else { |
| 61 | + return fmt.Errorf("creating PromQL round-tripper: %w", err) |
| 62 | + } |
| 63 | + |
| 64 | + promqlClient, err := api.NewClient(clientConfig) |
| 65 | + if err != nil { |
| 66 | + return fmt.Errorf("creating PromQL client: %w", err) |
| 67 | + } |
| 68 | + |
| 69 | + client := &statusCodeNotImplementedForPostClient{ |
| 70 | + client: promqlClient, |
| 71 | + } |
| 72 | + |
| 73 | + v1api := prometheusv1.NewAPI(client) |
| 74 | + |
| 75 | + queryContext := ctx |
| 76 | + if p.QueryTimeout > 0 { |
| 77 | + var cancel context.CancelFunc |
| 78 | + queryContext, cancel = context.WithTimeout(ctx, p.QueryTimeout) |
| 79 | + defer cancel() |
| 80 | + } |
| 81 | + |
| 82 | + r, err := v1api.Alerts(queryContext) |
| 83 | + if err != nil { |
| 84 | + return fmt.Errorf("failed to get alerts: %w", err) |
| 85 | + } |
| 86 | + o.cached = r |
| 87 | + klog.Infof("refreshed: %d alerts", len(o.cached.Alerts)) |
| 88 | + return nil |
| 89 | +} |
0 commit comments