Class: Miasma::Models::Orchestration::Aws

Inherits:
Miasma::Models::Orchestration show all
Includes:
Contrib::AwsApiCore::ApiCommon, Contrib::AwsApiCore::RequestUtils
Defined in:
lib/miasma/contrib/aws/orchestration.rb

Defined Under Namespace

Classes: Stack

Constant Summary collapse

API_SERVICE =

Service name of the API

'cloudformation'
EUCA_API_SERVICE =

Service name of the eucalyptus API

'CloudFormation'
API_VERSION =

Supported version of the AutoScaling API

'2010-05-15'
STACK_STATES =

Valid stack lookup states

[
  "CREATE_COMPLETE", "CREATE_FAILED", "CREATE_IN_PROGRESS", "DELETE_FAILED",
  "DELETE_IN_PROGRESS", "ROLLBACK_COMPLETE", "ROLLBACK_FAILED", "ROLLBACK_IN_PROGRESS",
  "UPDATE_COMPLETE", "UPDATE_COMPLETE_CLEANUP_IN_PROGRESS", "UPDATE_IN_PROGRESS",
  "UPDATE_ROLLBACK_COMPLETE", "UPDATE_ROLLBACK_COMPLETE_CLEANUP_IN_PROGRESS", "UPDATE_ROLLBACK_FAILED",
  "UPDATE_ROLLBACK_IN_PROGRESS"
]
RESOURCE_MAPPING =

Returns external to internal resource mapping.

Returns:

  • (Smash)

    external to internal resource mapping

Smash.new(
  'AWS::EC2::Instance' => Smash.new(
    :api => :compute,
    :collection => :servers
  ),
  'AWS::ElasticLoadBalancing::LoadBalancer' => Smash.new(
    :api => :load_balancer,
    :collection => :balancers
  ),
  'AWS::AutoScaling::AutoScalingGroup' => Smash.new(
    :api => :auto_scale,
    :collection => :groups
  ),
  'AWS::CloudFormation::Stack' => Smash.new(
    :api => :orchestration,
    :collection => :stacks
  )
)

Instance Method Summary collapse

Methods included from Contrib::AwsApiCore::RequestUtils

#all_result_pages

Methods included from Contrib::AwsApiCore::ApiCommon

#after_setup, #api_for, #connect, #connection, #custom_setup, #endpoint, included, #load_aws_file, #load_instance_credentials!, #make_request, #perform_request_retry, #retryable_allowed?, #sts_assume_role!, #sts_update_required?, #update_request, #uri_escape

Instance Method Details

#event_all(stack, evt_id = nil) ⇒ Array<Models::Orchestration::Stack::Event>

Return all events for stack

Parameters:

  • stack (Models::Orchestration::Stack)

Returns:

  • (Array<Models::Orchestration::Stack::Event>)


362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
# File 'lib/miasma/contrib/aws/orchestration.rb', line 362

def event_all(stack, evt_id=nil)
  results = all_result_pages(nil, :body, 'DescribeStackEventsResponse', 'DescribeStackEventsResult', 'StackEvents', 'member') do |options|
    request(
      :method => :post,
      :path => '/',
      :form => options.merge(
        'Action' => 'DescribeStackEvents',
        'StackName' => stack.id
      )
    )
  end
  events = results.map do |event|
    Stack::Event.new(
      stack,
      :id => event['EventId'],
      :resource_id => event['PhysicalResourceId'],
      :resource_name => event['LogicalResourceId'],
      :resource_logical_id => event['LogicalResourceId'],
      :resource_state => event['ResourceStatus'].downcase.to_sym,
      :resource_status => event['ResourceStatus'],
      :resource_status_reason => event['ResourceStatusReason'],
      :time => Time.parse(event['Timestamp'])
    ).valid_state
  end
  if(evt_id)
    idx = events.index{|d| e.id == evt_id}
    idx = idx ? idx + 1 : 0
    events.slice(idx, events.size)
  else
    events
  end
end

#event_all_new(events) ⇒ Array<Models::Orchestration::Stack::Event>

