Class: Chef::Knife::XapiGuestCreate

Inherits:
Chef::Knife show all
Includes:
XapiBase
Defined in:
lib/chef/knife/xapi_guest_create.rb

Instance Attribute Summary

Attributes included from XapiBase

#defaults

Instance Method Summary collapse

Methods included from XapiBase

#add_vif_by_name, #cleanup, #clear_vm_vifs, #color_kv, #create_vbd, #create_vdi, defaults, #destroy_vdi, #detach_vdi, #fail, #find_default_sr, #find_template, #generate_mac, #get_all_vdis, get_default, #get_host_ref, #get_sr_by_name, #get_sr_by_uuid, #get_task_ref, #get_template, #get_vbd_by_uuid, #get_vbds_from_vdi, #get_vdi_by_name_label, #get_vdi_by_uuid, #h, included, #input_to_bytes, #is_uuid?, #locate_config_value, #print_record, #print_vdi_info, set_defaults, #start, #stop, #user_select, #wait_on_task, #xapi, #yes_no?

Instance Method Details

#get_guest_ip(vm_ref) ⇒ Object



208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
# File 'lib/chef/knife/xapi_guest_create.rb', line 208

def get_guest_ip(vm_ref)
  timeout(locate_config_value(:ping_timeout).to_i) do
    ui.msg 'Waiting for guest ip address'
    guest_ip = ''
    while guest_ip.empty?
      print('.')
      sleep @initial_sleep_delay ||=  10
      vgm =  xapi.VM.get_guest_metrics(vm_ref)
      next if 'OpaqueRef:NULL' == vgm
      networks = xapi.VM_guest_metrics.get_networks(vgm)
      if networks.key?('0/ip')
        guest_ip = networks['0/ip']
      end
    end
    puts "\n"
    return guest_ip
  end
rescue Timeout::Error
  ui.msg 'Timeout waiting for XAPI to report IP address '
end

#pingable?(guest_ip, timeout = 5) ⇒ Boolean

Returns:

  • (Boolean)


203
204
205
206
# File 'lib/chef/knife/xapi_guest_create.rb', line 203

def pingable?(guest_ip, timeout = 5)
  sleep(20)
  system "ping -c 1 -t #{timeout} #{guest_ip} >/dev/null"
end

#resolve_sr_refObject



230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
# File 'lib/chef/knife/xapi_guest_create.rb', line 230

def resolve_sr_ref
  ui_sr = locate_config_value(:xapi_sr)
  sr_ref = nil
  if locate_config_value(:xapi_sr)
    if is_uuid?(ui_sr)
      sr_ref = get_sr_by_uuid(ui_sr)
    else
      sr_ref = get_sr_by_name(ui_sr)
    end
  else
    sr_ref = find_default_sr
  end

  if sr_ref.nil?
    ui.error "SR specified not found or can't be used Aborting"
    fail(vm_ref) if sr_ref.nil?
  end
  sr_ref
end

#runObject



250
251
252
253
254
255
256
257
258
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
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
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
# File 'lib/chef/knife/xapi_guest_create.rb', line 250

