Class: Chef::Knife::CloudstackServerCreate

Inherits:
Chef::Knife
  • Object
show all
Includes:
CloudstackBase
Defined in:
lib/chef/knife/cloudstack_server_create.rb

Instance Method Summary collapse

Methods included from CloudstackBase

#connection, included, #locate_config_value, #msg_pair, #validate!

Instance Method Details

#add_port_forward(public_start_port, public_end_port, server_id, ipaddressid, privateport) ⇒ Object



288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
# File 'lib/chef/knife/cloudstack_server_create.rb', line 288

def add_port_forward(public_start_port, public_end_port, server_id, ipaddressid, privateport)
  pfwdops = {}
  pfwdops['ipaddressid'] = ipaddressid
  pfwdops['privateport'] = privateport
  pfwdops['protocol'] = "TCP"
  pfwdops['virtualmachineid'] = server_id
  pfwdops['openfirewall'] = "true"
  pfwdops['publicport'] = public_start_port
  pfwdops['publicendport'] = public_end_port
  rule_create_job = connection.create_port_forwarding_rule(pfwdops)
  print "#{ui.color("Creating port forwarding rule.", :cyan)}"
  while (@connection.query_async_job_result({'jobid' => rule_create_job['createportforwardingruleresponse']['jobid']})['queryasyncjobresultresponse'].fetch('jobstatus') == 0)
    print("#{ui.color(".", :cyan)}")
    sleep 2
  end
  print("\n")
end

#bootstrap_for_node(server, ssh_host) ⇒ Object

def bootstrap_for_node(host, user, password)



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
# File 'lib/chef/knife/cloudstack_server_create.rb', line 146

def bootstrap_for_node(server, ssh_host)
  host = server["name"]
  user = config[:ssh_user]
  password = server["password"]
  Chef::Log.debug("Bootstrap host: #{host}")
  Chef::Log.debug("Bootstrap user: #{user}")
  Chef::Log.debug("Bootstrap pass: #{password}")
  bootstrap = Chef::Knife::Bootstrap.new
  bootstrap.name_args = [ssh_host]
  bootstrap.config[:run_list] = config[:run_list]
  bootstrap.config[:ssh_user] = user
  bootstrap.config[:ssh_password] = password
  bootstrap.config[:ssh_gateway] = config[:ssh_gateway]
  bootstrap.config[:identity_file] = locate_config_value(:identity_file)
  bootstrap.config[:chef_node_name] = config[:server_name] if config[:server_name]
  bootstrap.config[:prerelease] = config[:prerelease]
  bootstrap.config[:bootstrap_version] = locate_config_value(:bootstrap_version)
  bootstrap.config[:distro] = locate_config_value(:distro)
  bootstrap.config[:use_sudo] = true
  bootstrap.config[:template_file] = locate_config_value(:template_file)
  bootstrap.config[:environment] = config[:environment]
  # may be needed for vpc_mode

  bootstrap.config[:no_host_key_verify] = config[:no_host_key_verify]
  begin
    bootstrap
  rescue
    sleep @initial_sleep_delay
    retry
  end
end

#check_port_available(public_port, ipaddressid) ⇒ Object



259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
# File 'lib/chef/knife/cloudstack_server_create.rb', line 259

def check_port_available(public_port, ipaddressid)
  Chef::Log.debug("Checking if port #{public_port} is available.")
  pubport = public_port.to_i
  port_forward_rules_query = connection.list_port_forwarding_rules({'ipaddressid' => ipaddressid })
  port_rules = port_forward_rules_query['listportforwardingrulesresponse']['portforwardingrule']
  is_available = true
  some_possible_rules = port_rules.select { |rule| rule['publicport'].to_i <= pubport }
  possible_rules = some_possible_rules.select { |rule| rule['publicendport'].to_i >= pubport }
  possible_rules.each do |rule|
    startport = rule['publicport'].to_i
    endport = rule['publicendport'].to_i
    Chef::Log.debug("Determining if #{pubport} is between #{startport} and #{endport}.")
    if (endport != startport)
      if pubport.between?(startport, endport)
        is_available = false
      else
        is_available = true
      end
    else
      if (pubport == startport)
        is_available = false
      else
        is_available = true
      end
    end
  end
  return is_available
end

#create_server_defObject



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
# File 'lib/chef/knife/cloudstack_server_create.rb', line 306

