Top Level Namespace

Defined Under Namespace

Modules: OpsWorks, OpzWorks Classes: String

Constant Summary collapse

COMMANDS =

require our commands

%w(ssh cmd json berks elastic).each do |cmd|
  require "opzworks/commands/#{cmd}"
end
SSH_PREFIX =
'# --- OpzWorks ---'.freeze
SSH_POSTFIX =
'# --- End of OpzWorks ---'.freeze

Instance Method Summary collapse

Instance Method Details

#es_enable_allocation(ip, type) ⇒ Object



58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
# File 'lib/opzworks/commands/include/elastic.rb', line 58

def es_enable_allocation(ip, type)
  puts "Cluster routing.allocation is being set to #{type}".foreground(:blue)
  conn = Faraday.new(url: "http://#{ip}:9200") do |f|
    f.adapter :net_http
  end

  count = 0
  loop do
    begin
      conn.put do |req|
        req.url '/_cluster/settings'
        req.body = "{\"transient\": {\"cluster.routing.allocation.enable\": \"#{type}\"}}"
        req.options[:timeout]       = 5
        req.options[:open_timeout]  = 2
      end
      break
    rescue StandardError => e
      puts 'Caught exception while trying to change allocation state: '.foreground(:yellow) + e.to_s.foreground(:red) + ', looping around...'.foreground(:yellow) if count == 0
      count += 1
      sleep 1
    end
  end
end

#es_get_input(input, data = {}, *cmd) ⇒ Object



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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/opzworks/commands/include/elastic.rb', line 9

def es_get_input(input, data = {}, *cmd)
  match = {}
  count = 0

  data[:stacks].each do |stack|
    next unless stack[:name].chomp =~ /#{input}/
    count = count += 1
    match = stack.to_hash
  end

  # break?
  if count < 1
    puts 'No matching stacks found for input '.foreground(:yellow) + input.foreground(:green) + ', skipping.'.foreground(:yellow)
    return false
  elsif count > 1
    puts 'Found more than one stack matching input '.foreground(:yellow) + input.foreground(:green) + ', skipping.'.foreground(:yellow)
    return false
  else
    puts 'Operating on stack '.foreground(:blue) + match[:name].to_s.foreground(:green)
    layers = @client.describe_layers(stack_id: match[:stack_id])
    layers[:layers].each { |layer| printf("%-30s %-50s\n", layer[:name], layer[:layer_id]) }

    STDOUT.print 'Specify a layer: '.foreground(:blue)
    layer = STDIN.gets.chomp

    unless cmd.include? 'start'
      STDOUT.print 'Disable shard allocation before starting? (true/false, default is true): '.foreground(:blue)
      disable_allocation = STDIN.gets.chomp
      @disable_shard_allocation = case disable_allocation
                                  when 'false'
                                    false
                                  else
                                    true
                                  end
    end

    options = {}
    if layer == ''
      puts 'Must specify a layer.'.foreground(:red)
      return false
    else
      options[:layer_id] = layer
      get_shortname = @client.describe_layers(layer_ids: [layer])
      get_shortname[:layers].each { |l| @service_name = l[:shortname] }
    end
    opsworks_list_ips(options)
  end
end

#es_service(command, ips = [], service_name = 'elasticsearch') ⇒ Object



82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
# File 'lib/opzworks/commands/include/elastic.rb', line 82

def es_service(command, ips = [], service_name = 'elasticsearch')
  puts "Operating on ES with command #{command}".foreground(:yellow)
  user = ENV['USER']

  Net::SSH::Multi.start do |session|
    ips.each do |ip|
      session.use "#{user}@#{ip}"
    end

    Timeout.timeout(10) do
      session.exec "sudo service #{service_name} #{command}"
    end
    session.loop
  end
end

#es_wait_for_status(ip, color) ⇒ Object



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/opzworks/commands/include/elastic.rb', line 98

