Module: SpotBuild

Defined in:
lib/spot_build.rb,
lib/spot_build/sqs_event.rb,
lib/spot_build/spot_instance.rb,
lib/spot_build/buildkite_agents.rb

Defined Under Namespace

Classes: BuildkiteAgents, SpotInstance, SqsEvent

Constant Summary collapse

DEFAULT_TIMEOUT =
300

Class Method Summary collapse

Class Method Details

.parse_optionsObject



44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
# File 'lib/spot_build.rb', line 44

def self.parse_options
  options = {auto_retries: true}
  parser = OptionParser.new do |opts|
    opts.banner = "Usage: #{__FILE__} [options]"
    opts.on("-t", "--token TOKEN", "Buildkite API token") { |v| options[:token] = v }
    opts.on("-o", "--org-slug ORGANISATION-SLUG", "The Buildkite Organisation Slug") { |v| options[:org_slug] = v }
    opts.on("-s", "--sqs-queue SQS-QUEUE-URL", "The SQS Queue URL we should monitor for events that tell us to shutdown") { |v| options[:queue_url] = v }
    opts.on("--timeout TIMEOUT", "The amount of time to wait for the buildkite agent to stop before shutting down. Only used if --sqs-queue is specified") { |v| options[:timeout] = v.to_i }
    opts.on("-r", "--aws-region REGION", "The AWS Region the SQS queue resides in")  { |v| options[:aws_region] = v }
    opts.on("-n", "--[no-]auto-retry", "Disable automatic retries") { |v| options[:auto_retries] = v }
  end
  parser.parse!

  if options[:token].nil? || options[:org_slug].nil?
    raise OptionParser::MissingArgument, "You must specify Token and Organisational Slug.\n#{parser.help}"
  end

  options
end

.runObject



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
# File 'lib/spot_build.rb', line 9

def self.run
  options = parse_options
  options[:timeout] ||= DEFAULT_TIMEOUT

  checks = [SpotInstance.new]
  if options[:queue_url]
    checks.push(SqsEvent.new(url: options[:queue_url], timeout: options[:timeout], region: options[:aws_region]))
  end

  agents = BuildkiteAgents.new(options[:token], options[:org_slug])
  loop do
    checks.each do |check|
      terminating = check.shutdown_if_required do
        agents.stop
        if options[:auto_retries]
          timeout = SpotInstance.scheduled_for_termination? ? (SpotInstance.time_until_termination - 30) : options[:timeout]

          Timeout::timeout(timeout) do
            while agents.agents_running?
              sleep 5
            end
          end rescue Timeout::Error
          agents.the_end_is_nigh
        else
          while agents.agents_running?
            sleep 5
          end
        end
      end
      %x(shutdown -h now) if terminating
    end
    sleep 2
  end
end