Module: MovableInk::AWS::EC2

Included in:
MovableInk::AWS
Defined in:
lib/movable_ink/aws/ec2.rb

Instance Method Summary collapse

Instance Method Details

#all_instances(region: my_region, no_filter: false, client: nil) ⇒ Object



52
53
54
55
# File 'lib/movable_ink/aws/ec2.rb', line 52

def all_instances(region: my_region, no_filter: false, client: nil)
  @all_instances ||= {}
  @all_instances[region] ||= load_all_instances(region, no_filter: no_filter, client: client)
end

#assign_ip_address(role:, eip_pool: nil, allow_reassociation: false) ⇒ Object



332
333
334
335
336
337
338
339
340
# File 'lib/movable_ink/aws/ec2.rb', line 332

def assign_ip_address(role:, eip_pool: nil, allow_reassociation: false)
  run_with_backoff do
    ec2.associate_address({
      instance_id: instance_id,
      allocation_id: available_elastic_ips(role: role, eip_pool: eip_pool).sample.allocation_id,
      allow_reassociation: allow_reassociation
    })
  end
end

#assign_ip_address_with_retries(role:, eip_pool: nil, allow_reassociation: false) ⇒ Object



320
321
322
323
324
325
326
327
328
329
330
# File 'lib/movable_ink/aws/ec2.rb', line 320

def assign_ip_address_with_retries(role:, eip_pool: nil, allow_reassociation: false)
  response = nil
  run_with_backoff do
    response = ec2_with_retries.associate_address({
      instance_id: instance_id,
      allocation_id: available_elastic_ips(role: role, eip_pool: eip_pool).sample.allocation_id,
      allow_reassociation: allow_reassociation
    })
  end
  response
end

#available_elastic_ips(role:, eip_pool: nil) ⇒ Object



312
313
314
315
316
317
318
# File 'lib/movable_ink/aws/ec2.rb', line 312

def available_elastic_ips(role:, eip_pool: nil)
  if eip_pool
    unassigned_elastic_ips.select { |address| address.tags.detect { |t| t.key == 'mi:eip-pool' && t.value == eip_pool } }
  else
    unassigned_elastic_ips.select { |address| address.tags.detect { |t| t.key == 'mi:roles' && t.value == role } }
  end
end

#default_filterObject



57
58
59
60
61
62
63
64
65
66
# File 'lib/movable_ink/aws/ec2.rb', line 57

def default_filter
  [{
    name: 'instance-state-name',
    values: ['running']
  },
  {
    name: 'tag:mi:env',
    values: [mi_env]
  }]
end

#describe_ip(public_ip:) ⇒ Object



285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
# File 'lib/movable_ink/aws/ec2.rb', line 285