def create_server_def
  server_def = {
    "templateid" => locate_config_value(:cloudstack_templateid),
    "serviceofferingid" => locate_config_value(:cloudstack_serviceid),
    "zoneid" => locate_config_value(:cloudstack_zoneid)
  }

  if locate_config_value(:server_name) != nil
    server_def["displayname"] = locate_config_value(:server_name)
  end

  if locate_config_value(:host_name) != nil
    server_def["name"] = locate_config_value(:host_name)
  end

  network_ids = []
  if locate_config_value(:cloudstack_networkids) != []
    cs_networkids = locate_config_value(:cloudstack_networkids)
    cs_networkids.each do |id|
      network_ids.push(id)
    end
    server_def["networkids"] = network_ids
  end

  security_groups = []
  if locate_config_value(:cloudstack_groupids) != []
    cs_groupids = locate_config_value(:cloudstack_groupids)
    cs_groupids.each do |id|
      security_groups.push(id)
    end
    server_def["securitygroupids"] = security_groups
  elsif locate_config_value(:cloudstack_groupnames) != []
    cs_groupnames = locate_config_value(:cloudstack_groupnames)
    cs_groupnames.each do |name|
      security_groups.push(name)
    end
    server_def["securitygroupnames"] = security_groups
  end

  if locate_config_value(:keypair) != nil
    server_def["keypair"] = locate_config_value(:keypair)
  end

  if locate_config_value(:diskoffering) != nil
    server_def["diskofferingid"] = locate_config_value(:diskoffering)
  end

  if locate_config_value(:size) != nil
    server_def["size"] = locate_config_value(:size)
  end

  server_def
end

#runObject



360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
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
456
457
458
459
460
461
462
463
464
465
466
467
468
# File 'lib/chef/knife/cloudstack_server_create.rb', line 360

def run
  $stdout.sync = true
  options = create_server_def
  Chef::Log.debug("Options: #{options} \n")

  @initial_sleep_delay = 10        
  @sshport = 22
  if locate_config_value(:ssh_port) != nil
    @sshport = locate_config_value(:ssh_port).to_i
  end

  serverdeploy = connection.deploy_virtual_machine(options)
  jobid = serverdeploy['deployvirtualmachineresponse'].fetch('jobid')

  server_start = connection.query_async_job_result('jobid'=>jobid)

  Chef::Log.debug("Job ID: #{jobid} \n")

  print "#{ui.color("Waiting for server", :magenta)}"
  while server_start['queryasyncjobresultresponse'].fetch('jobstatus') == 0
    print "#{ui.color(".", :magenta)}"
    sleep @initial_sleep_delay
    server_start = connection.query_async_job_result('jobid'=>jobid)
    Chef::Log.debug("Server_Start: #{server_start} \n")
  end
  puts "\n\n"

  if server_start['queryasyncjobresultresponse'].fetch('jobstatus') == 2
    errortext = server_start['queryasyncjobresultresponse'].fetch('jobresult').fetch('errortext')
    puts "#{ui.color("ERROR! Job failed with #{errortext}", :red)}"
  end

  if server_start['queryasyncjobresultresponse'].fetch('jobstatus') == 1

    Chef::Log.debug("Job ID: #{jobid} \n")
    Chef::Log.debug("Options: #{options} \n")
    server_start = connection.query_async_job_result('jobid'=>jobid)
    Chef::Log.debug("Server_Start: #{server_start} \n")

    @server = server_start['queryasyncjobresultresponse']['jobresult']['virtualmachine']

    server_name = @server['displayname']
    server_id = @server['name']
    server_serviceoffering = @server['serviceofferingname']
    server_template = @server['templatename']
    if @server['password'] != nil
      ssh_password = @server['password']
    else
      ssh_password = locate_config_value(:ssh_password)
    end

    ssh_user = locate_config_value(:ssh_user)

    @primary_ip = nil

    if @server['nic'].size > 0
      @primary_ip = @server['nic'].first['ipaddress']
    end

    if locate_config_value(:random_ssh_port) != nil
      public_ips = connection.list_public_ip_addresses("associatednetworkid" => @server['nic'][0]['networkid'])
      primary_public_ip_id = public_ips['listpublicipaddressesresponse']['publicipaddress'][0]['id']
      @primary_ip = public_ips['listpublicipaddressesresponse']['publicipaddress'][0]['ipaddress']
      pubport = rand(49152..65535)
      while (check_port_available(pubport, primary_public_ip_id) == false)
        pubport = rand(49152..65535)
      end
      add_port_forward(pubport, pubport, server_id, primary_public_ip_id, @sshport)
      @sshport = pubport
    end



    Chef::Log.debug("Connecting over port #{@sshport}")

    puts "\n\n"
    puts "#{ui.color("Name", :cyan)}: #{server_name}"
    puts "#{ui.color("Primary IP", :cyan)}: #{@primary_ip}"
    puts "#{ui.color("Username", :cyan)}: #{ssh_user}"
    puts "#{ui.color("Password", :cyan)}: #{ssh_password}"

    print "\n#{ui.color("Waiting for sshd", :magenta)}"
    wait_for_sshd(ssh_connect_host)

    puts("#{ui.color("Waiting for password/keys to sync.", :magenta)}")
    sleep @initial_sleep_delay
    sleep @initial_sleep_delay
    sleep @initial_sleep_delay

    Chef::Log.debug("Connnecting to #{@server} via #{ssh_connect_host} and bootstrapping Chef.")

    bootstrap_for_node(@server,ssh_connect_host).run

    Chef::Log.debug("#{@server}")

    puts "\n"
    puts "#{ui.color("Instance Name", :green)}: #{server_name}"
    puts "#{ui.color("Instance ID", :green)}: #{server_id}"
    puts "#{ui.color("Service Offering", :green)}: #{server_serviceoffering}"
    puts "#{ui.color("Template", :green)}: #{server_template}"
    puts "#{ui.color("Public IP Address", :green)}: #{@primary_ip}"
    puts "#{ui.color("Port", :green)}: #{@sshport}"
    puts "#{ui.color("User", :green)}: #{ssh_user}"
    puts "#{ui.color("Password", :green)}: #{ssh_password}"
    puts "#{ui.color("Environment", :green)}: #{config[:environment] || '_default'}"
    puts "#{ui.color("Run List", :green)}: #{config[:run_list].join(', ')}"
  end

