Class: CloudFormation

Inherits:
Object
  • Object
show all
Defined in:
lib/zergrush_cf/init.rb

Instance Method Summary collapse

Instance Method Details

#clean(hive_location, task_name, task_hash, debug) ⇒ Object



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
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
# File 'lib/zergrush_cf/init.rb', line 168

def clean hive_location, task_name, task_hash, debug
    
    aws_key_id = task_hash["vm"]["driver"]["driveroptions"][0]["access_key_id"] 
    aws_secret = task_hash["vm"]["driver"]["driveroptions"][0]["secret_access_key"]

    # eval possible environment variables
    if aws_key_id =~ /^ENV\['.+'\]$/
        aws_key_id = eval(aws_key_id)
    end

    if aws_secret =~ /^ENV\['.+'\]$/
        aws_secret = eval(aws_secret)
    end 

    abort("AWS key id is not specified in task") unless aws_key_id != nil
    abort("AWS secret is not specified in task") unless aws_secret != nil

    rabbit_objects = initRabbitConnection(task_hash["vm"]["driver"]["driveroptions"][0]["rabbit"])

    puts("Cleaning task #{task_name} ...")

    # run fog cleanup on the stack.
    stack_name = "#{task_name}"

    Excon.defaults[:connect_timeout] = 600
    Excon.defaults[:read_timeout] = 600
    Excon.defaults[:write_timeout] = 600
    
    cf = Fog::AWS::CloudFormation.new(
        :aws_access_key_id => aws_key_id,
        :aws_secret_access_key => aws_secret,
        :connection_options => {
            :connect_timeout => 700,
            :read_timeout => 700
        }
    )

    stack_info = cf.delete_stack(stack_name)
    puts("Deleting stack #{stack_name}")

     # get the event collection and initial info
    outputs_info = nil
    while outputs_info == nil do
        sleep 3
        with_retries(:max_tries => 10, :base_sleep_seconds => 3, :max_sleep_seconds => 20) {
            outputs_info = cf.describe_stacks({ 'StackName' => stack_name }) 
            begin
                outputs_info = cf.describe_stacks({ 'StackName' => stack_name })
            rescue Fog::AWS::CloudFormation::NotFound
                rabbit_objects[:connection].close unless rabbit_objects == nil
                return 0
            end
        }
    end

    events = nil
    with_retries(:max_tries => 10, :base_sleep_seconds => 3, :max_sleep_seconds => 20) {
        events = cf.describe_stack_events(stack_name).body['StackEvents']
    }
    while events == nil do
        sleep 3
        with_retries(:max_tries => 10, :base_sleep_seconds => 3, :max_sleep_seconds => 20) {
            begin
                events = cf.describe_stack_events(stack_name).body['StackEvents']
            rescue Fog::AWS::CloudFormation::NotFound
                rabbit_objects[:connection].close unless rabbit_objects == nil
                return 0
            end
        }
    end

    event_counter = 0
    while outputs_info.body["Stacks"][0]["StackStatus"] == "DELETE_IN_PROGRESS" do
        logEvents(events.first(events.length - event_counter))
        logRabbitEvents(events.first(events.length - event_counter), rabbit_objects, eval_params(task_hash["vm"]["driver"]["driveroptions"][0]["rabbit"])) 

        event_counter = events.length
        with_retries(:max_tries => 10, :base_sleep_seconds => 3, :max_sleep_seconds => 20) {
            begin
                events = cf.describe_stack_events(stack_name).body['StackEvents']
                outputs_info = cf.describe_stacks({ 'StackName' => stack_name })
            rescue Fog::AWS::CloudFormation::NotFound
                logEvents(events.first(events.length - event_counter))
                logRabbitEvents(events.first(events.length - event_counter), rabbit_objects, eval_params(task_hash["vm"]["driver"]["driveroptions"][0]["rabbit"])) 
                rabbit_objects[:connection].close unless rabbit_objects == nil
                return 0
            end
        }
    end

    # log remaining events for error case
    logEvents(events.first(events.length - event_counter))
    logRabbitEvents(events.first(events.length - event_counter), rabbit_objects, eval_params(task_hash["vm"]["driver"]["driveroptions"][0]["rabbit"])) 

    rabbit_objects[:connection].close unless rabbit_objects == nil
    abort("ERROR: Failed with stack status: #{outputs_info.body["Stacks"][0]["StackStatus"]}")

    rescue Fog::Errors::Error => fog_cf_error
        rabbit_objects[:connection].close unless rabbit_objects == nil
        abort ("ERROR: AWS error: #{fog_cf_error.ai}")
end

#eval_params(params) ⇒ Object



340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
# File 'lib/zergrush_cf/init.rb', line 340

def eval_params(params)
    params.each do |k, v|
        # If v is nil, an array is being iterated and the value is k. 
        # If v is not nil, a hash is being iterated and the value is v.
        # 
        value = v || k

        if value.is_a?(Hash) || value.is_a?(Array)
            eval_params(value)
        else
            if value.is_a?(String)
                if value =~ /(^ENV\['.+'\]$)/
                    if v.nil?
                        k.replace eval(value)
                    else
                        params[k] = eval(value)
                    end
                end
            end
        end
    end

    return params