def es_wait_for_status(ip, color)
  puts 'Waiting for cluster to go '.foreground(:blue) + color.foreground(:"#{color}")
  conn = Faraday.new(url: "http://#{ip}:9200") do |f|
    f.adapter :net_http
  end

  count = 0
  rescue_count = 0
  loop do
    begin
      response = conn.get do |req|
        req.url '/_cluster/health'
        req.options[:timeout]       = 5
        req.options[:open_timeout]  = 2
      end
      json = JSON.parse response.body
    rescue StandardError => e
      puts 'Caught exception while trying to check cluster status: '.foreground(:yellow) + e.to_s.foreground(:red) + ', looping around...'.foreground(:yellow) if rescue_count == 0
      rescue_count += 1
      printf '.'
      sleep 1
    else
      case json['status']
      when color
        puts "\nCluster is now ".foreground(:blue) + color.foreground(:"#{color}")
        break
      when 'green'
        puts "\nCluster is green, proceeding without waiting for requested status of #{color}".foreground(:green)
        break
      else
        count += 1
        if count == 10
          puts "\nStill waiting, cluster is currently ".foreground(:blue) + json['status'].to_s.foreground(:"#{json['status']}")
          count = 0
        end
        printf '.'
        sleep 1
      end
    end
  end
end

#manage_berks_reposObject



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
# File 'lib/opzworks/commands/include/manage_berks_repos.rb', line 1

def manage_berks_repos
  config = OpzWorks.config
  @target_path = File.expand_path(config.berks_repository_path + "/opsworks-#{@project}", File.dirname(__FILE__))

  if !File.directory?(@target_path)
    if config.berks_github_org.nil?
      puts "#{@target_path} does not exist, and 'berks-github-org' is not set in ~/.aws/config, skipping.".foreground(:yellow)
      return false
    else
      repo = "[email protected]:#{config.berks_github_org}/opsworks-#{@project}.git"
      puts "#{@target_path} does not exist!".foreground(:red)
      puts 'Attempting git clone of '.foreground(:blue) + repo.foreground(:green)
      run_local "        cd \#{config.berks_repository_path}\n        git clone \#{repo}\n      BASH\n    end\n  else\n    puts \"Git pull from \#{@target_path}, branch: \".foreground(:blue) + @branch.foreground(:green)\n    run_local <<-BASH\n      cd \#{@target_path}\n      git checkout \#{@branch} && git pull origin \#{@branch}\n    BASH\n  end\nend\n"

#opsworks_list_ips(options = {}) ⇒ Object



1
2
3
4
5
6
7
# File 'lib/opzworks/commands/include/elastic.rb', line 1

def opsworks_list_ips(options = {})
  response = @client.describe_instances options
  @ip_addrs = []
  response[:instances].each { |instance| @ip_addrs << instance.private_ip if instance[:status] == 'online' }
rescue StandardError => e
  abort "Exception raised: #{e}".foreground(:red)
end

#populate_stack(input, data = {}) ⇒ Object



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/opzworks/commands/include/populate_stack.rb', line 1

def populate_stack(input, data = {})
  # loops over inputs
  match = {}
  count = 0

  data[:stacks].each do |stack|
    next unless stack[:name].chomp =~ /#{input}/
    count = count += 1
    match = stack.to_hash
  end

  # break?
  if count < 1
    puts 'No matching stacks found for input '.foreground(:yellow) + input.foreground(:green) + ', skipping.'.foreground(:yellow)
    return false
  elsif count > 1
    puts 'Found more than one stack matching input '.foreground(:yellow) + input.foreground(:green) + ', skipping.'.foreground(:yellow)
    return false
  else
    @stack_json     = match[:custom_json] || ''
    @project        = match[:name].split('::').first
    @s3_path        = match[:name].gsub('::', '-')
    @branch         = (match[:name].split('::')[1] + '-' + match[:name].split('::')[2]).gsub('::', '-')
    @stack_id       = match[:stack_id]
    @arn            = match[:arn]
    @region         = match[:region]
    @default_subnet = match[:default_subnet_id]
    @default_os     = match[:default_os]
    @chef_version   = match[:configuration_manager][:version]
    @s3_source_url  = match[:custom_cookbooks_source][:url] || ''
  end
end

#run_local(cmd) ⇒ Object

wrap run_locally so we can catch failures



2
3
4
5
6
7
8
9
# File 'lib/opzworks/commands/include/run_local.rb', line 2

def run_local(cmd)
  require 'English'

  system cmd
  return unless $CHILD_STATUS.exitstatus != 0
  puts 'exit code: ' + $CHILD_STATUS.exitstatus.to_s
  exit
end