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

SOURCE_VMXPATH_FILE_NAME =
"source-vmx"
SOURCE_SNAPSHOT_FILE_NAME =
"source-snapshot"
DEFAULT_NAT_DEVICE =

Default NAT device when detection is unavailable

"vmnet8".freeze
DEFAULT_NIC_DEVICE =

Default NIC device when setting up network

"e1000e".freeze
SECTOR_TO_BYTES =

Number of bytes in disk sector

512.freeze
VMRUN_START_TIMEOUT =

Number of seconds to allow the vmrun start command to complete

300.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.



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
172
173
174
175
176
177
178
179
180
181
182
183
184
185
# File 'lib/vagrant-vmware-desktop/driver/base.rb', line 132

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)


122
123
124
# File 'lib/vagrant-vmware-desktop/driver/base.rb', line 122

def config
  @config
end

#utility_versionGem::Version (readonly)

Vagrant utility version

Returns:

  • (Gem::Version)


127
128
129
# File 'lib/vagrant-vmware-desktop/driver/base.rb', line 127

def utility_version
  @utility_version
end

#vagrant_utilityHelper::VagrantUtility (readonly)

Helper utility for interacting with the Vagrant VMware Utility REST API



117
118
119
# File 'lib/vagrant-vmware-desktop/driver/base.rb', line 117

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)


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

def vm_dir
  @vm_dir
end

#vmx_pathPathname (readonly)

This is the path to the VMX file.

Returns:

  • (Pathname)


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

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



1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
# File 'lib/vagrant-vmware-desktop/driver/base.rb', line 1129

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>)


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

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.



318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
# File 'lib/vagrant-vmware-desktop/driver/base.rb', line 318

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.



341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
# File 'lib/vagrant-vmware-desktop/driver/base.rb', line 341

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

  # Sanity test
  if !destination.directory?
    raise Errors::CloneFolderNotFolder, path: destination.to_s
  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
      snap_name = destination.basename
      vmrun("snapshot", host_path(source_vmx), snap_name)
      # Do a linked clone!
      vmrun("clone", host_path(source_vmx), host_path(destination_vmx), "linked", "-snapshot=#{snap_name}")
      # store the snapshot name
      File.write(destination.join(SOURCE_SNAPSHOT_FILE_NAME).to_s, snap_name)
      File.write(destination.join(SOURCE_VMXPATH_FILE_NAME).to_s, source_vmx.to_s)
      # 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.")

    # 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



1108
1109
1110
1111
1112
1113
# File 'lib/vagrant-vmware-desktop/driver/base.rb', line 1108

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



434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
# File 'lib/vagrant-vmware-desktop/driver/base.rb', line 434

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.



454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
# File 'lib/vagrant-vmware-desktop/driver/base.rb', line 454

def delete
  @logger.info("Deleting VM: #{@vm_dir}")
  begin
    snap_file = @vmx_path.parent.join(SOURCE_SNAPSHOT_FILE_NAME)
    source_vmx_file = @vmx_path.parent.join(SOURCE_VMXPATH_FILE_NAME)
    if snap_file.exist? && source_vmx_file.exist?
      source_vmx = File.read(source_vmx_file.to_s)
      snap_name = File.read(snap_file.to_s)
      @logger.info("source snapshot name found, deleting snapshot (#{snap_name})")
      begin
        vmrun("deleteSnapshot", source_vmx, snap_name, "andDeleteChildren")
      rescue Errors::VMRunError => err
        # If we failed to remove the source snapshot, just log it and move on
        @logger.warn("failed to remove source clone snapshot '#{snap_name}': #{err}")
      end
    else
      @logger.debug("source snapshot information not found, ignoring")
    end
    @vm_dir.rmtree
  rescue Errno::ENOTEMPTY
    FileUtils.rm_rf(@vm_dir.to_s)
  end
end

#detect_nat_device!Object

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



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

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.



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

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.



494
495
496
497
# File 'lib/vagrant-vmware-desktop/driver/base.rb', line 494

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

#export(destination_vmx) ⇒ Object



422
423
424
425
426
427
428
# File 'lib/vagrant-vmware-desktop/driver/base.rb', line 422

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.



503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
# File 'lib/vagrant-vmware-desktop/driver/base.rb', line 503

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)


273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
# File 'lib/vagrant-vmware-desktop/driver/base.rb', line 273

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 => {}}
    if f_proto != :tcp && f_proto != :udp
      raise Errors::PortForwardInvalidProtocol,
        guest_ip: g_ip,
        guest_port: g_port,
        host_port: h_port,
        protocol: f_proto
    end
    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



1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
# File 'lib/vagrant-vmware-desktop/driver/base.rb', line 1172

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



1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
# File 'lib/vagrant-vmware-desktop/driver/base.rb', line 1086

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



1119
1120
1121
1122
# File 'lib/vagrant-vmware-desktop/driver/base.rb', line 1119

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



306
307
308
309
310
311
312
313
314
315
# File 'lib/vagrant-vmware-desktop/driver/base.rb', line 306

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

#is_linked_clone?Boolean

Returns Instance is a linked clone.

Returns:

  • (Boolean)

    Instance is a linked clone



1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
# File 'lib/vagrant-vmware-desktop/driver/base.rb', line 1201

def is_linked_clone?
  if @vmsd_path.nil?
    @vm_dir.children(true).each do |child|
      if child.basename.to_s.match(/\.vmsd$/)
        @vmsd_path = child
      end
    end
  end

  return false if @vmsd_path.nil?

  if @is_clone.nil?
    @is_clone = false

    File.readlines(@vmsd_path).each do |line|
      if line.start_with?("cloneOf")
        @is_clone = true
        break
      end
    end
  end

  @is_clone