end

#folder_schemaObject



328
329
330
# File 'lib/zergrush_cf/init.rb', line 328

def folder_schema
    return nil
end

#halt(hive_location, task_name, task_hash, debug) ⇒ Object



315
316
317
318
# File 'lib/zergrush_cf/init.rb', line 315

def halt hive_location, task_name, task_hash, debug
    puts("Halt is not implemented for CloudFormation.")
    return
end

#initRabbitConnection(rabbitInfo) ⇒ Object



281
282
283
284
285
286
287
288
289
290
291
292
# File 'lib/zergrush_cf/init.rb', line 281

def initRabbitConnection rabbitInfo
    return nil unless rabbitInfo != nil
    params = eval_params(rabbitInfo)
    conn = Bunny.new(Hash[params["bunny_params"].map{ |k, v| [k.to_sym, v] }])
    conn.start

    channel = conn.create_channel
    exch = (params["exchange"] == nil) ? channel.default_exchange : channel.direct(params["exchange"]["name"], Hash[params["exchange"]["params"].map{ |k, v| [k.to_sym, v] }])
    channel.queue(params["queue"]["name"], Hash[params["queue"]["params"].map{ |k, v| [k.to_sym, v] }]).bind(exch)

    return  { :connection => conn, :channel => channel, :exchange => exch }
end

#logEvents(events) ⇒ Object



270
271
272
273
274
275
276
277
278
279
# File 'lib/zergrush_cf/init.rb', line 270

def logEvents events
    events.each do |event|
        puts "Timestamp: #{Time.parse(event['Timestamp'].to_s).iso8601}"
        puts "LogicalResourceId: #{event['LogicalResourceId']}"
        puts "ResourceType: #{event['ResourceType']}"
        puts "ResourceStatus: #{event['ResourceStatus']}"
        puts "ResourceStatusReason: #{event['ResourceStatusReason']}" if event['ResourceStatusReason']
        puts "--"
    end
end

#logRabbitEvents(events, rabbit_objects, rabbit_properties) ⇒ Object



294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
# File 'lib/zergrush_cf/init.rb', line 294

def logRabbitEvents events, rabbit_objects, rabbit_properties
    timestamp = (rabbit_properties["event_timestamp_name"] == nil) ? "timestamp" : rabbit_properties["event_timestamp_name"]
    res_id_name = (rabbit_properties["event_resource_id_name"] == nil) ? "resource_id" : rabbit_properties["event_resource_id_name"]
    res_type_name = (rabbit_properties["event_resource_type_name"] == nil) ? "resource_type" : rabbit_properties["event_resource_type_name"]
    res_status = (rabbit_properties["event_resource_status_name"] == nil) ? "resource_status" : rabbit_properties["event_resource_status_name"]
    reason = (rabbit_properties["event_resource_reason_name"] == nil) ? "reason" : rabbit_properties["event_resource_reason_name"]


    events.each do |event|
        event_info = {
            timestamp.to_sym => "#{Time.parse(event['Timestamp'].to_s).iso8601}",
            res_id_name.to_sym => "#{event['LogicalResourceId']}",
            res_type_name.to_sym => "#{event['ResourceType']}",
            res_status.to_sym => "#{event['ResourceStatus']}",
            reason.to_sym => "#{event['ResourceStatusReason']}"
        }
        
        rabbit_objects[:exchange].publish(event_info.to_json, :routing_key => rabbit_properties["queue"]["name"])
    end
end

#option_schemaObject



324
325
326
# File 'lib/zergrush_cf/init.rb', line 324

def option_schema
    return File.open(File.join("#{File.dirname(__FILE__)}", "..", "..", "resources", "option_schema.template"), 'r').read
end

#port_schemaObject



332
333
334
# File 'lib/zergrush_cf/init.rb', line 332

def port_schema
    return nil
end

#rush(hive_location, task_name, task_hash, debug) ⇒ Object



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
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
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
# File 'lib/zergrush_cf/init.rb', line 36

