File: ecs.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 (264 lines) | stat: -rw-r--r-- 8,083 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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0

package ecs // import "go.opentelemetry.io/contrib/detectors/aws/ecs"

import (
	"context"
	"errors"
	"fmt"
	"net/http"
	"os"
	"runtime"
	"strings"

	ecsmetadata "github.com/brunoscheufler/aws-ecs-metadata-go"

	"go.opentelemetry.io/otel/attribute"
	"go.opentelemetry.io/otel/sdk/resource"
	semconv "go.opentelemetry.io/otel/semconv/v1.26.0"
)

const (
	// TypeStr is AWS ECS type.
	TypeStr           = "ecs"
	metadataV3EnvVar  = "ECS_CONTAINER_METADATA_URI"
	metadataV4EnvVar  = "ECS_CONTAINER_METADATA_URI_V4"
	containerIDLength = 64
	defaultCgroupPath = "/proc/self/cgroup"
)

var (
	empty                                 = resource.Empty()
	errCannotReadContainerName            = errors.New("failed to read hostname")
	errCannotParseTaskArn                 = errors.New("cannot parse region and account ID from the Task's ARN: the ARN does not contain at least 6 segments separated by the ':' character")
	errCannotRetrieveLogsGroupMetadataV4  = errors.New("the ECS Metadata v4 did not return a AwsLogGroup name")
	errCannotRetrieveLogsStreamMetadataV4 = errors.New("the ECS Metadata v4 did not return a AwsLogStream name")
)

// Create interface for methods needing to be mocked.
type detectorUtils interface {
	getContainerName() (string, error)
	getContainerID() (string, error)
	getContainerMetadataV4(ctx context.Context) (*ecsmetadata.ContainerMetadataV4, error)
	getTaskMetadataV4(ctx context.Context) (*ecsmetadata.TaskMetadataV4, error)
}

// struct implements detectorUtils interface.
type ecsDetectorUtils struct{}

// resource detector collects resource information from Elastic Container Service environment.
type resourceDetector struct {
	utils detectorUtils
}

// compile time assertion that ecsDetectorUtils implements detectorUtils interface.
var _ detectorUtils = (*ecsDetectorUtils)(nil)

// compile time assertion that resource detector implements the resource.Detector interface.
var _ resource.Detector = (*resourceDetector)(nil)

// NewResourceDetector returns a resource detector that will detect AWS ECS resources.
func NewResourceDetector() resource.Detector {
	return &resourceDetector{
		utils: ecsDetectorUtils{},
	}
}

// Detect finds associated resources when running on ECS environment.
func (detector *resourceDetector) Detect(ctx context.Context) (*resource.Resource, error) {
	metadataURIV3 := os.Getenv(metadataV3EnvVar)
	metadataURIV4 := os.Getenv(metadataV4EnvVar)

	if len(metadataURIV3) == 0 && len(metadataURIV4) == 0 {
		return nil, nil
	}
	hostName, err := detector.utils.getContainerName()
	if err != nil {
		return empty, err
	}
	containerID, err := detector.utils.getContainerID()
	if err != nil {
		return empty, err
	}
	attributes := []attribute.KeyValue{
		semconv.CloudProviderAWS,
		semconv.CloudPlatformAWSECS,
		semconv.ContainerName(hostName),
		semconv.ContainerID(containerID),
	}

	if len(metadataURIV4) > 0 {
		containerMetadata, err := detector.utils.getContainerMetadataV4(ctx)
		if err != nil {
			return empty, err
		}

		taskMetadata, err := detector.utils.getTaskMetadataV4(ctx)
		if err != nil {
			return empty, err
		}

		baseArn := detector.getBaseArn(
			taskMetadata.TaskARN,
			containerMetadata.ContainerARN,
			taskMetadata.Cluster,
		)

		if baseArn != "" {
			if !strings.HasPrefix(taskMetadata.Cluster, "arn:") {
				taskMetadata.Cluster = fmt.Sprintf("%s:cluster/%s", baseArn, taskMetadata.Cluster)
			}
			if !strings.HasPrefix(containerMetadata.ContainerARN, "arn:") {
				containerMetadata.ContainerARN = fmt.Sprintf("%s:container/%s", baseArn, containerMetadata.ContainerARN)
			}
			if !strings.HasPrefix(taskMetadata.TaskARN, "arn:") {
				taskMetadata.TaskARN = fmt.Sprintf("%s:task/%s", baseArn, taskMetadata.TaskARN)
			}
		}

		arnParts := strings.Split(taskMetadata.TaskARN, ":")
		// A valid ARN should have at least 6 parts.
		if len(arnParts) < 6 {
			return empty, errCannotParseTaskArn
		}

		attributes = append(
			attributes,
			semconv.CloudRegion(arnParts[3]),
			semconv.CloudAccountID(arnParts[4]),
		)

		availabilityZone := taskMetadata.AvailabilityZone
		if len(availabilityZone) > 0 {
			attributes = append(
				attributes,
				semconv.CloudAvailabilityZone(availabilityZone),
			)
		}

		logAttributes, err := detector.getLogsAttributes(containerMetadata)
		if err != nil {
			return empty, err
		}

		if len(logAttributes) > 0 {
			attributes = append(attributes, logAttributes...)
		}

		attributes = append(
			attributes,
			semconv.CloudResourceID(containerMetadata.ContainerARN),
			semconv.AWSECSContainerARN(containerMetadata.ContainerARN),
			semconv.AWSECSClusterARN(taskMetadata.Cluster),
			semconv.AWSECSLaunchtypeKey.String(strings.ToLower(taskMetadata.LaunchType)),
			semconv.AWSECSTaskARN(taskMetadata.TaskARN),
			semconv.AWSECSTaskFamily(taskMetadata.Family),
			semconv.AWSECSTaskRevision(taskMetadata.Revision),
		)
	}

	return resource.NewWithAttributes(semconv.SchemaURL, attributes...), nil
}

