blob: 01b4d27a0383992c235a19ec0fe67a601a5c4179 [file] [log] [blame]
Abhay Kumara2ae5992025-11-10 14:02:24 +00001// Copyright The OpenTelemetry Authors
2// SPDX-License-Identifier: Apache-2.0
3
4package resource // import "go.opentelemetry.io/otel/sdk/resource"
5
6import (
7 "context"
8 "strings"
9
10 "go.opentelemetry.io/otel/attribute"
11 semconv "go.opentelemetry.io/otel/semconv/v1.34.0"
12)
13
14type osDescriptionProvider func() (string, error)
15
16var defaultOSDescriptionProvider osDescriptionProvider = platformOSDescription
17
18var osDescription = defaultOSDescriptionProvider
19
20func setDefaultOSDescriptionProvider() {
21 setOSDescriptionProvider(defaultOSDescriptionProvider)
22}
23
24func setOSDescriptionProvider(osDescriptionProvider osDescriptionProvider) {
25 osDescription = osDescriptionProvider
26}
27
28type (
29 osTypeDetector struct{}
30 osDescriptionDetector struct{}
31)
32
33// Detect returns a *Resource that describes the operating system type the
34// service is running on.
35func (osTypeDetector) Detect(ctx context.Context) (*Resource, error) {
36 osType := runtimeOS()
37
38 osTypeAttribute := mapRuntimeOSToSemconvOSType(osType)
39
40 return NewWithAttributes(
41 semconv.SchemaURL,
42 osTypeAttribute,
43 ), nil
44}
45
46// Detect returns a *Resource that describes the operating system the
47// service is running on.
48func (osDescriptionDetector) Detect(ctx context.Context) (*Resource, error) {
49 description, err := osDescription()
50 if err != nil {
51 return nil, err
52 }
53
54 return NewWithAttributes(
55 semconv.SchemaURL,
56 semconv.OSDescription(description),
57 ), nil
58}
59
60// mapRuntimeOSToSemconvOSType translates the OS name as provided by the Go runtime
61// into an OS type attribute with the corresponding value defined by the semantic
62// conventions. In case the provided OS name isn't mapped, it's transformed to lowercase
63// and used as the value for the returned OS type attribute.
64func mapRuntimeOSToSemconvOSType(osType string) attribute.KeyValue {
65 // the elements in this map are the intersection between
66 // available GOOS values and defined semconv OS types
67 osTypeAttributeMap := map[string]attribute.KeyValue{
68 "aix": semconv.OSTypeAIX,
69 "darwin": semconv.OSTypeDarwin,
70 "dragonfly": semconv.OSTypeDragonflyBSD,
71 "freebsd": semconv.OSTypeFreeBSD,
72 "linux": semconv.OSTypeLinux,
73 "netbsd": semconv.OSTypeNetBSD,
74 "openbsd": semconv.OSTypeOpenBSD,
75 "solaris": semconv.OSTypeSolaris,
76 "windows": semconv.OSTypeWindows,
77 "zos": semconv.OSTypeZOS,
78 }
79
80 var osTypeAttribute attribute.KeyValue
81
82 if attr, ok := osTypeAttributeMap[osType]; ok {
83 osTypeAttribute = attr
84 } else {
85 osTypeAttribute = semconv.OSTypeKey.String(strings.ToLower(osType))
86 }
87
88 return osTypeAttribute
89}