def rush hive_location, task_name, task_hash, debug
    aws_key_id = task_hash["vm"]["driver"]["driveroptions"][0]["access_key_id"] 
    aws_secret = task_hash["vm"]["driver"]["driveroptions"][0]["secret_access_key"] 

    # eval possible environment variables
    if aws_key_id =~ /^ENV\['.+'\]$/
        aws_key_id = eval(aws_key_id)
    end

    if aws_secret =~ /^ENV\['.+'\]$/
        aws_secret = eval(aws_secret)
    end

    abort("AWS key id is not specified in task") unless aws_key_id != nil
    abort("AWS secret is not specified in task") unless aws_secret != nil

    rabbit_objects = initRabbitConnection(task_hash["vm"]["driver"]["driveroptions"][0]["rabbit"])

    renderer = ZergrushCF::Renderer.new(
        hive_location, 
        task_name, 
        task_hash)        
    template_body = renderer.render

    # see if we need to upload anything to s3?
    if task_hash["vm"]["driver"]["driveroptions"][0]["storage"] != nil
        if task_hash["vm"]["driver"]["driveroptions"][0]["storage"]["s3_bucket"] != nil 
            bucket_name = task_hash["vm"]["driver"]["driveroptions"][0]["storage"]["s3_bucket"]["name"]
            is_public = task_hash["vm"]["driver"]["driveroptions"][0]["storage"]["s3_bucket"]["public"]
            files = task_hash["vm"]["driver"]["driveroptions"][0]["storage"]["s3_bucket"]["files"]

            # create a connection
            connection = Fog::Storage.new({
                :provider => 'AWS',
                :aws_access_key_id => aws_key_id,
                :aws_secret_access_key => aws_secret
            })

            directory = connection.directories.create(
                :key => bucket_name,
                :public => is_public
            )

            files.each { |file|
                directory.files.create(
                    :key    => file,
                    :body   => File.open(File.join(hive_location, task_name, file)),
                    :public => is_public
                )
            }
        end
    end

    Excon.defaults[:connect_timeout] = 600
    Excon.defaults[:read_timeout] = 600
    Excon.defaults[:write_timeout] = 600

    cf = Fog::AWS::CloudFormation.new(
        :aws_access_key_id => aws_key_id,
        :aws_secret_access_key => aws_secret,
        :connection_options => {
            :connect_timeout => 700,
            :read_timeout => 700
        }
    )

    # create the cloudformation stack
    stack_name = "#{task_name}"

    params = eval_params(task_hash["vm"]["driver"]["driveroptions"][0]["template_parameters"])       
    stack_info = cf.create_stack(stack_name, { 'DisableRollback' => true, 'TemplateBody' => template_body.to_json, 'Parameters' => params, 'Capabilities' => [ "CAPABILITY_IAM" ] })

    # grab the id of the stack
    stack_id = stack_info.body["StackId"]
    puts("Creating stack #{stack_name} with id #{stack_id}")


    # get the event collection and initial info
    outputs_info = nil
    with_retries(:max_tries => 10, :base_sleep_seconds => 3, :max_sleep_seconds => 20) {
        outputs_info = cf.describe_stacks({ 'StackName' => stack_name })
    }
    while outputs_info == nil do
        sleep 3
        with_retries(:max_tries => 10, :base_sleep_seconds => 3, :max_sleep_seconds => 20) { 
            outputs_info = cf.describe_stacks({ 'StackName' => stack_name })
        }
    end

    events = nil
    with_retries(:max_tries => 10, :base_sleep_seconds => 3, :max_sleep_seconds => 20) {
        events = cf.describe_stack_events(stack_name).body['StackEvents']
    }
    while events == nil do
        sleep 3
        with_retries(:max_tries => 10, :base_sleep_seconds => 3, :max_sleep_seconds => 20) {
            events = cf.describe_stack_events(stack_name).body['StackEvents']
        }
    end

    event_counter = 0
    while outputs_info.body["Stacks"][0]["StackStatus"] == "CREATE_IN_PROGRESS" do
        logEvents(events.first(events.length - event_counter))
        logRabbitEvents(events.first(events.length - event_counter), rabbit_objects, eval_params(task_hash["vm"]["driver"]["driveroptions"][0]["rabbit"])) 
        event_counter = events.length

        with_retries(:max_tries => 10, :base_sleep_seconds => 3, :max_sleep_seconds => 20) {
            events = cf.describe_stack_events(stack_name).body['StackEvents']
            outputs_info = cf.describe_stacks({ 'StackName' => stack_name })
        }
        if outputs_info.body["Stacks"][0]["StackStatus"] == "CREATE_COMPLETE"
            logEvents(events.first(events.length - event_counter))
            logRabbitEvents(events.first(events.length - event_counter), rabbit_objects, eval_params(task_hash["vm"]["driver"]["driveroptions"][0]["rabbit"])) 
            puts("Stack outputs:")
            ap outputs_info.body["Stacks"][0]["Outputs"]
            rabbit_objects[:connection].close unless rabbit_objects == nil
            return 0
        end
    end

    # log the remaining events for failure case
    logEvents(events.first(events.length - event_counter))
    logRabbitEvents(events.first(events.length - event_counter), rabbit_objects, eval_params(task_hash["vm"]["driver"]["driveroptions"][0]["rabbit"]))

    rabbit_objects[:connection].close unless rabbit_objects == nil
    abort("ERROR: Failed with stack status: #{outputs_info.body["Stacks"][0]["StackStatus"]}")
    
    rescue Fog::Errors::Error => fog_cf_error
        rabbit_objects[:connection].close unless rabbit_objects == nil
        abort ("ERROR: AWS error: #{fog_cf_error.message}")
end

#ssh_schemaObject



336
337
338
# File 'lib/zergrush_cf/init.rb', line 336

def ssh_schema
    return nil
end

#task_schemaObject



320
321
322
# File 'lib/zergrush_cf/init.rb', line 320

def task_schema
    return nil
end