|
| 1 | +// Copyright 2025 The Gitea Authors. All rights reserved. |
| 2 | +// SPDX-License-Identifier: MIT |
| 3 | + |
| 4 | +package gtprof |
| 5 | + |
| 6 | +import ( |
| 7 | + "strconv" |
| 8 | + |
| 9 | + "code.gitea.io/gitea/modules/otelexporter" |
| 10 | +) |
| 11 | + |
| 12 | +func otelToSpan(traceID string, t *traceBuiltinSpan, scopeSpan *otelexporter.OtelScopeSpan) { |
| 13 | + t.ts.mu.RLock() |
| 14 | + defer t.ts.mu.RUnlock() |
| 15 | + |
| 16 | + span := &otelexporter.OtelSpan{ |
| 17 | + TraceID: traceID, |
| 18 | + SpanID: t.ts.id, |
| 19 | + Name: t.ts.name, |
| 20 | + StartTimeUnixNano: strconv.FormatInt(t.ts.startTime.UnixNano(), 10), |
| 21 | + EndTimeUnixNano: strconv.FormatInt(t.ts.endTime.UnixNano(), 10), |
| 22 | + Kind: 2, |
| 23 | + } |
| 24 | + |
| 25 | + if t.ts.parent != nil { |
| 26 | + span.ParentSpanID = t.ts.parent.id |
| 27 | + } |
| 28 | + |
| 29 | + scopeSpan.Spans = append(scopeSpan.Spans, span) |
| 30 | + |
| 31 | + for _, a := range t.ts.attributes { |
| 32 | + var otelVal any |
| 33 | + if a.Value.IsString() { |
| 34 | + otelVal = otelexporter.OtelAttributeStringValue{StringValue: a.Value.AsString()} |
| 35 | + } else { |
| 36 | + otelVal = otelexporter.OtelAttributeIntValue{IntValue: strconv.FormatInt(a.Value.AsInt64(), 10)} |
| 37 | + } |
| 38 | + span.Attributes = append(span.Attributes, &otelexporter.OtelAttribute{Key: a.Key, Value: otelVal}) |
| 39 | + } |
| 40 | + |
| 41 | + for _, c := range t.ts.children { |
| 42 | + child := c.internalSpans[t.internalSpanIdx].(*traceBuiltinSpan) |
| 43 | + otelToSpan(traceID, child, scopeSpan) |
| 44 | + } |
| 45 | +} |
| 46 | + |
| 47 | +func otelRecordTrace(t *traceBuiltinSpan) { |
| 48 | + exporter := otelexporter.GetDefaultOtelExporter() |
| 49 | + if exporter == nil { |
| 50 | + return |
| 51 | + } |
| 52 | + opts := tracerOptions.Load() |
| 53 | + scopeSpan := &otelexporter.OtelScopeSpan{ |
| 54 | + Scope: &otelexporter.OtelScope{Name: "gitea-server", Version: opts.AppVer}, |
| 55 | + } |
| 56 | + |
| 57 | + traceID := GetTracer().randomHexForBytes(16) |
| 58 | + otelToSpan(traceID, t, scopeSpan) |
| 59 | + |
| 60 | + resSpans := otelexporter.OtelResourceSpan{ |
| 61 | + Resource: &otelexporter.OtelResource{ |
| 62 | + Attributes: []*otelexporter.OtelAttribute{ |
| 63 | + {Key: "service.name", Value: otelexporter.OtelAttributeStringValue{StringValue: opts.ServiceName}}, |
| 64 | + }, |
| 65 | + }, |
| 66 | + ScopeSpans: []*otelexporter.OtelScopeSpan{scopeSpan}, |
| 67 | + } |
| 68 | + |
| 69 | + otelTrace := &otelexporter.OtelTrace{ResourceSpans: []*otelexporter.OtelResourceSpan{&resSpans}} |
| 70 | + exporter.ExportTrace(otelTrace) |
| 71 | +} |
0 commit comments