Class: Vagrant::Driver::VirtualBox_4_2

Inherits:
VirtualBoxBase show all
Defined in:
lib/vagrant/driver/virtualbox_4_2.rb

Overview

Driver for VirtualBox 4.2.x

Instance Method Summary collapse

Methods inherited from VirtualBoxBase

#execute, #raw

Methods included from Util::Retryable

#retryable

Constructor Details

#initialize(uuid) ⇒ VirtualBox_4_2

Returns a new instance of VirtualBox_4_2.



10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
# File 'lib/vagrant/driver/virtualbox_4_2.rb', line 10

def initialize(uuid)
  super()

  @logger = Log4r::Logger.new("vagrant::driver::virtualbox_4_2")
  @uuid = uuid

  # "Jank mode." VirtualBox 4.2.0 has a horrendous bug where
  # showvminfo with `--machinereadable` doesn't return proper output.
  # In this case, Vagrant works around it by using equally horrendous
  # regular expressions for the non-machine-readable output of
  # showvminfo. This, ladies and gentlemen, is jank mode.
  @jank_mode = false
  if Util::Platform.windows?
    if execute("--version").start_with?("4.2.0r")
      @logger.info("Windows with v4.2.0. Jank mode engage.")
      @jank_mode = true
    end
  end
end

Instance Method Details

#clear_forwarded_portsObject



30
31
32
33
34
35
36
37
# File 'lib/vagrant/driver/virtualbox_4_2.rb', line 30

def clear_forwarded_ports
  args = []
  read_forwarded_ports(@uuid).each do |nic, name, _, _|
    args.concat(["--natpf#{nic}", "delete", name])
  end

  execute("modifyvm", @uuid, *args) if !args.empty?
end

#clear_shared_foldersObject



39
40
41
42
43
44
45
46
47
48
# File 'lib/vagrant/driver/virtualbox_4_2.rb', line 39

def clear_shared_folders
  return jank_clear_shared_folders if @jank_mode

  info = execute("showvminfo", @uuid, "--machinereadable", :retryable => true)
  info.split("\n").each do |line|
    if line =~ /^SharedFolderNameMachineMapping\d+="(.+?)"$/
      execute("sharedfolder", "remove", @uuid, "--name", $1.to_s)
    end
  end
end

#create_dhcp_server(network, options) ⇒ Object



50
51
52
53
54
55
56
57
# File 'lib/vagrant/driver/virtualbox_4_2.rb', line 50

def create_dhcp_server(network, options)
  execute("dhcpserver", "add", "--ifname", network,
          "--ip", options[:dhcp_ip],
          "--netmask", options[:netmask],
          "--lowerip", options[:dhcp_lower],
          "--upperip", options[:dhcp_upper],
          "--enable")
end

#create_host_only_network(options) ⇒ Object



59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
# File 'lib/vagrant/driver/virtualbox_4_2.rb', line 59

def create_host_only_network(options)
  # Create the interface
  execute("hostonlyif", "create") =~ /^Interface '(.+?)' was successfully created$/
  name = $1.to_s

  # Configure it
  execute("hostonlyif", "ipconfig", name,
          "--ip", options[:adapter_ip],
          "--netmask", options[:netmask])

  # Return the details
  return {
    :name => name,
    :ip   => options[:adapter_ip],
    :netmask => options[:netmask],
    :dhcp => nil
  }
end

#deleteObject



78
79
80
# File 'lib/vagrant/driver/virtualbox_4_2.rb', line 78

def delete
  execute("unregistervm", @uuid, "--delete")
end

#delete_unused_host_only_networksObject



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
# File 'lib/vagrant/driver/virtualbox_4_2.rb', line 82

def delete_unused_host_only_networks
  networks = []
  execute("list", "hostonlyifs").split("\n").each do |line|
    networks << $1.to_s if line =~ /^Name:\s+(.+?)$/
  end

  execute("list", "vms").split("\n").each do |line|
    if line =~ /^".+?"\s+\{(.+?)\}$/
      if @jank_mode
        adapters = jank_read_hostonly_adapters($1.to_s)
        adapters.each do |adapter|
          networks.delete(adapter)
        end
      else
        info = execute("showvminfo", $1.to_s, "--machinereadable", :retryable => true)
        info.split("\n").each do |info_line|
          if info_line =~ /^hostonlyadapter\d+="(.+?)"$/
            networks.delete($1.to_s)
          end
        end
      end
    end
  end

  networks.each do |name|
    # First try to remove any DHCP servers attached. We use `raw` because
    # it is okay if this fails. It usually means that a DHCP server was
    # never attached.
    raw("dhcpserver", "remove", "--ifname", name)

    # Delete the actual host only network interface.
    execute("hostonlyif", "remove", name)
  end
