Debian Codegraph @

detectors/aws/ecs/ecs.go

raw
1 // Copyright The OpenTelemetry Authors
2 // SPDX-License-Identifier: Apache-2.0
3
4 // Package ecs provides a resource detector for AWS ECS instances.
5 package ecs // import "go.opentelemetry.io/contrib/detectors/aws/ecs"
6
7 import (
8 "context"
9 "errors"
10 "fmt"
11 "net/http"
12 "os"
13 "regexp"
14 "runtime"
15 "strings"
16
17 ecsmetadata "github.com/brunoscheufler/aws-ecs-metadata-go"
18 "go.opentelemetry.io/otel/attribute"
19 "go.opentelemetry.io/otel/sdk/resource"
20 semconv "go.opentelemetry.io/otel/semconv/v1.40.0"
21 )
22
23 const (
24 // TypeStr is AWS ECS type.
25 TypeStr = "ecs"
26 metadataV3EnvVar = "ECS_CONTAINER_METADATA_URI"
27 metadataV4EnvVar = "ECS_CONTAINER_METADATA_URI_V4"
28 containerIDLength = 64
29 defaultCgroupPath = "/proc/self/cgroup"
30 )
31
32 var (
33 empty = resource.Empty()
34 errCannotReadContainerName = errors.New("failed to read hostname")
35 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")
36 errCannotRetrieveLogsGroupMetadataV4 = errors.New("the ECS Metadata v4 did not return a AwsLogGroup name")
37 errCannotRetrieveLogsStreamMetadataV4 = errors.New("the ECS Metadata v4 did not return a AwsLogStream name")
38 ecsCgroupPathPattern = regexp.MustCompile(`/ecs/[^/]+/[a-f0-9]{64}$`)
39 )
40
41 // Create interface for methods needing to be mocked.
42 type detectorUtils interface {
43 getContainerName() (string, error)
44 getContainerID() (string, error)
45 getContainerMetadataV4(ctx context.Context) (*ecsmetadata.ContainerMetadataV4, error)
46 getTaskMetadataV4(ctx context.Context) (*ecsmetadata.TaskMetadataV4, error)
47 }
48
49 // struct implements detectorUtils interface.
50 type ecsDetectorUtils struct{}
51
52 // resource detector collects resource information from Elastic Container Service environment.
53 type resourceDetector struct {
54 utils detectorUtils
55 }
56
57 // compile time assertion that ecsDetectorUtils implements detectorUtils interface.
58 var _ detectorUtils = (*ecsDetectorUtils)(nil)
59
60 // compile time assertion that resource detector implements the resource.Detector interface.
61 var _ resource.Detector = (*resourceDetector)(nil)
62
63 // NewResourceDetector returns a resource detector that will detect AWS ECS resources.
64 func NewResourceDetector() resource.Detector {
65 return &resourceDetector{
66 utils: ecsDetectorUtils{},
67 }
68 }
69
70 // Detect finds associated resources when running on ECS environment.
71 func (detector *resourceDetector) Detect(ctx context.Context) (*resource.Resource, error) {
72 metadataURIV3 := os.Getenv(metadataV3EnvVar)
73 metadataURIV4 := os.Getenv(metadataV4EnvVar)
74
75 if metadataURIV3 == "" && metadataURIV4 == "" {
76 return nil, nil
77 }
78 hostName, err := detector.utils.getContainerName()
79 if err != nil {
80 return empty, err
81 }
82 containerID, err := detector.utils.getContainerID()
83 if err != nil {
84 return empty, err
85 }
86 attributes := []attribute.KeyValue{
87 semconv.CloudProviderAWS,
88 semconv.CloudPlatformAWSECS,
89 semconv.ContainerName(hostName),
90 semconv.ContainerID(containerID),
91 }
92
93 if metadataURIV4 != "" {
94 containerMetadata, err := detector.utils.getContainerMetadataV4(ctx)
95 if err != nil {
96 return empty, err
97 }
98
99 taskMetadata, err := detector.utils.getTaskMetadataV4(ctx)
100 if err != nil {
101 return empty, err
102 }
103
104 baseArn := detector.getBaseArn(
105 taskMetadata.TaskARN,
106 containerMetadata.ContainerARN,
107 taskMetadata.Cluster,
108 )
109
110 if baseArn != "" {
111 if !strings.HasPrefix(taskMetadata.Cluster, "arn:") {
112 taskMetadata.Cluster = fmt.Sprintf("%s:cluster/%s", baseArn, taskMetadata.Cluster)
113 }
114 if !strings.HasPrefix(containerMetadata.ContainerARN, "arn:") {
115 containerMetadata.ContainerARN = fmt.Sprintf("%s:container/%s", baseArn, containerMetadata.ContainerARN)
116 }
117 if !strings.HasPrefix(taskMetadata.TaskARN, "arn:") {
118 taskMetadata.TaskARN = fmt.Sprintf("%s:task/%s", baseArn, taskMetadata.TaskARN)
119 }
120 }
121
122 arnParts := strings.Split(taskMetadata.TaskARN, ":")
123 // A valid ARN should have at least 6 parts.
124 if len(arnParts) < 6 {
125 return empty, errCannotParseTaskArn
126 }
127
128 attributes = append(
129 attributes,
130 semconv.CloudRegion(arnParts[3]),
131 semconv.CloudAccountID(arnParts[4]),
132 )
133
134 availabilityZone := taskMetadata.AvailabilityZone
135 if availabilityZone != "" {
136 attributes = append(
137 attributes,
138 semconv.CloudAvailabilityZone(availabilityZone),
139 )
140 }
141
142 logAttributes, err := detector.getLogsAttributes(containerMetadata)
143 if err != nil {
144 return empty, err
145 }
146
147 if len(logAttributes) > 0 {
148 attributes = append(attributes, logAttributes...)
149 }
150
151 attributes = append(
152 attributes,
153 semconv.CloudResourceID(containerMetadata.ContainerARN),
154 semconv.AWSECSContainerARN(containerMetadata.ContainerARN),
155 semconv.AWSECSClusterARN(taskMetadata.Cluster),
156 semconv.AWSECSLaunchtypeKey.String(strings.ToLower(taskMetadata.LaunchType)),
157 semconv.AWSECSTaskARN(taskMetadata.TaskARN),
158 semconv.AWSECSTaskFamily(taskMetadata.Family),
159 semconv.AWSECSTaskRevision(taskMetadata.Revision),
160 )
161 }
162
163 return resource.NewWithAttributes(semconv.SchemaURL, attributes...), nil
164 }
165
166 func (*resourceDetector) getBaseArn(arns ...string) string {
167 for _, arn := range arns {
168 if i := strings.LastIndex(arn, ":"); i >= 0 {
169 return arn[:i]
170 }
171 }
172 return ""
173 }
174
175 func (*resourceDetector) getLogsAttributes(metadata *ecsmetadata.ContainerMetadataV4) ([]attribute.KeyValue, error) {
176 if metadata.LogDriver != "awslogs" {
177 return []attribute.KeyValue{}, nil
178 }
179
180 logsOptions := metadata.LogOptions
181
182 if len(logsOptions.AwsLogsGroup) < 1 {
183 return nil, errCannotRetrieveLogsGroupMetadataV4
184 }
185
186 if len(logsOptions.AwsLogsStream) < 1 {
187 return nil, errCannotRetrieveLogsStreamMetadataV4
188 }
189
190 containerArn := metadata.ContainerARN
191 // https://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html
192 const arnPartition = 1
193 const arnRegion = 3
194 const arnAccountId = 4
195 containerArnParts := strings.Split(containerArn, ":")
196 // a valid arn should have at least 6 parts
197 if len(containerArnParts) < 6 {
198 return nil, errCannotRetrieveLogsStreamMetadataV4
199 }
200 logsRegion := logsOptions.AwsRegion
201 if len(logsRegion) < 1 {
202 logsRegion = containerArnParts[arnRegion]
203 }
204
205 awsPartition := containerArnParts[arnPartition]
206 awsAccount := containerArnParts[arnAccountId]
207
208 awsLogGroupArn := strings.Join([]string{
209 "arn", awsPartition, "logs",
210 logsRegion, awsAccount, "log-group", logsOptions.AwsLogsGroup,
211 "*",
212 }, ":")
213 awsLogStreamArn := strings.Join([]string{
214 "arn", awsPartition, "logs",
215 logsRegion, awsAccount, "log-group", logsOptions.AwsLogsGroup,
216 "log-stream", logsOptions.AwsLogsStream,
217 }, ":")
218
219 return []attribute.KeyValue{
220 semconv.AWSLogGroupNames(logsOptions.AwsLogsGroup),
221 semconv.AWSLogGroupARNs(awsLogGroupArn),
222 semconv.AWSLogStreamNames(logsOptions.AwsLogsStream),
223 semconv.AWSLogStreamARNs(awsLogStreamArn),
224 }, nil
225 }
226
227 // returns metadata v4 for the container.
228 func (ecsDetectorUtils) getContainerMetadataV4(ctx context.Context) (*ecsmetadata.ContainerMetadataV4, error) {
229 return ecsmetadata.GetContainerV4(ctx, &http.Client{})
230 }
231
232 // returns metadata v4 for the task.
233 func (ecsDetectorUtils) getTaskMetadataV4(ctx context.Context) (*ecsmetadata.TaskMetadataV4, error) {
234 return ecsmetadata.GetTaskV4(ctx, &http.Client{})
235 }
236
237 // returns docker container ID from default c group path.
238 func (ecsDetectorUtils) getContainerID() (string, error) {
239 if runtime.GOOS != "linux" {
240 // Cgroups are used only under Linux.
241 return "", nil
242 }
243
244 fileData, err := os.ReadFile(defaultCgroupPath)
245 if err != nil {
246 // Cgroups file not found.
247 // For example, windows; or when running integration tests outside of a container.
248 return "", nil
249 }
250 return getCgroupContainerID(fileData), nil
251 }
252
253 // returns host name reported by the kernel.
254 func (ecsDetectorUtils) getContainerName() (string, error) {
255 hostName, err := os.Hostname()
256 if err != nil {
257 return "", errCannotReadContainerName
258 }
259 return hostName, nil
260 }
261
262 func getCgroupContainerID(fileData []byte) string {
263 splitData := strings.SplitSeq(strings.TrimSpace(string(fileData)), "\n")
264 for str := range splitData {
265 if ecsCgroupPathPattern.MatchString(str) {
266 return str[len(str)-containerIDLength:]
267 }
268 }
269 return ""
270 }