Return all new events for event collection

Parameters:

  • events (Models::Orchestration::Stack::Events)

Returns:

  • (Array<Models::Orchestration::Stack::Event>)


399
400
401
# File 'lib/miasma/contrib/aws/orchestration.rb', line 399

def event_all_new(events)
  event_all(events.stack, events.all.first.id)
end

#event_reload(event) ⇒ Models::Orchestration::Event

Reload the stack event data from the API

Parameters:

  • resource (Models::Orchestration::Stack::Event)

Returns:

  • (Models::Orchestration::Event)


407
408
409
410
# File 'lib/miasma/contrib/aws/orchestration.rb', line 407

def event_reload(event)
  event.stack.events.reload
  event.stack.events.get(event.id)
end

#load_stack_data(stack = nil) ⇒ Array<Models::Orchestration::Stack>

Fetch stacks or update provided stack data

Parameters:

  • stack (Models::Orchestration::Stack) (defaults to: nil)

Returns:

  • (Array<Models::Orchestration::Stack>)


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
# File 'lib/miasma/contrib/aws/orchestration.rb', line 57

def load_stack_data(stack=nil)
  d_params = Smash.new('Action' => 'DescribeStacks')
  l_params = Smash.new('Action' => 'ListStacks')
  STACK_STATES.each_with_index do |state, idx|
    l_params["StackStatusFilter.member.#{idx + 1}"] = state.to_s.upcase
  end
  if(stack)
    d_params['StackName'] = stack.id
    descriptions = all_result_pages(nil, :body, 'DescribeStacksResponse', 'DescribeStacksResult', 'Stacks', 'member') do |options|
      request(
        :method => :post,
        :path => '/',
        :form => options.merge(d_params)
      )
    end
  else
    lists = all_result_pages(nil, :body, 'ListStacksResponse', 'ListStacksResult', 'StackSummaries', 'member') do |options|
      request(
        :method => :post,
        :path => '/',
        :form => options.merge(l_params)
      )
    end
    descriptions = []
  end
  (lists || descriptions).map do |stk|
    if(lists)
      desc = descriptions.detect do |d_stk|
        d_stk['StackId'] == stk['StackId']
      end || Smash.new
      stk.merge!(desc)
    end
    if(stack)
      next if stack.id != stk['StackId'] && stk['StackId'].split('/')[1] != stack.id
    end
    state = stk['StackStatus'].downcase.to_sym
    unless(Miasma::Models::Orchestration::VALID_RESOURCE_STATES.include?(state))
      parts = state.to_s.split('_')
      state = [parts.first, *parts.slice(-2, parts.size)].join('_').to_sym
      unless(Miasma::Models::Orchestration::VALID_RESOURCE_STATES.include?(parts))
        state = :unknown
      end
    end
    new_stack = stack || Stack.new(self)
    new_stack.load_data(
      :id => stk['StackId'],
      :name => stk['StackName'],
      :capabilities => [stk.get('Capabilities', 'member')].flatten(1).compact,
      :description => stk['Description'],
      :created => stk['CreationTime'],
      :updated => stk['LastUpdatedTime'],
      :notification_topics => [stk.get('NotificationARNs', 'member')].flatten(1).compact,
      :timeout_in_minutes => stk['TimeoutInMinutes'] ? stk['TimeoutInMinutes'].to_i : nil,
      :status => stk['StackStatus'],
      :status_reason => stk['StackStatusReason'],
      :state => state,
      :template_description => stk['TemplateDescription'],
      :disable_rollback => !!stk['DisableRollback'],
      :outputs => [stk.get('Outputs', 'member')].flatten(1).compact.map{|o|
        Smash.new(
          :key => o['OutputKey'],
          :value => o['OutputValue'],
          :description => o['Description']
        )
      },
      :tags => Smash[
        [stk.fetch('Tags', 'member', [])].flatten(1).map{|param|
          [param['Key'], param['Value']]
        }
      ],
      :parameters => Smash[
        [stk.fetch('Parameters', 'member', [])].flatten(1).map{|param|
          [param['ParameterKey'], param['ParameterValue']]
        }
      ],
      :custom => Smash.new(
        :stack_policy => stk['StackPolicyBody'],
        :stack_policy_url => stk['StackPolicyURL']
      )
    ).valid_state
  end
