Class: HashiCorp::VagrantVMwareDesktop::Driver::Base

Inherits:
Object
  • Object
show all
Includes:
Vagrant::Util::Retryable
Defined in:
lib/vagrant-vmware-desktop/driver/base.rb

Overview

This is the base driver for VMware products, which contains some shared common helpers.

Constant Summary collapse

DEFAULT_NAT_DEVICE =

Default NAT device when detection is unavailable

"vmnet8".freeze
SECTOR_TO_BYTES =
512.freeze
VAGRANT_UTILITY_VERSION_REQUIREMENT =

Vagrant utility version requirement which must be satisfied to properly work with this version of the plugin. This should be used when new API end points are added to the utility to ensure expected functionality.

"~> 1.0.14".freeze
VMX_ETHERNET_ALLOWLIST_ENFORCE =

Enforce VMX ethernet allowlisting. Truthy or falsey values enable/disable. :quiet will enforce the allowlist without printing warning to user

false
VMX_ETHERNET_ALLOWLIST =

allowlisted networking settings that should not be removed from the VMX settings when configuring devices

["pcislotnumber"].map(&:freeze).freeze
VMX_ETHERNET_ALLOWLIST_DETECTION_PREWARNING =

Warning template printed to user when a allowlisted setting is detected in the VMX configuration before allowlisting is enabled

<<-EOW.gsub(/^ {10}/, "").freeze
  The VMX file for this box contains a setting that is automatically overwritten by Vagrant
  when started. Vagrant will stop overwriting this setting in an upcoming release which may
  prevent proper networking setup. Below is the detected VMX setting:

    %VMX_KEY% = "%VMX_VALUE%"

  If networking fails to properly configure, it may require this VMX setting. It can be manually
  applied via the Vagrantfile:

    Vagrant.configure(2) do |config|
      config.vm.provider :vmware_desktop do |vmware|
        vmware.vmx["%VMX_KEY%"] = "%VMX_VALUE%"
      end
    end

  For more information: https://www.vagrantup.com/docs/vmware/boxes.html#vmx-allowlisting
EOW
VMX_ETHERNET_ALLOWLIST_POSTFIX =

Customized setting messages to display after white list is enforced to fix boxes that may be broken by allowlisting

{
  "pcislotnumber" => <<-EOP.gsub(/^ {12}/, "").freeze
    If networking fails to properly configure, it may require adding the following setting to
    the Vagrantfile:

      Vagrant.configure(2) do |config|
        config.vm.provider :vmware_desktop do |vmware|
          vmware.vmx["%VMX_KEY%"] = "32"
        end
      end

    For more information: https://www.vagrantup.com/docs/vmware/boxes.html#vmx-allowlisting
  EOP
}
VMX_ETHERNET_ALLOWLIST_DETECTION_WARNING =

Warning template printed to user when a allowlisted setting is detected in the VMX configuration after allowlisting is enabled

<<-EOW.gsub(/^ {10}/, "").freeze
  The VMX file for this box contains a setting that is no longer overwritten by Vagrant. This
  may cause networking setup for the VM to fail. Below is the detected VMX setting that is
  no longer overwritten by Vagrant:

    %VMX_KEY% = "%VMX_VALUE%"

  For more information: https://www.vagrantup.com/docs/vmware/boxes.html#vmx-allowlisting
EOW

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(vmx_path, config) ⇒ Base

Returns a new instance of Base.



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
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
# File 'lib/vagrant-vmware-desktop/driver/base.rb', line 118

def initialize(vmx_path, config)
  @config = config

  @logger   = Log4r::Logger.new("hashicorp::provider::vmware_driver")
  @vmx_path = vmx_path
  @vmx_path = Pathname.new(@vmx_path) if @vmx_path

  if @vmx_path && @vmx_path.directory?
    # The VMX path is a directory, not a VMX. This is probably due to
    # legacy ID of a VM. Early versions of the VMware provider used the
    # directory as the ID rather than the VMX itself.
    @logger.info("VMX path is a directory. Finding VMX file...")

    # Set the VM dir
    @vm_dir = @vmx_path

    # Find the VMX file
    @vmx_path = nil
    @vm_dir.children(true).each do |child|
      if child.basename.to_s =~ /^(.+?)\.vmx$/
        @vmx_path = child
        break
      end
    end

    raise Errors::DriverMissingVMX, :vm_dir => @vm_dir.to_s if !@vmx_path
  end

  # Make sure the vm_dir is properly set always to the directory
  # containing the VMX
  @vm_dir = nil
  @vm_dir = @vmx_path.parent if @vmx_path

  @logger.info("VMX file: #{@vmx_path}")
  @vagrant_utility = Helper::VagrantUtility.new(
    config.utility_host, config.utility_port,
    certificate_path: config.utility_certificate_path
  )

  if config.force_vmware_license
    @logger.warn("overriding VMware license detection with value: #{config.force_vmware_license}")
    @license = config.force_vmware_license
  end

  set_vmware_info
  if config.nat_device.nil?
    if professional?
      detect_nat_device!
    else
      @logger.warn("standard license is in use - forcing default NAT device (#{DEFAULT_NAT_DEVICE})")
      config.nat_device = DEFAULT_NAT_DEVICE
    end
  end
end

Instance Attribute Details

#configVagrant::Config (readonly)

Provider config

Returns:

  • (Vagrant::Config)


