Module: Chef::Knife::XapiBase
- Included in:
- XapiGuestCreate, XapiGuestDelete, XapiGuestList, XapiGuestStart, XapiGuestStop, XapiNetList, XapiVdiAttach, XapiVdiCreate, XapiVdiDelete, XapiVdiDetach, XapiVdiList, XapiVlanList
- Defined in:
- lib/chef/knife/xapi_base.rb
Instance Attribute Summary collapse
-
#defaults ⇒ Object
readonly
Returns the value of attribute defaults.
Class Method Summary collapse
- .defaults ⇒ Object
- .get_default(key) ⇒ Object
- .included(includer) ⇒ Object
- .set_defaults(config) ⇒ Object
Instance Method Summary collapse
-
#add_vif_by_name(vm_ref, dev_num, net_name) ⇒ Object
add a new vif.
-
#cleanup(vm_ref) ⇒ Object
destroy/remove VM refs and exit.
-
#clear_vm_vifs(record) ⇒ Object
remove all vifs on a record.
- #color_kv(key, value, color = [:green, :cyan]) ⇒ Object
-
#create_vbd(vm_ref, vdi_ref, position, boot = true) ⇒ Object
create vbd and return a ref defaults to bootable.
-
#create_vdi(name, sr_ref, size) ⇒ Object
create a vdi return ref.
- #destroy_vdi(vdi_ref) ⇒ Object
-
#detach_vdi(vdi_ref) ⇒ Object
detach_vdi.
-
#fail(ref = nil) ⇒ Object
cleanup a vm and exit (fail).
-
#find_default_sr ⇒ Object
returns sr_ref to the default sr on pool.
-
#find_template(template) ⇒ Object
find a template matching what the user provided.
-
#generate_mac ⇒ Object
generate a random mac address.
- #get_all_vdis ⇒ Object
-
#get_guest_ip(vm_ref) ⇒ Object
try to get a guest ip and return it.
- #get_host_ref(hostname) ⇒ Object
-
#get_sr_by_name(name) ⇒ Object
return an SR record from the name_label.
-
#get_sr_by_uuid(uuid) ⇒ Object
return SR record from uuid.
-
#get_task_ref(task) ⇒ Object
return the opaque ref of the task that was run by a task record if it succeded.
-
#get_template(template) ⇒ Object
get template by name_label.
- #get_vbd_by_uuid(id) ⇒ Object
- #get_vbds_from_vdi(vdi_ref) ⇒ Object
- #get_vdi_by_name_label(name) ⇒ Object
- #get_vdi_by_uuid(id) ⇒ Object
- #h ⇒ Object
-
#input_to_bytes(size) ⇒ Object
convert 1g/1m/1t to bytes rounds to whole numbers.
-
#is_uuid?(uuid) ⇒ Boolean
returns true if uuid is a uuid.
- #locate_config_value(key) ⇒ Object
- #print_record(record) ⇒ Object
- #print_vdi_info(vdi) ⇒ Object
- #start(vm_ref, host = nil) ⇒ Object
- #stop(vm_ref) ⇒ Object
-
#user_select(items) ⇒ Object
present a list of options for a user to select return the selected item.
-
#wait_on_task(task) ⇒ Object
sit and wait for taks to exit pending state.
-
#xapi ⇒ Object
setup and return an authed xen api instance.
-
#yes_no?(msg) ⇒ Boolean
return true (yes) false (no) to the asked question.
Instance Attribute Details
#defaults ⇒ Object (readonly)
Returns the value of attribute defaults.
38 39 40 |
# File 'lib/chef/knife/xapi_base.rb', line 38 def defaults @defaults end |
Class Method Details
.defaults ⇒ Object
95 96 97 |
# File 'lib/chef/knife/xapi_base.rb', line 95 def self.defaults @defaults ||= {} end |
.get_default(key) ⇒ Object
99 100 101 |
# File 'lib/chef/knife/xapi_base.rb', line 99 def self.get_default(key) @defaults[key] || nil end |
.included(includer) ⇒ Object
40 41 42 43 44 45 46 47 48 49 50 51 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 79 80 81 82 83 84 85 |
# File 'lib/chef/knife/xapi_base.rb', line 40 def self.included(includer) includer.class_eval do deps do require_relative '../../xenapi/xenapi.rb' require 'highline' require 'highline/import' require 'readline' end option :xapi_host, short: '-h SERVER_URL', long: '--host SERVER_URL', proc: proc { |key| Chef::Config[:knife][:xapi_host] = key }, description: 'The url to the xenserver, http://somehost.local.lan/' option :xapi_password, short: '-K PASSWORD', long: '--xapi-password PASSWORD', proc: proc { |key| Chef::Config[:knife][:xapi_password] = key }, description: 'Your xenserver password' option :xapi_username, short: '-A USERNAME', long: '--xapi-username USERNAME', proc: proc { |key| Chef::Config[:knife][:xapi_username] = key }, description: 'Your xenserver username' option :domain, short: '-f Name', long: '--domain Name', description: 'the domain name for the guest', proc: proc { |key| Chef::Config[:knife][:domain] = key } option :no_color, long: '--no-color', default: false, description: "Don't colorize the output" option :xapi_ssl_verify, long: '--xapi-ssl-verify', default: false, description: "Enable SSL cert verification, Disabled by defaul because xenservers don't ship with proper certs" end end |
.set_defaults(config) ⇒ Object
87 88 89 90 |
# File 'lib/chef/knife/xapi_base.rb', line 87 def self.set_defaults(config) @defaults ||= {} @defaults.merge!(config) end |
Instance Method Details
#add_vif_by_name(vm_ref, dev_num, net_name) ⇒ Object
add a new vif
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 |
# File 'lib/chef/knife/xapi_base.rb', line 250 def add_vif_by_name(vm_ref, dev_num, net_name) Chef::Log.debug "Looking up vif for: #{h.color(net_name, :cyan)}" network_ref = xapi.network.get_by_name_label(net_name).first if network_ref.nil? if net_name =~ /Network (\d)+$/ # special handing for 'Network X' As displayed by XenCenter add_vif_by_name(vm_ref, dev_num, "Pool-wide network associated with eth#{Regexp.last_match[1]}") else ui.warn "#{h.color(net_name, :red)} not found, moving on" end return end mac = generate_mac Chef::Log.debug "Provisioning: #{h.color(net_name, :cyan)}, #{h.color(mac, :green)}, #{h.color(network_ref, :yellow)}" vif = { 'device' => dev_num.to_s, 'network' => network_ref, 'VM' => vm_ref, 'MAC' => generate_mac, 'MTU' => '1500', 'other_config' => {}, 'qos_algorithm_type' => '', 'qos_algorithm_params' => {} } vif_ref = xapi.VIF.create(vif) vif_ref end |
#cleanup(vm_ref) ⇒ Object
destroy/remove VM refs and exit
201 202 203 204 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 231 |
# File 'lib/chef/knife/xapi_base.rb', line 201 def cleanup(vm_ref) # shutdown and dest unless xapi.VM.get_power_state(vm_ref) == 'Halted' ui.msg 'Shutting down Guest' task = xapi.Async.VM.hard_shutdown(vm_ref) get_task_ref(task) unless task == 'Halted' end ui.msg 'Removing disks attached to Guest' Chef::Log.debug "getting vbds attached to #{vm_ref}" wait_tasks = [] xapi.VM.get_VBDs(vm_ref).to_a.each do |vbd| next unless vbd Chef::Log.debug "removing vbd: #{vbd}" wait_tasks << xapi.Async.VDI.destroy(xapi.VBD.get_record(vbd)['VDI']) wait_tasks << xapi.Async.VBD.destroy(vbd) end # wait for disk cleanup to finish up unless wait_tasks.empty? ui.msg 'waiting for disks to cleanup' wait_tasks.each do |task| wait_on_task(task) end end ui.msg 'Destroying Guest' task = xapi.Async.VM.destroy(vm_ref) wait_on_task(task) end |
#clear_vm_vifs(record) ⇒ Object
remove all vifs on a record
280 281 282 283 284 285 |
# File 'lib/chef/knife/xapi_base.rb', line 280 def clear_vm_vifs(record) record['VIFs'].each do |vif| Chef::Log.debug "Removing vif: #{h.color(vif, :red, :bold)}" xapi.VIF.destroy(vif) end end |
#color_kv(key, value, color = [:green, :cyan]) ⇒ Object
469 470 471 472 473 474 |
# File 'lib/chef/knife/xapi_base.rb', line 469 def color_kv(key, value, color = [:green, :cyan]) if config[:no_color] color = [:clear, :clear] end ui.msg "#{h.color(key, color[0])} #{ h.color(value, color[1])}" end |
#create_vbd(vm_ref, vdi_ref, position, boot = true) ⇒ Object
create vbd and return a ref defaults to bootable
384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 |
# File 'lib/chef/knife/xapi_base.rb', line 384 def create_vbd(vm_ref, vdi_ref, position, boot = true) vbd_record = { 'VM' => vm_ref, 'VDI' => vdi_ref, 'empty' => false, 'other_config' => { 'owner' => '' }, 'userdevice' => position.to_s, 'bootable' => boot, 'mode' => 'RW', 'qos_algorithm_type' => '', 'qos_algorithm_params' => {}, 'qos_supported_algorithms' => [], 'type' => 'Disk' } task = xapi.Async.VBD.create(vbd_record) ui.msg 'Waiting for VBD create' vbd_ref = get_task_ref(task) vbd_ref end |
#create_vdi(name, sr_ref, size) ⇒ Object
create a vdi return ref
332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 |
# File 'lib/chef/knife/xapi_base.rb', line 332 def create_vdi(name, sr_ref, size) vdi_record = { 'name_label' => "#{name}", 'name_description' => "Root disk for #{name} created by #{ENV['USER']} with knfie xapi", 'SR' => sr_ref, 'virtual_size' => input_to_bytes(size).to_s, 'type' => 'system', 'sharable' => false, 'read_only' => false, 'other_config' => {} } # Async create the VDI task = xapi.Async.VDI.create(vdi_record) ui.msg 'waiting for VDI Create' vdi_ref = get_task_ref(task) vdi_ref end |
#destroy_vdi(vdi_ref) ⇒ Object
519 520 521 522 523 524 525 526 527 528 529 |
# File 'lib/chef/knife/xapi_base.rb', line 519 def destroy_vdi(vdi_ref) vbds = get_vbds_from_vdi(vdi_ref) unless vbds.empty? detach_vdi(vdi_ref) end task = xapi.Async.VDI.destroy(vdi_ref) print 'Destroying volume ' puts "#{h.color xapi.VDI.get_name_label(vdi_ref), :cyan}" task_ref = get_task_ref(task) task_ref end |
#detach_vdi(vdi_ref) ⇒ Object
detach_vdi
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 |
# File 'lib/chef/knife/xapi_base.rb', line 406 def detach_vdi(vdi_ref) vbd_refs = xapi.VDI.get_VBDs(vdi_ref) # more than one VBD, so we ned to find the vbd with the vdi ref = nil Chef::Log.debug "VBD Refs: #{vbd_refs.inspect}" if vbd_refs.length > 1 vbd_refs.each do |vbd| record = xapi.VBD.get_record vbd Chef::Log.debug "Checking VBD: #{vbd}, #{record['device']}, #{record['VDI']}==#{vdi_ref}" if record['VDI'] == vdi_ref ref = vbd break end end else # if only vbd use it ref = vbd_refs.first end unless ref fail ArgumentError, "We weren't able to find a VBD for that VDI: #{vdi_ref}" end task = xapi.Async.VBD.destroy(ref) ui.msg 'Waiting for VDI detach' task_ref = get_task_ref(task) task_ref end |
#fail(ref = nil) ⇒ Object
cleanup a vm and exit (fail)
234 235 236 237 238 |
# File 'lib/chef/knife/xapi_base.rb', line 234 def fail(ref = nil) ui.warn 'Error encountered clenaing up and exiting' cleanup ref if ref exit 1 end |
#find_default_sr ⇒ Object
returns sr_ref to the default sr on pool
293 294 295 |
# File 'lib/chef/knife/xapi_base.rb', line 293 def find_default_sr xapi.pool.get_default_SR(xapi.pool.get_all[0]) end |
#find_template(template) ⇒ Object
find a template matching what the user provided
returns a ref to the vm or nil if nothing found
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 |
# File 'lib/chef/knife/xapi_base.rb', line 143 def find_template(template) template = locate_config_value(:template_regex) if template.nil? # if we got a string then try to find that template exact # if no exact template matches, search if template.is_a?(String) found = get_template(template) return found if found end # make sure our nil template gets set to default if template.nil? template = locate_config_value(:template_regex) end Chef::Log.debug "Name: #{template.class}" # quick and dirty string to regex unless template.is_a?(Regexp) template = /#{template}/ end # loop over all vm's and find the template # Wish there was a better API method for this, and there might be # but i couldn't find it Chef::Log.debug "Using regex: #{template}" xapi.VM.get_all_records.each_value do |vm| if vm['is_a_template'] && vm['name_label'] =~ template Chef::Log.debug "Matched: #{h.color(vm['name_label'], :yellow)}" found = vm # we're gonna go with the last found end end # ensure return values if found ui.msg "Using Template: #{h.color(found['name_label'], :cyan)}" return get_template(found['name_label']) # get the ref to this one end nil end |
#generate_mac ⇒ Object
generate a random mac address
241 242 243 244 245 246 247 |
# File 'lib/chef/knife/xapi_base.rb', line 241 def generate_mac if locate_config_value(:macaddress).nil? ('%02x' % (rand(64) * 4 | 2)) + (0..4).reduce('') { |s, _x|s + ':%02x' % rand(256) } else locate_config_value(:macaddress) end end |
#get_all_vdis ⇒ Object
457 458 459 |
# File 'lib/chef/knife/xapi_base.rb', line 457 def get_all_vdis xapi.VDI.get_all end |
#get_guest_ip(vm_ref) ⇒ Object
try to get a guest ip and return it
441 442 443 444 445 446 447 448 449 450 451 |
# File 'lib/chef/knife/xapi_base.rb', line 441 def get_guest_ip(vm_ref) guest_ip = 'unknown' vgm = xapi.VM.get_guest_metrics(vm_ref) unless 'OpaqueRef:NULL' == vgm networks = xapi.VM_guest_metrics.get_networks(vgm) if networks.key?('0/ip') guest_ip = networks['0/ip'] end end guest_ip end |
#get_host_ref(hostname) ⇒ Object
531 532 533 534 535 536 537 |
# File 'lib/chef/knife/xapi_base.rb', line 531 def get_host_ref(hostname) xapi.host.get_all.each do |ref| name = xapi.host.get_name_label ref return ref if hostname == name end nil end |
#get_sr_by_name(name) ⇒ Object
return an SR record from the name_label
298 299 300 301 302 303 304 305 |
# File 'lib/chef/knife/xapi_base.rb', line 298 def get_sr_by_name(name) sr_ref = xapi.SR.get_by_name_label(name)[0] if sr_ref.empty? || sr_ref.nil? ui.error "SR name #{h.color(name) } not found" return nil end sr_ref end |
#get_sr_by_uuid(uuid) ⇒ Object
return SR record from uuid
308 309 310 311 312 313 314 315 |
# File 'lib/chef/knife/xapi_base.rb', line 308 def get_sr_by_uuid(uuid) sr_ref = xapi.SR.get_by_uuid(uuid) if sr_ref.empty? || sr_ref.nil? ui.error "SR not found #{h.color(uuid)} " return nil end sr_ref end |
#get_task_ref(task) ⇒ Object
return the opaque ref of the task that was run by a task record if it succeded. else it returns nil
361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 |
# File 'lib/chef/knife/xapi_base.rb', line 361 def get_task_ref(task) Chef::Log.debug "Waiting on task #{task}" wait_on_task(task) status_ = xapi.task.get_status(task) case status_ when 'success' puts "#{h.color "#{status_}", :green }" # xapi task record returns result as <value>OpaqueRef:....</value> # we want the ref. this way it will work if they fix it to return jsut the ref ref = xapi.task.get_result(task).match(/OpaqueRef:[^<]+/).to_s # cleanup our task xapi.task.destroy(task) return ref else ui.msg("#{h.color "#{status_}", :red } ") ui.msg("#{h.color 'ERROR:', :red } #{xapi.task.get_error_info(task)}") end end |
#get_template(template) ⇒ Object
get template by name_label
134 135 136 |
# File 'lib/chef/knife/xapi_base.rb', line 134 def get_template(template) xapi.VM.get_by_name_label(template).first end |
#get_vbd_by_uuid(id) ⇒ Object
436 437 438 |
# File 'lib/chef/knife/xapi_base.rb', line 436 def get_vbd_by_uuid(id) xapi.VBD.get_by_uuid(id) end |
#get_vbds_from_vdi(vdi_ref) ⇒ Object
453 454 455 |
# File 'lib/chef/knife/xapi_base.rb', line 453 def get_vbds_from_vdi(vdi_ref) xapi.VDI.get_VBDs(vdi_ref) end |
#get_vdi_by_name_label(name) ⇒ Object
465 466 467 |
# File 'lib/chef/knife/xapi_base.rb', line 465 def get_vdi_by_name_label(name) xapi.VDI.get_by_name_label(name) end |
#get_vdi_by_uuid(id) ⇒ Object
461 462 463 |
# File 'lib/chef/knife/xapi_base.rb', line 461 def get_vdi_by_uuid(id) xapi.VDI.get_by_uuid(id) end |
#h ⇒ Object
103 104 105 |
# File 'lib/chef/knife/xapi_base.rb', line 103 def h @highline ||= ui.highline end |
#input_to_bytes(size) ⇒ Object
convert 1g/1m/1t to bytes rounds to whole numbers
319 320 321 322 323 324 325 326 327 328 329 |
# File 'lib/chef/knife/xapi_base.rb', line 319 def input_to_bytes(size) case size when /m|mb/i size.to_i * (1024**2) when /t|tb/i size.to_i * (1024**4) else # default is gigabytes size.to_i * (1024**3) end end |
#is_uuid?(uuid) ⇒ Boolean
returns true if uuid is a uuid
288 289 290 |
# File 'lib/chef/knife/xapi_base.rb', line 288 def is_uuid?(uuid) uuid =~ /[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}/i end |
#locate_config_value(key) ⇒ Object
128 129 130 131 |
# File 'lib/chef/knife/xapi_base.rb', line 128 def locate_config_value(key) key = key.to_sym config[key] || Chef::Config[:knife][key] || Chef::Knife::XapiBase.get_default(key) end |
#print_record(record) ⇒ Object
497 498 499 500 |
# File 'lib/chef/knife/xapi_base.rb', line 497 def print_record(record) puts '' PP.pp record end |
#print_vdi_info(vdi) ⇒ Object
476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 |
# File 'lib/chef/knife/xapi_base.rb', line 476 def print_vdi_info(vdi) record = xapi.VDI.get_record vdi color_kv 'VDI Name: ', record['name_label'] color_kv ' UUID: ', record['uuid'], [:magenta, :cyan] color_kv ' Description: ', record['name_description'], [:magenta, :cyan] color_kv ' Type: ', record['type'], [:magenta, :cyan] color_kv ' Size (gb): ', (record['virtual_size'].to_i / (1024**3)).to_s, [:magenta, :cyan] color_kv ' Utilized (gb): ', (record['physical_utilisation'].to_i / (1024**3)).to_s, [:magenta, :cyan] record['VBDs'].each do |vbd| vm = xapi.VBD.get_VM(vbd) color_kv ' VM name: ', xapi.VM.get_name_label(vm) color_kv ' VM state: ', "#{xapi.VM.get_power_state(vm) } \n" end if record['VBDs'].length == 0 ui.msg h.color ' No VM Attached', :red end ui.msg '' end |
#start(vm_ref, host = nil) ⇒ Object
539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 |
# File 'lib/chef/knife/xapi_base.rb', line 539 def start(vm_ref, host = nil) if host host_ref = get_host_ref(host) unless host_ref ui.msg "Host not found #{host}" exit 1 end ui.msg("Starting #{vm_ref} on #{host}") task = xapi.Async.VM.start_on(vm_ref, host_ref, false, true) else ui.msg("Starting #{vm_ref} ") task = xapi.Async.VM.start(vm_ref, false, true) end wait_on_task(task) ui.msg("#{ h.color 'OK!', :green}") end |
#stop(vm_ref) ⇒ Object
556 557 558 559 560 561 |
# File 'lib/chef/knife/xapi_base.rb', line 556 def stop(vm_ref) ui.msg("Stopping #{vm_ref}") task = xapi.Async.VM.clean_shutdown(vm_ref) wait_on_task(task) ui.msg("#{ h.color 'OK!', :green}") end |
#user_select(items) ⇒ Object
present a list of options for a user to select return the selected item
184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 |
# File 'lib/chef/knife/xapi_base.rb', line 184 def user_select(items) h.choose do || .index = :number .prompt = 'Please Choose One:' .select_by = :index_or_name items.each do |item| .choice item.to_sym do |command| ui.msg "Using: #{command}" selected = command.to_s end end .choice :all do return :all end .choice :exit do exit 1 end end end |
#wait_on_task(task) ⇒ Object
sit and wait for taks to exit pending state
352 353 354 355 356 357 |
# File 'lib/chef/knife/xapi_base.rb', line 352 def wait_on_task(task) while xapi.task.get_status(task) == 'pending' xapi.task.get_progress(task) sleep 1 end end |
#xapi ⇒ Object
setup and return an authed xen api instance
108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 |
# File 'lib/chef/knife/xapi_base.rb', line 108 def xapi @xapi ||= begin ui.fatal 'Must provide a xapi host with --host ' unless locate_config_value(:xapi_host) verify = :verify_none verify = :verify_peer if locate_config_value(:xapi_ssl_verify) == true session = XenApi::Client.new(locate_config_value(:xapi_host), 10, verify) # get the password from the user password = locate_config_value(:xapi_password) || nil username = locate_config_value(:xapi_username) || 'root' if password.nil? || password.empty? password = h.ask("Enter password for user #{username}: ") { |input| input.echo = '*' } end session.login_with_password(username, password) session end end |
#yes_no?(msg) ⇒ Boolean
return true (yes) false (no) to the asked question
504 505 506 507 508 509 510 511 512 513 514 515 516 517 |
# File 'lib/chef/knife/xapi_base.rb', line 504 def yes_no?(msg) answer = ui.ask("#{msg} yes/no ? ") do |res| res.case = :down res.validate = /y|n|yes|no/ res.responses[:not_valid] = "Use 'yes', 'no', 'y', 'n':" end case answer when 'y', 'yes' true when 'n', 'no' false end end |