end

#resource_all(stack) ⇒ Array<Models::Orchestration::Stack::Resource>

Return all resources for stack

Parameters:

  • stack (Models::Orchestration::Stack)

Returns:

  • (Array<Models::Orchestration::Stack::Resource>)


310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
# File 'lib/miasma/contrib/aws/orchestration.rb', line 310

def resource_all(stack)
  results = all_result_pages(nil, :body, 'ListStackResourcesResponse', 'ListStackResourcesResult', 'StackResourceSummaries', 'member') do |options|
    request(
      :method => :post,
      :path => '/',
      :form => options.merge(
        Smash.new(
          'Action' => 'ListStackResources',
          'StackName' => stack.id
        )
      )
    )
  end.map do |res|
    Stack::Resource.new(
      stack,
      :id => res['PhysicalResourceId'],
      :name => res['LogicalResourceId'],
      :logical_id => res['LogicalResourceId'],
      :type => res['ResourceType'],
      :state => res['ResourceStatus'].downcase.to_sym,
      :status => res['ResourceStatus'],
      :updated => res['LastUpdatedTimestamp']
    ).valid_state
  end
end

#resource_reload(resource) ⇒ Models::Orchestration::Resource

Reload the stack resource data from the API

Parameters:

  • resource (Models::Orchestration::Stack::Resource)

Returns:

  • (Models::Orchestration::Resource)


340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
# File 'lib/miasma/contrib/aws/orchestration.rb', line 340

def resource_reload(resource)
  result = request(
    :method => :post,
    :path => '/',
    :form => Smash.new(
      'LogicalResourceId' => resource.logical_id,
      'StackName' => resource.stack.name
    )
  ).get(:body, 'DescribeStackResourceResponse', 'DescribeStackResourceResult', 'StackResourceDetail')
  resource.updated = result['LastUpdatedTimestamp']
  resource.type = result['ResourceType']
  resource.state = result['ResourceStatus'].downcase.to_sym
  resource.status = result['ResourceStatus']
  resource.status_reason = result['ResourceStatusReason']
  resource.valid_state
  resource
end

#stack_allArray<Models::Orchestration::Stack>

TODO:

check if we need any mappings on state set

Return all stacks

Parameters:

  • options (Hash)

    filter

Returns:

  • (Array<Models::Orchestration::Stack>)


302
303
304
# File 'lib/miasma/contrib/aws/orchestration.rb', line 302

def stack_all
  load_stack_data
end

#stack_destroy(stack) ⇒ TrueClass, FalseClass

Delete the stack

Parameters:

  • stack (Models::Orchestration::Stack)

Returns:

  • (TrueClass, FalseClass)


226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
# File 'lib/miasma/contrib/aws/orchestration.rb', line 226

def stack_destroy(stack)
  if(stack.persisted?)
    request(
      :method => :post,
      :path => '/',
      :form => Smash.new(
        'Action' => 'DeleteStack',
        'StackName' => stack.id
      )
    )
    true
  else
    false
  end
end

#stack_get(ident) ⇒ Stack

Return single stack

Parameters:

  • ident (String)

    name or ID

Returns:



290
291
292
293
294
295
# File 'lib/miasma/contrib/aws/orchestration.rb', line 290

def stack_get(ident)
  i = Stack.new(self)
  i.id = ident
  i.reload
  i.name ? i : nil
end

#stack_reload(stack) ⇒ Models::Orchestration::Stack

Reload the stack data from the API

Parameters:

  • stack (Models::Orchestration::Stack)

Returns:

  • (Models::Orchestration::Stack)


206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
# File 'lib/miasma/contrib/aws/orchestration.rb', line 206

