Module: Veewee::Provider::Virtualbox::BoxCommand

Included in:
Box
Defined in:
lib/veewee/provider/virtualbox/box/up.rb,
lib/veewee/provider/virtualbox/box/ssh.rb,
lib/veewee/provider/virtualbox/box/halt.rb,
lib/veewee/provider/virtualbox/box/build.rb,
lib/veewee/provider/virtualbox/box/winrm.rb,
lib/veewee/provider/virtualbox/box/create.rb,
lib/veewee/provider/virtualbox/box/destroy.rb,
lib/veewee/provider/virtualbox/box/poweroff.rb,
lib/veewee/provider/virtualbox/box/helper/ip.rb,
lib/veewee/provider/virtualbox/box/screenshot.rb,
lib/veewee/provider/virtualbox/box/helper/status.rb,
lib/veewee/provider/virtualbox/box/helper/create.rb,
lib/veewee/provider/virtualbox/box/helper/version.rb,
lib/veewee/provider/virtualbox/box/export_vagrant.rb,
lib/veewee/provider/virtualbox/box/helper/buildinfo.rb,
lib/veewee/provider/virtualbox/box/validate_vagrant.rb,
lib/veewee/provider/virtualbox/box/helper/forwarding.rb,
lib/veewee/provider/virtualbox/box/helper/ssh_options.rb,
lib/veewee/provider/virtualbox/box/helper/console_type.rb,
lib/veewee/provider/virtualbox/box/helper/natinterface.rb,
lib/veewee/provider/virtualbox/box/helper/winrm_options.rb,
lib/veewee/provider/virtualbox/box/helper/guest_additions.rb

Defined Under Namespace

Classes: ErbBinding

Constant Summary

UNSYNCED_VERSIONS =
{"4.2.1" => "4.2.0", "4.1.23" => "4.1.22"}

Instance Method Summary collapse

Instance Method Details

#add_floppy_controllerObject



141
142
143
144
145
146
147
148
# File 'lib/veewee/provider/virtualbox/box/helper/create.rb', line 141

def add_floppy_controller
  # Create floppy controller
  unless definition.floppy_files.nil?

    command="#{@vboxcmd} storagectl \"#{name}\" --name \"Floppy Controller\" --add floppy"
    shell_exec("#{command}")
  end
end

#add_ide_controllerObject



6
7
8
9
10
# File 'lib/veewee/provider/virtualbox/box/helper/create.rb', line 6

def add_ide_controller
  #unless => "${vboxcmd} showvminfo \"${vname}\" | grep \"IDE Controller\" "
  command ="#{@vboxcmd} storagectl \"#{name}\" --name \"IDE Controller\" --add ide"
  shell_exec("#{command}")
end

#add_sata_controllerObject



12
13
14
15
16
17
18
19
20
# File 'lib/veewee/provider/virtualbox/box/helper/create.rb', line 12

def add_sata_controller 
  #unless => "${vboxcmd} showvminfo \"${vname}\" | grep \"SATA Controller\" ";
  if vbox_version >= '4.3.0'
    command ="#{@vboxcmd} storagectl \"#{name}\" --name \"SATA Controller\" --add sata --hostiocache #{definition.hostiocache} --portcount #{definition.disk_count}"
  else
    command ="#{@vboxcmd} storagectl \"#{name}\" --name \"SATA Controller\" --add sata --hostiocache #{definition.hostiocache} --sataportcount #{definition.disk_count}"
  end
  shell_exec("#{command}")
end

#add_shared_folderObject



59
60
61
62
# File 'lib/veewee/provider/virtualbox/box/helper/create.rb', line 59

def add_shared_folder
  command="#{@vboxcmd} sharedfolder add  \"#{name}\" --name \"veewee-validation\" --hostpath \"#{File.expand_path(env.validation_dir)}\" --automount"
  shell_exec("#{command}")
end

#add_ssh_nat_mappingObject



29
30
31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/veewee/provider/virtualbox/box/helper/create.rb', line 29

def add_ssh_nat_mapping

  unless definition.nil?
    unless definition.skip_nat_mapping == true
      #Map SSH Ports
      if self.running?
        command="#{@vboxcmd} controlvm \"#{name}\" natpf#{self.natinterface} \"guestssh,tcp,,#{definition.ssh_host_port},,#{definition.ssh_guest_port}\""
      else
        command="#{@vboxcmd} modifyvm \"#{name}\" --natpf#{self.natinterface} \"guestssh,tcp,,#{definition.ssh_host_port},,#{definition.ssh_guest_port}\""
      end
      shell_exec("#{command}")
    end
  end
end

#add_winrm_nat_mappingObject