108
109
110
# File 'lib/vagrant-vmware-desktop/driver/base.rb', line 108

def config
  @config
end

#utility_versionGem::Version (readonly)

Vagrant utility version

Returns:

  • (Gem::Version)


113
114
115
# File 'lib/vagrant-vmware-desktop/driver/base.rb', line 113

def utility_version
  @utility_version
end

#vagrant_utilityHelper::VagrantUtility (readonly)

Helper utility for interacting with the Vagrant VMware Utility REST API



103
104
105
# File 'lib/vagrant-vmware-desktop/driver/base.rb', line 103

def vagrant_utility
  @vagrant_utility
end

#vm_dirPathname (readonly)

This is the path to the VM folder. If it is nil then the VM hasn’t yet been created.

Returns:

  • (Pathname)


93
94
95
# File 'lib/vagrant-vmware-desktop/driver/base.rb', line 93

def vm_dir
  @vm_dir
end

#vmx_pathPathname (readonly)

This is the path to the VMX file.

Returns:

  • (Pathname)


98
99
100
# File 'lib/vagrant-vmware-desktop/driver/base.rb', line 98

def vmx_path
  @vmx_path
end

Instance Method Details

#add_disk_to_vmx(filename, slot, extra_opts = {}) ⇒ Object

Adds a disk to the vm’s vmx file



1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
# File 'lib/vagrant-vmware-desktop/driver/base.rb', line 1035

def add_disk_to_vmx(filename, slot, extra_opts={})
  root_key, _ = slot.split(":", 2)
  vmx_modify do |vmx|
    vmx["#{root_key}.present"] = "TRUE"
    vmx["#{slot}.filename"] = filename
    vmx["#{slot}.present"] = "TRUE"
    extra_opts.each do |key, value|
      vmx["#{slot}.#{key}"] = value
    end
  end
end

#all_forwarded_ports(full_info = false) ⇒ Array<Integer>

Returns an array of all forwarded ports from the VMware NAT configuration files.

Returns:

  • (Array<Integer>)


215
216
217
218
219
220
221
222
223
224
225
# File 'lib/vagrant-vmware-desktop/driver/base.rb', line 215

def all_forwarded_ports(full_info = false)
  all_fwds = vagrant_utility.get("/vmnet/#{config.nat_device}/portforward")
  if all_fwds.success?
    fwds = all_fwds.get(:content, :port_forwards) || []
    @logger.debug("existing port forwards: #{fwds}")
    full_info ? fwds : fwds.map{|fwd| fwd[:port]}
  else
    raise Errors::DriverAPIPortForwardListError,
      message: all_fwds[:content][:message]
  end
end

#clear_shared_foldersObject

This removes all the shared folders from the VM.



269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
# File 'lib/vagrant-vmware-desktop/driver/base.rb', line 269

def clear_shared_folders
  @logger.info("Clearing shared folders...")

  vmx_modify do |vmx|
    vmx.keys.each do |key|
      # Delete all specific shared folder configs
      if key =~ /^sharedfolder\d+\./i
        vmx.delete(key)
      end
    end

    # Tell VMware that we have no shared folders
    vmx["sharedfolder.maxnum"] = "0"
  end
end

#clone(source_vmx, destination, linked = false) ⇒ Pathname

This clones a VMware VM from one folder to another.

Parameters:

  • source_vmx (Pathname)

    The path to the VMX file of the source.

  • destination (Pathname)

    The path to the directory where the VM will be placed.

  • use (Boolean)

    linked clone

Returns:

  • (Pathname)

    The path to the new VMX file.



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
# File 'lib/vagrant-vmware-desktop/driver/base.rb', line 292

def clone(source_vmx, destination, linked=false)
  # If we're prior to Vagrant 1.8, then we don't do any linked
  # clones since we don't have some of the core things in to make
  # this a smoother experience.
  if Gem::Version.new(Vagrant::VERSION) < Gem::Version.new("1.8.0")
    linked = false
  end

  # We can't just check if the user has a standard license since
  # workstation with a standard license (player) will not allow
  # linked cloning, but a standard license on fusion will allow it
  if @license.to_s.downcase == "player"
    @logger.warn("disabling linked clone due to insufficient access based on VMware license")
    linked = false
  end

  if linked
    @logger.info("Cloning machine using VMware linked clones.")
    # The filename of the resulting VMX
    destination_vmx = destination.join(source_vmx.basename)

    begin
      # Do a linked clone!
      vmrun("clone", host_path(source_vmx), host_path(destination_vmx), "linked")
      # Common cleanup
    rescue Errors::VMRunError => e
      # Check if this version of VMware doesn't support linked clones
      # and just super it up.
      stdout = e.extra_data[:stdout] || ""
      if stdout.include?("parameters was invalid")
        @logger.warn("VMware version doesn't support linked clones, falling back")
        destination_vmx = false
      else
        raise
      end
    end
  end

  if !destination_vmx
    @logger.info("Cloning machine using direct copy.")
    # Sanity test
    if !destination.directory?
      raise Errors::CloneFolderNotFolder, path: destination.to_s
    end

    # Just copy over the files within the folder of the source
    @logger.info("Cloning VM to #{destination}")
    source_vmx.parent.children(true).each do |child|
      @logger.debug("Copying: #{child.basename}")
      begin
        FileUtils.cp_r child.to_s, destination.to_s
      rescue Errno::EACCES
        raise Errors::DriverClonePermissionFailure,
          destination: destination.to_s
      end

      # If we suddenly didn't become a directory, something is
      # really messed up. We should see in the stack trace its
      # from this case.
      if !destination.directory?
        raise Errors::CloneFolderNotFolder, path: destination.to_s
      end
    end

    # Calculate the VMX file of the destination
    destination_vmx = destination.join(source_vmx.basename)
  end

  # Perform the cleanup
  clone_cleanup(destination_vmx)

  # Return the final name
  destination_vmx
