forked from aws/aws-xray-sdk-ruby
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathecs.rb
90 lines (78 loc) · 2.42 KB
/
ecs.rb
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
require 'socket'
require 'aws-xray-sdk/logger'
module XRay
module Plugins
# Due to lack of ECS container metadata service, the only host information
# available is the host name.
module ECS
include Logging
ORIGIN = 'AWS::ECS::Container'.freeze
# Only compatible with v4!
# The v3 metadata url does not contain cloudwatch informations
METADATA_ENV_KEY = 'ECS_CONTAINER_METADATA_URI_V4'
def self.aws
@@aws = {}
metadata = get_metadata()
@@aws = {
ecs: metadata[:ecs],
cloudwatch_logs: metadata[:cloudwatch_logs]
}
end
private
def self.get_metadata()
begin
metadata_uri = URI(ENV[METADATA_ENV_KEY])
req = Net::HTTP::Get.new(metadata_uri)
metadata_json = do_request(req)
return parse_metadata(metadata_json)
rescue StandardError => e
Logging.logger.warn %(cannot get the ecs instance metadata due to: #{e.message}.)
{}
end
end
def self.parse_metadata(json_str)
data = JSON(json_str)
begin
container_hostname = Socket.gethostname
rescue StandardError => e
@@aws = {}
Logging.logger.warn %(cannot get the ecs container hostname due to: #{e.message}.)
end
metadata = {
ecs: {
container: container_hostname,
container_arn: data['ContainerARN'],
},
cloudwatch_logs: {
log_group: data["LogOptions"]['awslogs-group'],
log_region: data["LogOptions"]['awslogs-region'],
arn: data['ContainerARN']
}
}
metadata
end
def self.do_request(request)
begin
response = Net::HTTP.start(request.uri.hostname, read_timeout: 1) { |http|
http.request(request)
}
if response.code == '200'
return response.body
else
raise(StandardError.new('Unsuccessful response::' + response.code + '::' + response.message))
end
rescue StandardError => e
# Two attempts in total to complete the request successfully
@retries ||= 0
if @retries < 1
@retries += 1
retry
else
Logging.logger.warn %(Failed to complete request due to: #{e.message}.)
raise e
end
end
end
end
end
end