Module: OpenTelemetry::Resource::Detector::AWS::ECS

Extended by:
ECS
Included in:
ECS
Defined in:
lib/opentelemetry/resource/detector/aws/ecs.rb

Overview

ECS contains detect class method for determining the ECS resource attributes

Constant Summary collapse

CONTAINER_ID_LENGTH =

Container ID length from cgroup file

64
HTTP_TIMEOUT =

HTTP request timeout in seconds

5
RESOURCE =

Create a constant for resource semantic conventions

OpenTelemetry::SemanticConventions::Resource

Instance Method Summary collapse

Instance Method Details

#detectObject



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
# File 'lib/opentelemetry/resource/detector/aws/ecs.rb', line 30

def detect
  # Return empty resource if not running on ECS
   = ENV.fetch('ECS_CONTAINER_METADATA_URI', nil)
   = ENV.fetch('ECS_CONTAINER_METADATA_URI_V4', nil)

  return OpenTelemetry::SDK::Resources::Resource.create({}) if .nil? && .nil?

  resource_attributes = {}
  container_id = fetch_container_id

  # Base ECS resource attributes
  resource_attributes[RESOURCE::CLOUD_PROVIDER] = 'aws'
  resource_attributes[RESOURCE::CLOUD_PLATFORM] = 'aws_ecs'
  resource_attributes[RESOURCE::CONTAINER_NAME] = Socket.gethostname
  resource_attributes[RESOURCE::CONTAINER_ID] = container_id unless container_id.empty?

  # If v4 endpoint is not available, return basic resource
  return OpenTelemetry::SDK::Resources::Resource.create(resource_attributes) if .nil?

  begin
    # Fetch container and task metadata
     = JSON.parse(http_get(.to_s))
     = JSON.parse(http_get("#{}/task"))

    task_arn = ['TaskARN']
    base_arn = task_arn[0..(task_arn.rindex(':') - 1)]

    cluster = ['Cluster']
    cluster_arn = cluster.start_with?('arn:') ? cluster : "#{base_arn}:cluster/#{cluster}"

    # Set ECS-specific attributes
    resource_attributes[RESOURCE::AWS_ECS_CONTAINER_ARN] = ['ContainerARN']
    resource_attributes[RESOURCE::AWS_ECS_CLUSTER_ARN] = cluster_arn
    resource_attributes[RESOURCE::AWS_ECS_LAUNCHTYPE] = ['LaunchType'].downcase
    resource_attributes[RESOURCE::AWS_ECS_TASK_ARN] = task_arn
    resource_attributes[RESOURCE::AWS_ECS_TASK_FAMILY] = ['Family']
    resource_attributes[RESOURCE::AWS_ECS_TASK_REVISION] = ['Revision']

    # Add logging attributes if awslogs is used
    logs_attributes = get_logs_resource()
    resource_attributes.merge!(logs_attributes)
  rescue StandardError => e
    OpenTelemetry.handle_error(exception: e, message: 'ECS resource detection failed')
    return OpenTelemetry::SDK::Resources::Resource.create({})
  end

  # Filter out nil or empty values
  resource_attributes.delete_if { |_key, value| value.nil? || value.empty? }
  OpenTelemetry::SDK::Resources::Resource.create(resource_attributes)
end