end

#discard_saved_stateObject



117
118
119
# File 'lib/vagrant/driver/virtualbox_4_2.rb', line 117

def discard_saved_state
  execute("discardstate", @uuid)
end

#enable_adapters(adapters) ⇒ Object



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
# File 'lib/vagrant/driver/virtualbox_4_2.rb', line 121

def enable_adapters(adapters)
  args = []
  adapters.each do |adapter|
    args.concat(["--nic#{adapter[:adapter]}", adapter[:type].to_s])

    if adapter[:bridge]
      args.concat(["--bridgeadapter#{adapter[:adapter]}",
                   adapter[:bridge]])
    end

    if adapter[:hostonly]
      args.concat(["--hostonlyadapter#{adapter[:adapter]}",
                   adapter[:hostonly]])
    end

    if adapter[:mac_address]
      args.concat(["--macaddress#{adapter[:adapter]}",
                   adapter[:mac_address]])
    end

    if adapter[:nic_type]
      args.concat(["--nictype#{adapter[:adapter]}", adapter[:nic_type].to_s])
    end
  end

  execute("modifyvm", @uuid, *args)
end

#execute_command(command) ⇒ Object



149
150
151
# File 'lib/vagrant/driver/virtualbox_4_2.rb', line 149

def execute_command(command)
  raw(*command)
end

#export(path) ⇒ Object



153
154
155
156
# File 'lib/vagrant/driver/virtualbox_4_2.rb', line 153

def export(path)
  # TODO: Progress
  execute("export", @uuid, "--output", path.to_s)
end

#forward_ports(ports) ⇒ Object



158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
# File 'lib/vagrant/driver/virtualbox_4_2.rb', line 158

def forward_ports(ports)
  args = []
  ports.each do |options|
    pf_builder = [options[:name],
                  options[:protocol] || "tcp",
                  "",
                  options[:hostport],
                  "",
                  options[:guestport]]

    args.concat(["--natpf#{options[:adapter] || 1}",
                 pf_builder.join(",")])
  end

  execute("modifyvm", @uuid, *args) if !args.empty?
end

#haltObject



175
176
177
# File 'lib/vagrant/driver/virtualbox_4_2.rb', line 175

def halt
  execute("controlvm", @uuid, "poweroff")
end

#import(ovf) ⇒ Object



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
220
221
# File 'lib/vagrant/driver/virtualbox_4_2.rb', line 179

def import(ovf)
  output = ""
  total = ""
  last  = 0
  execute("import", ovf) do |type, data|
    if type == :stdout
      # Keep track of the stdout so that we can get the VM name
      output << data
    elsif type == :stderr
      # Append the data so we can see the full view
      total << data

      # Break up the lines. We can't get the progress until we see an "OK"
      lines = total.split("\n")
      if lines.include?("OK.")
        # The progress of the import will be in the last line. Do a greedy
        # regular expression to find what we're looking for.
        if lines.last =~ /.+(\d{2})%/
          current = $1.to_i
          if current > last
            last = current
            yield current if block_given?
          end
        end
      end
    end
  end

  # Find the name of the VM name
  if output !~ /Suggested VM name "(.+?)"/
    @logger.error("Couldn't find VM name in the output.")
    return nil
  end

  name = $1.to_s

  output = execute("list", "vms")
  if output =~ /^"#{Regexp.escape(name)}" \{(.+?)\}$/
    return $1.to_s
  end

  nil
end

#read_bridged_interfacesObject



254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
# File 'lib/vagrant/driver/virtualbox_4_2.rb', line 254

def read_bridged_interfaces
  execute("list", "bridgedifs").split("\n\n").collect do |block|
    info = {}

    block.split("\n").each do |line|
      if line =~ /^Name:\s+(.+?)$/
        info[:name] = $1.to_s
      elsif line =~ /^IPAddress:\s+(.+?)$/
        info[:ip] = $1.to_s
      elsif line =~ /^NetworkMask:\s+(.+?)$/
        info[:netmask] = $1.to_s
      elsif line =~ /^Status:\s+(.+?)$/
        info[:status] = $1.to_s
      end
    end

    # Return the info to build up the results
    info
  end
end

#read_forwarded_ports(uuid = nil, active_only = false) ⇒ Object



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
# File 'lib/vagrant/driver/virtualbox_4_2.rb', line 223

