|
| 1 | +/* |
| 2 | +Copyright 2025 The Flux authors |
| 3 | +
|
| 4 | +Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | +you may not use this file except in compliance with the License. |
| 6 | +You may obtain a copy of the License at |
| 7 | +
|
| 8 | + http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | +
|
| 10 | +Unless required by applicable law or agreed to in writing, software |
| 11 | +distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | +See the License for the specific language governing permissions and |
| 14 | +limitations under the License. |
| 15 | +*/ |
| 16 | + |
| 17 | +package notifier |
| 18 | + |
| 19 | +import ( |
| 20 | + "context" |
| 21 | + "crypto/sha256" |
| 22 | + "crypto/tls" |
| 23 | + "encoding/base64" |
| 24 | + "fmt" |
| 25 | + "net/http" |
| 26 | + "net/url" |
| 27 | + "slices" |
| 28 | + |
| 29 | + "go.opentelemetry.io/otel/attribute" |
| 30 | + "go.opentelemetry.io/otel/codes" |
| 31 | + "go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp" |
| 32 | + sdktrace "go.opentelemetry.io/otel/sdk/trace" |
| 33 | + "go.opentelemetry.io/otel/trace" |
| 34 | + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" |
| 35 | + "sigs.k8s.io/controller-runtime/pkg/log" |
| 36 | + |
| 37 | + eventv1 "github.com/fluxcd/pkg/apis/event/v1beta1" |
| 38 | + |
| 39 | + apiv1beta3 "github.com/fluxcd/notification-controller/api/v1beta3" |
| 40 | +) |
| 41 | + |
| 42 | +type alertMetadataContextKey struct{} |
| 43 | + |
| 44 | +// Context key functions |
| 45 | +func WithAlertMetadata(ctx context.Context, metadata metav1.ObjectMeta) context.Context { |
| 46 | + return context.WithValue(ctx, alertMetadataContextKey{}, metadata) |
| 47 | +} |
| 48 | + |
| 49 | +func GetAlertMetadata(ctx context.Context) (metav1.ObjectMeta, bool) { |
| 50 | + metadata, ok := ctx.Value(alertMetadataContextKey{}).(metav1.ObjectMeta) |
| 51 | + return metadata, ok |
| 52 | +} |
| 53 | + |
| 54 | +type OTLPTracer struct { |
| 55 | + tracerProvider *sdktrace.TracerProvider |
| 56 | + tracer trace.Tracer |
| 57 | +} |
| 58 | + |
| 59 | +func NewOTLPTracer(ctx context.Context, urlStr string, proxyURL string, headers map[string]string, tlsConfig *tls.Config, username string, password string) (*OTLPTracer, error) { |
| 60 | + // Set up OTLP exporter options |
| 61 | + httpOptions := []otlptracehttp.Option{ |
| 62 | + otlptracehttp.WithEndpointURL(urlStr), |
| 63 | + } |
| 64 | + |
| 65 | + // Add headers if available |
| 66 | + if len(headers) > 0 { |
| 67 | + // Add authentication header, if it doesn't exist yet |
| 68 | + if headers["Authorization"] == "" { |
| 69 | + // If username is not set, password is considered as token |
| 70 | + if username == "" { |
| 71 | + headers["Authorization"] = "Bearer " + password |
| 72 | + } else if username != "" && password != "" { |
| 73 | + auth := base64.StdEncoding.EncodeToString([]byte(username + ":" + password)) |
| 74 | + headers["Authorization"] = "Basic " + auth |
| 75 | + } |
| 76 | + } |
| 77 | + httpOptions = append(httpOptions, otlptracehttp.WithHeaders(headers)) |
| 78 | + } |
| 79 | + |
| 80 | + // Add TLS config if available |
| 81 | + if tlsConfig != nil { |
| 82 | + httpOptions = append(httpOptions, otlptracehttp.WithTLSClientConfig(tlsConfig)) |
| 83 | + } |
| 84 | + |
| 85 | + // Add proxy if available |
| 86 | + if proxyURL != "" { |
| 87 | + proxyURLparsed, err := url.Parse(proxyURL) |
| 88 | + if err != nil { |
| 89 | + return nil, fmt.Errorf("failed to proxy URL - %s: %w", proxyURL, err) |
| 90 | + } else { |
| 91 | + if username != "" && password != "" { |
| 92 | + proxyURLparsed.User = url.UserPassword(username, password) |
| 93 | + } |
| 94 | + httpOptions = append(httpOptions, otlptracehttp.WithProxy(func(*http.Request) (*url.URL, error) { |
| 95 | + return proxyURLparsed, nil |
| 96 | + })) |
| 97 | + } |
| 98 | + } |
| 99 | + |
| 100 | + exporter, err := otlptracehttp.New(ctx, httpOptions...) |
| 101 | + if err != nil { |
| 102 | + return nil, err |
| 103 | + } |
| 104 | + |
| 105 | + // Create TracerProvider once |
| 106 | + tp := sdktrace.NewTracerProvider( |
| 107 | + sdktrace.WithBatcher(exporter), |
| 108 | + ) |
| 109 | + |
| 110 | + log.FromContext(ctx).Info("Successfully created OTEL tracer") |
| 111 | + return &OTLPTracer{ |
| 112 | + tracerProvider: tp, |
| 113 | + tracer: tp.Tracer("flux:notification-controller"), |
| 114 | + }, nil |
| 115 | +} |
| 116 | + |
| 117 | +// Post implements the notifier.Interface |
| 118 | +func (t *OTLPTracer) Post(ctx context.Context, event eventv1.Event) error { |
| 119 | + // Skip Git commit status update event. |
| 120 | + if event.HasMetadata(eventv1.MetaCommitStatusKey, eventv1.MetaCommitStatusUpdateValue) { |
| 121 | + return nil |
| 122 | + } |
| 123 | + |
| 124 | + logger := log.FromContext(ctx).WithValues( |
| 125 | + "event", event.Reason, |
| 126 | + "object", fmt.Sprintf("%s/%s/%s", event.InvolvedObject.Kind, event.InvolvedObject.Namespace, event.InvolvedObject.Name), |
| 127 | + "severity", event.Severity, |
| 128 | + ) |
| 129 | + logger.Info("OTEL Post function called", "event", event.Reason) |
| 130 | + |
| 131 | + alert, ok := GetAlertMetadata(ctx) |
| 132 | + if !ok { |
| 133 | + return fmt.Errorf("alert metadata not found in context") |
| 134 | + } |
| 135 | + |
| 136 | + // Extract revision from event metadata |
| 137 | + revision := extractMetadata(event.Metadata, "revision") |
| 138 | + |
| 139 | + // TraceID: <AlertUID>:<revisionID> |
| 140 | + logger.V(1).Info("Generating trace IDs", "alertUID", string(alert.UID), "revision", revision) |
| 141 | + traceIDStr := generateID(string(alert.UID), revision) |
| 142 | + // spanIDStr := generateID(string(event.InvolvedObject.UID), |
| 143 | + // fmt.Sprintf("%s/%s/%s", event.InvolvedObject.Kind, |
| 144 | + // event.InvolvedObject.Namespace, event.InvolvedObject.Name)) |
| 145 | + |
| 146 | + var traceID trace.TraceID |
| 147 | + // var spanID trace.SpanID |
| 148 | + copy(traceID[:], traceIDStr[:16]) |
| 149 | + // copy(spanID[:], spanIDStr[:8]) |
| 150 | + |
| 151 | + // Determine span relationship based on Flux object hierarchy |
| 152 | + var spanCtx context.Context = t.createSpanContext(ctx, event, traceID) |
| 153 | + |
| 154 | + // Create single span with proper attributes |
| 155 | + if event.InvolvedObject.Kind != "HelmRepository" { |
| 156 | + logger.Info("Processing OTEL notification", "alert", alert.Name) |
| 157 | + |
| 158 | + } else { |
| 159 | + logger.Info("OTEL notification skipped", "alert", alert.Name) |
| 160 | + } |
| 161 | + |
| 162 | + span := t.processSpan(spanCtx, event) |
| 163 | + // Set status based on event severity |
| 164 | + if event.Severity == eventv1.EventSeverityError { |
| 165 | + span.SetStatus(codes.Error, event.Message) |
| 166 | + } else { |
| 167 | + span.SetStatus(codes.Ok, event.Message) |
| 168 | + } |
| 169 | + |
| 170 | + defer span.End() |
| 171 | + |
| 172 | + serviceName := fmt.Sprintf("%s: %s/%s", apiv1beta3.AlertKind, alert.Namespace, alert.Name) |
| 173 | + logger.Info("Successfully sent trace to OTLP endpoint", |
| 174 | + "alert", serviceName, |
| 175 | + ) |
| 176 | + |
| 177 | + return nil |
| 178 | +} |
| 179 | + |
| 180 | +func (t *OTLPTracer) createSpanContext(ctx context.Context, event eventv1.Event, traceID trace.TraceID) context.Context { |
| 181 | + kind := event.InvolvedObject.Kind |
| 182 | + |
| 183 | + spanContext := trace.NewSpanContext(trace.SpanContextConfig{ |
| 184 | + TraceID: traceID, |
| 185 | + TraceFlags: trace.FlagsSampled, |
| 186 | + }) |
| 187 | + |
| 188 | + // Root spans: Sources that start the deployment flow |
| 189 | + if isSource(kind) { |
| 190 | + return trace.ContextWithSpanContext(context.Background(), |
| 191 | + spanContext.WithTraceFlags(spanContext.TraceFlags())) |
| 192 | + } |
| 193 | + |
| 194 | + // Child spans: Everything else inherits from the same trace |
| 195 | + return trace.ContextWithSpanContext(ctx, |
| 196 | + spanContext.WithTraceFlags(spanContext.TraceFlags())) |
| 197 | +} |
| 198 | + |
| 199 | +func (t *OTLPTracer) processSpan(ctx context.Context, event eventv1.Event) trace.Span { |
| 200 | + // Build span attributes including metadata |
| 201 | + eventAttrs := []attribute.KeyValue{ |
| 202 | + attribute.String("object.uid", string(event.InvolvedObject.UID)), |
| 203 | + attribute.String("object.kind", event.InvolvedObject.Kind), |
| 204 | + attribute.String("object.name", event.InvolvedObject.Name), |
| 205 | + attribute.String("object.namespace", event.InvolvedObject.Namespace), |
| 206 | + } |
| 207 | + |
| 208 | + // Add metadata as event attributes |
| 209 | + for k, v := range event.Metadata { |
| 210 | + eventAttrs = append(eventAttrs, attribute.String(k, v)) |
| 211 | + } |
| 212 | + |
| 213 | + // Start span |
| 214 | + spanName := fmt.Sprintf("%s: %s/%s", event.InvolvedObject.Kind, event.InvolvedObject.Namespace, event.InvolvedObject.Name) |
| 215 | + _, span := t.tracer.Start(ctx, spanName, |
| 216 | + trace.WithAttributes(eventAttrs...), |
| 217 | + trace.WithTimestamp(event.Timestamp.Time)) |
| 218 | + |
| 219 | + return span |
| 220 | +} |
| 221 | + |
| 222 | +// Add cleanup method |
| 223 | +func (t *OTLPTracer) Close(ctx context.Context) error { |
| 224 | + return t.tracerProvider.Shutdown(ctx) |
| 225 | +} |
| 226 | + |
| 227 | +// Add this function to generate trace and span ID |
| 228 | +func generateID(UID string, rest string) []byte { |
| 229 | + input := fmt.Sprintf("%s:%s", UID, rest) |
| 230 | + hash := sha256.Sum256([]byte(input)) |
| 231 | + return hash[:] |
| 232 | +} |
| 233 | + |
| 234 | +func extractMetadata(metadata map[string]string, key string) string { |
| 235 | + if v, ok := metadata[key]; ok { |
| 236 | + return v |
| 237 | + } |
| 238 | + return "unknown" |
| 239 | +} |
| 240 | + |
| 241 | +func isSource(kind string) bool { |
| 242 | + sourceKinds := []string{"GitRepository", "HelmChart", "OCIRepository", "Bucket"} |
| 243 | + return slices.Contains(sourceKinds, kind) |
| 244 | +} |
0 commit comments