|
| 1 | +package notifier |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "crypto/sha256" |
| 6 | + "crypto/tls" |
| 7 | + "fmt" |
| 8 | + "net/http" |
| 9 | + "net/url" |
| 10 | + "strings" |
| 11 | + |
| 12 | + apiv1beta3 "github.com/fluxcd/notification-controller/api/v1beta3" |
| 13 | + eventv1 "github.com/fluxcd/pkg/apis/event/v1beta1" |
| 14 | + "go.opentelemetry.io/otel/attribute" |
| 15 | + "go.opentelemetry.io/otel/codes" |
| 16 | + "go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp" |
| 17 | + "go.opentelemetry.io/otel/sdk/resource" |
| 18 | + sdktrace "go.opentelemetry.io/otel/sdk/trace" |
| 19 | + semconv "go.opentelemetry.io/otel/semconv/v1.34.0" |
| 20 | + "go.opentelemetry.io/otel/trace" |
| 21 | + "sigs.k8s.io/controller-runtime/pkg/log" |
| 22 | +) |
| 23 | + |
| 24 | +type OTLPNotifier struct { |
| 25 | + URL string |
| 26 | + ProxyURL string |
| 27 | + Headers map[string]string |
| 28 | + TLSConfig *tls.Config |
| 29 | +} |
| 30 | + |
| 31 | +func NewOTELTraceNotifier(url string, proxyURL string, headers map[string]string, tlsConfig *tls.Config) (*OTLPNotifier, error) { |
| 32 | + return &OTLPNotifier{ |
| 33 | + URL: url, |
| 34 | + ProxyURL: proxyURL, |
| 35 | + Headers: headers, |
| 36 | + TLSConfig: tlsConfig, |
| 37 | + }, nil |
| 38 | +} |
| 39 | + |
| 40 | +// Post implements the notifier.Interface |
| 41 | +func (t *OTLPNotifier) Post(ctx context.Context, event eventv1.Event) error { |
| 42 | + logger := log.FromContext(ctx).WithValues( |
| 43 | + "event", event.Reason, |
| 44 | + "object", fmt.Sprintf("%s/%s/%s", event.InvolvedObject.Kind, event.InvolvedObject.Namespace, event.InvolvedObject.Name), |
| 45 | + "severity", event.Severity, |
| 46 | + ) |
| 47 | + |
| 48 | + // Set up OTLP exporter options |
| 49 | + logger.V(1).Info("Configuring OTLP HTTP options", "url", t.URL) |
| 50 | + // Parse URL to extract host and port |
| 51 | + parsedURL, err := url.Parse(t.URL) |
| 52 | + if err != nil { |
| 53 | + logger.Error(err, "Failed to parse URL", "url", t.URL) |
| 54 | + return fmt.Errorf("failed to parse URL: %w", err) |
| 55 | + } |
| 56 | + httpOptions := []otlptracehttp.Option{ |
| 57 | + otlptracehttp.WithEndpoint(parsedURL.Host), |
| 58 | + } |
| 59 | + |
| 60 | + // Add headers if available |
| 61 | + if len(t.Headers) > 0 { |
| 62 | + logger.V(1).Info("Adding headers to OTLP exporter", "headerCount", len(t.Headers)) |
| 63 | + httpOptions = append(httpOptions, otlptracehttp.WithHeaders(t.Headers)) |
| 64 | + } |
| 65 | + |
| 66 | + // Add TLS config if available |
| 67 | + if t.TLSConfig != nil { |
| 68 | + logger.V(1).Info("Configuring TLS for OTLP exporter") |
| 69 | + httpOptions = append(httpOptions, otlptracehttp.WithTLSClientConfig(t.TLSConfig)) |
| 70 | + } else if parsedURL.Scheme == "http" { |
| 71 | + logger.V(1).Info("Using insecure connection for OTLP exporter") |
| 72 | + httpOptions = append(httpOptions, otlptracehttp.WithInsecure()) |
| 73 | + } |
| 74 | + |
| 75 | + // Add proxy if available |
| 76 | + if t.ProxyURL != "" { |
| 77 | + logger.V(1).Info("Setting up Proxy URL for OTLP exporter", "proxyURL", t.ProxyURL) |
| 78 | + proxyURL, err := url.Parse(t.ProxyURL) |
| 79 | + if err != nil { |
| 80 | + logger.Error(err, "Failed to parse proxy URL", "proxyURL", t.ProxyURL) |
| 81 | + } else { |
| 82 | + httpOptions = append(httpOptions, otlptracehttp.WithProxy(func(*http.Request) (*url.URL, error) { |
| 83 | + return proxyURL, nil |
| 84 | + })) |
| 85 | + } |
| 86 | + } |
| 87 | + |
| 88 | + // Create exporter |
| 89 | + logger.V(1).Info("Creating OTLP exporter") |
| 90 | + exporter, err := otlptracehttp.New(ctx, httpOptions...) |
| 91 | + if err != nil { |
| 92 | + return fmt.Errorf("failed to create OTLP exporter: %w", err) |
| 93 | + } |
| 94 | + |
| 95 | + // Extract revision from event metadata |
| 96 | + revision := "" |
| 97 | + for k, v := range event.Metadata { |
| 98 | + if strings.Contains(k, "revision") { |
| 99 | + revision = v |
| 100 | + logger.V(1).Info("Found revision in metadata", "revision", revision) |
| 101 | + break |
| 102 | + } |
| 103 | + } |
| 104 | + |
| 105 | + // Get value from context (this would need to be passed in from event_handlers.go) |
| 106 | + alertUID, ok := ctx.Value("alertUID").(string) |
| 107 | + if !ok { |
| 108 | + alertUID = "unknown" |
| 109 | + logger.V(1).Info("alertUID not found in context, using default", "alertUID", alertUID) |
| 110 | + } else { |
| 111 | + logger.V(1).Info("Using alertUID from context", "alertUID", alertUID) |
| 112 | + } |
| 113 | + alertName, ok := ctx.Value("alertName").(string) |
| 114 | + if !ok { |
| 115 | + alertUID = "unknown" |
| 116 | + logger.V(1).Info("alertName not found in context, using default", "alertName", alertName) |
| 117 | + } else { |
| 118 | + logger.V(1).Info("Using alertName from context", "alertName", alertName) |
| 119 | + } |
| 120 | + alertNamespace, ok := ctx.Value("alertNamespace").(string) |
| 121 | + if !ok { |
| 122 | + alertNamespace = "unknown" |
| 123 | + logger.V(1).Info("alertNamespace not found in context, using default", "alertNamespace", alertNamespace) |
| 124 | + } else { |
| 125 | + logger.V(1).Info("Using alertNamespace from context", "alertNamespace", alertNamespace) |
| 126 | + } |
| 127 | + |
| 128 | + // Create trace provider with resource attributes |
| 129 | + logger.V(1).Info("Creating trace provider") |
| 130 | + serviceName := fmt.Sprintf("%s:%s/%s", apiv1beta3.AlertKind, alertNamespace, alertName) |
| 131 | + resource := resource.NewWithAttributes( |
| 132 | + semconv.SchemaURL, |
| 133 | + semconv.ServiceInstanceID(alertUID), |
| 134 | + semconv.ServiceName(serviceName), |
| 135 | + semconv.ServiceNamespace(alertNamespace), |
| 136 | + ) |
| 137 | + tp := sdktrace.NewTracerProvider( |
| 138 | + sdktrace.WithBatcher(exporter), |
| 139 | + sdktrace.WithResource(resource), |
| 140 | + ) |
| 141 | + |
| 142 | + // Use the trace provider's tracer for span creation |
| 143 | + tracer := tp.Tracer("flux:notification-controller") |
| 144 | + |
| 145 | + // alertName, ok := ctx.Value("alert.Name").(string) |
| 146 | + // if !ok { |
| 147 | + // alertName = "unknown" |
| 148 | + // logger.V(1).Info("Alert UID not found in context, using default", "alertUID", alertUID) |
| 149 | + // } else { |
| 150 | + // logger.V(1).Info("Using alert UID from context", "alertUID", alertUID) |
| 151 | + // } |
| 152 | + |
| 153 | + // alertNamespace, ok := ctx.Value("alert.Namespace").(string) |
| 154 | + // if !ok { |
| 155 | + // alertNamespace = "unknown" |
| 156 | + // logger.V(1).Info("Alert UID not found in context, using default", "alertUID", alertUID) |
| 157 | + // } else { |
| 158 | + // logger.V(1).Info("Using alert UID from context", "alertUID", alertUID) |
| 159 | + // } |
| 160 | + |
| 161 | + // Generate root span ID |
| 162 | + logger.V(1).Info("Generating trace IDs", "alertUID", alertUID, "revision", revision) |
| 163 | + spanIDStr := generateID(string(event.InvolvedObject.UID), revision) |
| 164 | + traceIDStr := generateID(alertUID, revision) |
| 165 | + |
| 166 | + var traceID trace.TraceID |
| 167 | + var spanID trace.SpanID |
| 168 | + copy(traceID[:], traceIDStr[:16]) |
| 169 | + copy(spanID[:], spanIDStr[:8]) |
| 170 | + |
| 171 | + // Create trace context with the generated ID |
| 172 | + var spanCtx context.Context = ctx |
| 173 | + |
| 174 | + // Replace trace context to use Alert UID + revision |
| 175 | + logger.Info("Trace context", "kind", event.InvolvedObject.Kind) |
| 176 | + // Create new context for root span |
| 177 | + currentSpanContext := trace.SpanContextFromContext(ctx) |
| 178 | + if !currentSpanContext.IsValid() || (currentSpanContext.HasTraceID() && |
| 179 | + currentSpanContext.TraceID() == traceID) { |
| 180 | + spanCtx = trace.ContextWithSpanContext(ctx, |
| 181 | + trace.NewSpanContext(trace.SpanContextConfig{ |
| 182 | + TraceID: traceID, |
| 183 | + // SpanID: spanID, |
| 184 | + TraceFlags: trace.FlagsSampled, // Ensure the trace is sampled |
| 185 | + }), |
| 186 | + ) |
| 187 | + } else { |
| 188 | + logger.V(1).Info("The current Trace is valid and already exists") |
| 189 | + } |
| 190 | + |
| 191 | + // Create single span with proper attributes |
| 192 | + spanName := fmt.Sprintf("%s:%s/%s", event.InvolvedObject.Kind, event.InvolvedObject.Namespace, event.InvolvedObject.Name) |
| 193 | + _, span := tracer.Start(spanCtx, spanName, |
| 194 | + trace.WithAttributes( |
| 195 | + attribute.String("flux.object.uid", string(event.InvolvedObject.UID)), |
| 196 | + attribute.String("flux.object.kind", event.InvolvedObject.Kind), |
| 197 | + attribute.String("flux.object.name", event.InvolvedObject.Name), |
| 198 | + attribute.String("flux.object.namespace", event.InvolvedObject.Namespace), |
| 199 | + attribute.String("flux.event.severity", event.Severity), |
| 200 | + attribute.String("flux.event.reason", event.Reason), |
| 201 | + attribute.String("flux.event.message", event.Message), |
| 202 | + ), |
| 203 | + trace.WithTimestamp(event.Timestamp.Time), |
| 204 | + ) |
| 205 | + |
| 206 | + // Add metadata attributes |
| 207 | + for k, v := range event.Metadata { |
| 208 | + span.SetAttributes(attribute.String(fmt.Sprintf("flux.event.metadata.%s", k), v)) |
| 209 | + } |
| 210 | + |
| 211 | + // Set status based on event severity |
| 212 | + if event.Severity == eventv1.EventSeverityError { |
| 213 | + span.SetStatus(codes.Error, event.Message) |
| 214 | + } else { |
| 215 | + span.SetStatus(codes.Ok, event.Message) |
| 216 | + } |
| 217 | + |
| 218 | + logger.Info("Successfully sent trace to OTLP endpoint", |
| 219 | + "url", t.URL, |
| 220 | + "object", fmt.Sprintf("%s/%s/%s", event.InvolvedObject.Kind, event.InvolvedObject.Namespace, event.InvolvedObject.Name), |
| 221 | + "reason", event.Reason) |
| 222 | + |
| 223 | + defer func() { |
| 224 | + span.End() |
| 225 | + tp.ForceFlush(ctx) |
| 226 | + tp.Shutdown(ctx) |
| 227 | + exporter.Shutdown(ctx) |
| 228 | + }() |
| 229 | + |
| 230 | + return nil |
| 231 | +} |
| 232 | + |
| 233 | +// Add this function to generate trace and span ID |
| 234 | +func generateID(alertUID, sourceRevision string) []byte { |
| 235 | + input := fmt.Sprintf("%s:%s", alertUID, sourceRevision) |
| 236 | + hash := sha256.Sum256([]byte(input)) |
| 237 | + return hash[:] |
| 238 | +} |
0 commit comments