Class: Simplerubysteps::Tool

Inherits:
Object
  • Object
show all
Defined in:
lib/simplerubysteps/tool.rb

Instance Method Summary collapse

Constructor Details

#initializeTool

Returns a new instance of Tool.



17
18
19
20
21
22
# File 'lib/simplerubysteps/tool.rb', line 17

def initialize
  @cloudformation_client = Aws::CloudFormation::Client.new
  @s3_client = Aws::S3::Client.new
  @states_client = Aws::States::Client.new
  @logs_client = Aws::CloudWatchLogs::Client.new
end

Instance Method Details

#cloudformation_template(lambda_cf_config, deploy_state_machine) ⇒ Object



241
242
243
244
245
246
247
248
249
250
251
# File 'lib/simplerubysteps/tool.rb', line 241

def cloudformation_template(lambda_cf_config, deploy_state_machine)
  data = {
    state_machine: deploy_state_machine,
  }

  if lambda_cf_config
    data[:functions] = lambda_cf_config # see StateMachine.cloudformation_config()
  end

  Simplerubysteps::cloudformation_yaml(data)
end

#create_zip(zip_file, files_by_name) ⇒ Object



195
196
197
198
199
200
201
202
# File 'lib/simplerubysteps/tool.rb', line 195

def create_zip(zip_file, files_by_name)
  Zip::File.open(zip_file, create: true) do |zipfile|
    base_dir = File.expand_path(File.dirname(__FILE__))
    files_by_name.each do |n, f|
      zipfile.add n, f
    end
  end
end

#deploy(version) ⇒ Object



302
303
304
305
306
307
308
309
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
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
# File 'lib/simplerubysteps/tool.rb', line 302

def deploy(version)
  stack = versioned_stack_name_from_current_dir(version)

  puts "Stack: #{stack}"

  current_stack_outputs = stack_outputs(stack)

  unless current_stack_outputs
    current_stack_outputs = stack_create(stack, cloudformation_template(nil, false), {})

    puts "Deployment bucket created"
  end

  deploy_bucket = current_stack_outputs["DeployBucket"]

  puts "Deployment bucket: #{deploy_bucket}"

  function_zip_temp = Tempfile.new("function")
  create_zip function_zip_temp.path, my_lib_files.merge(workflow_files)
  lambda_sha = Digest::SHA1.file function_zip_temp.path
  lambda_zip_name = "function-#{lambda_sha}.zip"
  upload_file_to_s3 deploy_bucket, lambda_zip_name, function_zip_temp.path

  puts "Uploaded: #{lambda_zip_name}"

  lambda_cf_config = JSON.parse(`ruby -e 'require "./workflow.rb";puts $sm.cloudformation_config.to_json'`)

  if current_stack_outputs["LambdaCount"].nil? or current_stack_outputs["LambdaCount"].to_i != lambda_cf_config.length # FIXME Do not implicitly delete the state machine when versioning is turned off.
    current_stack_outputs = stack_update(stack, cloudformation_template(lambda_cf_config, false), {
      "LambdaS3" => lambda_zip_name,
    })

    puts "Lambda function created"
  end

  lambda_arns = []
  (0..current_stack_outputs["LambdaCount"].to_i - 1).each do |i|
    lambda_arn = current_stack_outputs["LambdaFunctionARN#{i}"]

    puts "Lambda function: #{lambda_arn}"

    lambda_arns.push lambda_arn
  end

  workflow_type = `ruby -e 'require "./workflow.rb";puts $sm.kind'`.strip

  state_machine_json = JSON.parse(`LAMBDA_FUNCTION_ARNS=#{lambda_arns.join(",")} ruby -e 'require "./workflow.rb";puts $sm.render.to_json'`).to_json
  state_machine_json_sha = Digest::SHA1.hexdigest state_machine_json
  state_machine_json_name = "statemachine-#{state_machine_json_sha}.json"
  upload_to_s3 deploy_bucket, state_machine_json_name, state_machine_json

  puts "Uploaded: #{state_machine_json_name}"

  current_stack_outputs = stack_update(stack, cloudformation_template(lambda_cf_config, true), { # FIXME when versioning is turned off: 1) create additional lambdas 2) update State Machine
    "LambdaS3" => lambda_zip_name,
    "StepFunctionsS3" => state_machine_json_name,
    "StateMachineType" => workflow_type,
  })

  if current_stack_outputs[:no_update]
    puts "Stack not updated"
  else
    puts "Stack updated"
  end

  puts "State machine: #{current_stack_outputs["StepFunctionsStateMachineARN"]}"
end

#describe_execution(execution_arn) ⇒ Object