def run
  server_name = @name_args[0]
  domainname = locate_config_value(:domain)
  if domainname.empty?
    fqdn = server_name
  else
    fqdn = "#{server_name}.#{domainname}"
  end

  # get the template vm we are going to build from
  template_ref = find_template(locate_config_value(:xapi_vm_template))
  sr_ref = resolve_sr_ref 

  if locate_config_value(:xapi_sr)
  Chef::Log.debug "Copying Guest from Template: #{h.color(template_ref, :bold, :cyan)}"
    task = xapi.Async.VM.copy(template_ref, fqdn, sr_ref)
  else 
  Chef::Log.debug "Cloning Guest from Template: #{h.color(template_ref, :bold, :cyan)}"
    task = xapi.Async.VM.clone(template_ref, fqdn)
  end

  ui.msg 'Waiting on Template Clone'
  vm_ref = get_task_ref(task)

  Chef::Log.debug "New VM ref: #{vm_ref}"

  # TODO: lift alot of this
  begin
    xapi.VM.set_name_description(vm_ref, "VM from knife-xapi as #{server_name} by #{ENV['USER']}")

    # configure the install repo
    repo = locate_config_value(:install_repo)

    # make sure we don't clobber existing params
    other_config = {}
    record = xapi.VM.get_record(vm_ref)
    if record.key? 'other_config'
      other_config = record['other_config']
    end
    other_config['install-repository'] = repo
   
    # remove any disk config/xml template might be trying to do (ubuntu)
    other_config.delete_if {|k,v| k=="disks"} 

    Chef::Log.debug "Other_config: #{other_config.inspect}"
    xapi.VM.set_other_config(vm_ref, other_config)

    cpus = locate_config_value(:xapi_cpus).to_s

    xapi.VM.set_VCPUs_max(vm_ref, cpus)
    xapi.VM.set_VCPUs_at_startup(vm_ref, cpus)

    memory_size = input_to_bytes(locate_config_value(:xapi_mem)).to_s
    #  static-min <= dynamic-min = dynamic-max = static-max
    xapi.VM.set_memory_limits(vm_ref, memory_size, memory_size, memory_size, memory_size)

    #
    # setup the Boot args
    #
    boot_args = locate_config_value(:kernel_params)

    # if no hostname param set hostname to given vm name
    boot_args << " hostname=#{server_name}" unless boot_args.match(/hostname=.+\s?/)
    # if domainname is supplied we put that in there as well
    # ubuntu/debian wants domain rhat wants dnsdomain
    boot_args << " domain=#{domainname}" unless boot_args.match(/domain=.+\s?/)
    boot_args << " dnsdomain=#{domainname}" unless boot_args.match(/dnsdomain=.+\s?/)

    xapi.VM.set_PV_args(vm_ref, boot_args)

    # TODO: validate that the vm gets a network here
    networks = @name_args[1..-1]
    # if the user has provided networks
    if networks.length >= 1
      clear_vm_vifs(xapi.VM.get_record(vm_ref))
      networks.each_with_index do |net, index|
        add_vif_by_name(vm_ref, index, net)
      end
    end

    Chef::Log.debug "SR: #{h.color sr_ref, :cyan}"

    unless locate_config_value(:xapi_skip_disk)
      disk_size = locate_config_value(:xapi_disk_size)
      # setup disks
      if !disk_size.nil? && disk_size.to_i > 0
        # when a template already has disks, we decide the position number based on it.
        position = xapi.VM.get_VBDs(vm_ref).length

        # Create the VDI
        vdi_ref = create_vdi("#{server_name}-root", sr_ref, locate_config_value(:xapi_disk_size))
        fail(vm_ref) unless vdi_ref

        # Attach the VDI to the VM
        # if its position is 0 set it bootable
        position == 0 ?  bootable = true : bootable = false

        vbd_ref = create_vbd(vm_ref, vdi_ref, position, bootable)
        fail(vm_ref) unless vbd_ref
      end
    end

    ui.msg "Provisioning new Guest: #{h.color(fqdn, :bold, :cyan)}"
    ui.msg "Boot Args: #{h.color boot_args, :bold, :cyan}"
    ui.msg "Install Repo: #{ h.color(repo, :bold, :cyan)}"
    ui.msg "Memory: #{ h.color(locate_config_value(:xapi_mem).to_s, :bold, :cyan)}"
    ui.msg "CPUs:   #{ h.color(locate_config_value(:xapi_cpus).to_s, :bold, :cyan)}"
    ui.msg "Disk:   #{ h.color(disk_size.to_s, :bold, :cyan)}"
    provisioned = xapi.VM.provision(vm_ref)

    ui.msg "Starting new Guest #{h.color(provisioned, :cyan)} "
    start(vm_ref)

    exit 0 unless locate_config_value(:run_list)
  rescue => e
    ui.msg "#{h.color 'ERROR:'} #{h.color(e.message, :red)}"
    # have to use join here to pass a string to highline
    puts 'Nested backtrace:'
    ui.msg "#{h.color(e.backtrace.join("\n"), :yellow)}"
    raise(vm_ref)
  end

  if locate_config_value(:run_list).empty?
    unless locate_config_value(:template_file) or
           locate_config_value(:bootstrap_template) != 'chef-full' 
      exit 0
    end
  end

  guest_addr = wait_for_guest_ip(vm_ref)
  if guest_addr.nil? || guest_addr.empty?
    ui.msg('ip seems wrong using host+domain name instead')
    guest_addr = "#{server_name}.#{domainname}"
  end
  ui.msg "Trying to connect to guest @ #{guest_addr} "

  begin
    timeout(480) do
      print('.') until tcp_test_ssh(guest_addr) do
        sleep @initial_sleep_delay ||=  10
        ui.msg("#{ h.color 'OK!', :green}")
      end
    end
  rescue Timeout::Error
    ui.msg 'Timeout trying to login Wont bootstrap'
    raise
  end

  begin
    bootstrap = Chef::Knife::Bootstrap.new
    bootstrap.name_args = [guest_addr]
    bootstrap.config[:run_list] = locate_config_value(:run_list)
    bootstrap.config[:ssh_user] = locate_config_value(:ssh_user)
    bootstrap.config[:ssh_port] = locate_config_value(:ssh_port)
    bootstrap.config[:ssh_password] = locate_config_value(:ssh_password)
    bootstrap.config[:identity_file] = locate_config_value(:identity_file)
    bootstrap.config[:chef_node_name] = config[:chef_node_name] || fqdn
    bootstrap.config[:bootstrap_version] = locate_config_value(:bootstrap_version)
    bootstrap.config[:first_boot_attributes] = locate_config_value(:json_attributes)
    bootstrap.config[:distro] = locate_config_value(:bootstrap_template)
    bootstrap.config[:use_sudo] = true unless locate_config_value(:ssh_user) == 'root'
    bootstrap.config[:template_file] = locate_config_value(:template_file)
    bootstrap.config[:environment] = config[:environment]
    bootstrap.config[:host_key_verify] = false
    bootstrap.config[:run_list] = locate_config_value(:run_list)

    bootstrap.run
  rescue => e
    ui.msg "#{h.color 'ERROR:'} #{h.color(e.message, :red)}"
    puts 'Nested backtrace:'
    ui.msg "#{h.color(e.backtrace.join("\n"), :yellow)}"
    raise
  end
end

#tcp_test_ssh(hostname) ⇒ Object



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

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

#wait_for_guest_ip(vm_ref) ⇒ Object



190
191
192
193
194
195
196
197
198
199
200
201
# File 'lib/chef/knife/xapi_guest_create.rb', line 190

def wait_for_guest_ip(vm_ref)
  guest_ip = get_guest_ip(vm_ref)
  if pingable?(guest_ip)
    ui.msg "found guest_ip = #{guest_ip}"
    return guest_ip
  else
    ui.msg "#{guest_ip} is not pingable, trying to get guest ip again"
    guest_ip = get_guest_ip(vm_ref)
    ui.msg "found guest_ip = #{guest_ip}"
    return guest_ip
  end
end