def read_forwarded_ports(uuid=nil, active_only=false)
  uuid ||= @uuid
  @logger.debug("read_forward_ports: uuid=#{uuid} active_only=#{active_only}")

  return jank_read_forwarded_ports(uuid, active_only) if @jank_mode

  results = []
  current_nic = nil
  info = execute("showvminfo", uuid, "--machinereadable", :retryable => true)
  info.split("\n").each do |line|
    # This is how we find the nic that a FP is attached to,
    # since this comes first.
    current_nic = $1.to_i if line =~ /^nic(\d+)=".+?"$/

    # If we care about active VMs only, then we check the state
    # to verify the VM is running.
    if active_only && line =~ /^VMState="(.+?)"$/ && $1.to_s != "running"
      return []
    end

    # Parse out the forwarded port information
    if line =~ /^Forwarding.+?="(.+?),.+?,.*?,(.+?),.*?,(.+?)"$/
      result = [current_nic, $1.to_s, $2.to_i, $3.to_i]
      @logger.debug("  - #{result.inspect}")
      results << result
    end
  end

  results
end

#read_guest_additions_versionObject



275
276
277
278
279
280
281
282
283
284
285
286
287
# File 'lib/vagrant/driver/virtualbox_4_2.rb', line 275

def read_guest_additions_version
  output = execute("guestproperty", "get", @uuid, "/VirtualBox/GuestAdd/Version",
                   :retryable => true)
  if output =~ /^Value: (.+?)$/
    # Split the version by _ since some distro versions modify it
    # to look like this: 4.1.2_ubuntu, and the distro part isn't
    # too important.
    value = $1.to_s
    return value.split("_").first
  end

  return nil
end

#read_host_only_interfacesObject



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
# File 'lib/vagrant/driver/virtualbox_4_2.rb', line 289

def read_host_only_interfaces
  dhcp = {}
  execute("list", "dhcpservers", :retryable => true).split("\n\n").each do |block|
    info = {}

    block.split("\n").each do |line|
      if line =~ /^NetworkName:\s+HostInterfaceNetworking-(.+?)$/
        info[:network] = $1.to_s
      elsif line =~ /^IP:\s+(.+?)$/
        info[:ip] = $1.to_s
      elsif line =~ /^lowerIPAddress:\s+(.+?)$/
        info[:lower] = $1.to_s
      elsif line =~ /^upperIPAddress:\s+(.+?)$/
        info[:upper] = $1.to_s
      end
    end

    # Set the DHCP info
    dhcp[info[:network]] = info
  end

  execute("list", "hostonlyifs", :retryable => true).split("\n\n").collect do |block|
    info = {}

    block.split("\n").each do |line|
      if line =~ /^Name:\s+(.+?)$/
        info[:name] = $1.to_s
      elsif line =~ /^IPAddress:\s+(.+?)$/
        info[:ip] = $1.to_s
      elsif line =~ /^NetworkMask:\s+(.+?)$/
        info[:netmask] = $1.to_s
      elsif line =~ /^Status:\s+(.+?)$/
        info[:status] = $1.to_s
      end
    end

    # Set the DHCP info if it exists
    info[:dhcp] = dhcp[info[:name]] if dhcp[info[:name]]

    info
  end
end

#read_mac_addressObject



332
333
334
335
336
337
338
339
340
341
# File 'lib/vagrant/driver/virtualbox_4_2.rb', line 332

def read_mac_address
  return jank_read_mac_address if @jank_mode

  info = execute("showvminfo", @uuid, "--machinereadable", :retryable => true)
  info.split("\n").each do |line|
    return $1.to_s if line =~ /^macaddress1="(.+?)"$/
  end

  nil
end

#read_machine_folderObject



343
344
345
346
347
348
349
350
351
# File 'lib/vagrant/driver/virtualbox_4_2.rb', line 343

def read_machine_folder
  execute("list", "systemproperties", :retryable => true).split("\n").each do |line|
    if line =~ /^Default machine folder:\s+(.+?)$/i
      return $1.to_s
    end
  end

  nil
end

#read_network_interfacesObject



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
# File 'lib/vagrant/driver/virtualbox_4_2.rb', line 353

def read_network_interfaces
  return jank_read_network_interfaces if @jank_mode

  nics = {}
  info = execute("showvminfo", @uuid, "--machinereadable", :retryable => true)
  info.split("\n").each do |line|
    if line =~ /^nic(\d+)="(.+?)"$/
      adapter = $1.to_i
      type    = $2.to_sym

      nics[adapter] ||= {}
      nics[adapter][:type] = type
    elsif line =~ /^hostonlyadapter(\d+)="(.+?)"$/
      adapter = $1.to_i
      network = $2.to_s

      nics[adapter] ||= {}
      nics[adapter][:hostonly] = network
    elsif line =~ /^bridgeadapter(\d+)="(.+?)"$/
      adapter = $1.to_i
      network = $2.to_s

      nics[adapter] ||= {}
      nics[adapter][:bridge] = network
    end
  end

  nics