384
385
386
387
388
# File 'lib/simplerubysteps/tool.rb', line 384

def describe_execution(execution_arn)
  @states_client.describe_execution(
    execution_arn: execution_arn,
  )
end

#destroy(optional_version) ⇒ Object



292
293
294
295
296
297
298
299
300
# File 'lib/simplerubysteps/tool.rb', line 292

def destroy(optional_version)
  if optional_version
    destroy_stack versioned_stack_name_from_current_dir(optional_version)
  else
    list_stacks_with_prefix(unversioned_stack_name_from_current_dir).each do |stack|
      destroy_stack stack
    end
  end
end

#destroy_stack(stack) ⇒ Object



275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
# File 'lib/simplerubysteps/tool.rb', line 275

def destroy_stack(stack)
  current_stack_outputs = stack_outputs(stack)
  raise "No CloudFormation stack to destroy" unless current_stack_outputs

  deploy_bucket = current_stack_outputs["DeployBucket"]
  raise "No CloudFormation stack to destroy" unless deploy_bucket

  empty_s3_bucket deploy_bucket

  puts "Bucket emptied: #{deploy_bucket}"

  @cloudformation_client.delete_stack(stack_name: stack)
  @cloudformation_client.wait_until(:stack_delete_complete, stack_name: stack)

  puts "Stack deleted: #{stack}"
end

#dir_files(base_dir, glob) ⇒ Object



204
205
206
207
208
209
210
211
# File 'lib/simplerubysteps/tool.rb', line 204

def dir_files(base_dir, glob)
  files_by_name = {}
  base_dir = File.expand_path(base_dir)
  Dir.glob("#{base_dir}/#{glob}").select { |path| File.file?(path) }.each do |f|
    files_by_name[File.expand_path(f)[base_dir.length + 1..-1]] = f
  end
  files_by_name
end

#empty_s3_bucket(bucket_name) ⇒ Object



189
190
191
192
193
# File 'lib/simplerubysteps/tool.rb', line 189

def empty_s3_bucket(bucket_name)
  @s3_client.list_objects_v2(bucket: bucket_name).contents.each do |object|
    @s3_client.delete_object(bucket: bucket_name, key: object.key)
  end
end

#list_stacks_with_prefix(prefix) ⇒ Object



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
# File 'lib/simplerubysteps/tool.rb', line 123

def list_stacks_with_prefix(prefix)
  stack_list = []
  next_token = nil
  loop do
    response = @cloudformation_client.list_stacks({
      next_token: next_token,
      stack_status_filter: %w[
        CREATE_COMPLETE
        UPDATE_COMPLETE
        ROLLBACK_COMPLETE
      ],
    })

    response.stack_summaries.each do |stack|
      if stack.stack_name =~ /^#{prefix}$|^#{prefix}-(.+)/
        stack_list << stack.stack_name
      end
    end

    next_token = response.next_token
    break if next_token.nil?
  end

  stack_list
end

#log(extract_pattern, version) ⇒ Object



253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
# File 'lib/simplerubysteps/tool.rb', line 253

def log(extract_pattern, version)
  stack = nil
  if version
    stack = versioned_stack_name_from_current_dir(version)
  else
    stack = most_recent_stack_with_prefix unversioned_stack_name_from_current_dir
  end
  raise "State Machine is not deployed" unless stack

  current_stack_outputs = stack_outputs(stack)
  raise "State Machine is not deployed" unless current_stack_outputs

  last_thread = nil
  (0..current_stack_outputs["LambdaCount"].to_i - 1).each do |i|
    function_name = current_stack_outputs["LambdaFunctionName#{i}"]
    last_thread = Thread.new do # FIXME Less brute force approach (?)
      tail_follow_logs "/aws/lambda/#{function_name}", extract_pattern
    end
  end
  last_thread.join if last_thread
end

#most_recent_stack_with_prefix(prefix) ⇒ Object



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
# File 'lib/simplerubysteps/tool.rb', line 149

def most_recent_stack_with_prefix(prefix)
  stack_list = {}
  next_token = nil
  loop do
    response = @cloudformation_client.list_stacks({
      next_token: next_token,
      stack_status_filter: %w[
        CREATE_COMPLETE
        UPDATE_COMPLETE
        ROLLBACK_COMPLETE
      ],
    })

    response.stack_summaries.each do |stack|
      if stack.stack_name =~ /^#{prefix}$|^#{prefix}-(.+)/
        stack_list[stack.creation_time] = stack.stack_name
      end
    end

    next_token = response.next_token
    break if next_token.nil?
  end

  stack_list.empty? ? nil : stack_list[stack_list.keys.sort.last]
