Class: Kitchen::Driver::Cloudstack

Inherits:
SSHBase
  • Object
show all
Defined in:
lib/kitchen/driver/cloudstack.rb

Overview

Cloudstack driver for Kitchen.

Author:

Instance Method Summary collapse

Instance Method Details

#computeObject



38
39
40
41
42
43
44
45
46
47
48
49
50
# File 'lib/kitchen/driver/cloudstack.rb', line 38

def compute
  cloudstack_uri =  URI.parse(config[:cloudstack_api_url])
  connection = Fog::Compute.new(
    :provider => :cloudstack,
    :cloudstack_api_key => config[:cloudstack_api_key],
    :cloudstack_secret_access_key => config[:cloudstack_secret_key],
    :cloudstack_host => cloudstack_uri.host,
    :cloudstack_port => cloudstack_uri.port,
    :cloudstack_path => cloudstack_uri.path,
    :cloudstack_project_id => config[:cloudstack_project_id],
    :cloudstack_scheme => cloudstack_uri.scheme
  )
end

#create(state) ⇒ Object



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
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
201
202
203
# File 'lib/kitchen/driver/cloudstack.rb', line 80

def create(state)
  if not config[:name]
    # Generate what should be a unique server name

    config[:name] = "#{instance.name}-#{Etc.getlogin}-" +
      "#{Socket.gethostname}-#{Array.new(8){rand(36).to_s(36)}.join}"
  end
  if config[:disable_ssl_validation]
    require 'excon'
    Excon.defaults[:ssl_verify_peer] = false
  end

  server = create_server
  debug(server)

  state[:server_id] = server['deployvirtualmachineresponse'].fetch('id')
  start_jobid = {
    'jobid' => server['deployvirtualmachineresponse'].fetch('jobid')
  }
  info("CloudStack instance <#{state[:server_id]}> created.")
  debug("Job ID #{start_jobid}")
  # Cloning the original job id hash because running the

  # query_async_job_result updates the hash to include

  # more than just the job id (which I could work around, but I'm lazy).

  jobid = start_jobid.clone

  server_start = compute.query_async_job_result(jobid)
  # jobstatus of zero is a running job

  while server_start['queryasyncjobresultresponse'].fetch('jobstatus').to_i == 0
    debug("Job status: #{server_start}")
    print ". "
    sleep(10)
    debug("Running Job ID #{jobid}")
    debug("Start Job ID #{start_jobid}")
    # We have to reclone on each iteration, as the hash keeps getting updated.

    jobid = start_jobid.clone
    server_start = compute.query_async_job_result(jobid)
  end
  debug("Server_Start: #{server_start} \n")

  # jobstatus of 2 is an error response

  if server_start['queryasyncjobresultresponse'].fetch('jobstatus').to_i == 2
    errortext = server_start['queryasyncjobresultresponse']
      .fetch('jobresult')
      .fetch('errortext')

    error("ERROR! Job failed with #{errortext}")

    raise ActionFailed, "Could not create server #{errortext}"
  end

  # jobstatus of 1 is a succesfully completed async job

  if server_start['queryasyncjobresultresponse'].fetch('jobstatus').to_i == 1
    server_info = server_start['queryasyncjobresultresponse']['jobresult']['virtualmachine']
    debug(server_info)
    print "(server ready)"

    keypair = nil
    if config[:keypair_search_directory] and File.exist?(
      "#{config[:keypair_search_directory]}/#{config[:cloudstack_ssh_keypair_name]}.pem"
    )
      keypair = "#{config[:keypair_search_directory]}/#{config[:cloudstack_ssh_keypair_name]}.pem"
      debug("Keypair being used is #{keypair}")
    elsif File.exist?("./#{config[:cloudstack_ssh_keypair_name]}.pem")
      keypair = "./#{config[:cloudstack_ssh_keypair_name]}.pem"
      debug("Keypair being used is #{keypair}")
    elsif File.exist?("#{ENV["HOME"]}/#{config[:cloudstack_ssh_keypair_name]}.pem")
      keypair = "#{ENV["HOME"]}/#{config[:cloudstack_ssh_keypair_name]}.pem"
      debug("Keypair being used is #{keypair}")
    elsif File.exist?("#{ENV["HOME"]}/.ssh/#{config[:cloudstack_ssh_keypair_name]}.pem")
      keypair = "#{ENV["HOME"]}/.ssh/#{config[:cloudstack_ssh_keypair_name]}.pem"
      debug("Keypair being used is #{keypair}")
    elsif (!config[:cloudstack_ssh_keypair_name].nil?)
      info("Keypair specified but not found. Using password if enabled.")
    end

    if config[:associate_public_ip]
      info("Associating public ip...")
      state[:hostname] = associate_public_ip(state, server_info)
      info("Creating port forward...")
      create_port_forward(state, server_info['id'])
    else
      state[:hostname] = default_public_ip(server_info) unless config[:associate_public_ip]
    end

    if keypair
      debug("Using keypair: #{keypair}")
      info("SSH for #{state[:hostname]} with keypair #{config[:cloudstack_ssh_keypair_name]}.")
      ssh_key = File.read(keypair)
      if ssh_key.split[0] == "ssh-rsa" or ssh_key.split[0] == "ssh-dsa"
        error("SSH key #{keypair} is not a Private Key. Please modify your .kitchen.yml")
      end

      wait_for_sshd(state[:hostname], config[:username], {:keys => keypair})
      debug("SSH connectivity validated with keypair.")

      ssh = Fog::SSH.new(state[:hostname], config[:username], {:keys => keypair})
      debug("Connecting to : #{state[:hostname]} as #{config[:username]} using keypair #{keypair}.")
    elsif server_info.fetch('passwordenabled')
      password = server_info.fetch('password')
      config[:password] = password
      # Print out IP and password so you can record it if you want.

      info("Password for #{config[:username]} at #{state[:hostname]} is #{password}")

      wait_for_sshd(state[:hostname], config[:username], {:password => password})
      debug("SSH connectivity validated with cloudstack-set password.")

      ssh = Fog::SSH.new(state[:hostname], config[:username], {:password => password})
      debug("Connecting to : #{state[:hostname]} as #{config[:username]} using password #{password}.")
    elsif config[:password]
      info("Connecting with user #{config[:username]} with password #{config[:password]}")

      wait_for_sshd(state[:hostname], config[:username], {:password => config[:password]})
      debug("SSH connectivity validated with fixed password.")

      ssh = Fog::SSH.new(state[:hostname], config[:username], {:password => config[:password]})
    else
      info("No keypair specified (or file not found) nor is this a password enabled template. You will have to manually copy your SSH public key to #{state[:hostname]} to use this Kitchen.")
    end

    validate_ssh_connectivity(ssh)

    deploy_private_key(ssh)
  end