44
45
46
47
48
49
50
51
52
53
54
55
56
57
# File 'lib/veewee/provider/virtualbox/box/helper/create.rb', line 44

def add_winrm_nat_mapping

  unless definition.nil?
    #Map SSH Ports
    unless definition.skip_nat_mapping == true
      if self.running?
        command="#{@vboxcmd} controlvm \"#{name}\" natpf#{self.natinterface} \"guestwinrm,tcp,,#{definition.winrm_host_port},,#{definition.winrm_guest_port}\""
      else
        command="#{@vboxcmd} modifyvm \"#{name}\" --natpf#{self.natinterface} \"guestwinrm,tcp,,#{definition.winrm_host_port},,#{definition.winrm_guest_port}\""
      end
      shell_exec("#{command}")
    end
  end
end

#attach_disk_common(storagectl, device_number) ⇒ Object



102
103
104
105
106
107
108
109
110
111
112
113
114
115
# File 'lib/veewee/provider/virtualbox/box/helper/create.rb', line 102

def attach_disk_common(storagectl, device_number)
  place=get_vbox_home
  
  1.upto(definition.disk_count.to_i) do |f|
    location=name+"#{f}."+definition.disk_format.downcase
  
    location="#{File.join(place,name,location)}"
    ui.info "Attaching disk: #{location}"
  
    #command => "${vboxcmd} storageattach \"${vname}\" --storagectl \"SATA Controller\" --port 0 --device 0 --type hdd --medium \"${vname}.vdi\"",
    command ="#{@vboxcmd} storageattach \"#{name}\" --storagectl \"#{storagectl}\" --port #{f-1} --device #{device_number} --type hdd --medium \"#{location}\""
    shell_exec("#{command}")
  end
end

#attach_disk_ide(device_number = 0) ⇒ Object



117
118
119
# File 'lib/veewee/provider/virtualbox/box/helper/create.rb', line 117

def attach_disk_ide(device_number=0)
  self.attach_disk_common("IDE Controller", device_number)
end

#attach_disk_sata(device_number = 0) ⇒ Object



121
122
123
# File 'lib/veewee/provider/virtualbox/box/helper/create.rb', line 121

def attach_disk_sata(device_number=0)
  self.attach_disk_common("SATA Controller", device_number)
end

#attach_floppyObject



151
152
153
154
155
156
157
158
159
# File 'lib/veewee/provider/virtualbox/box/helper/create.rb', line 151

def attach_floppy
  unless definition.floppy_files.nil?

    # Attach floppy to machine (the vfd extension is crucial to detect msdos type floppy)
    floppy_file=File.join(definition.path,"virtualfloppy.vfd")
    command="#{@vboxcmd} storageattach \"#{name}\" --storagectl \"Floppy Controller\" --port 0 --device 0 --type fdd --medium \"#{floppy_file}\""
    shell_exec("#{command}")
  end
end

#attach_guest_additionsObject



133
134
135
136
137
138
# File 'lib/veewee/provider/virtualbox/box/helper/create.rb', line 133

def attach_guest_additions
  full_iso_file=File.join(env.config.veewee.iso_dir,"VBoxGuestAdditions_#{self.vboxga_version}.iso")
  ui.info "Mounting guest additions: #{full_iso_file}"
  command ="#{@vboxcmd} storageattach \"#{name}\" --storagectl \"IDE Controller\" --type dvddrive --port 1 --device 0 --medium \"#{full_iso_file}\""
  shell_exec("#{command}")
end

#attach_isofile(device_number = 0) ⇒ Object



126
127
128
129
130
131
# File 'lib/veewee/provider/virtualbox/box/helper/create.rb', line 126

def attach_isofile(device_number=0)
  full_iso_file=File.join(env.config.veewee.iso_dir,definition.iso_file)
  ui.info "Mounting cdrom: #{full_iso_file}"
  command ="#{@vboxcmd} storageattach \"#{name}\" --storagectl \"IDE Controller\" --type dvddrive --port 0 --device #{device_number} --medium \"#{full_iso_file}\""
  shell_exec("#{command}")
end

#attach_serial_consoleObject



22
23
24
25
26
27
# File 'lib/veewee/provider/virtualbox/box/helper/create.rb', line 22

def attach_serial_console
  command ="#{@vboxcmd} modifyvm \"#{name}\" --uart1 0x3F8 4"
  shell_exec("#{command}")
  command ="#{@vboxcmd} modifyvm \"#{name}\" --uartmode1 file \"#{File.join(FileUtils.pwd,name+"-serial-console"+".log")}\""
  shell_exec("#{command}")
end

#build(options = {}) ⇒ Object



6
7
8
9
10
11
12
13
14
15
16
17
18
# File 'lib/veewee/provider/virtualbox/box/build.rb', line 6