end

#my_lib_filesObject



237
238
239
# File 'lib/simplerubysteps/tool.rb', line 237

def my_lib_files
  files = dir_files(File.dirname(__FILE__) + "/..", "**/*.rb").filter { |f| not(f =~ /cloudformation\.rb|tool\.rb/) }
end

#runObject



468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
# File 'lib/simplerubysteps/tool.rb', line 468

def run
  options = {
    :wait => false,
    :input => $stdin,
    :version => "latest",
    :destroy_all => true,
  }

  subcommands = {
    "deploy" => OptionParser.new do |opts|
      opts.banner = "Usage: #{$0} deploy [options]"

      opts.on("--version VALUE", "fix version (\"latest\" per default)") do |value|
        options[:version] = value
      end

      opts.on("--versioned", "enable auto versioning (\"latest\" per default)") do |value|
        options[:version] = nil
      end

      opts.on("-h", "--help", "Display this help message") do
        puts opts
        exit
      end
    end,
    "destroy" => OptionParser.new do |opts|
      opts.banner = "Usage: #{$0} destroy [options]"

      opts.on("--version VALUE", "fix version (all versions per default)") do |value|
        options[:version] = value
        options[:destroy_all] = nil
      end

      opts.on("-h", "--help", "Display this help message") do
        puts opts
        exit
      end
    end,
    "log" => OptionParser.new do |opts|
      opts.banner = "Usage: #{$0} log [options]"

      opts.on("--extract_pattern VALUE", "Wait for and extract pattern") do |value|
        options[:extract_pattern] = value
      end

      opts.on("--version VALUE", "fix version (\"latest\" per default)") do |value|
        options[:version] = value
      end

      opts.on("--most-recent-version", "Use the version of the last stack created") do |value|
        options[:version] = nil
      end

      opts.on("-h", "--help", "Display this help message") do
        puts opts
        exit
      end
    end,
    "start" => OptionParser.new do |opts|
      opts.banner = "Usage: #{$0} start [options]"

      opts.on("--wait", "Wait for STANDARD state machine to complete") do
        options[:wait] = true
      end

      opts.on("--input VALUE", "/path/to/file (STDIN will be used per default)") do |value|
        options[:input] = File.new(value)
      end

      opts.on("--version VALUE", "fix version (\"latest\" per default)") do |value|
        options[:version] = value
      end

      opts.on("--most-recent-version", "Use the version of the last stack created") do |value|
        options[:version] = nil
      end

      opts.on("-h", "--help", "Display this help message") do
        puts opts
        exit
      end
    end,
    "task-success" => OptionParser.new do |opts|
      opts.banner = "Usage: #{$0} task-success [options]"

      opts.on("--input VALUE", "/path/to/file (STDIN will be used per default)") do |value|
        options[:input] = File.new(value)
      end

      opts.on("--token VALUE", "The task token") do |value|
        options[:token] = value
      end

      opts.on("-h", "--help", "Display this help message") do
        puts opts
        exit
      end
    end,
    "stack" => OptionParser.new do |opts|
      opts.banner = "Usage: #{$0} stack [options]"

      opts.on("--output VALUE", "Stack output") do |value|
        options[:output] = value
      end

      opts.on("--version VALUE", "fix version (\"latest\" per default)") do |value|
        options[:version] = value
      end

      opts.on("-h", "--help", "Display this help message") do
        puts opts
        exit
      end
    end,
  }

  global = OptionParser.new do |opts|
    opts.banner = "Usage: #{$0} [command] [options]"
    opts.separator ""
    opts.separator "Commands (#{Simplerubysteps::VERSION}):"
    opts.separator "    deploy        Create Step Functions State Machine"
    opts.separator "    destroy       Delete Step Functions State Machine"
    opts.separator "    log           Continuously prints Lambda function log output"
    opts.separator "    start         Start State Machine execution"
    opts.separator "    stack         Display stack infos"
    opts.separator "    task-success  Continue Start State Machine execution"
    opts.separator ""

    opts.on_tail("-h", "--help", "Display this help message") do
      puts opts
      exit
    end
  end

  begin
    global.order!(ARGV)
    command = ARGV.shift
    options[:command] = command
    subcommands.fetch(command).parse!(ARGV)
  rescue KeyError
    puts "Unknown command: '#{command}'"
    puts
    puts global
    exit 1
  rescue OptionParser::ParseError => error
    puts error.message
    puts subcommands.fetch(command)
    exit 1
  end

  if options[:command] == "deploy"
    deploy options[:version]
  elsif options[:command] == "start"
    start options[:wait], options[:input], options[:version]
  elsif options[:command] == "log"
    log options[:extract_pattern], options[:version]
  elsif options[:command] == "task-success"
    send_task_success options[:token], options[:input]
  elsif options[:command] == "stack"
    stack_output options[:version], options[:output]
  elsif options[:command] == "destroy"
    if options[:destroy_all]
      destroy(nil)
    else
      destroy(options[:version])
    end
  end