end

#product_typeString

Product type value used by vmrun based on platform and license

Returns:

  • (String)

    fusion, ws, or player



190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
# File 'lib/vagrant-vmware-desktop/driver/base.rb', line 190

def product_type
  return @product_type if @product_type

  @logger.debug("determining product type")
  case @product_name.downcase
  when "workstation"
    # If the license is standard, the type is player
    if standard?
      @logger.debug("workstation product with standard license: player")
      @product_type = "player"
    else
      @logger.debug("workstation product with professional license: ws")
      @product_type = "ws"
    end
  when "fusion"
    @logger.debug("fusion product: fusion")
    @product_type = "fusion"
  else
    @logger.debug("unknown product (#{@product_name}), defaulting: player")
    @product_type = "player"
  end

  @product_type
end

#professional?Boolean

Returns using professional license.

Returns:

  • (Boolean)

    using professional license



221
222
223
# File 'lib/vagrant-vmware-desktop/driver/base.rb', line 221

def professional?
  @pro_license
end

#prune_forwarded_portsObject

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



556
557
558
559
560
561
562
563
# File 'lib/vagrant-vmware-desktop/driver/base.rb', line 556

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)


590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
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
# File 'lib/vagrant-vmware-desktop/driver/base.rb', line 590

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

  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, "-wait", {timeout: 10, retryable: true})
      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 Vagrant::Util::Subprocess::TimeoutExceeded
      @logger.info("vmrun getGuestIPAddress failed: TimeoutExceeded")
      # 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

  # 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

  nil
end

#read_mac_addressesObject

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



765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
# File 'lib/vagrant-vmware-desktop/driver/base.rb', line 765

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>)


679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
# File 'lib/vagrant-vmware-desktop/driver/base.rb', line 679

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>)


705
706
707
708
709
# File 'lib/vagrant-vmware-desktop/driver/base.rb', line 705

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)


715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
# File 'lib/vagrant-vmware-desktop/driver/base.rb', line 715

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>)


809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
# File 'lib/vagrant-vmware-desktop/driver/base.rb', line 809

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



1161
1162
1163
1164
1165
# File 'lib/vagrant-vmware-desktop/driver/base.rb', line 1161

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



1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
# File 'lib/vagrant-vmware-desktop/driver/base.rb', line 1145

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)


794
795
796
797
798
799
800
801
802
803
804
# File 'lib/vagrant-vmware-desktop/driver/base.rb', line 794

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



567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
# File 'lib/vagrant-vmware-desktop/driver/base.rb', line 567

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)


832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
# File 'lib/vagrant-vmware-desktop/driver/base.rb', line 832

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"] = DEFAULT_NIC_DEVICE

      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.



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

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



895
896
897
# File 'lib/vagrant-vmware-desktop/driver/base.rb', line 895

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

#snapshot_listObject



903
904
905
906
907
908
909
910
911
912
# File 'lib/vagrant-vmware-desktop/driver/base.rb', line 903

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



899
900
901
# File 'lib/vagrant-vmware-desktop/driver/base.rb', line 899

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.



891
892
893
# File 'lib/vagrant-vmware-desktop/driver/base.rb', line 891

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

#snapshot_treeObject



914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
# File 'lib/vagrant-vmware-desktop/driver/base.rb', line 914

def snapshot_tree
  snapshots = []
  snap_level = 0
  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/)
        current_level = line.count("\t")
        if current_level > snap_level
          name = "#{snapshots.last}/#{line.gsub(/\s/, "")}"
        elsif current_level == snap_level
          path = snapshots.last.split("/")
          path.pop
          path << line.gsub(/\s/, "")
          name = path.join("/")
        else
          path = snapshots.last.split("/")
          diff = snap_level - current_level
          (0..diff).to_a.each { |i| path.pop }
          path << line.gsub(/\s/, "")
          name = path.join("/")
        end
        snap_level = current_level
        snapshots << name
      else
        snapshots << line
      end
    end
  end

  snapshots
end

#standard?Boolean

Returns using standard license.

Returns:

  • (Boolean)

    using standard license



216
217
218
# File 'lib/vagrant-vmware-desktop/driver/base.rb', line 216

def standard?
  !professional?
end

#start(gui = false) ⇒ Object

This will start the VMware machine.



949
950
951
952
953
954
955
956
# File 'lib/vagrant-vmware-desktop/driver/base.rb', line 949

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

#stop(stop_mode = "soft") ⇒ Object

This will stop the VMware machine.



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 959

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.



982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
# File 'lib/vagrant-vmware-desktop/driver/base.rb', line 982

def suppress_messages
  if @product_name.downcase == "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.



977
978
979
# File 'lib/vagrant-vmware-desktop/driver/base.rb', line 977

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.



1006
1007
1008
1009
1010
1011
1012
1013
# File 'lib/vagrant-vmware-desktop/driver/base.rb', line 1006

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.



1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
# File 'lib/vagrant-vmware-desktop/driver/base.rb', line 1017

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)


1074
1075
1076
1077
1078
1079
1080
# File 'lib/vagrant-vmware-desktop/driver/base.rb', line 1074

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)


1031
1032
1033
1034
1035
1036
1037
# File 'lib/vagrant-vmware-desktop/driver/base.rb', line 1031

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)


1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
# File 'lib/vagrant-vmware-desktop/driver/base.rb', line 1042

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