def build(options={})

  download_vbox_guest_additions_iso(options)

  super(options)

  unless definition.floppy_files.nil?
    unless self.shell_exec("java -version").status == 0
      raise Veewee::Error,"This box contains floppyfiles, to create it you require to have java installed or have it in your path"
    end
  end

end

#build_infoObject



6
7
8
9
10
# File 'lib/veewee/provider/virtualbox/box/helper/buildinfo.rb', line 6

def build_info
  info=super
  info << { :filename => ".vbox_version",
            :content => "#{self.vboxga_version}" }
end

#console_type(sequence) ⇒ Object



9
10
11
# File 'lib/veewee/provider/virtualbox/box/helper/console_type.rb', line 9

def console_type(sequence)
  send_virtualbox_sequence(sequence)
end

#create(options = {}) ⇒ Object



6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
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
61
62
63
64
65
66
67
68
69
70
71
72
73
# File 'lib/veewee/provider/virtualbox/box/create.rb', line 6

def create(options={})

  # First check if the directory where we create the VM is empty
  # Sometimes there are leftovers from badly terminated vms
  box_directory=File.join(self.get_vbox_home,name)
  if File.exists?(box_directory)
    raise Veewee::Error,"To create the vm '#{name}' the directory '#{box_directory}' needs to be empty. \nThis could be caused by an badly closed vm.\nRemove it manually before you proceed."
  end

  # Suppress those annoying virtualbox messages
  self.suppress_messages

  self.create_vm

  # Attach ttyS0 to the VM for console output
  redirect_console=options[:redirectconsole]
  if redirect_console
    self.attach_serial_console
  end

  # Adds a folder to the vm for testing purposes
  self.add_shared_folder

  #Create a disk with the same name as the box_name
  self.create_disk

  use_sata = definition.use_sata
  if use_sata
    disk_device_number = 0
    isofile_ide_device_number = 0
  else
    disk_device_number = 0
    isofile_ide_device_number = 1
  end

  self.add_ide_controller
  if use_sata
    self.add_sata_controller
    self.attach_disk_sata(disk_device_number)
  else
    self.attach_disk_ide(disk_device_number)
  end
  self.attach_isofile(isofile_ide_device_number)
  self.attach_guest_additions

  self.create_floppy("virtualfloppy.vfd")

  self.add_floppy_controller
  self.attach_floppy

  if definition.winrm_user && definition.winrm_password # prefer winrm 
    env.ui.warn "Using winrm because winrm_user and winrm_password are both set"
    guessed_port=guess_free_port(definition.winrm_host_port.to_i,definition.winrm_host_port.to_i+40).to_s
    if guessed_port.to_s!=definition.winrm_host_port
      env.ui.warn "Changing winrm port from #{definition.winrm_host_port} to #{guessed_port}"
      definition.winrm_host_port=guessed_port.to_s
    end
    self.add_winrm_nat_mapping
  else
    guessed_port=guess_free_ssh_port(definition.ssh_host_port.to_i,definition.ssh_host_port.to_i+40).to_s
    if guessed_port.to_s!=definition.ssh_host_port
      env.ui.warn "Changing ssh port from #{definition.ssh_host_port} to #{guessed_port}"
      definition.ssh_host_port=guessed_port.to_s
    end
    self.add_ssh_nat_mapping
  end

end

#create_diskObject



93
94
95
96
97
98
99
100
# File 'lib/veewee/provider/virtualbox/box/helper/create.rb', line 93

def create_disk
    place=get_vbox_home
    1.upto(definition.disk_count.to_i) do |f|
      ui.info "Creating new harddrive of size #{definition.disk_size.to_i}, format #{definition.disk_format}, variant #{definition.disk_variant} "
      command ="#{@vboxcmd} createhd --filename \"#{File.join(place,name,name+"#{f}."+definition.disk_format.downcase)}\" --size \"#{definition.disk_size.to_i}\" --format #{definition.disk_format.downcase} --variant #{definition.disk_variant.downcase}"
      shell_exec("#{command}")
    end
end

#create_vmObject



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
206
207
208
209
210
211
212
213
214
215
216
217
218
219
# File 'lib/veewee/provider/virtualbox/box/helper/create.rb', line 167

