File: collector_test.go

package info (click to toggle)
golang-opentelemetry-contrib 0.56.0-5
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 4,884 kB
  • sloc: makefile: 278; sh: 211; sed: 1
file content (89 lines) | stat: -rw-r--r-- 2,430 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0

package xrayconfig

// Pared down version of go.opentelemetry.io/otel/exporters/otlp/otlptrace/internal/otlptracetest/collector.go
// for end to end testing

import (
	"sort"

	collectortracepb "go.opentelemetry.io/proto/otlp/collector/trace/v1"
	commonpb "go.opentelemetry.io/proto/otlp/common/v1"
	resourcepb "go.opentelemetry.io/proto/otlp/resource/v1"
	tracepb "go.opentelemetry.io/proto/otlp/trace/v1"
)

// SpansStorage stores the spans. Mock collectors can use it to
// store spans they have received.
type SpansStorage struct {
	rsm       map[string]*tracepb.ResourceSpans
	spanCount int
}

// NewSpansStorage creates a new spans storage.
func NewSpansStorage() SpansStorage {
	return SpansStorage{
		rsm: make(map[string]*tracepb.ResourceSpans),
	}
}

// AddSpans adds spans to the spans storage.
func (s *SpansStorage) AddSpans(request *collectortracepb.ExportTraceServiceRequest) {
	for _, rs := range request.GetResourceSpans() {
		rstr := resourceString(rs.Resource)
		if existingRs, ok := s.rsm[rstr]; !ok {
			s.rsm[rstr] = rs
			// TODO (rghetia): Add support for library Info.
			if len(rs.ScopeSpans) == 0 {
				rs.ScopeSpans = []*tracepb.ScopeSpans{
					{
						Spans: []*tracepb.Span{},
					},
				}
			}
			s.spanCount += len(rs.ScopeSpans[0].Spans)
		} else {
			if len(rs.ScopeSpans) > 0 {
				newSpans := rs.ScopeSpans[0].GetSpans()
				existingRs.ScopeSpans[0].Spans = append(existingRs.ScopeSpans[0].Spans, newSpans...)
				s.spanCount += len(newSpans)
			}
		}
	}
}

// GetSpans returns the stored spans.
func (s *SpansStorage) GetSpans() []*tracepb.Span {
	spans := make([]*tracepb.Span, 0, s.spanCount)
	for _, rs := range s.rsm {
		spans = append(spans, rs.ScopeSpans[0].Spans...)
	}
	return spans
}

// GetResourceSpans returns the stored resource spans.
func (s *SpansStorage) GetResourceSpans() []*tracepb.ResourceSpans {
	rss := make([]*tracepb.ResourceSpans, 0, len(s.rsm))
	for _, rs := range s.rsm {
		rss = append(rss, rs)
	}
	return rss
}

func resourceString(res *resourcepb.Resource) string {
	sAttrs := sortedAttributes(res.GetAttributes())
	rstr := ""
	for _, attr := range sAttrs {
		rstr = rstr + attr.String()
	}
	return rstr
}

func sortedAttributes(attrs []*commonpb.KeyValue) []*commonpb.KeyValue {
	sort.Slice(attrs[:], func(i, j int) bool {
		return attrs[i].Key < attrs[j].Key
	})
	return attrs
}