end

#create_disk(disk_filename, disk_size, disk_type, disk_adapter) ⇒ Object

Create a vmdk disk



1014
1015
1016
1017
1018
1019
# File 'lib/vagrant-vmware-desktop/driver/base.rb', line 1014

def create_disk(disk_filename, disk_size, disk_type, disk_adapter)
  disk_path = File.join(File.dirname(@vmx_path), disk_filename)
  disk_size = "#{Vagrant::Util::Numeric.bytes_to_megabytes(disk_size).to_s}MB"
  vdiskmanager("-c", "-s", disk_size, "-t", disk_type.to_s, "-a", disk_adapter, disk_path)
  disk_path
end

#create_vmnet_device(config) ⇒ Object

This creates a new vmnet device and returns information about that device.

Parameters:

  • config (Hash)

    Configuration for the new vmnet device



379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
# File 'lib/vagrant-vmware-desktop/driver/base.rb', line 379

def create_vmnet_device(config)
  result = vagrant_utility.post("/vmnet",
    subnet: config[:subnet_ip],
    mask: config[:netmask]
  )
  if !result.success?
    raise Errors::DriverAPIDeviceCreateError,
      message: result[:content][:message]
  end
  result_device = result.get(:content)
  new_device = {
    name: result_device[:name],
    nummber: result_device[:name].sub('vmnet', '').to_i,
    dhcp: result_device[:dhcp],
    hostonly_netmask: result_device[:mask],
    hostonly_subnet: result_device[:subnet]
  }
end

#deleteObject

This deletes the VM.



399
400
401
402
# File 'lib/vagrant-vmware-desktop/driver/base.rb', line 399

def delete
  @logger.info("Deleting VM: #{@vm_dir}")
  @vm_dir.rmtree
end

#detect_nat_device!Object

Pull list of vmware devices and detect any NAT types. Use first device discovered



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
# File 'lib/vagrant-vmware-desktop/driver/base.rb', line 185

def detect_nat_device!
  vmnets = read_vmnet_devices
  # First check the default device and if it has NAT enabled, use that
  device = vmnets.detect do |dev|
    dev[:name] == DEFAULT_NAT_DEVICE &&
      dev[:type].to_s.downcase == "nat" &&
      dev[:dhcp] && dev[:hostonly_subnet]
  end
  # If the default device isn't properly configured, now we detect
  if !device
    device = vmnets.detect do |dev|
      @logger.debug("checking device for NAT usage #{dev}")
      dev[:type].to_s.downcase == "nat" &&
        dev[:dhcp] && dev[:hostonly_subnet]
    end
  end
  # If we aren't able to properly detect the device, just use the default
  if device.nil?
    @logger.warn("failed to locate configured NAT device, using default - #{DEFAULT_NAT_DEVICE}")
    config.nat_device = DEFAULT_NAT_DEVICE
    return
  end
  @logger.debug("discovered vmware NAT device: #{device[:name]}")
  config.nat_device = device[:name]
end

#discard_suspended_stateObject

This discards the suspended state of the machine.



405
406
407
408
409
410
411
412
413
414
415
416
417
# File 'lib/vagrant-vmware-desktop/driver/base.rb', line 405

def discard_suspended_state
  Dir.glob("#{@vm_dir}/*.vmss").each do |file|
    @logger.info("Deleting VM state file: #{file}")
    File.delete(file)
  end

  vmx_modify do |vmx|
    # Remove the checkpoint keys
    vmx.delete("checkpoint.vmState")
    vmx.delete("checkpoint.vmState.readOnly")
    vmx.delete("vmotion.checkpointFBSize")
  end
end

#enable_shared_foldersObject

This enables shared folders on the VM.



420
421
422
423
# File 'lib/vagrant-vmware-desktop/driver/base.rb', line 420

def enable_shared_folders
  @logger.info("Enabling shared folders...")
  vmrun("enableSharedFolders", host_vmx_path, :retryable => true)
end

#export(destination_vmx) ⇒ Object



367
368
369
370
371
372
373
# File 'lib/vagrant-vmware-desktop/driver/base.rb', line 367

def export(destination_vmx)
  destination_vmx = Pathname.new(destination_vmx)
  @logger.debug("Starting full clone export to: #{destination_vmx}")
  vmrun("clone", host_vmx_path, host_path(destination_vmx), "full")
  clone_cleanup(destination_vmx)
  @logger.debug("Full clone export complete #{vmx_path} -> #{destination_vmx}")
end

#forward_ports(definitions) ⇒ Object

This configures a set of forwarded port definitions on the machine.

Parameters:

  • <Array<Hash>] (<Array<Hash>] definitions The ports to forward.)

    definitions The ports to forward.



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
# File 'lib/vagrant-vmware-desktop/driver/base.rb', line 429