def create_vm
  command="#{@vboxcmd} createvm --name \"#{name}\" --ostype \"#{vbox_os_type_id(definition.os_type_id)}\" --register"

  #Exec and system stop the execution here
  shell_exec("#{command}")

  ui.info "Creating vm #{name} : #{definition.memory_size}M - #{definition.cpu_count} CPU - #{vbox_os_type_id(definition.os_type_id)}"

  #setting cpu's
  command="#{@vboxcmd} modifyvm \"#{name}\" --cpus #{definition.cpu_count}"
  shell_exec("#{command}")

  #setting memory size
  command="#{@vboxcmd} modifyvm \"#{name}\" --memory #{definition.memory_size}"
  shell_exec("#{command}")

  #setting video memory size
  command="#{@vboxcmd} modifyvm \"#{name}\" --vram #{definition.video_memory_size}"
  shell_exec("#{command}")

  #setting bootorder
  command="#{@vboxcmd} modifyvm \"#{name}\" --boot1 disk --boot2 dvd --boot3 none --boot4 none"
  shell_exec("#{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}

	  #setextradata
  unless definition.virtualbox[:extradata].nil?
      command="#{@vboxcmd} setextradata \"#{name}\" #{definition.virtualbox[:extradata]}"
      puts "Setting extra data with #{command}"
      shell_exec("#{command}")
  end

  vm_flags.each do |vm_flag|
    if definition.instance_variable_defined?("@#{vm_flag}")
      vm_flag_value=definition.instance_variable_get("@#{vm_flag}")
      ui.info "Setting VM Flag #{vm_flag} to #{vm_flag_value}"
      ui.warn "Used of #{vm_flag} is deprecated - specify your options in the definition file as \n :virtualbox => { :vm_options => [\"#{vm_flag}\" => \"#{vm_flag_value}\"]}"
      command="#{@vboxcmd} modifyvm \"#{name}\" --#{vm_flag.to_s} #{vm_flag_value}"
      shell_exec("#{command}")
    end
  end

  unless definition.virtualbox[:vm_options].nil? || definition.virtualbox[:vm_options][0].nil?
    definition.virtualbox[:vm_options][0].each do |vm_flag,vm_flag_value|
      ui.info "Setting VM Flag #{vm_flag} to #{vm_flag_value}"
      command="#{@vboxcmd} modifyvm \"#{name}\" --#{vm_flag.to_s} #{vm_flag_value}"
      shell_exec("#{command}")
    end
  end

end

#delete_forwarding(name) ⇒ Object



29
30
31
32
33
34
35
36
37
# File 'lib/veewee/provider/virtualbox/box/helper/forwarding.rb', line 29

def delete_forwarding(name)
  forward=self.forwarding(name)
  if self.running?
    command="#{@vboxcmd} controlvm \"#{self.name}\" natpf#{self.natinterface} delete \"#{name}\""
  else
    command="#{@vboxcmd} modifyvm \"#{self.name}\" --natpf#{self.natinterface} delete \"#{name}\""
  end
  shell_results=shell_exec("#{command}")
end

#destroy(option = {}) ⇒ Object



6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
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
# File 'lib/veewee/provider/virtualbox/box/destroy.rb', line 6

def destroy(option={})

  unless self.exists?
    raise Veewee::Error, "Error:: You tried to destroy a non-existing box '#{name}'"
  end

  # If it has a save state,remove that first

  if self.running?
    # Poweroff
    self.poweroff
    # Wait for it to happen
    sleep 2
  end

  command="#{@vboxcmd} unregistervm  \"#{name}\" --delete"
  ui.info command
  ui.info "Deleting vm #{name}"

  #Exec and system stop the execution here
  shell_exec("#{command}",{:mute => true})
  sleep 1

  #if the disk was not attached when the machine was destroyed we also need to delete the disk
  pattern= File::SEPARATOR+name+"."
  #+definition.disk_format.downcase
  found=false
  command="#{@vboxcmd} list hdds -l"
  hdds=shell_exec("#{command}",{:mute => true}).stdout.split(/\n\n/)

  hdds.each do |hdd_text|
    location=hdd_text.split(/\n/).grep(/^Location/).first.split(':')[1].strip
    if location.match(/#{pattern}/)

      if File.exists?(location)
        command="#{@vboxcmd} closemedium disk \"#{location}\" --delete"
      else
        command="#{@vboxcmd} closemedium disk \"#{location}\""
      end

      ui.info "Deleting disk #{location}"
      ui.info "#{command}"

      shell_exec("#{command}",{:mute => true})

      if File.exists?(location)
        ui.info "We tried to delete the disk file via virtualbox '#{location} but failed"
        ui.info "Removing it manually"
        FileUtils.rm(location)
      end
      break
    end
  end
end

#download_vbox_guest_additions_iso(options) ⇒ Object



6
7
8
9
10
11
12
# File 'lib/veewee/provider/virtualbox/box/helper/guest_additions.rb', line 6

def download_vbox_guest_additions_iso(options)
  version=self.vboxga_version
  isofile="VBoxGuestAdditions_#{version}.iso"
  url="http://download.virtualbox.org/virtualbox/#{version}/#{isofile}"
  ui.info "Downloading vbox guest additions iso v #{version} - #{url}"
  download_iso(url,isofile)
end

#exists?Boolean



6
7
8
# File 'lib/veewee/provider/virtualbox/box/helper/status.rb', line 6

def exists?
  return check?(:exists)
end

#export_vagrant(options) ⇒ Object

Shellutil.execute(“vagrant package –base #vmname –include /tmp/Vagrantfile –output /tmp/#vmname.box”, => “on”)



16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
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
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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
# File 'lib/veewee/provider/virtualbox/box/export_vagrant.rb', line 16

def export_vagrant(options)

  # Check if box already exists
  unless self.exists?
    ui.info "#{name} is not found, maybe you need to build it first?"
    exit
  end

  if File.exists?("#{name}.box")
    if options["force"]
      env.logger.debug("#{name}.box exists, but --force was provided")
      env.logger.debug("removing #{name}.box first")
      FileUtils.rm("#{name}.box")
      env.logger.debug("#{name}.box removed")
    else
      raise Veewee::Error, "export file #{name}.box already exists. Use --force option to overwrite."
    end
  end


  # We need to shutdown first
  if self.running?
    ui.info "Vagrant requires the box to be shutdown, before it can export"
    ui.info "Sudo also needs to work for user #{definition.ssh_user}"
    ui.info "Performing a clean shutdown now."

    self.halt

    #Wait for state poweroff
    while (self.running?) do
      ui.info ".",{:new_line => false}
      sleep 1
    end
    ui.info ""
    ui.info "Machine #{name} is powered off cleanly"
  end

  #Vagrant requires a relative path for output of boxes

  #4.0.x. not using boxes as a subdir
  boxdir=Pathname.new(Dir.pwd)

  full_path=File.join(boxdir,name+".box")
  path1=Pathname.new(full_path)
  path2=Pathname.new(Dir.pwd)
  box_path=File.expand_path(path1.relative_path_from(path2).to_s)

  if File.exists?("#{box_path}")
    raise Veewee::Error, "box #{name}.box already exists"
  end

  # Create temp directory
  current_dir = FileUtils.pwd
  ui.info "Creating a temporary directory for export"
  tmp_dir = Dir.mktmpdir
  env.logger.debug("Create temporary directory for export #{tmp_dir}")

  begin

    ui.info "Adding additional files"

    # Handling the Vagrantfile
    if options["vagrantfile"].to_s == ""

      # Fetching mac address

      data = {
        :macaddress => get_mac_address
      }

      # Prepare the vagrant erb
      vars = ErbBinding.new(data)
      template_path = File.join(File.dirname(__FILE__),'..','..','..','templates',"Vagrantfile.erb")
      template = File.open(template_path).readlines.join
      erb = ERB.new(template)
      vars_binding = vars.send(:get_binding)
      result = erb.result(vars_binding)
      ui.info("Creating Vagrantfile")
      vagrant_path = File.join(tmp_dir,'Vagrantfile')
      env.logger.debug("Path: #{vagrant_path}")
      env.logger.debug(result)
      File.open(vagrant_path,'w') {|f| f.write(result) }
    else
      f = options["vagrantfile"]
      env.logger.debug("Including vagrantfile: #{f}")
      FileUtils.cp(f,File.join(tmp_dir,"Vagrantfile"))
    end

    # Handling other includes
    unless options["include"].nil?
      options["include"].each do |f|
        env.logger.debug("Including file: #{f}")
        FileUtils.cp(f,File.join(tmp_dir,f))
      end
    end

    ui.info "Exporting the box"
    command = "#{@vboxcmd} export \"#{name}\" --output \"#{File.join(tmp_dir,'box.ovf')}\""
    env.logger.debug("Command: #{command}")
    shell_exec(command, {:mute => false})

    ui.info "Packaging the box"
    FileUtils.cd(tmp_dir)
    command_box_path = box_path
    is_windows = (RbConfig::CONFIG['host_os'] =~ /mswin|mingw|cygwin/)
    if is_windows
      command_box_path = command_box_path.gsub(/^([A-Z])\:\/(.*)$/i, '/\1/\2')
    end
    command = "tar -cvf '#{command_box_path}' ."
    env.logger.debug(command)
    shell_exec (command)

  rescue Errno::ENOENT => ex
    raise Veewee::Error, "#{ex}"
  rescue Error => ex
    raise Veewee::Error, "Packaging of the box failed:\n+#{ex}"
  ensure
    # Remove temporary directory
    ui.info "Cleaning up temporary directory"
    env.logger.debug("Removing temporary dir #{tmp_dir}")
    FileUtils.rm_rf(tmp_dir)

    FileUtils.cd(current_dir)
  end
  ui.info ""

  #add_ssh_nat_mapping back!!!!
  #vagrant removes the mapping
  #we need to restore it in order to be able to login again
  #self.add_ssh_nat_mapping

  ui.info "To import it into vagrant type:"
  ui.info "vagrant box add '#{name}' '#{box_path}'"
  ui.info ""
  ui.info "To use it:"
  ui.info "vagrant init '#{name}'"
  ui.info "vagrant up"
  ui.info "vagrant ssh"
end

#forwarding(name) ⇒ Object



6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
# File 'lib/veewee/provider/virtualbox/box/helper/forwarding.rb', line 6

def forwarding(name)
  command="#{@vboxcmd} showvminfo --details --machinereadable \"#{self.name}\""
  shell_results=shell_exec("#{command}")
  rules=shell_results.stdout.split(/\n/).grep(/^Forward/)
  result=nil
  rules.each do |rule|
    #Forwarding(0)
    nr=rule.split('=')[0].split('(')[1].split(')')[0].to_i + 1
    #  guestssh,tcp,,2222,,22
    details=rule.split('=')[1].split('"')[1].split(',')
    result = {
      :nr => nr,
      :name => details[0],
      :protocol => details[1],
      :host_ip => details[2],
      :host_port => details[3],
      :guest_ip => details[4],
      :guest_port => details[5]
    }
  end
  return result
end

#get_mac_addressObject



156
157
158
159
160
161
162
# File 'lib/veewee/provider/virtualbox/box/export_vagrant.rb', line 156

def get_mac_address
  command = "#{@vboxcmd} showvminfo --details --machinereadable \"#{self.name}\""
  shell_results = shell_exec("#{command}")
  mac = shell_results.stdout.split(/\n/).grep(/^macaddress1/)[0].split('=')[1].split('"')[1]
  env.logger.debug("mac address: #{mac}")
  return mac
end

#get_vbox_homeObject



64
65
66
67
68
69
70
71
72
# File 'lib/veewee/provider/virtualbox/box/helper/create.rb', line 64

def get_vbox_home
  command="#{@vboxcmd}  list  systemproperties"
  shell_results=shell_exec("#{command}")
  # On windows Default machine path would include a drive letter, then ':'.
  # So here we tell to split no more than 2 elements to keep the full path
  # This should work for all OS as we just need to separate the parameter name with first ':' from the value
  location=shell_results.stdout.split(/\n/).grep(/Default machine/)[0].split(":", 2)[1].strip
  return location
end

#halt(options = {}) ⇒ Object



6
7
8
# File 'lib/veewee/provider/virtualbox/box/halt.rb', line 6

def halt(options={})
  super(options)
end

#host_ip_as_seen_by_guestObject



7
8
9
# File 'lib/veewee/provider/virtualbox/box/helper/ip.rb', line 7

def host_ip_as_seen_by_guest
  "10.0.2.2"
end

#ip_addressObject

Get the IP address of the box



12
13
14
# File 'lib/veewee/provider/virtualbox/box/helper/ip.rb', line 12

def ip_address
  return "127.0.0.1"
end

#natinterfaceObject



6
7
8
9
10
11
12
# File 'lib/veewee/provider/virtualbox/box/helper/natinterface.rb', line 6

def natinterface
  command="#{@vboxcmd} showvminfo --details --machinereadable \"#{self.name}\""
  shell_results=shell_exec("#{command}")

  nic_id=shell_results.stdout.split(/\n/).grep(/^nic/).grep(/nat/)[0].split('=')[0][-1,1]
  return nic_id
end

#poweroff(options = {}) ⇒ Object



6
7
8
9
10
11
12
13
14
# File 'lib/veewee/provider/virtualbox/box/poweroff.rb', line 6

def poweroff(options={})
  # If the vm is not powered off, perform a shutdown
  if (self.exists? && self.running?)
    ui.info "Shutting down vm #{name}"
    #We force it here, maybe vm.shutdown is cleaner
    command="#{@vboxcmd} controlvm \"#{name}\" poweroff"
    shell_exec("#{command}")
  end
end

#running?Boolean



10
11
12
# File 'lib/veewee/provider/virtualbox/box/helper/status.rb', line 10

def running?
  return check?(:running)
end

#screenshot(filename, options = {}) ⇒ Object

Raises:



6
7
8
9
10
11
12
13
14
15
16
17
18
19
# File 'lib/veewee/provider/virtualbox/box/screenshot.rb', line 6

def screenshot(filename,options={})
  raise Veewee::Error, "The VM needs to exist before we can take a screenshot" unless self.exists?
  raise Veewee::Error, "The VM needs to be running before we can test a screenshot" unless self.running?
  # If the vm is not powered off, take a screenshot
  if (self.exists? && self.running?)
    ui.info "Saving screenshot of vm #{name} in #{filename}"

    command="#{@vboxcmd} controlvm \"#{name}\" screenshotpng \"#{filename}\""
    shell_exec("#{command}")
    unless File.exists?(filename)
      raise Veewee::Error,"Saving Screenshot #{filename} failed"
    end
  end
end

#send_keycode(keycode) ⇒ Object



53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
# File 'lib/veewee/provider/virtualbox/box/helper/console_type.rb', line 53

def send_keycode(keycode)
  command= "#{@vboxcmd} controlvm \"#{name}\" keyboardputscancode #{keycode}"
  env.logger.debug "#{command}"
  sshresult = shell_exec("#{command}",{:mute => true})
  env.logger.debug "\
sshresult.stdout: #{sshresult.stdout.inspect},
sshresult.stderr: #{sshresult.stderr.inspect}"
  if sshresult.stdout.index("E_ACCESSDENIED")
    error= "There was an error typing the commands on the console"
    error+="Probably the VM did not get started."
    error+= ""
    error+= "#{sshresult.stdout}"
    raise Veewee::Error, error
  end
end

#send_virtualbox_sequence(sequence) ⇒ Object



13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# File 'lib/veewee/provider/virtualbox/box/helper/console_type.rb', line 13

def send_virtualbox_sequence(sequence)

  ui.info ""

  counter=0
  sequence.each { |s|
    counter=counter+1

    ui.info "Typing:[#{counter}]: "+s

    keycodes=Veewee::Provider::Core::Helper::Scancode.string_to_keycode(s)

    env.logger.info "Sending keycodes: #{keycodes}"

    # VBox seems to have issues with sending the scancodes as one big
    # .join()-ed string. It seems to get them out or order or ignore some.
    # A workaround is to send the scancodes one-by-one.
    codes=""
    for keycode in keycodes.split(' ') do
      case keycode
      when /^wait(\d*)$/ then sleep_guess($1)
      else
        send_keycode(keycode)
        sleep 0.01
      end
    end
    #sleep after each sequence (needs to be param)
    sleep 0.5
  }

  ui.info "Done typing."
  ui.info ""

end

#sleep_guess(str) ⇒ Object



48
49
50
51
# File 'lib/veewee/provider/virtualbox/box/helper/console_type.rb', line 48

def sleep_guess(str)
  str = "1" if str == ""
  sleep str.to_i
end

#ssh(command, options = {}) ⇒ Object



6
7
8
# File 'lib/veewee/provider/virtualbox/box/ssh.rb', line 6

def ssh(command,options={})
  super(command,options)
end

#ssh_optionsObject



6
7
8
9
10
11
12
13
14
15
16
17
# File 'lib/veewee/provider/virtualbox/box/helper/ssh_options.rb', line 6

def ssh_options
  build_ssh_options.tap do |options|
    port = definition.ssh_host_port
    if self.exists?
      forward=self.forwarding("guestssh")
      unless forward.nil?
        port=forward[:host_port]
      end
    end
    options[:port] = port
  end
end

#suppress_messagesObject



75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
# File 'lib/veewee/provider/virtualbox/box/helper/create.rb', line 75

def suppress_messages
  day=24*60*60
  update_date=Time.now+365*day

  extraData = [
    ["GUI/RegistrationData","triesLeft=0"],
    ["GUI/SuppressMessages","confirmInputCapture,remindAboutAutoCapture,remindAboutMouseIntegrationOff,remindAboutMouseIntegrationOn,remindAboutWrongColorDepth"],
    ["GUI/UpdateDate", "1 d, #{update_date.year}-#{update_date.month.to_s.rjust(2,'0')}-#{update_date.day.to_s.rjust(2,'0')}, stable"],
    ["GUI/UpdateCheckCount","60"]
  ]
  extraData.each do |data|
    command="#{@vboxcmd} setextradata global \"#{data[0]}\" \"#{data[1]}\""
    shell_results=shell_exec("#{command}")
  end

end

#transfer_buildinfo(options) ⇒ Object

Transfer information provide by the provider to the box



15
16
17
18
19
20
21
22
23
# File 'lib/veewee/provider/virtualbox/box/helper/buildinfo.rb', line 15

def transfer_buildinfo(options)
  super(options)
  # with windows, we just use the mounted volume 
  if not (definition.winrm_user && definition.winrm_password)
    iso_image="VBoxGuestAdditions_#{self.vboxga_version}.iso"
    env.logger.info "About to transfer virtualbox guest additions iso to the box #{name} - #{ip_address} - #{ssh_options}"
    self.copy_to_box("#{File.join(env.config.veewee.iso_dir,iso_image)}",File.basename(iso_image))
  end
end

#up(options = {}) ⇒ Object

Raises:



6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
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
61
62
63
# File 'lib/veewee/provider/virtualbox/box/up.rb', line 6

def up(options={})

  unless self.exists?
    raise Veewee::Error, "Error:: You tried to up a non-existing box '#{name}'. Please run 'veewee vbox build #{name}' first."
  end

  gui_enabled=options['nogui']==true ? false : true

  raise Veewee::Error,"Box is already running" if self.running?

  if definition.winrm_user && definition.winrm_password # prefer winrm 
    # Before we start,correct the ssh/winrm port if needed
    forward=self.forwarding("guestwinrm")
    guessed_port=guess_free_port(definition.winrm_host_port.to_i,definition.winrm_host_port.to_i+40).to_s
    definition.winrm_host_port=guessed_port.to_s
    
    unless forward.nil?
      if guessed_port!=forward[:host_port]
        # Remove the existing one
        self.delete_forwarding("guestwinrm")
        env.ui.warn "Changing winrm port on UP from #{forward[:host_port]} to #{guessed_port}"
      self.add_winrm_nat_mapping
      end
    else
      self.add_winrm_nat_mapping
    end
    
  else

    # Before we start,correct the ssh port if needed
    forward=self.forwarding("guestssh")
    guessed_port=guess_free_ssh_port(definition.ssh_host_port.to_i,definition.ssh_host_port.to_i+40).to_s
    definition.ssh_host_port=guessed_port.to_s
    
    unless forward.nil?
      if guessed_port!=forward[:host_port]
        # Remove the existing one
        self.delete_forwarding("guestssh")
        env.ui.warn "Changing ssh port from #{forward[:host_port]} to #{guessed_port}"
      self.add_ssh_nat_mapping
      end
    else
      self.add_ssh_nat_mapping
    end
    
  end

  self.suppress_messages

  # Once assembled we start the machine
  env.logger.info "Started the VM with GUI Enabled? #{gui_enabled}"

  command="#{@vboxcmd} startvm --type gui \"#{name}\""
  unless (gui_enabled)
    command="#{@vboxcmd} startvm --type headless \"#{name}\""
  end
  shell_results=shell_exec("#{command}",{:mute => true})
end

#validate_vagrant(options = {}) ⇒ Object



6
7
8
# File 'lib/veewee/provider/virtualbox/box/validate_vagrant.rb', line 6

def validate_vagrant(options = {})
  validate_tags( options['tags'],options)
end

#vbox_os_type_id(veewee_type_id) ⇒ Object



161
162
163
164
165
# File 'lib/veewee/provider/virtualbox/box/helper/create.rb', line 161

def vbox_os_type_id(veewee_type_id)
  type=env.ostypes[veewee_type_id][:vbox]
  env.logger.info("Using VBOX os_type_id #{type}")
  return type
end

#vbox_versionObject

Return the major/minor/incremental version of VirtualBox. For example: 4.1.8_Debianr75467 -> 4.1.8



9
10
11
12
13
14
15
16
17
# File 'lib/veewee/provider/virtualbox/box/helper/version.rb', line 9

def vbox_version
  command="#{@vboxcmd} --version"
  stderr = "/dev/null"
  is_windows = (RbConfig::CONFIG['host_os'] =~ /mswin|mingw|cygwin/)
  stderr = "nul" if is_windows
  shell_results=shell_exec("#{command}",{:mute => true, :stderr => stderr})
  version=shell_results.stdout.strip.split(/[^0-9\.]/)[0]
  return version
end

#vboxga_versionObject



19
20
21
# File 'lib/veewee/provider/virtualbox/box/helper/version.rb', line 19

def vboxga_version
  affected_version?(self.vbox_version) ? UNSYNCED_VERSIONS[self.vbox_version] : self.vbox_version
end

#winrm(command, options = {}) ⇒ Object



6
7
8
# File 'lib/veewee/provider/virtualbox/box/winrm.rb', line 6

def winrm(command,options={})
  super(command,options)
end

#winrm_optionsObject



6
7
8
9
10
11
12
13
14
15
16
17
# File 'lib/veewee/provider/virtualbox/box/helper/winrm_options.rb', line 6

def winrm_options
  build_winrm_options.tap do |options|
    port=definition.winrm_host_port
    if self.exists?
      forward=self.forwarding("guestwinrm")
      unless forward.nil?
        port=forward[:host_port]
      end
    end
    options[:port] = port
  end
end