Class: Chef::Knife::EsxVmCreate

Inherits:
Chef::Knife show all
Includes:
ESXBase
Defined in:
lib/chef/knife/esx_vm_create.rb

Instance Method Summary collapse

Methods included from ESXBase

#connection, included, #locate_config_value

Instance Method Details

#bootstrap_for_node(vm) ⇒ Object



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

def bootstrap_for_node(vm)
  bootstrap = Chef::Knife::Bootstrap.new
  bootstrap.name_args = [vm.ip_address]
  bootstrap.config[:async] = config[:async]
  bootstrap.config[:run_list] = config[:run_list]
  bootstrap.config[:ssh_user] = config[:ssh_user] 
  bootstrap.config[:identity_file] = config[:identity_file]
  bootstrap.config[:chef_node_name] = config[:chef_node_name] || vm.name
  bootstrap.config[:bootstrap_version] = locate_config_value(:bootstrap_version)
  bootstrap.config[:distro] = locate_config_value(:distro)
  # bootstrap will run as root...sudo (by default) also messes up Ohai on CentOS boxes
  bootstrap.config[:use_sudo] = true unless config[:ssh_user] == 'root'
  bootstrap.config[:template_file] = locate_config_value(:template_file)
  bootstrap.config[:environment] = config[:environment]
  bootstrap.config[:no_host_key_verify] = config[:no_host_key_verify]
  bootstrap.config[:ssh_password] = config[:ssh_password]
  bootstrap
end

#create_nics(networks, macs) ⇒ Object



424
425
426
427
428
429
430
431
432
# File 'lib/chef/knife/esx_vm_create.rb', line 424

def create_nics(networks, macs)
  net_arr = networks.split(/,/).map { |x| { :network => x } }
  if macs
    mac_arr = macs.split(/,/)
    net_arr.each_index { |x| net_arr[x][:mac_address] = mac_arr[x] if mac_arr[x] and !mac_arr[x].empty? }
  else
    net_arr
  end
end

#runObject



285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
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
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
# File 'lib/chef/knife/esx_vm_create.rb', line 285

def run
  $stdout.sync = true
  
  if config[:batch]
    KnifeESX::CLogger.instance.info "Running in batch mode. Extra arguments will be ignored."
    if not config[:async]
      counter = 0
      script = KnifeESX::DeployScript.new(config[:batch])
      script.each_job do |job|
        counter += 1
        status, stdout, stderr = job.run
        if status == 0 
          KnifeESX::CLogger.instance.info 'Ok'
        else
          KnifeESX::CLogger.instance.error 'Failed'
          stderr.each_line do |l|
            ui.error l
          end
        end
      end
    else
      KnifeESX::CLogger.instance.info! "Asynchronous boostrapping selected"
      KnifeESX::CLogger.instance.info! "Now do something productive while I finish my job ;)"
      script = KnifeESX::DeployScript.new(config[:batch])
      futures = []
      script.each_job do |job|
        futures << job.future(:run)
      end
      futures.each do |f|
        f.value
      end
    end
    return
  end

  if not config[:use_template]
    unless config[:vm_disk]
      ui.error("You have not provided a valid VMDK file. (--vm-disk)")
      exit 1
    end
    
    unless File.exist?(config[:vm_disk])
      ui.error("Invalid VMDK disk file (--vm-disk)")
      exit 1
    end
  end
  
  vm_name = config[:vm_name]
  if not vm_name
    ui.error("Invalid Virtual Machine name (--vm-name)")
    exit 1
  end

    
  datastore = config[:datastore]
  memory = config[:memory]
  vm_disk = config[:vm_disk]
  guest_id =config[:guest_id]
  destination_path = "/vmfs/volumes/#{datastore}/#{vm_name}"

  connection.remote_command "mkdir #{destination_path}"
  ui.info "Creating VM #{vm_name}"

  if config[:use_template]
    ui.info "Using template #{config[:use_template]}"
    if connection.template_exist?(config[:use_template])
      puts "#{ui.color("Cloning template...",:magenta)}"
      connection.copy_from_template config[:use_template], destination_path + "/#{vm_name}.vmdk"
    else
      ui.error "Template #{config[:use_template]} not found"
      exit 1
    end
  else
    puts "#{ui.color("Importing VM disk... ", :magenta)}"
    connection.import_disk vm_disk, destination_path + "/#{vm_name}.vmdk"
  end
  vm = connection.create_vm :vm_name => vm_name,
                       :datastore => datastore,
                       :disk_file => "#{vm_name}/#{vm_name}.vmdk",
                       :memory => memory,
                       :guest_id => guest_id,
                       :nics => create_nics(config[:vm_network], config[:mac_address])
  vm.power_on
  
  puts "#{ui.color("VM Created", :cyan)}"
  puts "#{ui.color("VM Name", :cyan)}: #{vm.name}"
  puts "#{ui.color("VM Memory", :cyan)}: #{(vm.memory_size.to_f/1024/1024).round} MB"
  
  return if config[:skip_bootstrap]

  # wait for it to be ready to do stuff
  print "\n#{ui.color("Waiting server... ", :magenta)}"
  timeout = 100
  found = connection.virtual_machines.find { |v| v.name == vm.name }
  loop do 
    if not vm.ip_address.nil? and not vm.ip_address.empty?
      puts "\n#{ui.color("VM IP Address: #{vm.ip_address}", :cyan)}"
      break
    end
    timeout -= 1
    if timeout == 0
      ui.error "Timeout trying to reach the VM. Does it have vmware-tools installed?"
      exit 1
    end
    sleep 1
    found = connection.virtual_machines.find { |v| v.name == vm.name }
  end

  print "\n#{ui.color("Waiting for sshd... ", :magenta)}"
  print(".") until tcp_test_ssh(vm.ip_address) { sleep @initial_sleep_delay ||= 10; puts(" done") }
  bootstrap_for_node(vm).run

  puts "\n"
  puts "#{ui.color("Name", :cyan)}: #{vm.name}"
  puts "#{ui.color("IP Address", :cyan)}: #{vm.ip_address}"
  puts "#{ui.color("Environment", :cyan)}: #{config[:environment] || '_default'}"
  puts "#{ui.color("Run List", :cyan)}: #{config[:run_list].join(', ')}"
  puts "#{ui.color("Done!", :green)}"
end

#tcp_test_ssh(hostname) ⇒ Object



266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
# File 'lib/chef/knife/esx_vm_create.rb', line 266

def tcp_test_ssh(hostname)
  tcp_socket = TCPSocket.new(hostname, 22)
  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 Errno::ETIMEDOUT, Errno::EPERM
  false
rescue Errno::ECONNREFUSED, Errno::EHOSTUNREACH, Errno::ENETUNREACH
  sleep 2
  false
ensure
  tcp_socket && tcp_socket.close
end