Class: Vbox::Session
- Inherits:
-
Object
- Object
- Vbox::Session
- Defined in:
- lib/vbox/session.rb
Instance Attribute Summary collapse
-
#definition ⇒ Object
Returns the value of attribute definition.
-
#definition_dir ⇒ Object
Returns the value of attribute definition_dir.
-
#iso_dir ⇒ Object
Returns the value of attribute iso_dir.
-
#name ⇒ Object
Returns the value of attribute name.
-
#template_dir ⇒ Object
Returns the value of attribute template_dir.
-
#vbox_dir ⇒ Object
Returns the value of attribute vbox_dir.
Class Method Summary collapse
- .add_ide_controller(boxname) ⇒ Object
- .add_sata_controller(boxname) ⇒ Object
- .add_ssh_nat_mapping(boxname) ⇒ Object
- .attach_disk(boxname) ⇒ Object
- .build(boxname, options) ⇒ Object
- .calculate_checksums(definition, boxname) ⇒ Object
- .clean ⇒ Object
- .create_disk(boxname) ⇒ Object
- .create_vm(boxname, force = false) ⇒ Object
- .declare(options) ⇒ Object
- .define(boxname, template_name, options = {}) ⇒ Object
- .definition_exists?(boxname) ⇒ Boolean
- .destroy_vm(boxname) ⇒ Object
- .determine_vboxcmd ⇒ Object
- .download_progress(url, localfile) ⇒ Object
- .export_box(boxname) ⇒ Object
- .list_boxes ⇒ Object
- .list_definitions ⇒ Object
- .list_ostypes ⇒ Object
- .list_templates(options = { :format => 'vagrant'}) ⇒ Object
- .load_definition(boxname) ⇒ Object
- .local_ip ⇒ Object
- .mount_isofile(boxname, isofile) ⇒ Object
- .remove_box(boxname) ⇒ Object
- .setenv(env) ⇒ Object
- .start_vm(boxname, mode) ⇒ Object
- .suppress_messages ⇒ Object
- .transaction(boxname, step_name, checksums, &block) ⇒ Object
- .undefine(boxname) ⇒ Object
- .validate_box(boxname, options) ⇒ Object
- .verify_iso(filename, autodownload = false) ⇒ Object
Instance Attribute Details
#definition ⇒ Object
Returns the value of attribute definition.
19 20 21 |
# File 'lib/vbox/session.rb', line 19 def definition @definition end |
#definition_dir ⇒ Object
Returns the value of attribute definition_dir.
15 16 17 |
# File 'lib/vbox/session.rb', line 15 def definition_dir @definition_dir end |
#iso_dir ⇒ Object
Returns the value of attribute iso_dir.
17 18 19 |
# File 'lib/vbox/session.rb', line 17 def iso_dir @iso_dir end |
#name ⇒ Object
Returns the value of attribute name.
18 19 20 |
# File 'lib/vbox/session.rb', line 18 def name @name end |
#template_dir ⇒ Object
Returns the value of attribute template_dir.
16 17 18 |
# File 'lib/vbox/session.rb', line 16 def template_dir @template_dir end |
#vbox_dir ⇒ Object
Returns the value of attribute vbox_dir.
14 15 16 |
# File 'lib/vbox/session.rb', line 14 def vbox_dir @vbox_dir end |
Class Method Details
.add_ide_controller(boxname) ⇒ Object
636 637 638 639 640 |
# File 'lib/vbox/session.rb', line 636 def self.add_ide_controller(boxname) #unless => "${vboxcmd} showvminfo '${vname}' | grep 'IDE Controller' " command ="#{@vboxcmd} storagectl '#{boxname}' --name 'IDE Controller' --add ide" Vbox::Shell.execute("#{command}") end |
.add_sata_controller(boxname) ⇒ Object
642 643 644 645 646 |
# File 'lib/vbox/session.rb', line 642 def self.add_sata_controller(boxname) #unless => "${vboxcmd} showvminfo '${vname}' | grep 'SATA Controller' "; command ="#{@vboxcmd} storagectl '#{boxname}' --name 'SATA Controller' --add sata --sataportcount 1 --hostiocache #{@definition[:hostiocache]}" Vbox::Shell.execute("#{command}") end |
.add_ssh_nat_mapping(boxname) ⇒ Object
406 407 408 409 410 411 412 413 414 415 416 417 |
# File 'lib/vbox/session.rb', line 406 def self.add_ssh_nat_mapping(boxname) vm=VirtualBox::VM.find(boxname) #Map SSH Ports # command => "${vboxcmd} modifyvm '${vname}' --natpf1 'guestssh,tcp,,${hostsshport},,${guestsshport}'", port = VirtualBox::NATForwardedPort.new port.name = "guestssh" port.guestport = @definition[:ssh_guest_port].to_i port.hostport = @definition[:ssh_host_port].to_i vm.network_adapters[0].nat_driver.forwarded_ports << port port.save vm.save end |
.attach_disk(boxname) ⇒ Object
648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 |
# File 'lib/vbox/session.rb', line 648 def self.attach_disk(boxname) location=boxname+"."+@definition[:disk_format].downcase @vboxcmd=determine_vboxcmd command="#{@vboxcmd} list systemproperties|grep '^Default machine'|cut -d ':' -f 2|sed -e 's/^[ ]*//'" results=IO.popen("#{command}") place=results.gets.chop results.close location="#{place}/#{boxname}/"+location puts "Attaching disk: #{location}" #command => "${vboxcmd} storageattach '${vname}' --storagectl 'SATA Controller' --port 0 --device 0 --type hdd --medium '${vname}.vdi'", command ="#{@vboxcmd} storageattach '#{boxname}' --storagectl 'SATA Controller' --port 0 --device 0 --type hdd --medium '#{location}'" Vbox::Shell.execute("#{command}") end |
.build(boxname, options) ⇒ Object
222 223 224 225 226 227 228 229 230 231 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 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 |
# File 'lib/vbox/session.rb', line 222 def self.build(boxname,) = { "force" => false, "format" => "vagrant", "nogui" => false }.merge() #Now we have to load the definition (reads definition.rb) load_definition(boxname) #Command to execute locally @vboxcmd=determine_vboxcmd ={ :user => @definition[:ssh_user], :port => @definition[:ssh_host_port], :password => @definition[:ssh_password], :timeout => @definition[:ssh_timeout]} #Suppress those annoying virtualbox messages vm=VirtualBox::VM.find(boxname) if (!vm.nil? && (vm.saved?)) puts "Removing save state" vm.discard_state vm.reload end if (!vm.nil? && !(vm.powered_off?)) puts "Shutting down vm #{boxname}" #We force it here, maybe vm.shutdown is cleaner begin vm.stop rescue VirtualBox::Exceptions::InvalidVMStateException puts "There was problem sending the stop command because the machine is in an Invalid state" puts "Please verify leftovers from a previous build in your vm folder" exit end sleep 3 end verify_iso(@definition[:iso_file]) if (["force"]==false) else puts "Forcing build by destroying #{boxname} machine" destroy_vm(boxname) end if Vbox::Utils.is_port_open?("localhost", @definition[:ssh_host_port]) puts "Hmm, the port #{@definition[:ssh_host_port]} is open. And we shut down?" exit end checksums=calculate_checksums(@definition,boxname) transaction(boxname,"0-initial-#{checksums[0]}",checksums) do #Create the Virtualmachine and set all the memory and other stuff create_vm(boxname) #Create a disk with the same name as the boxname create_disk(boxname) #These command actually call the commandline of Virtualbox, I hope to use the virtualbox-ruby library in the future add_ide_controller(boxname) add_sata_controller(boxname) attach_disk(boxname) mount_isofile(boxname,@definition[:iso_file]) add_ssh_nat_mapping(boxname) #Starting machine if (["nogui"]==true) start_vm(boxname,"vrdp") else start_vm(boxname,"gui") end #waiting for it to boot puts "Waiting for the machine to boot" sleep @definition[:boot_wait].to_i Vbox::Scancode.send_sequence("#{@vboxcmd}","#{boxname}",@definition[:boot_cmd_sequence],@definition[:kickstart_port]) kickstartfile=@definition[:kickstart_file] if kickstartfile.nil? || kickstartfile.length == 0 puts "Skipping webserver as no kickstartfile was specified" else puts "Starting a webserver on port #{@definition[:kickstart_port]}" #:kickstart_port => "7122", :kickstart_ip => self.local_ip, :kickstart_timeout => 1000,:kickstart_file => "preseed.cfg", if kickstartfile.is_a? String Vbox::Web.wait_for_request(kickstartfile,{:port => @definition[:kickstart_port], :host => @definition[:kickstart_ip], :timeout => @definition[:kickstart_timeout], :web_dir => File.join(@definition_dir,boxname)}) end if kickstartfile.is_a? Array kickstartfiles=kickstartfile kickstartfiles.each do |kickfile| Vbox::Web.wait_for_request(kickfile,{:port => @definition[:kickstart_port], :host => @definition[:kickstart_ip], :timeout => @definition[:kickstart_timeout], :web_dir => File.join(@definition_dir,boxname)}) end end end Vbox::Ssh.when_ssh_login_works("localhost",) do #Transfer version of Virtualbox to $HOME/.vbox_version versionfile=Tempfile.open("vbox.version") versionfile.puts "#{VirtualBox::Global.global.lib.virtualbox.version.split('_')[0]}" versionfile.rewind begin Vbox::Ssh.transfer_file("localhost",versionfile.path,".vbox_version", ) rescue RuntimeError puts "error transfering file, possible not enough permissions to write?" exit end puts "" versionfile.close versionfile.delete end end #initial Transaction counter=1 @definition[:postinstall_files].each do |postinstall_file| filename=File.join(@definition_dir,boxname,postinstall_file) transaction(boxname,"#{counter}-#{postinstall_file}-#{checksums[counter]}",checksums) do Vbox::Ssh.when_ssh_login_works("localhost",) do begin Vbox::Ssh.transfer_file("localhost",filename,File.basename(filename),) rescue RuntimeError puts "error transferring file, possible not enough permissions to write?" exit end command=@definition[:sudo_cmd] newcommand=command.gsub(/%p/,"#{@definition[:ssh_password]}") newcommand.gsub!(/%u/,"#{@definition[:ssh_user]}") newcommand.gsub!(/%f/,"#{postinstall_file}") puts "***#{newcommand}" Vbox::Ssh.execute("localhost","#{newcommand}",) end end counter+=1 end puts "#{boxname} was built successfully. " puts "" puts "Now you can: " puts "- verify your box by running : vagrant vbox validate #{boxname}" puts "- export your vm to a .box file by running : vagrant vbox export #{boxname}" end |
.calculate_checksums(definition, boxname) ⇒ Object
732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 |
# File 'lib/vbox/session.rb', line 732 def self.calculate_checksums(definition,boxname) #TODO: get rid of definitiondir and so one initial=definition.clone keys=[:postinstall_files,:sudo_cmd,:postinstall_timeout] keys.each do |key| initial.delete(key) end checksums=Array.new checksums << Digest::MD5.hexdigest(initial.to_s) postinstall_files=definition[:postinstall_files] unless postinstall_files.nil? for filename in postinstall_files begin full_filename=File.join(@definition_dir,boxname,filename) checksums << Digest::MD5.hexdigest(File.read(full_filename)) rescue puts "Error reading postinstall file #{filename} - checksum" exit end end end return checksums end |
.clean ⇒ Object
153 154 155 |
# File 'lib/vbox/session.rb', line 153 def self.clean puts "Not yet implemented" end |
.create_disk(boxname) ⇒ Object
595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 |
# File 'lib/vbox/session.rb', line 595 def self.create_disk(boxname) #Now check the disks #Maybe one day we can use the name, now we have to check location #disk=VirtualBox::HardDrive.find(boxname) location=boxname+"."+@definition[:disk_format].downcase found=false VirtualBox::HardDrive.all.each do |d| if !d.location.match(/#{location}/).nil? found=true break end end @vboxcmd=determine_vboxcmd if !found puts "Creating new harddrive of size #{@definition[:disk_size].to_i} " #newdisk=VirtualBox::HardDrive.new #newdisk.format=@definition[:disk_format] #newdisk.logical_size=@definition[:disk_size].to_i #newdisk.location=location ##PDB: again problems with the virtualbox GEM ##VirtualBox::Global.global.max_vdi_size=1000000 #newdisk.save command="#{@vboxcmd} list systemproperties|grep '^Default machine'|cut -d ':' -f 2|sed -e 's/^[ ]*//'" results=IO.popen("#{command}") place=results.gets.chop results.close command ="#{@vboxcmd} createhd --filename '#{place}/#{boxname}/#{boxname}.#{@definition[:disk_format].downcase}' --size '#{@definition[:disk_size].to_i}' --format #{@definition[:disk_format].downcase} > /dev/null" puts "#{command}" Vbox::Shell.execute("#{command}") end end |
.create_vm(boxname, force = false) ⇒ Object
486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 |
# File 'lib/vbox/session.rb', line 486 def self.create_vm(boxname,force=false) #Verifying the os.id with the :os_type_id specified matchfound=false VirtualBox::Global.global.lib.virtualbox.guest_os_types.collect { |os| if @definition[:os_type_id] == os.id matchfound=true end } unless matchfound puts "The ostype: #{@definition[:os_type_id]} is not available in your Virtualbox version" exit end vm=VirtualBox::VM.find(boxname) if (!vm.nil? && !(vm.powered_off?)) puts "shutting down box" #We force it here, maybe vm.shutdown is cleaner vm.stop end if !vm.nil? puts "Box already exists" #vm.stop #vm.destroy else #TODO One day ruby-virtualbox will be able to handle this creation #Box does not exist, we can start to create it command="#{@vboxcmd} createvm --name '#{boxname}' --ostype '#{@definition[:os_type_id]}' --register" #Exec and system stop the execution here Vbox::Shell.execute("#{command}") # Modify the vm to enable or disable hw virtualization extensions vm_flags=%w{pagefusion acpi ioapic pae hpet hwvirtex hwvirtexcl nestedpaging largepages vtxvpid synthxcpu rtcuseutc} vm_flags.each do |vm_flag| unless @definition[vm_flag.to_sym].nil? puts "Setting VM Flag #{vm_flag} to #{@definition[vm_flag.to_sym]}" command="#{@vboxcmd} modifyvm #{boxname} --#{vm_flag.to_s} #{@definition[vm_flag.to_sym]}" Vbox::Shell.execute("#{command}") end end # Todo Check for java # Todo check output of commands # Check for floppy unless @definition[:floppy_files].nil? require 'tmpdir' temp_dir=Dir.tmpdir @definition[:floppy_files].each do |filename| full_filename=full_filename=File.join(@definition_dir,boxname,filename) FileUtils.cp("#{full_filename}","#{temp_dir}") end javacode_dir=File.(File.join(__FILE__,'..','..','java')) floppy_file=File.join(@definition_dir,boxname,"virtualfloppy.vfd") command="java -jar #{javacode_dir}/dir2floppy.jar '#{temp_dir}' '#{floppy_file}'" puts "#{command}" Vbox::Shell.execute("#{command}") # Create floppy controller command="#{@vboxcmd} storagectl '#{boxname}' --name 'Floppy Controller' --add floppy" puts "#{command}" Vbox::Shell.execute("#{command}") # Attach floppy to machine (the vfd extension is crucial to detect msdos type floppy) command="#{@vboxcmd} storageattach '#{boxname}' --storagectl 'Floppy Controller' --port 0 --device 0 --type fdd --medium '#{floppy_file}'" puts "#{command}" Vbox::Shell.execute("#{command}") end #Exec and system stop the execution here Vbox::Shell.execute("#{command}") command="#{@vboxcmd} sharedfolder add '#{boxname}' --name 'vbox-validation' --hostpath '#{File.(@validation_dir)}' --automount" Vbox::Shell.execute("#{command}") end vm=VirtualBox::VM.find(boxname) if vm.nil? puts "we tried to create a box or a box was here before" puts "but now it's gone" exit end #Set all params we know vm.memory_size=@definition[:memory_size].to_i vm.os_type_id=@definition[:os_type_id] vm.cpu_count=@definition[:cpu_count].to_i vm.name=boxname puts "Creating vm #{vm.name} : #{vm.memory_size}M - #{vm.cpu_count} CPU - #{vm.os_type_id}" #setting bootorder vm.boot_order[0]=:hard_disk vm.boot_order[1]=:dvd vm.boot_order[2]=:null vm.boot_order[3]=:null vm.validate vm.save end |
.declare(options) ⇒ Object
31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 |
# File 'lib/vbox/session.rb', line 31 def self.declare() defaults={ :cpu_count => '1', :memory_size=> '256', :disk_size => '10240', :disk_format => 'VDI', :hostiocache => 'off' , :os_type_id => 'Ubuntu', :iso_file => "ubuntu-10.10-server-i386.iso", :iso_src => "", :iso_md5 => "", :iso_download_timeout => 1000, :boot_wait => "10", :boot_cmd_sequence => [ "boot"], :kickstart_port => "7122", :kickstart_ip => self.local_ip, :kickstart_timeout => 10000, :ssh_login_timeout => "100", :ssh_user => "vagrant", :ssh_password => "vagrant", :ssh_key => "", :ssh_host_port => "2222", :ssh_guest_port => "22", :sudo_cmd => "echo '%p'|sudo -S sh '%f'", :shutdown_cmd => "shutdown -h now", :postinstall_files => [ "postinstall.sh"], :postinstall_timeout => 10000} @definition=defaults.merge() end |
.define(boxname, template_name, options = {}) ⇒ Object
62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 |
# File 'lib/vbox/session.rb', line 62 def self.define(boxname,template_name, = {}) #Check if template_name exists = { "force" => false, "format" => "vagrant" }.merge() if File.directory?(File.join(@template_dir,template_name)) else puts "This template can not be found, use vagrant vbox templates to list all templates" exit end if !File.exists?(@definition_dir) FileUtils.mkdir(@definition_dir) end if File.directory?(File.join(@definition_dir,boxname)) if !["force"] puts "The definition for #{boxname} already exists. Use --force to overwrite" exit end else FileUtils.mkdir(File.join(@definition_dir,boxname)) end FileUtils.cp_r(File.join(@template_dir,template_name,'.'),File.join(@definition_dir,boxname)) puts "The vbox '#{boxname}' has been successfully created from the template ''#{template_name}'" puts "You can now edit the definition files stored in definitions/#{boxname}" puts "or build the box with:" if (["format"]=='vagrant') puts "vagrant vbox build '#{boxname}'" end if (["format"]=='vbox') puts "vbox build '#{boxname}'" end end |
.definition_exists?(boxname) ⇒ Boolean
97 98 99 100 101 102 103 104 105 106 107 108 |
# File 'lib/vbox/session.rb', line 97 def self.definition_exists?(boxname) if File.directory?(File.join(@definition_dir,boxname)) if File.exists?(File.join(@definition_dir,boxname,'definition.rb')) return true else return false end else return false end end |
.destroy_vm(boxname) ⇒ Object
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 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 |
# File 'lib/vbox/session.rb', line 419 def self.destroy_vm(boxname) load_definition(boxname) @vboxcmd=determine_vboxcmd #:destroy_medium => :delete, will delete machine + all media attachments #vm.destroy(:destroy_medium => :delete) ##vm.destroy(:destroy_image => true) #VBoxManage unregistervm "test-machine" --delete #because the destroy does remove the .vbox file on 4.0.x #PDB #vm.destroy() vm=VirtualBox::VM.find(boxname) if (!vm.nil? && !(vm.powered_off?)) puts "Shutting down vm #{boxname}" #We force it here, maybe vm.shutdown is cleaner begin vm.stop rescue VirtualBox::Exceptions::InvalidVMStateException puts "There was problem sending the stop command because the machine is in an Invalid state" puts "Please verify leftovers from a previous build in your vm folder" exit end sleep 3 end command="#{@vboxcmd} unregistervm '#{boxname}' --delete" puts command puts "Deleting vm #{boxname}" #Exec and system stop the execution here Vbox::Shell.execute("#{command}") sleep 1 #if the disk was not attached when the machine was destroyed we also need to delete the disk location=boxname+"."+@definition[:disk_format].downcase found=false VirtualBox::HardDrive.all.each do |d| if d.location.match(/#{location}/) if File.exists?(d.location) command="#{@vboxcmd} closemedium disk '#{d.location}' --delete" else command="#{@vboxcmd} closemedium disk '#{d.location}'" end #command="#{@vboxcmd} closemedium disk '#{d.location}' --delete" puts "Deleting disk #{d.location}" puts "#{command}" Vbox::Shell.execute("#{command}") if File.exists?(d.location) puts "We tried to delete the disk file via virtualbox '#{d.location} but failed" puts "Removing it manually" FileUtils.rm(d.location) exit end #v.3 #d.destroy(true) break end end end |
.determine_vboxcmd ⇒ Object
380 381 382 |
# File 'lib/vbox/session.rb', line 380 def self.determine_vboxcmd return "VBoxManage" end |
.download_progress(url, localfile) ⇒ Object
763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 |
# File 'lib/vbox/session.rb', line 763 def self.download_progress(url,localfile) = nil URI.parse(url).open( :content_length_proc => lambda {|t| if t && 0 < t = ProgressBar.new("Fetching file", t) .file_transfer_mode end }, :progress_proc => lambda {|s| .set s if }) { |src| open("#{localfile}","wb") { |dst| dst.write(src.read) } } end |
.export_box(boxname) ⇒ Object
207 208 209 210 211 212 213 214 215 216 |
# File 'lib/vbox/session.rb', line 207 def self.export_box(boxname) #Now we have to load the definition (reads definition.rb) load_definition(boxname) Vbox::Export.vagrant(boxname,@box_dir,@definition) #vagrant removes the mapping #we need to restore it in order to be able to login again add_ssh_nat_mapping(boxname) end |
.list_boxes ⇒ Object
141 142 143 |
# File 'lib/vbox/session.rb', line 141 def self.list_boxes puts "Not yet implemented" end |
.list_definitions ⇒ Object
145 146 147 148 149 150 151 |
# File 'lib/vbox/session.rb', line 145 def self.list_definitions puts "The following defined vboxes exist:" subdirs=Dir.glob("#{@definition_dir}/*") subdirs.each do |sub| puts "- "+File.basename(sub) end end |
.list_ostypes ⇒ Object
724 725 726 727 728 729 730 |
# File 'lib/vbox/session.rb', line 724 def self.list_ostypes puts puts "Available os types:" VirtualBox::Global.global.lib.virtualbox.guest_os_types.collect { |os| puts "#{os.id}: #{os.description}" } end |
.list_templates(options = { :format => 'vagrant'}) ⇒ Object
122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 |
# File 'lib/vbox/session.rb', line 122 def self.list_templates( = { :format => 'vagrant'}) puts "The following templates are available:" subdirs=Dir.glob("#{@template_dir}/*").sort_by {|f| File.basename f} subdirs.each do |sub| if File.directory?("#{sub}") definition=Dir.glob("#{sub}/definition.rb") if definition.length!=0 name=sub.sub(/#{@template_dir}\//,'') if ([:format]=='vagrant') puts "vagrant vbox define '<boxname>' '#{name}'" end if ([:format]=='vbox') puts "vbox define '<boxname>' '#{name}'" end end end end end |
.load_definition(boxname) ⇒ Object
389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 |
# File 'lib/vbox/session.rb', line 389 def self.load_definition(boxname) if definition_exists?(boxname) definition_file=File.join(@definition_dir,boxname,"definition.rb") begin require definition_file rescue LoadError puts "Error loading definition of #{boxname}" exit end else puts "Error: definition for vbox '#{boxname}' does not exist." list_definitions exit end end |
.local_ip ⇒ Object
687 688 689 690 691 692 693 694 695 696 |
# File 'lib/vbox/session.rb', line 687 def self.local_ip orig, Socket.do_not_reverse_lookup = Socket.do_not_reverse_lookup, true # turn off reverse DNS resolution temporarily UDPSocket.open do |s| s.connect '64.233.187.99', 1 s.addr.last end ensure Socket.do_not_reverse_lookup = orig end |
.mount_isofile(boxname, isofile) ⇒ Object
667 668 669 670 671 672 673 |
# File 'lib/vbox/session.rb', line 667 def self.mount_isofile(boxname,isofile) full_iso_file=File.join(@iso_dir,isofile) puts "Mounting cdrom: #{full_iso_file}" #command => "${vboxcmd} storageattach '${vname}' --storagectl 'IDE Controller' --type dvddrive --port 1 --device 0 --medium '${isodst}' "; command ="#{@vboxcmd} storageattach '#{boxname}' --storagectl 'IDE Controller' --type dvddrive --port 1 --device 0 --medium '#{full_iso_file}'" Vbox::Shell.execute("#{command}") end |
.remove_box(boxname) ⇒ Object
218 219 220 |
# File 'lib/vbox/session.rb', line 218 def self.remove_box(boxname) puts "Not yet implemented" end |
.setenv(env) ⇒ Object
21 22 23 24 25 26 27 28 29 |
# File 'lib/vbox/session.rb', line 21 def self.setenv(env) @vbox_dir=env[:vbox_dir] @definition_dir=env[:definition_dir] @template_dir=env[:template_dir] @validation_dir=env[:validation_dir] @box_dir=env[:box_dir] @iso_dir=env[:iso_dir] @tmp_dir=env[:tmp_dir] end |
.start_vm(boxname, mode) ⇒ Object
384 385 386 387 |
# File 'lib/vbox/session.rb', line 384 def self.start_vm(boxname,mode) vm=VirtualBox::VM.find(boxname) vm.start(mode) end |
.suppress_messages ⇒ Object
675 676 677 678 679 680 681 682 683 684 685 |
# File 'lib/vbox/session.rb', line 675 def self. #Setting this annoying messages to register VirtualBox::ExtraData.global["GUI/RegistrationData"]="triesLeft=0" VirtualBox::ExtraData.global["GUI/UpdateDate"]="1 d, 2009-09-20" VirtualBox::ExtraData.global["GUI/SuppressMessages"]="confirmInputCapture,remindAboutAutoCapture,remindAboutMouseIntegrationOff" VirtualBox::ExtraData.global["GUI/UpdateCheckCount"]="60" update_date=Time.now+86400 VirtualBox::ExtraData.global["GUI/UpdateDate"]="1 d, #{update_date.year}-#{update_date.month}-#{update_date.day}, stable" VirtualBox::ExtraData.global.save end |
.transaction(boxname, step_name, checksums, &block) ⇒ Object
782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 |
# File 'lib/vbox/session.rb', line 782 def self.transaction(boxname,step_name,checksums,&block) current_step_nr=step_name.split("-")[0].to_i vm=VirtualBox::VM.find(boxname) snapnames=Array.new #If vm exists , look for snapshots if !vm.nil? start_snapshot=vm.root_snapshot snapshot=start_snapshot counter=0 while (snapshot!=nil) #puts "#{counter}:#{snapshot.name}" snapnames[counter]=snapshot.name counter=counter+1 snapshot=snapshot.children[0] end end #find the last snapshot matching the state counter=[snapnames.length, checksums.length].min-1 last_good_state=counter for c in 0..counter do #puts "#{c}- #{snapnames[c]} - #{checksums[c]}" if !snapnames[c].match("#{c}.*-#{checksums[c]}") # puts "we found a bad state" last_good_state=c-1 break end end #puts "Last good state: #{last_good_state}" if (current_step_nr < last_good_state) #puts "fast forwarding #{step_name}" return end #puts "Current step: #{current_step_nr}" if (current_step_nr == last_good_state) if vm.running? vm.stop end #invalidate later snapshots #puts "remove old snapshots" for s in (last_good_state+1)..(snapnames.length-1) puts "Removing step [#{s}] snapshot as it is no more valid" snapshot=vm.find_snapshot(snapnames[s]) snapshot.destroy #puts snapshot end vm.reload puts "Loading step #{current_step_nr} snapshots as it has not changed" sleep 2 goodsnap=vm.find_snapshot(snapnames[last_good_state]) goodsnap.restore sleep 2 #TODO:Restore snapshot!!! vm.start sleep 4 puts "Starting machine" end #puts "last good state #{last_good_state}" if (current_step_nr > last_good_state) if (last_good_state==-1) #no initial snapshot is found, clean machine! vm=VirtualBox::VM.find(boxname) if !vm.nil? if vm.running? puts "Stopping machine" vm.stop while vm.running? sleep 1 end end vm.reload puts "We found no good state so we are destroying the previous machine+disks" destroy_vm(boxname) end end #puts "(re-)executing step #{step_name}" yield #Need to look it up again because if it was an initial load vm=VirtualBox::VM.find(boxname) puts "Step [#{current_step_nr}] was successfully - saving state" vm.save_state sleep 2 #waiting for it to be ok #puts "about to snapshot #{vm}" #take snapshot after successful execution vm.take_snapshot(step_name,"snapshot taken by vbox") sleep 2 #waiting for it to be started again vm.start end #pp snapnames end |
.undefine(boxname) ⇒ Object
110 111 112 113 114 115 116 117 118 119 120 |
# File 'lib/vbox/session.rb', line 110 def self.undefine(boxname) name_dir=File.join(@definition_dir,boxname) if File.directory?(name_dir) #TODO: Needs to be more defensive!! puts "Removing definition #{boxname}" FileUtils.rm_rf(name_dir) else puts "Can not undefine , definition #{boxname} does not exist" exit end end |
.validate_box(boxname, options) ⇒ Object
698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 |
# File 'lib/vbox/session.rb', line 698 def self.validate_box(boxname,) require 'cucumber' require 'cucumber/rspec/disable_option_parser' require 'cucumber/cli/main' ENV['vbox_user']=[:user] feature_path=File.join(File.dirname(__FILE__),"..","..","validation","vagrant.feature") features=Array.new features[0]=feature_path begin # The dup is to keep ARGV intact, so that tools like ruby-debug can respawn. failure = Cucumber::Cli::Main.execute(features.dup) Kernel.exit(failure ? 1 : 0) rescue SystemExit => e Kernel.exit(e.status) rescue Exception => e STDERR.puts("#{e.} (#{e.class})") STDERR.puts(e.backtrace.join("\n")) Kernel.exit(1) end end |
.verify_iso(filename, autodownload = false) ⇒ Object
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 204 205 |
# File 'lib/vbox/session.rb', line 157 def self.verify_iso(filename,autodownload = false) if File.exists?(File.join(@iso_dir,filename)) puts puts "Verifying the isofile #{filename} is ok." else full_path=File.join(@iso_dir,filename) path1=Pathname.new(full_path) path2=Pathname.new(Dir.pwd) rel_path=path1.relative_path_from(path2).to_s puts puts "We did not find an isofile in <currentdir>/iso. \n\nThe definition provided the following download information:" unless "#{@definition[:iso_src]}"=="" puts "- Download url: #{@definition[:iso_src]}" end puts "- Md5 Checksum: #{@definition[:iso_md5]}" puts "#{@definition[:iso_download_instructions]}" puts if @definition[:iso_src] == "" puts "Please follow the instructions above:" puts "- to get the ISO" puts" - put it in <currentdir>/iso" puts "- then re-run the command" puts exit else question=ask("Download? (Yes/No)") {|q| q.default="No"} if question.downcase == "yes" if !File.exists?(@iso_dir) puts "Creating an iso directory" FileUtils.mkdir(@iso_dir) end download_progress(@definition[:iso_src],full_path) else puts "You have choosen for manual download: " puts "curl -C - -L '#{@definition[:iso_src]}' -o '#{rel_path}'" puts "md5 '#{rel_path}' " puts exit end end end end |