...
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15 package resource
16
17 import (
18 "context"
19 "fmt"
20 "os"
21 "path/filepath"
22
23 "go.opentelemetry.io/otel/attribute"
24 "go.opentelemetry.io/otel/sdk"
25 semconv "go.opentelemetry.io/otel/semconv/v1.21.0"
26 )
27
28 type (
29
30
31
32
33
34 telemetrySDK struct{}
35
36
37
38
39
40
41 host struct{}
42
43 stringDetector struct {
44 schemaURL string
45 K attribute.Key
46 F func() (string, error)
47 }
48
49 defaultServiceNameDetector struct{}
50 )
51
52 var (
53 _ Detector = telemetrySDK{}
54 _ Detector = host{}
55 _ Detector = stringDetector{}
56 _ Detector = defaultServiceNameDetector{}
57 )
58
59
60 func (telemetrySDK) Detect(context.Context) (*Resource, error) {
61 return NewWithAttributes(
62 semconv.SchemaURL,
63 semconv.TelemetrySDKName("opentelemetry"),
64 semconv.TelemetrySDKLanguageGo,
65 semconv.TelemetrySDKVersion(sdk.Version()),
66 ), nil
67 }
68
69
70 func (host) Detect(ctx context.Context) (*Resource, error) {
71 return StringDetector(semconv.SchemaURL, semconv.HostNameKey, os.Hostname).Detect(ctx)
72 }
73
74
75
76
77 func StringDetector(schemaURL string, k attribute.Key, f func() (string, error)) Detector {
78 return stringDetector{schemaURL: schemaURL, K: k, F: f}
79 }
80
81
82
83 func (sd stringDetector) Detect(ctx context.Context) (*Resource, error) {
84 value, err := sd.F()
85 if err != nil {
86 return nil, fmt.Errorf("%s: %w", string(sd.K), err)
87 }
88 a := sd.K.String(value)
89 if !a.Valid() {
90 return nil, fmt.Errorf("invalid attribute: %q -> %q", a.Key, a.Value.Emit())
91 }
92 return NewWithAttributes(sd.schemaURL, sd.K.String(value)), nil
93 }
94
95
96 func (defaultServiceNameDetector) Detect(ctx context.Context) (*Resource, error) {
97 return StringDetector(
98 semconv.SchemaURL,
99 semconv.ServiceNameKey,
100 func() (string, error) {
101 executable, err := os.Executable()
102 if err != nil {
103 return "unknown_service:go", nil
104 }
105 return "unknown_service:" + filepath.Base(executable), nil
106 },
107 ).Detect(ctx)
108 }
109
View as plain text