func (detector *resourceDetector) getBaseArn(arns ...string) string {
	for _, arn := range arns {
		if i := strings.LastIndex(arn, ":"); i >= 0 {
			return arn[:i]
		}
	}
	return ""
}

func (detector *resourceDetector) getLogsAttributes(metadata *ecsmetadata.ContainerMetadataV4) ([]attribute.KeyValue, error) {
	if metadata.LogDriver != "awslogs" {
		return []attribute.KeyValue{}, nil
	}

	logsOptions := metadata.LogOptions

	if len(logsOptions.AwsLogsGroup) < 1 {
		return nil, errCannotRetrieveLogsGroupMetadataV4
	}

	if len(logsOptions.AwsLogsStream) < 1 {
		return nil, errCannotRetrieveLogsStreamMetadataV4
	}

	containerArn := metadata.ContainerARN
	// https://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html
	const arnPartition = 1
	const arnRegion = 3
	const arnAccountId = 4
	containerArnParts := strings.Split(containerArn, ":")
	// a valid arn should have at least 6 parts
	if len(containerArnParts) < 6 {
		return nil, errCannotRetrieveLogsStreamMetadataV4
	}
	logsRegion := logsOptions.AwsRegion
	if len(logsRegion) < 1 {
		logsRegion = containerArnParts[arnRegion]
	}

	awsPartition := containerArnParts[arnPartition]
	awsAccount := containerArnParts[arnAccountId]

	awsLogGroupArn := strings.Join([]string{
		"arn", awsPartition, "logs",
		logsRegion, awsAccount, "log-group", logsOptions.AwsLogsGroup,
		"*",
	}, ":")
	awsLogStreamArn := strings.Join([]string{
		"arn", awsPartition, "logs",
		logsRegion, awsAccount, "log-group", logsOptions.AwsLogsGroup,
		"log-stream", logsOptions.AwsLogsStream,
	}, ":")

	return []attribute.KeyValue{
		semconv.AWSLogGroupNames(logsOptions.AwsLogsGroup),
		semconv.AWSLogGroupARNs(awsLogGroupArn),
		semconv.AWSLogStreamNames(logsOptions.AwsLogsStream),
		semconv.AWSLogStreamARNs(awsLogStreamArn),
	}, nil
}

// returns metadata v4 for the container.
func (ecsUtils ecsDetectorUtils) getContainerMetadataV4(ctx context.Context) (*ecsmetadata.ContainerMetadataV4, error) {
	return ecsmetadata.GetContainerV4(ctx, &http.Client{})
}

// returns metadata v4 for the task.
func (ecsUtils ecsDetectorUtils) getTaskMetadataV4(ctx context.Context) (*ecsmetadata.TaskMetadataV4, error) {
	return ecsmetadata.GetTaskV4(ctx, &http.Client{})
}

// returns docker container ID from default c group path.
func (ecsUtils ecsDetectorUtils) getContainerID() (string, error) {
	if runtime.GOOS != "linux" {
		// Cgroups are used only under Linux.
		return "", nil
	}

	fileData, err := os.ReadFile(defaultCgroupPath)
	if err != nil {
		// Cgroups file not found.
		// For example, windows; or when running integration tests outside of a container.
		return "", nil
	}
	splitData := strings.Split(strings.TrimSpace(string(fileData)), "\n")
	for _, str := range splitData {
		if len(str) > containerIDLength {
			return str[len(str)-containerIDLength:], nil
		}
	}
	return "", nil
}

// returns host name reported by the kernel.
func (ecsUtils ecsDetectorUtils) getContainerName() (string, error) {
	hostName, err := os.Hostname()
	if err != nil {
		return "", errCannotReadContainerName
	}
	return hostName, nil
}