end

#create_serverObject



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
# File 'lib/kitchen/driver/cloudstack.rb', line 52

def create_server
  options = {}

  config[:server_name] ||= generate_name(instance.name)

  options['displayname'] = config[:server_name]
  options['networkids']  = config[:cloudstack_network_id]
  options['securitygroupids'] = config[:cloudstack_security_group_id]
  options['affinitygroupids'] = config[:cloudstack_affinity_group_id]
  options['keypair'] = config[:cloudstack_ssh_keypair_name]
  options['diskofferingid'] = config[:cloudstack_diskoffering_id]
  options['size'] = config[:cloudstack_diskoffering_size]
  options['name'] = config[:host_name]
  options['details[0].cpuNumber'] = config[:cloudstack_serviceoffering_cpu]
  options['details[0].cpuSpeed'] = config[:cloudstack_serviceoffering_cpuspeed]
  options['details[0].memory'] = config[:cloudstack_serviceoffering_memory]
  options[:userdata] = convert_userdata(config[:cloudstack_userdata]) if config[:cloudstack_userdata]

  options = sanitize(options)

  options[:templateid] = config[:cloudstack_template_id]
  options[:serviceofferingid] = config[:cloudstack_serviceoffering_id]
  options[:zoneid] = config[:cloudstack_zone_id]

  debug(options)
  compute.deploy_virtual_machine(options)