end

#read_stateObject



383
384
385
386
387
388
389
390
391
392
393
394
# File 'lib/vagrant/driver/virtualbox_4_2.rb', line 383

def read_state
  return jank_read_state if @jank_mode

  output = execute("showvminfo", @uuid, "--machinereadable", :retryable => true)
  if output =~ /^name="<inaccessible>"$/
    return :inaccessible
  elsif output =~ /^VMState="(.+?)"$/
    return $1.to_sym
  end

  nil
end

#read_used_portsObject



396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
# File 'lib/vagrant/driver/virtualbox_4_2.rb', line 396

def read_used_ports
  ports = []
  execute("list", "vms", :retryable => true).split("\n").each do |line|
    if line =~ /^".+?" \{(.+?)\}$/
      uuid = $1.to_s

      # Ignore our own used ports
      next if uuid == @uuid

      read_forwarded_ports(uuid, true).each do |_, _, hostport, _|
        ports << hostport
      end
    end
  end

  ports
end

#read_vmsObject



414
415
416
417
418
419
420
421
422
423
# File 'lib/vagrant/driver/virtualbox_4_2.rb', line 414

def read_vms
  results = []
  execute("list", "vms", :retryable => true).split("\n").each do |line|
    if line =~ /^".+?" \{(.+?)\}$/
      results << $1.to_s
    end
  end

  results
end

#set_mac_address(mac) ⇒ Object



425
426
427
# File 'lib/vagrant/driver/virtualbox_4_2.rb', line 425

def set_mac_address(mac)
  execute("modifyvm", @uuid, "--macaddress1", mac)
end

#set_name(name) ⇒ Object



429
430
431
# File 'lib/vagrant/driver/virtualbox_4_2.rb', line 429

def set_name(name)
  execute("modifyvm", @uuid, "--name", name, :retryable => true)
end

#share_folders(folders) ⇒ Object



433
434
435
436
437
438
439
440
441
442
# File 'lib/vagrant/driver/virtualbox_4_2.rb', line 433

def share_folders(folders)
  folders.each do |folder|
    args = ["--name",
            folder[:name],
            "--hostpath",
            folder[:hostpath]]
    args << "--transient" if folder.has_key?(:transient) && folder[:transient]
    execute("sharedfolder", "add", @uuid, *args)
  end
end

#ssh_port(expected_port) ⇒ Object



444
445
446
447
448
449
450
451
452
453
# File 'lib/vagrant/driver/virtualbox_4_2.rb', line 444

def ssh_port(expected_port)
  @logger.debug("Searching for SSH port: #{expected_port.inspect}")

  # Look for the forwarded port only by comparing the guest port
  read_forwarded_ports.each do |_, _, hostport, guestport|
    return hostport if guestport == expected_port
  end

  nil
end

#start(mode) ⇒ Object



455
456
457
458
459
460
461
462
463
464
465
466
467
# File 'lib/vagrant/driver/virtualbox_4_2.rb', line 455

def start(mode)
  command = ["startvm", @uuid, "--type", mode.to_s]
  r = raw(*command)

  if r.exit_code == 0 || r.stdout =~ /VM ".+?" has been successfully started/
    # Some systems return an exit code 1 for some reason. For that
    # we depend on the output.
    return true
  end

  # If we reached this point then it didn't work out.
  raise Errors::VBoxManageError, :command => command.inspect
end

#suspendObject



469
470
471
# File 'lib/vagrant/driver/virtualbox_4_2.rb', line 469

def suspend
  execute("controlvm", @uuid, "savestate")
end

#verify!Object



473
474
475
476
477
# File 'lib/vagrant/driver/virtualbox_4_2.rb', line 473

def verify!
  # This command sometimes fails if kernel drivers aren't properly loaded
  # so we just run the command and verify that it succeeded.
  execute("list", "hostonlyifs")
end

#verify_image(path) ⇒ Object



479
480
481
482
# File 'lib/vagrant/driver/virtualbox_4_2.rb', line 479

def verify_image(path)
  r = raw("import", path.to_s, "--dry-run")
  return r.exit_code == 0
end

#vm_exists?(uuid) ⇒ Boolean

Returns:

  • (Boolean)


484
485
486
# File 'lib/vagrant/driver/virtualbox_4_2.rb', line 484

def vm_exists?(uuid)
  raw("showvminfo", uuid).exit_code == 0
end