def stack_reload(stack)
  if(stack.persisted?)
    ustack = Stack.new(self)
    ustack.id = stack.id
    load_stack_data(ustack)
    if(ustack.data[:name])
      stack.load_data(ustack.attributes).valid_state
    else
      stack.status = 'DELETE_COMPLETE'
      stack.state = :delete_complete
      stack.valid_state
    end
  end
  stack
end

#stack_save(stack) ⇒ Models::Orchestration::Stack

Save the stack

Parameters:

  • stack (Models::Orchestration::Stack)

Returns:

  • (Models::Orchestration::Stack)


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
# File 'lib/miasma/contrib/aws/orchestration.rb', line 144

def stack_save(stack)
  params = Smash.new('StackName' => stack.name)
  (stack.parameters || {}).each_with_index do |pair, idx|
    params["Parameters.member.#{idx + 1}.ParameterKey"] = pair.first
    params["Parameters.member.#{idx + 1}.ParameterValue"] = pair.last
  end
  (stack.capabilities || []).each_with_index do |cap, idx|
    params["Capabilities.member.#{idx + 1}"] = cap
  end
  (stack.notification_topics || []).each_with_index do |topic, idx|
    params["NotificationARNs.member.#{idx + 1}"] = topic
  end
  (stack.tags || {}).each_with_index do |tag, idx|
    params["Tags.member.#{idx + 1}.Key"] = tag.first
    params["Tags.member.#{idx + 1}.Value"] = tag.last
  end
  if(stack.custom[:stack_policy_body])
    params['StackPolicyBody'] = MultiJson.dump(stack.custom[:stack_policy_body])
  end
  if(stack.custom[:stack_policy_url])
    params['StackPolicyURL'] = stack.custom[:stack_policy_url]
  end
  unless(stack.disable_rollback.nil?)
    params['OnFailure'] = stack.disable_rollback ? 'DO_NOTHING' : 'ROLLBACK'
  end
  if(stack.on_failure)
    params['OnFailure'] = stack.on_failure == 'nothing' ? 'DO_NOTHING' : stack.on_failure.upcase
  end
  if(!stack.dirty?(:template) && stack.persisted?)
    params['UsePreviousTemplate'] = true
  else
    params['TemplateBody'] = MultiJson.dump(stack.template)
  end
  if(stack.persisted?)
    result = request(
      :path => '/',
      :method => :post,
      :form => Smash.new(
        'Action' => 'UpdateStack'
      ).merge(params)
    )
    stack
  else
    if(stack.timeout_in_minutes)
      params['TimeoutInMinutes'] = stack.timeout_in_minutes
    end
    result = request(
      :path => '/',
      :method => :post,
      :form => Smash.new(
        'Action' => 'CreateStack'
      ).merge(params)
    )
    stack.id = result.get(:body, 'CreateStackResponse', 'CreateStackResult', 'StackId')
    stack.valid_state
  end
end

#stack_template_load(stack) ⇒ Smash

Fetch stack template

Parameters:

Returns:

  • (Smash)

    stack template



246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
# File 'lib/miasma/contrib/aws/orchestration.rb', line 246

def stack_template_load(stack)
  if(stack.persisted?)
    result = request(
      :method => :post,
      :path => '/',
      :form => Smash.new(
        'Action' => 'GetTemplate',
        'StackName' => stack.id
      )
    )
    MultiJson.load(
      result.get(:body, 'GetTemplateResponse', 'GetTemplateResult', 'TemplateBody')
    ).to_smash
  else
    Smash.new
  end
end

#stack_template_validate(stack) ⇒ NilClass, String

Validate stack template

Parameters:

Returns:

  • (NilClass, String)

    nil if valid, string error message if invalid



268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
# File 'lib/miasma/contrib/aws/orchestration.rb', line 268

def stack_template_validate(stack)
  begin
    result = request(
      :method => :post,
      :path => '/',
      :form => Smash.new(
        'Action' => 'ValidateTemplate',
        'TemplateBody' => MultiJson.dump(stack.template)
      )
    )
    nil
  rescue Error::ApiError::RequestError => e
    MultiXml.parse(e.response.body.to_s).to_smash.get(
      'ErrorResponse', 'Error', 'Message'
    )
  end
end