end

#deploy_private_key(ssh) ⇒ Object



270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
# File 'lib/kitchen/driver/cloudstack.rb', line 270

def deploy_private_key(ssh)
  debug("Deploying user private key to server using connection #{ssh} to guarantee connectivity.")
  if File.exist?("#{ENV["HOME"]}/.ssh/id_rsa.pub")
    user_public_key = File.read("#{ENV["HOME"]}/.ssh/id_rsa.pub")
  elsif File.exist?("#{ENV["HOME"]}/.ssh/id_dsa.pub")
    user_public_key = File.read("#{ENV["HOME"]}/.ssh/id_dsa.pub")
  else
    debug("No public SSH key for user. Skipping.")
  end

  if user_public_key
    ssh.run([
      %{mkdir .ssh},
      %{echo "#{user_public_key}" >> ~/.ssh/authorized_keys}
    ])
  end
end

#destroy(state) ⇒ Object



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
# File 'lib/kitchen/driver/cloudstack.rb', line 205

def destroy(state)
  return unless state[:server_id]
  if config[:associate_public_ip]
    delete_port_forward(state)
    release_public_ip(state)
  end
  debug("Destroying #{state[:server_id]}")
  server = compute.servers.get(state[:server_id])
  expunge =
    if !!config[:cloudstack_expunge] == config[:cloudstack_expunge]
      config[:cloudstack_expunge]
    else
      false
    end
  if server
    compute.destroy_virtual_machine(
      {
        'id' => state[:server_id],
        'expunge' => expunge
      }
    )
  end
  info("CloudStack instance <#{state[:server_id]}> destroyed.")
  state.delete(:server_id)
  state.delete(:hostname)
end

#generate_name(base) ⇒ Object



288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
# File 'lib/kitchen/driver/cloudstack.rb', line 288

def generate_name(base)
  # Generate what should be a unique server name

  sep = '-'
  pieces = [
    base,
    Etc.getlogin,
    Socket.gethostname,
    Array.new(8) { rand(36).to_s(36) }.join
  ]
  until pieces.join(sep).length <= 64 do
    if pieces[2] && pieces[2].length > 24
      pieces[2] = pieces[2][0..-2]
    elsif pieces[1] && pieces[1].length > 16
      pieces[1] = pieces[1][0..-2]
    elsif pieces[0] && pieces[0].length > 16
      pieces[0] = pieces[0][0..-2]
    end
  end
  pieces.join sep
end

#validate_ssh_connectivity(ssh) ⇒ Object



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/kitchen/driver/cloudstack.rb', line 232

def validate_ssh_connectivity(ssh)
rescue Errno::ETIMEDOUT
  debug("SSH connection timed out. Retrying.")
  sleep 2
  false
rescue Errno::EPERM
  debug("SSH connection returned error. Retrying.")
  false
rescue Errno::ECONNREFUSED
  debug("SSH connection returned connection refused. Retrying.")
  sleep 2
  false
rescue Errno::EHOSTUNREACH
  debug("SSH connection returned host unreachable. Retrying.")
  sleep 2
  false
rescue Errno::ENETUNREACH
  debug("SSH connection returned network unreachable. Retrying.")
  sleep 30
  false
rescue Net::SSH::Disconnect
  debug("SSH connection has been disconnected. Retrying.")
  sleep 15
  false
rescue Net::SSH::AuthenticationFailed
  debug("SSH authentication has failed. Password or Keys may not be in place yet. Retrying.")
  sleep 15
  false
ensure
  sync_time = 0
  if (config[:cloudstack_sync_time])
    sync_time = config[:cloudstack_sync_time]
  end
  sleep(sync_time)
  debug("Connecting to host and running ls")
  ssh.run('ls')
end