end

#send_task_success(task_token, output = $stdin) ⇒ Object



457
458
459
460
461
462
463
464
465
466
# File 'lib/simplerubysteps/tool.rb', line 457

def send_task_success(task_token, output = $stdin)
  raise "No token" unless task_token

  output_json = JSON.parse(output.read).to_json

  puts @states_client.send_task_success(
    task_token: task_token,
    output: output_json,
  ).to_json
end

#stack_create(stack_name, template, parameters) ⇒ Object



106
107
108
109
110
# File 'lib/simplerubysteps/tool.rb', line 106

def stack_create(stack_name, template, parameters)
  @cloudformation_client.create_stack(stack_params(stack_name, template, parameters))
  @cloudformation_client.wait_until(:stack_create_complete, stack_name: stack_name)
  stack_outputs(stack_name)
end

#stack_output(version, optional_output) ⇒ Object



405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
# File 'lib/simplerubysteps/tool.rb', line 405

def stack_output(version, optional_output)
  stack = nil
  if version
    stack = versioned_stack_name_from_current_dir(version)
  else
    stack = most_recent_stack_with_prefix unversioned_stack_name_from_current_dir
  end
  raise "State Machine is not deployed" unless stack

  current_stack_outputs = stack_outputs(stack)
  raise "State Machine is not deployed" unless current_stack_outputs

  if optional_output
    puts current_stack_outputs[optional_output]
  else
    puts current_stack_outputs.to_json
  end
end

#stack_outputs(stack_name) ⇒ Object



76
77
78
79
80
81
82
83
84
85
86
87
88
# File 'lib/simplerubysteps/tool.rb', line 76

def stack_outputs(stack_name)
  begin
    response = @cloudformation_client.describe_stacks(stack_name: stack_name)
    outputs = {}
    response.stacks.first.outputs.each do |output|
      outputs[output.output_key] = output.output_value
    end
    outputs
  rescue Aws::CloudFormation::Errors::ServiceError => error
    return nil if error.message =~ /Stack .* does not exist/
    raise error
  end
end

#stack_params(stack_name, template, parameters) ⇒ Object



90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
# File 'lib/simplerubysteps/tool.rb', line 90

def stack_params(stack_name, template, parameters)
  params = {
    stack_name: stack_name,
    template_body: template,
    capabilities: ["CAPABILITY_IAM", "CAPABILITY_NAMED_IAM"],
    parameters: [],
  }
  parameters.each do |k, v|
    params[:parameters].push({
      parameter_key: k,
      parameter_value: v,
    })
  end
  params
end

#stack_update(stack_name, template, parameters) ⇒ Object



112
113
114
115
116
117
118
119
120
121
# File 'lib/simplerubysteps/tool.rb', line 112

def stack_update(stack_name, template, parameters)
  begin
    @cloudformation_client.update_stack(stack_params(stack_name, template, parameters))
    @cloudformation_client.wait_until(:stack_update_complete, stack_name: stack_name)
    stack_outputs(stack_name)
  rescue Aws::CloudFormation::Errors::ServiceError => error
    return stack_outputs(stack_name).merge({ :no_update => true }) if error.message =~ /No updates are to be performed/
    raise unless error.message =~ /No updates are to be performed/
  end
end

#start(wait, input, version) ⇒ Object



424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
# File 'lib/simplerubysteps/tool.rb', line 424

def start(wait, input, version)
  stack = nil
  if version
    stack = versioned_stack_name_from_current_dir(version)
  else
    stack = most_recent_stack_with_prefix unversioned_stack_name_from_current_dir
  end
  raise "State Machine is not deployed" unless stack

  current_stack_outputs = stack_outputs(stack)
  raise "State Machine is not deployed" unless current_stack_outputs

  state_machine_arn = current_stack_outputs["StepFunctionsStateMachineARN"]

  input_json = JSON.parse(input.read).to_json

  if current_stack_outputs["StateMachineType"] == "STANDARD"
    start_response = start_async_execution(state_machine_arn, input_json)

    unless wait
      puts start_response.to_json
    else
      execution_arn = start_response.execution_arn

      puts wait_for_async_execution_completion(execution_arn).to_json
    end
  elsif current_stack_outputs["StateMachineType"] == "EXPRESS"
    puts start_sync_execution(state_machine_arn, input_json).to_json
  else
    raise "Unknown state machine type: #{current_stack_outputs["StateMachineType"]}"
  end