def forward_ports(definitions)
  if Vagrant::Util::Platform.windows?
    vmxpath = @vmx_path.to_s.gsub("/", 92.chr)
  elsif VagrantVMwareDesktop.wsl?
    vmxpath = host_vmx_path
  else
    vmxpath = @vmx_path.to_s
  end
  @logger.debug("requesting ports to be forwarded: #{definitions}")
  # Starting with utility version 1.0.7 we can send all port forward
  # requests at once to be processed. We include backwards compatible
  # support to allow earlier utility versions to remain functional.
  if utility_version > Gem::Version.new("1.0.6")
    @logger.debug("forwarding ports via collection method")
    definitions.group_by{|f| f[:device]}.each_pair do |device, pfwds|
      fwds = pfwds.map do |fwd|
        {
          :port => fwd[:host_port],
          :protocol => fwd.fetch(:protocol, "tcp").to_s.downcase,
          :description => "vagrant: #{vmxpath}",
          :guest => {
            :ip => fwd[:guest_ip],
            :port => fwd[:guest_port]
          }
        }
      end
      result = vagrant_utility.put("/vmnet/#{device}/portforward", fwds)
      if !result.success?
        raise Errors::DriverAPIPortForwardError,
          message: result[:content][:message]
      end
    end
  else
    @logger.debug("forwarding ports via individual method")
    definitions.each do |fwd|
      result = vagrant_utility.put("/vmnet/#{fwd[:device]}/portforward",
        :port => fwd[:host_port],
        :protocol => fwd.fetch(:protocol, "tcp").to_s.downcase,
        :description => "vagrant: #{vmxpath}",
        :guest => {
          :ip => fwd[:guest_ip],
          :port => fwd[:guest_port]
        }
      )
      if !result.success?
        raise Errors::DriverAPIPortForwardError,
          message: result.get(:content, :message)
      end
    end
  end
end

#forwarded_ports_by_ip(ip = nil) ⇒ Hash

Returns port forwards grouped by IP

Parameters:

  • ip (String) (defaults to: nil)

    guest IP address (optional)

Returns:

  • (Hash)


231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
# File 'lib/vagrant-vmware-desktop/driver/base.rb', line 231

def forwarded_ports_by_ip(ip = nil)
  all_fwds = vagrant_utility.get("/vmnet/#{config.nat_device}/portforward")
  result = {}
  Array(all_fwds.get(:content, :port_forwards)).each do |fwd|
    g_ip = fwd[:guest][:ip]
    g_port = fwd[:guest][:port]
    h_port = fwd[:port]
    f_proto = fwd[:protocol].downcase.to_sym
    result[g_ip] ||= {:tcp => {}, :udp => {}}
    result[g_ip][f_proto][g_port] = h_port
  end
  if ip
    @logger.debug("port forwards for IP #{ip}: #{result[ip]}")
    result[ip]
  else
    @logger.debug("port forwards by IP: #{result}")
    result
  end
end

#get_disk_size(disk_path) ⇒ int?

Returns:

  • (int, nil)

    size of disk in bytes, nil if path does not exist



1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
# File 'lib/vagrant-vmware-desktop/driver/base.rb', line 1078

def get_disk_size(disk_path)
  return nil if !File.exist?(disk_path)

  disk_size = 0
  at_extent_description = false
  File.foreach(disk_path) do |line|
    next if !line.valid_encoding?
    # Look for `# Extent description` header
    if line.include?("# Extent description")
      at_extent_description = true
      next
    end
    if at_extent_description
      # Exit once the "Extent description" section is done
      # signified by the new line
      if line == "\n"
        break
      else
        # Get the 2nd entry on each line - number of sectors
        sectors = line.split(" ")[1].to_i
        # Convert sectors to bytes
        disk_size += (sectors * SECTOR_TO_BYTES)
      end
    end
  end
  disk_size
end

#get_disks(types) ⇒ Hash

Gets the currently attached disks

Parameters:

  • List (List<String>)

    of disk types to search for

Returns:

  • (Hash)

    Hash of disks



992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
# File 'lib/vagrant-vmware-desktop/driver/base.rb', line 992

