Skip to content

Commit

Permalink
Add alertmanager exporter implementation (#28906)
Browse files Browse the repository at this point in the history
**Description:** Export Implementation of Alertmanager Exporter
Second PR - exporter implementation

**Link to tracking Issue:**
[#23659](#23569)

**Testing:** Unit tests for exporter implementation

**Documentation:** Readme and Sample Configs to use Alertmanager
exporter
  • Loading branch information
mcube8 authored Dec 6, 2023
1 parent 5d413ae commit 10a79dc
Show file tree
Hide file tree
Showing 10 changed files with 705 additions and 14 deletions.
27 changes: 27 additions & 0 deletions .chloggen/alertmanager-exporter-implementation.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
# Use this changelog template to create an entry for release notes.

# One of 'breaking', 'deprecation', 'new_component', 'enhancement', 'bug_fix'
change_type: 'new_component'

# The name of the component, or a single word describing the area of concern, (e.g. filelogreceiver)
component: alertmanagerexporter

# A brief description of the change. Surround your text with quotes ("") if it needs to start with a backtick (`).
note: "Add Alertmanager exporter implementation and tests"

# Mandatory: One or more tracking issues related to the change. You can use the PR number here if no issue exists.
issues: [23569]

# (Optional) One or more lines of additional information to render under the primary note.
# These lines will be padded with 2 spaces and then inserted directly into the document.
# Use pipe (|) for multiline entries.
subtext:

# If your change doesn't affect end users or the exported elements of any package,
# you should instead start your pull request title with [chore] or use the "Skip Changelog" label.
# Optional: The change log or logs in which this entry should be included.
# e.g. '[user]' or '[user, api]'
# Include 'user' if the change is relevant to end users.
# Include 'api' if there is a change to a library API.
# Default: '[user]'
change_logs: [user]
3 changes: 1 addition & 2 deletions exporter/alertmanagerexporter/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ Supported pipeline types: traces
The following settings are required:

- `endpoint` : Alertmanager endpoint to send events
- `severity` (default info): Default severity for Alerts
- `severity`: Default severity for Alerts


The following settings are optional:
Expand All @@ -33,7 +33,6 @@ The following settings are optional:
eg: If severity_attribute is set to "foo" and the SpanEvent has an attribute called foo, foo's attribute value will be used as the severity value for that particular Alert generated from the SpanEvent.



Example config:

```yaml
Expand Down
171 changes: 164 additions & 7 deletions exporter/alertmanagerexporter/alertmanager_exporter.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,17 +4,27 @@
package alertmanagerexporter // import "github.com/open-telemetry/opentelemetry-collector-contrib/exporter/alertmanagerexporter"

import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"time"

"github.com/prometheus/common/model"
"go.opentelemetry.io/collector/component"
"go.opentelemetry.io/collector/consumer"
"go.opentelemetry.io/collector/exporter"
"go.opentelemetry.io/collector/exporter/exporterhelper"
"go.opentelemetry.io/collector/pdata/pcommon"
"go.opentelemetry.io/collector/pdata/ptrace"
"go.uber.org/zap"
)

type alertmanagerExporter struct {
config *Config
client *http.Client
tracesMarshaler ptrace.Marshaler
settings component.TelemetrySettings
endpoint string
Expand All @@ -23,20 +33,167 @@ type alertmanagerExporter struct {
severityAttribute string
}

func (s *alertmanagerExporter) pushTraces(_ context.Context, _ ptrace.Traces) error {
type alertmanagerEvent struct {
spanEvent ptrace.SpanEvent
traceID string
spanID string
severity string
}

func (s *alertmanagerExporter) convertEventSliceToArray(eventSlice ptrace.SpanEventSlice, traceID pcommon.TraceID, spanID pcommon.SpanID) []*alertmanagerEvent {
if eventSlice.Len() > 0 {
events := make([]*alertmanagerEvent, eventSlice.Len())

// To Be Implemented
for i := 0; i < eventSlice.Len(); i++ {
var severity string
severityAttrValue, ok := eventSlice.At(i).Attributes().Get(s.severityAttribute)
if ok {
severity = severityAttrValue.AsString()
} else {
severity = s.defaultSeverity
}
event := alertmanagerEvent{
spanEvent: eventSlice.At(i),
traceID: traceID.String(),
spanID: spanID.String(),
severity: severity,
}

events[i] = &event
}
return events
}
return nil
}

func (s *alertmanagerExporter) start(_ context.Context, _ component.Host) error {
func (s *alertmanagerExporter) extractEvents(td ptrace.Traces) []*alertmanagerEvent {

// Stitch parent trace ID and span ID
rss := td.ResourceSpans()
var events []*alertmanagerEvent
if rss.Len() == 0 {
return nil
}

for i := 0; i < rss.Len(); i++ {
resource := rss.At(i).Resource()
ilss := rss.At(i).ScopeSpans()

if resource.Attributes().Len() == 0 && ilss.Len() == 0 {
return nil
}

for j := 0; j < ilss.Len(); j++ {
spans := ilss.At(j).Spans()
for k := 0; k < spans.Len(); k++ {
traceID := spans.At(k).TraceID()
spanID := spans.At(k).SpanID()
events = append(events, s.convertEventSliceToArray(spans.At(k).Events(), traceID, spanID)...)
}
}
}
return events
}

func createAnnotations(event *alertmanagerEvent) model.LabelSet {
labelMap := make(model.LabelSet, event.spanEvent.Attributes().Len()+2)
event.spanEvent.Attributes().Range(func(key string, attr pcommon.Value) bool {
labelMap[model.LabelName(key)] = model.LabelValue(attr.AsString())
return true
})
labelMap["TraceID"] = model.LabelValue(event.traceID)
labelMap["SpanID"] = model.LabelValue(event.spanID)
return labelMap
}

func (s *alertmanagerExporter) convertEventsToAlertPayload(events []*alertmanagerEvent) []model.Alert {

payload := make([]model.Alert, len(events))

for i, event := range events {
annotations := createAnnotations(event)

alert := model.Alert{
StartsAt: time.Now(),
Labels: model.LabelSet{"severity": model.LabelValue(event.severity), "event_name": model.LabelValue(event.spanEvent.Name())},
Annotations: annotations,
GeneratorURL: s.generatorURL,
}

payload[i] = alert
}
return payload
}

func (s *alertmanagerExporter) postAlert(ctx context.Context, payload []model.Alert) error {

msg, err := json.Marshal(payload)
if err != nil {
return fmt.Errorf("error marshaling alert to JSON: %w", err)
}

req, err := http.NewRequestWithContext(ctx, "POST", s.endpoint, bytes.NewBuffer(msg))
if err != nil {
return fmt.Errorf("error creating HTTP request: %w", err)
}
req.Header.Set("Content-Type", "application/json")

// To Be Implemented
resp, err := s.client.Do(req)
if err != nil {
return fmt.Errorf("error sending HTTP request: %w", err)
}

defer func() {
if closeErr := resp.Body.Close(); closeErr != nil {
s.settings.Logger.Warn("failed to close response body", zap.Error(closeErr))
}
}()

_, err = io.ReadAll(resp.Body)
if err != nil {
return fmt.Errorf("failed to read response body %w", err)
}

if resp.StatusCode != http.StatusOK {
s.settings.Logger.Debug("post request to Alertmanager failed", zap.Error(err))
return fmt.Errorf("request POST %s failed - %q", req.URL.String(), resp.Status)
}
return nil
}

func (s *alertmanagerExporter) pushTraces(ctx context.Context, td ptrace.Traces) error {

events := s.extractEvents(td)

if len(events) == 0 {
return nil
}

alert := s.convertEventsToAlertPayload(events)
err := s.postAlert(ctx, alert)

if err != nil {
return err
}

return nil
}

func (s *alertmanagerExporter) start(_ context.Context, host component.Host) error {

client, err := s.config.HTTPClientSettings.ToClient(host, s.settings)
if err != nil {
return fmt.Errorf("failed to create HTTP Client: %w", err)
}
s.client = client
return nil
}

func (s *alertmanagerExporter) shutdown(context.Context) error {
// To Be Implemented

if s.client != nil {
s.client.CloseIdleConnections()
}
return nil
}

Expand All @@ -46,14 +203,15 @@ func newAlertManagerExporter(cfg *Config, set component.TelemetrySettings) *aler
config: cfg,
settings: set,
tracesMarshaler: &ptrace.JSONMarshaler{},
endpoint: cfg.HTTPClientSettings.Endpoint,
endpoint: fmt.Sprintf("%s/api/v1/alerts", cfg.HTTPClientSettings.Endpoint),
generatorURL: cfg.GeneratorURL,
defaultSeverity: cfg.DefaultSeverity,
severityAttribute: cfg.SeverityAttribute,
}
}

func newTracesExporter(ctx context.Context, cfg component.Config, set exporter.CreateSettings) (exporter.Traces, error) {

config := cfg.(*Config)

s := newAlertManagerExporter(config, set.TelemetrySettings)
Expand All @@ -64,7 +222,6 @@ func newTracesExporter(ctx context.Context, cfg component.Config, set exporter.C
cfg,
s.pushTraces,
exporterhelper.WithCapabilities(consumer.Capabilities{MutatesData: false}),
// Disable Timeout/RetryOnFailure and SendingQueue
exporterhelper.WithStart(s.start),
exporterhelper.WithTimeout(config.TimeoutSettings),
exporterhelper.WithRetry(config.RetrySettings),
Expand Down
Loading

0 comments on commit 10a79dc

Please sign in to comment.