end

#start_async_execution(state_machine_arn, input) ⇒ Object



377
378
379
380
381
382
# File 'lib/simplerubysteps/tool.rb', line 377

def start_async_execution(state_machine_arn, input)
  @states_client.start_execution(
    state_machine_arn: state_machine_arn,
    input: input,
  )
end

#start_sync_execution(state_machine_arn, input) ⇒ Object



370
371
372
373
374
375
# File 'lib/simplerubysteps/tool.rb', line 370

def start_sync_execution(state_machine_arn, input)
  @states_client.start_sync_execution(
    state_machine_arn: state_machine_arn,
    input: input,
  )
end

#tail_follow_logs(log_group_name, extract_pattern = nil) ⇒ Object

FIXME too hacky



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
# File 'lib/simplerubysteps/tool.rb', line 24

def tail_follow_logs(log_group_name, extract_pattern = nil) # FIXME too hacky
  Signal.trap("INT") do
    exit
  end

  first_event_time = Time.now.to_i * 1000

  next_tokens = {}
  first_round = true
  loop do
    log_streams = @logs_client.describe_log_streams(
      log_group_name: log_group_name,
      order_by: "LastEventTime",
      descending: true,
    ).log_streams

    log_streams.each do |log_stream|
      get_log_events_params = {
        log_group_name: log_group_name,
        log_stream_name: log_stream.log_stream_name,
      }

      if next_tokens.key?(log_stream.log_stream_name)
        get_log_events_params[:next_token] = next_tokens[log_stream.log_stream_name]
      else
        get_log_events_params[:start_time] = first_round ? log_stream.last_event_timestamp : first_event_time
      end

      response = @logs_client.get_log_events(get_log_events_params)

      response.events.each do |event|
        if event.timestamp >= first_event_time
          if extract_pattern
            if /#{extract_pattern}/ =~ event.message
              puts $1
              exit
            end
          else
            puts "#{Time.at(event.timestamp / 1000).utc} - #{log_stream.log_stream_name} - #{event.message}"
          end
        end
      end

      next_tokens[log_stream.log_stream_name] = response.next_forward_token
    end

    sleep 5

    first_round = false
  end
end

#unversioned_stack_name_from_current_dirObject



213
214
215
# File 'lib/simplerubysteps/tool.rb', line 213

def unversioned_stack_name_from_current_dir
  File.basename(File.expand_path("."))
end

#upload_file_to_s3(bucket, key, file_path) ⇒ Object



183
184
185
186
187
# File 'lib/simplerubysteps/tool.rb', line 183

def upload_file_to_s3(bucket, key, file_path)
  File.open(file_path, "rb") do |file|
    upload_to_s3(bucket, key, file)
  end
end

#upload_to_s3(bucket, key, body) ⇒ Object



175
176
177
178
179
180
181
# File 'lib/simplerubysteps/tool.rb', line 175

def upload_to_s3(bucket, key, body)
  @s3_client.put_object(
    bucket: bucket,
    key: key,
    body: body,
  )
end

#versioned_stack_name_from_current_dir(version) ⇒ Object



229
230
231
232
233
234
235
# File 'lib/simplerubysteps/tool.rb', line 229

def versioned_stack_name_from_current_dir(version)
  if version
    "#{unversioned_stack_name_from_current_dir}-#{version}"
  else
    "#{unversioned_stack_name_from_current_dir}-#{workflow_files_hash()[0...8]}"
  end
end

#wait_for_async_execution_completion(execution_arn) ⇒ Object



390
391
392
393
394
395
396
397
398
399
400
401
402
403
# File 'lib/simplerubysteps/tool.rb', line 390

def wait_for_async_execution_completion(execution_arn)
  response = nil

  loop do
    response = describe_execution(execution_arn)
    status = response.status

    break if %w[SUCCEEDED FAILED TIMED_OUT].include?(status)

    sleep 5
  end

  response
end

#workflow_filesObject



217
218
219
# File 'lib/simplerubysteps/tool.rb', line 217

def workflow_files
  dir_files ".", "**/*.rb"
end

#workflow_files_hashObject



221
222
223
224
225
226
227
# File 'lib/simplerubysteps/tool.rb', line 221

def workflow_files_hash
  file_hashes = []
  workflow_files.each do |name, file|
    file_hashes.push Digest::SHA1.file(file)
  end
  Digest::SHA1.hexdigest file_hashes.join(",")
end