def get_disks(types)
  vmx = read_vmx_data
  disks = {}
  vmx.each do |k, v|
    if k.match(/(#{types.map{|t| Regexp.escape(t)}.join("|")})\d+:\d+/)
      key, attribute = k.split(".", 2)
      if disks[key].nil?
        disks[key] = {attribute => v}
      else
        disks[key].merge!({attribute => v})
      end
    end
  end
  disks
end

#grow_disk(disk_path, disk_size) ⇒ Object

Make a disk larger



1025
1026
1027
1028
# File 'lib/vagrant-vmware-desktop/driver/base.rb', line 1025

def grow_disk(disk_path, disk_size)
  disk_size = "#{Vagrant::Util::Numeric.bytes_to_megabytes(disk_size).to_s}MB"
  vdiskmanager("-x", disk_size, disk_path)
end

#host_port_forward(ip, proto, guest_port) ⇒ Integer?

Returns host port mapping for the given guest port

Parameters:

  • ip (String)

    guest IP address

  • proto (String, Symbol)

    protocol type (tcp/udp)

  • guest_port (Integer)

    guest port

Returns:

  • (Integer, nil)

    host port



257
258
259
260
261
262
263
264
265
266
# File 'lib/vagrant-vmware-desktop/driver/base.rb', line 257

def host_port_forward(ip, proto, guest_port)
  proto = proto.to_sym
  if ![:udp, :tcp].include?(proto)
    raise ArgumentError.new("Unsupported protocol provided!")
  end
  fwd_ports = forwarded_ports_by_ip(ip)
  if fwd_ports && fwd_ports[proto]
    fwd_ports[proto][guest_port]
  end
end

#professional?Boolean

Returns using professional license.

Returns:

  • (Boolean)

    using professional license



179
180
181
# File 'lib/vagrant-vmware-desktop/driver/base.rb', line 179

def professional?
  @pro_license
end

#prune_forwarded_portsObject

This is called to prune the forwarded ports from NAT configurations.



482
483
484
485
486
487
488
489
# File 'lib/vagrant-vmware-desktop/driver/base.rb', line 482

def prune_forwarded_ports
  @logger.debug("requesting prune of unused port forwards")
  result = vagrant_utility.delete("/portforwards")
  if !result.success?
    raise Errors::DriverAPIPortForwardPruneError,
      message: result.get(:content, :message)
  end
end

#read_ip(enable_vmrun_ip_lookup = true) ⇒ String

This returns an IP that can be used to access the machine.

Returns:

  • (String)


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
594
595
# File 'lib/vagrant-vmware-desktop/driver/base.rb', line 516

def read_ip(enable_vmrun_ip_lookup=true)
  @logger.info("Reading an accessible IP for machine...")

  # NOTE: Read from DHCP leases first so we can attempt to fetch the address
  # for the vmnet8 device first. If multiple networks are defined on the guest
  # it will return the address of the last device, which will fail when doing
  # port forward lookups

  # Read the VMX data so that we can look up the network interfaces
  # and find a properly accessible IP.
  vmx = read_vmx_data

  0.upto(8).each do |slot|
    # We don't care if this adapter isn't present
    next if vmx["ethernet#{slot}.present"] != "TRUE"

    # Get the type of this adapter. Bail if there is no type.
    type = vmx["ethernet#{slot}.connectiontype"]
    next if !type

    if type != "nat" && type != "custom"
      @logger.warn("Non-NAT interface on slot #{slot}. We can only read IPs of NATs for now.")
      next
    end

    # Get the MAC address
    @logger.debug("Trying to get MAC address for ethernet#{slot}")
    mac = vmx["ethernet#{slot}.address"]
    if !mac || mac == ""
      @logger.debug("No explicitly set MAC, looking or auto-generated one...")
      mac = vmx["ethernet#{slot}.generatedaddress"]

      if !mac
        @logger.warn("Couldn't find MAC, can't determine IP.")
        next
      end
    end

    @logger.debug(" -- MAC: #{mac}")

    # Look up the IP!
    dhcp_ip = read_dhcp_lease(config.nat_device, mac)
    return dhcp_ip if dhcp_ip
  end

  if enable_vmrun_ip_lookup
    # Try to read the IP using vmrun getGuestIPAddress. This
    # won't work if the guest doesn't have guest tools installed or
    # is using an old version of VMware.
    begin
      @logger.info("Trying vmrun getGuestIPAddress...")
      result = vmrun("getGuestIPAddress", host_vmx_path)
      result = result.stdout.chomp

      # If returned address ends with a ".1" do not accept address
      # and allow lookup via VMX.
      # see: https://github.com/vmware/open-vm-tools/issues/93
      if result.end_with?(".1")
        @logger.warn("vmrun getGuestIPAddress returned: #{result}. Result resembles address retrieval from wrong " \
          "interface. Discarding value and proceeding with VMX based lookup.")
        result = nil
      else
        # Try to parse the IP Address. This will raise an exception
        # if it fails, which will halt our attempt to use it.
        IPAddr.new(result)
        @logger.info("vmrun getGuestIPAddress success: #{result}")
        return result
      end
    rescue Errors::VMRunError
      @logger.info("vmrun getGuestIPAddress failed: VMRunError")
      # Ignore, try the MAC address way.
    rescue IPAddr::InvalidAddressError
      @logger.info("vmrun getGuestIPAddress failed: InvalidAddressError for #{result.inspect}")
      # Ignore, try the MAC address way.
    end
  else
    @logger.info("Skipping vmrun getGuestIPAddress as requested by config.")
  end
  nil
end

#read_mac_addressesObject

This reads all the network adapters and returns their assigned MAC addresses



687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
# File 'lib/vagrant-vmware-desktop/driver/base.rb', line 687

def read_mac_addresses
  vmx = read_vmx_data
  macs = {}
  vmx.keys.each do |key|
    # We only care about finding present ethernet adapters
    match = /^ethernet(\d+)\.present$/i.match(key)
    next if !match
    next if vmx[key] != "TRUE"

    slot = match[1].to_i

    # Vagrant's calling code assumes the MAC is all caps no colons
    mac = vmx["ethernet#{slot}.generatedaddress"].to_s
    mac = mac.upcase.gsub(/:/, "")

    # Vagrant's calling code assumes these will be 1-indexed
    slot += 1

    macs[slot] = mac
  end
  macs
end

#read_network_adaptersArray<Hash>

This reads all the network adapters that are on the machine and enabled.

Returns:

  • (Array<Hash>)


601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
# File 'lib/vagrant-vmware-desktop/driver/base.rb', line 601

def read_network_adapters
  vmx = read_vmx_data

  adapters = []
  vmx.keys.each do |key|
    # We only care about finding present ethernet adapters
    match = /^ethernet(\d+)\.present$/i.match(key)
    next if !match
    next if vmx[key] != "TRUE"

    # We found one, so store it away
    slot    = match[1]
    adapter = {
      :slot => slot,
      :type => vmx["ethernet#{slot}.connectiontype"]
    }

    adapters << adapter
  end

  return adapters
end

#read_running_vmsArray<String>

This returns an array of paths to all the running VMX files.

Returns:

  • (Array<String>)


627
628
629
630
631
# File 'lib/vagrant-vmware-desktop/driver/base.rb', line 627

def read_running_vms
  vmrun("list").stdout.split("\n").find_all do |path|
    path !~ /running VMs:/
  end
end

#read_stateSymbol

This reads the state of this VM and returns a symbol representing it.

Returns:

  • (Symbol)


637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
# File 'lib/vagrant-vmware-desktop/driver/base.rb', line 637

def read_state
  # The VM is not created if we don't have a directory
  return :not_created if !@vm_dir

  # Check to see if the VM is running, which requires shelling out
  vmx_path = nil
  begin
    vmx_path = @vmx_path.realpath.to_s
  rescue Errno::ENOENT
    @logger.info("VMX path doesn't exist, not created: #{@vmx_path}")
    return :not_created
  end

  vmx_path = host_vmx_path

  # Downcase the lines in certain case-insensitive cases
  downcase = VagrantVMwareDesktop.case_insensitive_fs?(vmx_path)

  # OS X is case insensitive so just lowercase everything
  vmx_path = vmx_path.downcase if downcase

  if Vagrant::Util::Platform.windows?
    # Replace any slashes to be unix-style.
    vmx_path.gsub!(92.chr, "/")
  end

  vmrun("list").stdout.split("\n").each do |line|
    if Vagrant::Util::Platform.windows?
      # On Windows, we normalize the paths to unix-style.
      line.gsub!("\\", "/")

      # We also change any drive letter to be lowercased
      line[0] = line[0].downcase
    end

    # Case insensitive filesystems, so we downcase.
    line = line.downcase if downcase
    return :running if line == vmx_path
  end

  # Check to see if the VM is suspended based on whether a file
  # exists in the VM directory
  return :suspended if Dir.glob("#{@vm_dir}/*.vmss").length >= 1

  # I guess it is not running.
  return :not_running
end

#read_vmnet_devicesArray<Hash>

This reads the vmnet devices and various information about them.

Returns:

  • (Array<Hash>)


731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
# File 'lib/vagrant-vmware-desktop/driver/base.rb', line 731

def read_vmnet_devices
  result = vagrant_utility.get("/vmnet")
  if !result.success?
    raise Errors::DriverAPIDeviceListError,
      message: result[:content][:message]
  end
  Array(result.get(:content, :vmnets)).map do |vmnet|
    {
      name: vmnet[:name],
      type: vmnet[:type],
      number: vmnet[:name].sub('vmnet', '').to_i,
      dhcp: vmnet[:dhcp],
      hostonly_netmask: vmnet[:mask],
      hostonly_subnet: vmnet[:subnet],
      virtual_adapter: "yes"
    }
  end
end

#remove_disk(disk_filename) ⇒ Object



1067
1068
1069
1070
1071
# File 'lib/vagrant-vmware-desktop/driver/base.rb', line 1067

def remove_disk(disk_filename)
  disk_path = File.join(File.dirname(@vmx_path), disk_filename)
  vdiskmanager("-U", disk_path) if File.exist?(disk_path)
  remove_disk_from_vmx(disk_filename)
end

#remove_disk_from_vmx(filename, extra_opts = []) ⇒ Object

Removes a disk to the vm’s vmx file



1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
# File 'lib/vagrant-vmware-desktop/driver/base.rb', line 1051

def remove_disk_from_vmx(filename, extra_opts=[])
  vmx = read_vmx_data
  vmx_disk_entry = vmx.select { |_, v| v == filename }
  if !vmx_disk_entry.empty?
    slot = vmx_disk_entry.keys.first.split(".").first
    vmx_modify do |vmx|
      vmx.delete("#{slot}.filename")
      vmx.delete("#{slot}.present")
      extra_opts.each do |opt|
        vmx.delete("#{slot}.#{opt}")
      end
    end
  end
end

#reserve_dhcp_address(ip, mac, vmnet = "vmnet8") ⇒ true

Reserve an address on the DHCP sever for the given MAC address. Defaults to the NAT device at vmnet8

Parameters:

  • ip (String)

    IP address to reserve

  • mac (String)

    MAC address to associate

Returns:

  • (true)


716
717
718
719
720
721
722
723
724
725
726
# File 'lib/vagrant-vmware-desktop/driver/base.rb', line 716

def reserve_dhcp_address(ip, mac, vmnet="vmnet8")
  result = vagrant_utility.put("/vmnet/#{vmnet}/dhcpreserve/#{mac}/#{ip}")
  if !result.success?
    raise Errors::DriverAPIAddressReservationError,
      device: vmnet,
      address: ip,
      mac: mac,
      message: result[:content][:message]
  end
  true
end

#scrub_forwarded_portsObject

This is used to remove all forwarded ports, including those not registered with the plugin



493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
# File 'lib/vagrant-vmware-desktop/driver/base.rb', line 493

def scrub_forwarded_ports
  fwds = all_forwarded_ports(true)
  return if fwds.empty?
  if utility_version > Gem::Version.new("1.0.7")
    result = vagrant_utility.delete("/vmnet/#{config.nat_device}/portforward", fwds)
    if !result.success?
      raise Errors::DriverAPIPortForwardPruneError,
        message: result[:content][:message]
    end
  else
    fwds.each do |fwd|
      result = vagrant_utility.delete("/vmnet/#{config.nat_device}/portforward", fwd)
      if !result.success?
        raise Errors::DriverAPIPortForwardPruneError,
          message: result.get(:content, :message)
      end
    end
  end
end

#setup_adapters(adapters, allowlist_verified = false) ⇒ Object

This modifies the metadata of the virtual machine to add the given network adapters.

Parameters:

  • adapters (Array)


754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
# File 'lib/vagrant-vmware-desktop/driver/base.rb', line 754

def setup_adapters(adapters, allowlist_verified=false)
  vmx_modify do |vmx|
    # Remove all previous adapters
    vmx.keys.each do |key|
      check_key = key.downcase
      ethernet_key = key.match(/^ethernet\d\.(?<setting_name>.+)$/)
      if !ethernet_key.nil? && !VMX_ETHERNET_ALLOWLIST.include?(ethernet_key["setting_name"])
        @logger.warn("setup_adapter: Removing VMX key: #{ethernet_key}")
        vmx.delete(key)
      elsif ethernet_key
        if !allowlist_verified
          display_ethernet_allowlist_warning(key, vmx[key])
        elsif allowlist_verified  == :disable_warning
          @logger.warn("VMX allowlisting warning message has been disabled via configuration. `#{key}`")
        else
          @logger.info("VMX allowlisting has been verified via configuration. `#{key}`")
        end
        if !VMX_ETHERNET_ALLOWLIST_ENFORCE && allowlist_verified != true
          @logger.warn("setup_adapter: Removing allowlisted VMX key: #{ethernet_key}")
          vmx.delete(key)
        end
      end
    end

    # Go through the adapters to enable and set them up properly
    adapters.each do |adapter|
      key = "ethernet#{adapter[:slot]}"

      vmx["#{key}.present"] = "TRUE"
      vmx["#{key}.connectiontype"] = adapter[:type].to_s
      vmx["#{key}.virtualdev"] = "e1000"

      if adapter[:mac_address]
        vmx["#{key}.addresstype"] = "static"
        vmx["#{key}.address"] = adapter[:mac_address]
      else
        # Dynamically generated MAC address
        vmx["#{key}.addresstype"] = "generated"
      end

      if adapter[:vnet]
        # Some adapters define custom vmnet devices to connect to
        vmx["#{key}.vnet"] = adapter[:vnet]
        vmx["#{key}.connectiontype"] = "custom" if adapter[:type] == :nat
      end
    end
  end
end

#share_folder(id, hostpath) ⇒ Object

This creates a shared folder within the VM.



804
805
806
807
808
809
# File 'lib/vagrant-vmware-desktop/driver/base.rb', line 804

def share_folder(id, hostpath)
  @logger.info("Adding a shared folder '#{id}': #{hostpath}")

  vmrun("addSharedFolder", host_vmx_path, id, host_path(hostpath))
  vmrun("setSharedFolderState", host_vmx_path, id, host_path(hostpath), "writable")
end

#snapshot_delete(name) ⇒ Object



817
818
819
# File 'lib/vagrant-vmware-desktop/driver/base.rb', line 817

def snapshot_delete(name)
  vmrun("deleteSnapshot", host_vmx_path, name)
end

#snapshot_listObject



825
826
827
828
829
830
831
832
833
834
# File 'lib/vagrant-vmware-desktop/driver/base.rb', line 825

def snapshot_list
  snapshots = []
  vmrun("listSnapshots", host_vmx_path).stdout.split("\n").each do |line|
    if !line.include?("Total snapshot")
      snapshots << line
    end
  end

  snapshots
end

#snapshot_revert(name) ⇒ Object



821
822
823
# File 'lib/vagrant-vmware-desktop/driver/base.rb', line 821

def snapshot_revert(name)
  vmrun("revertToSnapshot", host_vmx_path, name)
end

#snapshot_take(name) ⇒ Object

All the methods below deal with snapshots: taking them, restoring them, deleting them, etc.



813
814
815
# File 'lib/vagrant-vmware-desktop/driver/base.rb', line 813

def snapshot_take(name)
  vmrun("snapshot", host_vmx_path, name)
end

#snapshot_treeObject



836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
# File 'lib/vagrant-vmware-desktop/driver/base.rb', line 836

def snapshot_tree
  snapshots = []
  vmrun("listSnapshots", host_vmx_path, "showTree").stdout.split("\n").each do |line|
    if !line.include?("Total snapshot")
      # if the line starts with white space then it is a child
      # of the previous line
      if line.start_with?(/\s/)
        name = "#{snapshots.last}/#{line.gsub(/\s/, "")}"
        snapshots << name
      else
        snapshots << line
      end
    end
  end

  snapshots
end

#standard?Boolean

Returns using standard license.

Returns:

  • (Boolean)

    using standard license



174
175
176
# File 'lib/vagrant-vmware-desktop/driver/base.rb', line 174

def standard?
  !professional?
end

#start(gui = false) ⇒ Object

This will start the VMware machine.



855
856
857
858
859
860
861
862
# File 'lib/vagrant-vmware-desktop/driver/base.rb', line 855

def start(gui=false)
  gui_arg = gui ? "gui" : "nogui"
  vmrun("start", host_vmx_path, gui_arg, retryable: true, timeout: 45)
rescue Vagrant::Util::Subprocess::TimeoutExceeded
  # Sometimes vmrun just hangs. We give it a generous timeout
  # of 45 seconds, and then throw this.
  raise Errors::StartTimeout
end

#stop(stop_mode = "soft") ⇒ Object

This will stop the VMware machine.



865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
# File 'lib/vagrant-vmware-desktop/driver/base.rb', line 865

def stop(stop_mode="soft")
  begin
    vmrun("stop", host_vmx_path, stop_mode, :retryable => true, timeout: 15)
  rescue Errors::VMRunError, Vagrant::Util::Subprocess::TimeoutExceeded
    begin
      vmrun("stop", host_vmx_path, "hard", :retryable => true)
    rescue Errors::VMRunError
      # There is a chance that the "soft" stop may have timed out, yet
      # still succeeded which would result in the "hard" stop failing
      # due to the guest not running. Because of this we do a quick
      # state check and only allow the error if the guest is still
      # running
      raise if read_state == :running
    end
  end
end

#suppress_messagesObject

This is called to do any message suppression if we need to.



888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
# File 'lib/vagrant-vmware-desktop/driver/base.rb', line 888

def suppress_messages
  if PRODUCT_NAME == "fusion"
    contents = <<-DATA
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
	<key>disallowUpgrade</key>
	<true/>
</dict>
</plist>
  DATA

    if @vmx_path
      filename = @vmx_path.basename.to_s.gsub(".vmx", ".plist")
      @vmx_path.dirname.join(filename).open("w+") do |f|
        f.puts(contents.strip)
      end
    end
  end
end

#suspendObject

This will suspend the VMware machine.



883
884
885
# File 'lib/vagrant-vmware-desktop/driver/base.rb', line 883

def suspend
  vmrun("suspend", host_vmx_path, :retryable => true)
end

#verify!Object

This method is called to verify that the installation looks good, and raises an exception if it doesn’t.



912
913
914
915
916
917
918
919
# File 'lib/vagrant-vmware-desktop/driver/base.rb', line 912

def verify!
  utility_requirement = Gem::Requirement.new(VAGRANT_UTILITY_VERSION_REQUIREMENT.split(","))
  if !utility_requirement.satisfied_by?(utility_version)
    raise Errors::UtilityUpgradeRequired,
      utility_version: utility_version.to_s,
      utility_requirement: utility_requirement.to_s
  end
end

#verify_vmnet!Object

This method is called to verify whether the vmnet devices are healthy. If not, an exception should be raised.



923
924
925
926
927
928
929
930
931
932
933
934
# File 'lib/vagrant-vmware-desktop/driver/base.rb', line 923

def verify_vmnet!
  result = vagrant_utility.post("/vmnet/verify")
  if !result.success?
    # Check if the result was a 404. This indicates a utility service
    # running before the vmnet verification endpoint was introduced
    # and is not really an error
    if result[:code] == 404
      return
    end
    raise Errors::VMNetDevicesWontStart
  end
end

#vmware_utility_versionString?

Gets the version of the vagrant-vmware-utility currently in use

Returns:

  • (String, nil)


980
981
982
983
984
985
986
# File 'lib/vagrant-vmware-desktop/driver/base.rb', line 980

def vmware_utility_version
  @logger.debug("Getting version from vagrant-vmware-utility")
  result = vagrant_utility.get("/version")
  if result.success?
    result.get(:content, :version)
  end
end

#vmx_alive?Boolean

This method returns whether or not the VMX process is still alive.

Returns:

  • (Boolean)


937
938
939
940
941
942
943
# File 'lib/vagrant-vmware-desktop/driver/base.rb', line 937

def vmx_alive?
  # If we haven't cleanly shut down, then it is alive.
  read_vmx_data["cleanshutdown"] != "TRUE"

  # Note at some point it would be nice to actually track the VMX
  # process itself. But at this point this isn't very feasible.
end

#vmx_modify {|vmx_data| ... } ⇒ Object

This allows modifications of the VMX file by handling it as a simple hash. By adding/modifying/deleting keys in the hash, the VMX is modified.

Yields:

  • (vmx_data)


948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
# File 'lib/vagrant-vmware-desktop/driver/base.rb', line 948

def vmx_modify
  # Read the data once
  vmx_data = read_vmx_data

  # Yield it so that it can be modified
  yield vmx_data

  # And write it back!
  @logger.info("Modifying VMX data...")
  @vmx_path.open("w") do |f|
    vmx_data.keys.sort.each do |key|
      value = vmx_data[key]

      # We skip nil values and remove them from the output
      if value.nil?
        @logger.debug("  - DELETE #{key}")
        next
      end

      # Write the value
      @logger.debug("  - SET #{key} = \"#{value}\"")
      f.puts("#{key} = \"#{value}\"")
    end

    f.fsync
  end
end