end

#ssh_connect_hostObject



225
226
227
228
229
230
231
232
233
# File 'lib/chef/knife/cloudstack_server_create.rb', line 225

def ssh_connect_host
  @ssh_connect_host ||= if config[:server_connect_attribute]
    server.send(config[:server_connect_attribute])
  else
    Chef::Log.debug("Connecting to #{@primary_ip}")
    @primary_ip
    # vpc_mode? ? server.private_ip_address : server.dns_name

  end
end

#tcp_test_ssh(hostname, ssh_port) ⇒ Object



235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
# File 'lib/chef/knife/cloudstack_server_create.rb', line 235

def tcp_test_ssh(hostname, ssh_port)
  Chef::Log.debug("Conecting to #{hostname} on #{ssh_port}.")
  print("#{ui.color(".", :magenta)}")
  tcp_socket = TCPSocket.new(hostname, ssh_port)
  readable = IO.select([tcp_socket], nil, nil, 5)
  if readable
    Chef::Log.debug("sshd accepting connections on #{hostname}, banner is #{tcp_socket.gets}")
  yield
    true
  else
    false
  end
  rescue SocketError, Errno::ECONNREFUSED, Errno::EHOSTUNREACH, Errno::ENETUNREACH, IOError
    sleep 2
    false
  rescue Errno::EPERM, Errno::ETIMEDOUT
    false
  rescue Errno::Disconnect
    sleep @initial_sleep_delay
    retry
  ensure
  tcp_socket && tcp_socket.close
end

#tunnel_test_ssh(hostname, &block) ⇒ Object



196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
# File 'lib/chef/knife/cloudstack_server_create.rb', line 196

def tunnel_test_ssh(hostname, &block)
  gw_host, gw_user = config[:ssh_gateway].split('@').reverse
  gw_host, gw_port = gw_host.split(':')
  Chef::Log.debug("Connecting to #{hostname} via #{gw_host} over port #{gw_port}.")
  gateway = Net::SSH::Gateway.new(gw_host, gw_user, :port => gw_port || 22)
  status = false
  gateway.open(hostname, config[:ssh_port]) do |local_tunnel_port|
    status = tcp_test_ssh('localhost', local_tunnel_port, &block)
    Chef::Log.debug "Opened local port #{local_tunnel_port} to tunnel the connection."
  end
  status
  rescue SocketError, Errno::ECONNREFUSED, Errno::EHOSTUNREACH, Errno::ENETUNREACH, IOError
    sleep 2
    false
  rescue Errno::EPERM, Errno::ETIMEDOUT
    false
  rescue Errno::Disconnect
    sleep @initial_sleep_delay
    retry
end

#vpc_mode?Boolean

Returns:

  • (Boolean)


177
178
179
180
181
# File 'lib/chef/knife/cloudstack_server_create.rb', line 177

def vpc_mode?
  # Virtual Private Cloud / Isolated Networking requires a network id. If

  # present, do a few things differently

  !!locate_config_value(:cloudstack_networkids)
end

#wait_for_direct_sshd(hostname, ssh_port) ⇒ Object



217
218
219
220
221
222
223
# File 'lib/chef/knife/cloudstack_server_create.rb', line 217

def wait_for_direct_sshd(hostname, ssh_port)
  Chef::Log.debug("Connecting directly to #{hostname} over port #{ssh_port}")
  print("#{ui.color(".", :magenta)}") until tcp_test_ssh(ssh_connect_host, ssh_port) {
    sleep @initial_sleep_delay ||= (vpc_mode? ? 40 : 10)
    puts("#{ui.color(". Done.", :magenta)}")
  }
end

#wait_for_sshd(hostname) ⇒ Object



183
184
185
# File 'lib/chef/knife/cloudstack_server_create.rb', line 183

def wait_for_sshd(hostname)
  config[:ssh_gateway] ? wait_for_tunnelled_sshd(hostname) : wait_for_direct_sshd(hostname, @sshport)
end

#wait_for_tunnelled_sshd(hostname) ⇒ Object



187
188
189
190
191
192
193
194
# File 'lib/chef/knife/cloudstack_server_create.rb', line 187

def wait_for_tunnelled_sshd(hostname)
  Chef::Log.debug("Connecting to #{hostname} via wait_for_tunnelled_sshd")
  print("#{ui.color(".", :magenta)}")
  print("#{ui.color(".", :magenta)}") until tunnel_test_ssh(ssh_connect_host) {
    sleep @initial_sleep_delay ||= (vpc_mode? ? 40 : 10)
    puts("#{ui.color(". Done.", :magenta)}")
  }
end