def describe_ip(public_ip:)
  expected_errors = [
    MovableInk::AWS::Errors::ExpectedError.new(Aws::EC2::Errors::InvalidAddressNotFound, [/Address \'#{public_ip}\' not found./])
  ]
  begin
    run_with_backoff(expected_errors: expected_errors) do
      response = ec2_with_retries.describe_addresses({
        public_ips: [public_ip]
      })
      raise MovableInk::AWS::Errors::ServiceError if response.length > 1
      return response[0]
    end
  rescue MovableInk::AWS::Errors::ServiceError, Aws::EC2::Errors::InvalidAddressNotFound
    return nil
  end
end

#ec2(region: my_region, client: nil) ⇒ Object



8
9
10
11
# File 'lib/movable_ink/aws/ec2.rb', line 8

def ec2(region: my_region, client: nil)
  @ec2_client ||= {}
  @ec2_client[region] ||= (client) ? client : Aws::EC2::Client.new(region: region)
end

#ec2_with_retries(region: my_region, client: nil) ⇒ Object



13
14
15
16
17
18
19
20
21
# File 'lib/movable_ink/aws/ec2.rb', line 13

def ec2_with_retries(region: my_region, client: nil)
  @ec2_client_with_retries ||= {}
  if (client)
    @ec2_client_with_retries[region] ||= client
  else
    instance_credentials = Aws::InstanceProfileCredentials.new(retries: 5)
    @ec2_client_with_retries[region] ||= Aws::EC2::Client.new(region: region, credentials: instance_credentials)
  end
end

#elastic_ip_address_exist?(public_ip:) ⇒ Boolean

Returns:

  • (Boolean)


342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
# File 'lib/movable_ink/aws/ec2.rb', line 342

def elastic_ip_address_exist?(public_ip:)
  expected_errors = [
    MovableInk::AWS::Errors::ExpectedError.new(Aws::EC2::Errors::InvalidAddressNotFound, [/Address \'#{public_ip}\' not found./])
  ]
  begin
    run_with_backoff(expected_errors: expected_errors) do
      ec2.describe_addresses({
        public_ips: [public_ip]
      })
      return true
    end
  rescue MovableInk::AWS::Errors::ServiceError, Aws::EC2::Errors::InvalidAddressNotFound
    return false
  end
  # returns false if it ran out of API retries
  return false
end

#elastic_ipsObject



302
303
304
305
306
# File 'lib/movable_ink/aws/ec2.rb', line 302

def elastic_ips
  @all_elastic_ips ||= run_with_backoff do
    ec2.describe_addresses.addresses
  end
end

#get_managed_prefix_list_entries(managed_prefix_list_name) ⇒ Object



360
361
362
363
364
365
366
367
368
369
370
# File 'lib/movable_ink/aws/ec2.rb', line 360

def get_managed_prefix_list_entries(managed_prefix_list_name)
  entries = []
  run_with_backoff do
    result = ec2.describe_managed_prefix_lists({filters: [{name: "prefix-list-name", values: [managed_prefix_list_name]}]})
    raise MovableInk::AWS::Errors::ServiceError if result.prefix_lists.nil? || result.prefix_lists[0].nil?
    prefix_list_id = result.prefix_lists[0].prefix_list_id
    result = ec2.get_managed_prefix_list_entries({prefix_list_id: prefix_list_id})
    entries = result.data.entries.map {|e| e.cidr}
  end
  return entries
end

#instance_ip_addresses_by_role(role:, exclude_roles: [], region: my_region, availability_zone: nil, exact_match: false, use_cache: true) ⇒ Object



252
253
254
# File 'lib/movable_ink/aws/ec2.rb', line 252

def instance_ip_addresses_by_role(role:, exclude_roles: [], region: my_region, availability_zone: nil, exact_match: false, use_cache: true)
  private_ip_addresses(instances(role: role, exclude_roles: exclude_roles, region: region, availability_zone: availability_zone, exact_match: exact_match, use_cache: use_cache))
end

#instance_ip_addresses_by_role_ordered(role:, exclude_roles: [], region: my_region, exact_match: false) ⇒ Object



256
257
258
259
260
261
# File 'lib/movable_ink/aws/ec2.rb', line 256

def instance_ip_addresses_by_role_ordered(role:, exclude_roles: [], region: my_region, exact_match: false)
  instances = instances(role: role, exclude_roles: exclude_roles, region: region, exact_match: exact_match)
  instances_in_my_az = instances.select { |instance| instance.placement.availability_zone == availability_zone }
  ordered_instances = instances_in_my_az.shuffle + (instances - instances_in_my_az).shuffle
  private_ip_addresses(ordered_instances)
end

#instance_tagsObject



78
79
80
81
82
83
84
# File 'lib/movable_ink/aws/ec2.rb', line 78

def instance_tags
  @instance_tags ||= run_with_backoff(quiet: true) do
    ec2.describe_tags({
      filters: [{ name: 'resource-id', values: [instance_id] } ]
    }).tags
  end
end

#instances(role:, exclude_roles: [], region: my_region, availability_zone: nil, exact_match: false, use_cache: true, discovery_type: 'ec2') ⇒ Object



230
231
232
233
234
235
236
237
238
# File 'lib/movable_ink/aws/ec2.rb', line 230

def instances(role:, exclude_roles: [], region: my_region, availability_zone: nil, exact_match: false, use_cache: true, discovery_type: 'ec2')
  if discovery_type == 'ec2'
    instances_with_ec2_discovery(role: role, exclude_roles: exclude_roles, region: region, availability_zone: availability_zone, exact_match: exact_match, use_cache: use_cache)
  elsif discovery_type == 'consul'
    instances_with_consul_discovery(role: role, region: region, availability_zone: availability_zone)
  else
    raise MovableInk::AWS::Errors::InvalidDiscoveryTypeError
  end
end

#instances_with_consul_discovery(role:, region: my_region, availability_zone: nil) ⇒ Object



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
# File 'lib/movable_ink/aws/ec2.rb', line 121

def instances_with_consul_discovery(role:, region: my_region, availability_zone: nil)
  if role == nil || role == ''
    raise MovableInk::AWS::Errors::RoleNameRequiredError
  end

  consul_service_options = {
    dc: datacenter(region: region),
    stale: true,
    cached: true,
    passing: true,
  }
  consul_service_options[:node_meta] = "availability_zone:#{availability_zone}" unless availability_zone.nil?

  # We replace underscores with dashes in the role name in order to comply with
  # consul service naming conventions while still retaining the role name we use
  # within MI configuration
  Diplomat::Health.service(role.gsub('_', '-'), consul_service_options).map { |endpoint|
    if endpoint.Node.dig('Meta', 'external-source') == 'kubernetes'
      # Legacy catalog sync
      map_k8s_consul_endpoint(endpoint, role)
    elsif endpoint.Service && endpoint.Service.dig('Meta', 'managed-by') == 'consul-k8s-endpoints-controller'
      # Consul mesh with service mesh sidecar
      map_k8s_consul_mesh_endpoint(endpoint, role)
    else
      map_ec2_consul_endpoint(endpoint)
    end
  }
end

#instances_with_ec2_discovery(role:, exclude_roles: [], region: my_region, availability_zone: nil, exact_match: false, use_cache: true) ⇒ Object



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
# File 'lib/movable_ink/aws/ec2.rb', line 90

def instances_with_ec2_discovery(role:, exclude_roles: [], region: my_region, availability_zone: nil, exact_match: false, use_cache: true)
  roles = role.split(/\s*,\s*/)
  if use_cache == false
    filter = default_filter.push({
      name: 'tag:mi:roles',
      values: roles
    })
    instances = load_all_instances(region, filter: filter)
  else
    instances = all_instances(region: region).select { |instance|
      instance.tags.select{ |tag| tag.key == 'mi:roles' }.detect { |tag|
        tag_roles = tag.value.split(/\s*,\s*/)
        if exact_match
          tag_roles == roles
        else
          exclude_roles.push('decommissioned')
          tag_roles.any? { |tag_role| roles.include?(tag_role) } && !tag_roles.any? { |role| exclude_roles.include?(role) }
        end
      }
    }
  end

  if availability_zone
    instances.select { |instance|
      instance.placement.availability_zone == availability_zone
    }
  else
    instances
  end
end

#load_all_instances(region, no_filter: false, filter: nil, client: nil) ⇒ Object



68
69
70
71
72
73
74
75
76
# File 'lib/movable_ink/aws/ec2.rb', line 68

def load_all_instances(region, no_filter: false, filter: nil, client: nil)
  filters = no_filter ? nil : (filter || default_filter)

  run_with_backoff do
    ec2(region: region, client: client).describe_instances(filters: filters).flat_map do |resp|
      resp.reservations.flat_map(&:instances)
    end
  end
end

#load_mi_envObject



36
37
38
39
40
41
42
# File 'lib/movable_ink/aws/ec2.rb', line 36

def load_mi_env
  instance_tags
    .detect { |tag| tag.key == 'mi:env' }
    .value
rescue NoMethodError
  raise MovableInk::AWS::Errors::NoEnvironmentTagError
end

#map_ec2_consul_endpoint(endpoint) ⇒ Object



206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
# File 'lib/movable_ink/aws/ec2.rb', line 206

def map_ec2_consul_endpoint(endpoint)
  OpenStruct.new ({
    private_ip_address: endpoint.Node.dig('Address'),
    instance_id: endpoint.Node.dig('Meta', 'instance_id'),
    tags: [
      {
        key: 'Name',
        value: endpoint.Node.dig('Node')
      },
      {
        key: 'mi:roles',
        value: endpoint.Node.dig('Meta', 'mi_roles')
      },
      {
        key: 'mi:monitoring_roles',
        value: endpoint.Node.dig('Meta', 'mi_monitoring_roles')
      }
    ],
    placement: {
      availability_zone: endpoint.Node.dig('Meta', 'availability_zone')
    }
  })
end

#map_k8s_consul_endpoint(endpoint, role) ⇒ Object



150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
# File 'lib/movable_ink/aws/ec2.rb', line 150

def map_k8s_consul_endpoint(endpoint, role)
  OpenStruct.new ({
    private_ip_address: endpoint.Service.dig('Address'),
    instance_id: nil,
    tags: [
      {
        key: 'Name',
        value: endpoint.Service.dig('ID')
      },
      {
        key: 'mi:roles',
        value: role
      },
      {
        key: 'mi:monitoring_roles',
        value: role
      }
    ],
    placement: { availability_zone: endpoint.Service.dig('Meta', 'external-k8s-topology-zone') }
  })
end

#map_k8s_consul_mesh_endpoint(endpoint, role) ⇒ Object



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
# File 'lib/movable_ink/aws/ec2.rb', line 172

def map_k8s_consul_mesh_endpoint(endpoint, role)
  OpenStruct.new ({
    private_ip_address: endpoint.Service.dig('Address'),
    instance_id: nil,
    tags: [
      {
        key: 'Name',
        value: endpoint.Service.dig('Meta', 'pod-name')
      },
      {
        key: 'mi:roles',
        value: role
      },
      {
        key: 'mi:monitoring_roles',
        value: role
      },
      {
        key: 'k8s:namespace',
        value: endpoint.Service.dig('Meta', 'k8s-namespace')
      },
      {
        key: 'k8s:service',
        value: endpoint.Service.dig('Meta', 'k8s-service-name')
      },
      {
        key: 'k8s:pod-uid',
        value: endpoint.Service.dig('Meta', 'pod-uid')
      }
    ],
    placement: { availability_zone: endpoint.Service.dig('Locality', 'Zone') }
  })
end

#meObject



86
87
88
# File 'lib/movable_ink/aws/ec2.rb', line 86

def me
  @me ||= all_instances.select{|instance| instance.instance_id == instance_id}.first rescue nil
end

#mi_envObject



27
28
29
30
31
32
33
34
# File 'lib/movable_ink/aws/ec2.rb', line 27

def mi_env
  @mi_env ||= if File.exist?(mi_env_cache_file_path)
    environments = JSON.parse(File.read(mi_env_cache_file_path))
    environments[my_region] || load_mi_env
  else
    load_mi_env
  end
end

#mi_env_cache_file_pathObject



23
24
25
# File 'lib/movable_ink/aws/ec2.rb', line 23

def mi_env_cache_file_path
  '/etc/movableink/environments.json'
end

#private_ip_addresses(instances) ⇒ Object



248
249
250
# File 'lib/movable_ink/aws/ec2.rb', line 248

def private_ip_addresses(instances)
  instances.map(&:private_ip_address)
end

#redis(host, port) ⇒ Object



270
271
272
# File 'lib/movable_ink/aws/ec2.rb', line 270

def redis(host, port)
  {"host" => host, "port" => port}
end

#redis_by_role(role, port, availability_zones = []) ⇒ Object



263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
# File 'lib/movable_ink/aws/ec2.rb', line 263

def redis_by_role(role, port, availability_zones = [])
  if availability_zones.class != Array
    raise MovableInk::AWS::Errors::AvailabilityZonesListInvalidError
  end

  redis_instances = []

  def redis(host, port)
    {"host" => host, "port" => port}
  end

  if availability_zones.length > 0
    availability_zones.each do |az|
      redis_instances << instance_ip_addresses_by_role(role: role, availability_zone: az).inject([]) { |redii, instance| redii.push(redis(instance, port)) }
    end
  else
    redis_instances << instance_ip_addresses_by_role(role: role).inject([]) { |redii, instance| redii.push(redis(instance, port)) }
  end

  redis_instances.flatten.shuffle
end

#statsd_hostObject



244
245
246
# File 'lib/movable_ink/aws/ec2.rb', line 244

def statsd_host
  instance_ip_addresses_by_role(role: 'statsd', availability_zone: availability_zone, use_cache: false).sample
end

#thopterObject



240
241
242
# File 'lib/movable_ink/aws/ec2.rb', line 240

def thopter
  private_ip_addresses(thopter_instance).first
end

#thopter_instanceObject



44
45
46
47
48
49
50
# File 'lib/movable_ink/aws/ec2.rb', line 44

def thopter_instance
  @thopter_instance ||= all_instances(region: 'us-east-1').select do |instance|
    instance.tags.select{ |tag| tag.key == 'mi:roles' }.detect do |tag|
      tag.value.include?('thopter')
    end
  end
end

#unassigned_elastic_ipsObject



308
309
310
# File 'lib/movable_ink/aws/ec2.rb', line 308

def unassigned_elastic_ips
  @unassigned_elastic_ips ||= elastic_ips.select { |address| address.association_id.nil? }
end