Class: MiqVimVm

Inherits:
Object
  • Object
show all
Includes:
DRb::DRbUndumped, MiqBrokerObjRegistry, MiqBrokerVimConnectionCheck, MiqVimVdlVcConnectionMod
Defined in:
lib/VMwareWebService/MiqVimBrokerMods.rb,
lib/VMwareWebService/MiqVimVm.rb

Overview

class VdlConnection alias :release_orig :release remove_method :release include MiqBrokerObjRegistry end

Constant Summary collapse

EVM_SNAPSHOT_NAME =

TODO: externalize - not VIM specific

"EvmSnapshot".freeze
CH_SNAPSHOT_NAME =
/^Consolidate Helper/
VCB_SNAPSHOT_NAME =
'_VCB-BACKUP_'.freeze
NETAPP_SNAPSHOT_NAME =
/^smvi/
VIRTUAL_SCSI_CONTROLLERS =
%w( VirtualBusLogicController
VirtualLsiLogicController
VirtualLsiLogicSASController
ParaVirtualSCSIController ).freeze
VIRTUAL_NICS =
%w( VirtualE1000
VirtualE1000e
VirtualPCNet32
VirtualVmxnet
VirtualVmxnet2
VirtualVmxnet3 ).freeze
MAX_SCSI_DEVICES =
15
MAX_SCSI_CONTROLLERS =
4
MIQ_ALARM_PFX =
"MiqControl".freeze
VmSafeAttributePrefix =
  • vmSafe

'vmsafe'
VmSafeAttributes =
['vmsafe.enable', 'vmsafe.agentAddress', 'vmsafe.agentPort', 'vmsafe.failOpen', 'vmsafe.immutableVM', 'vmsafe.timeoutMS']
RemoteDisplayVncAttributePrefix =
  • remoteDisplayVnc

'RemoteDisplay.vnc'
RemoteDisplayVncAttributes =
['RemoteDisplay.vnc.enabled', 'RemoteDisplay.vnc.key', 'RemoteDisplay.vnc.password', 'RemoteDisplay.vnc.port']

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from MiqBrokerVimConnectionCheck

#connectionRemoved?

Methods included from MiqBrokerObjRegistry

#holdBrokerObj, #registerBrokerObj, #unregisterBrokerObj

Methods included from MiqVimVdlVcConnectionMod

#vdlVcConnection

Constructor Details

#initialize(invObj, vmh) ⇒ MiqVimVm

Returns a new instance of MiqVimVm.



38
39
40
41
42
43
44
45
46
47
48
49
50
# File 'lib/VMwareWebService/MiqVimVm.rb', line 38

def initialize(invObj, vmh)
  @invObj                 = invObj
  @sic                    = invObj.sic
  @cdSave         = nil
  @cfManager        = nil

  init(vmh)

  @miqAlarmSpecEnabled    = miqAlarmSpecEnabled
  @miqAlarmSpecDisabled   = miqAlarmSpecDisabled

  @cacheLock              = Sync.new
end

Instance Attribute Details

#annotationObject (readonly)

Returns the value of attribute annotation.



34
35
36
# File 'lib/VMwareWebService/MiqVimVm.rb', line 34

def annotation
  @annotation
end

#customValuesObject (readonly)

Returns the value of attribute customValues.



34
35
36
# File 'lib/VMwareWebService/MiqVimVm.rb', line 34

def customValues
  @customValues
end

#devicesObject (readonly)

Returns the value of attribute devices.



34
35
36
# File 'lib/VMwareWebService/MiqVimVm.rb', line 34

def devices
  @devices
end

#dsPathObject (readonly)

Returns the value of attribute dsPath.



34
35
36
# File 'lib/VMwareWebService/MiqVimVm.rb', line 34

def dsPath
  @dsPath
end

#hostSystemObject (readonly)

Returns the value of attribute hostSystem.



34
35
36
# File 'lib/VMwareWebService/MiqVimVm.rb', line 34

def hostSystem
  @hostSystem
end

#invObjObject (readonly)

Returns the value of attribute invObj.



34
35
36
# File 'lib/VMwareWebService/MiqVimVm.rb', line 34

def invObj
  @invObj
end

#localPathObject (readonly)

Returns the value of attribute localPath.



34
35
36
# File 'lib/VMwareWebService/MiqVimVm.rb', line 34

def localPath
  @localPath
end

#nameObject (readonly)

Returns the value of attribute name.



34
35
36
# File 'lib/VMwareWebService/MiqVimVm.rb', line 34

def name
  @name
end

#uuidObject (readonly)

Returns the value of attribute uuid.



34
35
36
# File 'lib/VMwareWebService/MiqVimVm.rb', line 34

def uuid
  @uuid
end

#vmhObject (readonly)

Returns the value of attribute vmh.



34
35
36
# File 'lib/VMwareWebService/MiqVimVm.rb', line 34

def vmh
  @vmh
end

#vmMorObject (readonly)

Returns the value of attribute vmMor.



34
35
36
# File 'lib/VMwareWebService/MiqVimVm.rb', line 34

def vmMor
  @vmMor
end

Instance Method Details

#acquireMksTicketObject



1268
1269
1270
1271
1272
1273
# File 'lib/VMwareWebService/MiqVimVm.rb', line 1268

def acquireMksTicket
  $vim_log.info "MiqVimVm(#{@invObj.server}, #{@invObj.username}).acquireMksTicket: calling acquireMksTicket" if $vim_log
  rv = @invObj.acquireMksTicket(@vmMor)
  $vim_log.info "MiqVimVm(#{@invObj.server}, #{@invObj.username}).acquireMksTicket: returned from acquireMksTicket" if $vim_log
  (rv)
end

#acquireTicket(ticketType) ⇒ Object

def acquireMksTicket



1275
1276
1277
1278
1279
1280
# File 'lib/VMwareWebService/MiqVimVm.rb', line 1275

def acquireTicket(ticketType)
  $vim_log.info "MiqVimVm(#{@invObj.server}, #{@invObj.username}).acquireTicket: calling acquireTicket" if $vim_log
  rv = @invObj.acquireTicket(@vmMor, ticketType)
  $vim_log.info "MiqVimVm(#{@invObj.server}, #{@invObj.username}).acquireTicket: returned from acquireTicket" if $vim_log
  (rv)
end

#addDisk(backingFile, sizeInMB, label = nil, summary = nil, options = {}) ⇒ Object

Add a new SCSI disk to the VM. Find an existing SCSI controller and add the disk to the next available unit number.

If sizeInMB < 0, then assume the backing file already exists.

In this case, backingFile must be the path to the existing VMDK.

If backingFile is just the datastore name, “[storage 1]” for example,

file names will be generated as appropriate.

Options available: thin_provisioned - if new disk is thin (grow on demand, allowing storage overcommitment) or thick (pre-allocated) dependent - if new disk is dependent (usual one) or not (meaning no delta file and no live snapshots of running VM) persistent - if new disk should really save changes or discard them on VM poweroff

P.S. Good overview of use cases for dependent / independent and persistent / nonpersistent disks can be found at cormachogan.com/2013/04/16/what-are-dependent-independent-disks-persistent-and-non-persisent-modes/



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
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
# File 'lib/VMwareWebService/MiqVimVm.rb', line 757

def addDisk(backingFile, sizeInMB, label = nil, summary = nil, options = {})
  # Remove nil keys if any, since the next line may not work
  options.reject! { |_k, v| v.nil? }
  # Merge default values:
  # - persistent is set to true to be backward compatible
  # - thin_provisioned is set to false explicitly since we call to_s on it further, so nil will not work for us
  options = {:persistent => true, :thin_provisioned => false}.merge(options)
  ck, un = available_scsi_units.first
  raise "addDisk: no SCSI controller found" unless ck

  vmConfigSpec = VimHash.new("VirtualMachineConfigSpec") do |vmcs|
    vmcs.deviceChange = VimArray.new("ArrayOfVirtualDeviceConfigSpec") do |vmcs_vca|
      vmcs_vca << VimHash.new("VirtualDeviceConfigSpec") do |vdcs|
        vdcs.operation = VirtualDeviceConfigSpecOperation::Add
        if sizeInMB < 0
          sizeInMB = -sizeInMB
        else
          vdcs.fileOperation = VirtualDeviceConfigSpecFileOperation::Create
        end
        vdcs.device = VimHash.new("VirtualDisk") do |vDev|
          vDev.key      = -100 # temp key for creation
          vDev.capacityInKB = sizeInMB * 1024
          vDev.controllerKey  = ck
          vDev.unitNumber   = un
          # The following doesn't seem to work.
          vDev.deviceInfo = VimHash.new("Description") do |desc|
            desc.label    = label
            desc.summary  = summary
          end if label || summary
          vDev.connectable = VimHash.new("VirtualDeviceConnectInfo") do |con|
            con.allowGuestControl = "false"
            con.startConnected    = "true"
            con.connected     = "true"
          end
          if options[:dependent]
            mode = (options[:persistent] ? VirtualDiskMode::Persistent : VirtualDiskMode::Nonpersistent)
          else
            mode = (options[:persistent] ? VirtualDiskMode::Independent_persistent : VirtualDiskMode::Independent_nonpersistent)
          end
          vDev.backing = VimHash.new("VirtualDiskFlatVer2BackingInfo") do |bck|
            bck.diskMode    = mode
            bck.split     = "false"
            bck.thinProvisioned = options[:thin_provisioned].to_s
            bck.writeThrough  = "false"
            bck.fileName    = backingFile
            begin
                dsn = @invObj.path2dsName(@dsPath)
                bck.datastore = @invObj.dsName2mo_local(dsn)
              rescue
                bck.datastore = nil
              end
          end
        end
      end
    end
  end

  $vim_log.info "MiqVimVm(#{@invObj.server}, #{@invObj.username}).addDisk: calling reconfigVM_Task" if $vim_log
  taskMor = @invObj.reconfigVM_Task(@vmMor, vmConfigSpec)
  $vim_log.info "MiqVimVm(#{@invObj.server}, #{@invObj.username}).addDisk: returned from reconfigVM_Task" if $vim_log
  waitForTask(taskMor)
end

#addExtraConfigPrefix(hash, prefix) ⇒ Object



1168
1169
1170
1171
1172
1173
# File 'lib/VMwareWebService/MiqVimVm.rb', line 1168

def addExtraConfigPrefix(hash, prefix)
  hash.each_with_object({}) do |(k, v), rh|
    k = "#{prefix}.#{k}"
    rh[k] = v
  end
end

#addMiqAlarmObject

Public accessor



1038
1039
1040
1041
1042
1043
1044
# File 'lib/VMwareWebService/MiqVimVm.rb', line 1038

def addMiqAlarm
  aMor = nil
  @cacheLock.synchronize(:SH) do
    aMor = addMiqAlarm_locked
  end
  (aMor)
end

#attachIsoToCd(isoPath, cd = nil) ⇒ Object

def connectDevice



684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
# File 'lib/VMwareWebService/MiqVimVm.rb', line 684

def attachIsoToCd(isoPath, cd = nil)
  raise "MiqVimVmMod.attachIsoToCd: CD already set" if @cdSave

  unless cd
    cd = devicesByFilter("deviceInfo.label" => "CD/DVD Drive 1")
    raise "MiqVimVmMod.attachIsoToCd: VM has no CD/DVD drive" if cd.empty?
    cd = cd.first
  end

  if (dsName = @invObj.path2dsName(isoPath)).empty?
    dsMor = nil
  else
    dsMor = @invObj.dsName2mo(dsName)
  end

  @cdSave = @invObj.deepClone(cd)

  vmConfigSpec = VimHash.new("VirtualMachineConfigSpec") do |vmcs|
    vmcs.deviceChange = VimArray.new("ArrayOfVirtualDeviceConfigSpec") do |vmcs_vca|
      vmcs_vca << VimHash.new("VirtualDeviceConfigSpec") do |vdcs|
        vdcs.operation = VirtualDeviceConfigSpecOperation::Edit
        vdcs.device = @invObj.deepClone(cd)
        vdcs.device.connectable.startConnected = "true"
        vdcs.device.connectable.connected = "true"
        vdcs.device.backing = VimHash.new("VirtualCdromIsoBackingInfo") do |vdb|
          vdb.fileName = isoPath
          vdb.datastore = dsMor if dsMor
        end
      end
    end
  end

  $vim_log.info "MiqVimVm(#{@invObj.server}, #{@invObj.username}).attachIsoToCd: calling reconfigVM_Task" if $vim_log
  taskMor = @invObj.reconfigVM_Task(@vmMor, vmConfigSpec)
  $vim_log.info "MiqVimVm(#{@invObj.server}, #{@invObj.username}).attachIsoToCd: returned from reconfigVM_Task" if $vim_log
  waitForTask(taskMor)
end

#available_scsi_buses(hardware = nil) ⇒ Object

def available_scsi_units



915
916
917
918
919
920
921
922
923
924
# File 'lib/VMwareWebService/MiqVimVm.rb', line 915

def available_scsi_buses(hardware = nil)
  scsi_controller_bus_numbers = [*0..MAX_SCSI_CONTROLLERS - 1]

  scsi_controllers = getScsiControllers(hardware)
  scsi_controllers.each do |controller|
    scsi_controller_bus_numbers -= [controller["busNumber"].to_i]
  end

  scsi_controller_bus_numbers
end

#available_scsi_units(hardware = nil) ⇒ Object

Find a SCSI controller and return its key and next available unit number.



880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
# File 'lib/VMwareWebService/MiqVimVm.rb', line 880

def available_scsi_units(hardware = nil)
  scsi_units       = []
  all_unit_numbers = [*0..MAX_SCSI_DEVICES]

  hardware ||= getHardware()

  devices = hardware["device"]
  scsi_controllers = getScsiControllers(hardware)

  scsi_controllers.sort_by { |s| s["key"].to_i }.each do |scsi_controller|
    # Skip if all controller units are populated
    # Bus has 16 units, controller takes up 1 unit itself
    next if scsi_controller["device"].to_miq_a.count >= MAX_SCSI_DEVICES

    # We've found the lowest scsi controller with an available unit
    controller_key = scsi_controller["key"]

    # Get a list of disks on this controller
    disks = devices.select { |dev| scsi_controller["device"].to_miq_a.include?(dev["key"]) }

    # Get a list of all populated units on the controller
    populated_units = disks.collect { |disk| disk["unitNumber"].to_i }
    populated_units << scsi_controller["scsiCtlrUnitNumber"].to_i

    # Pick the lowest available unit number
    available_units  = all_unit_numbers - populated_units

    available_units.each do |unit|
      scsi_units << [controller_key, unit]
    end
  end

  scsi_units
end

#cfManagerObject

Custom field methods.



1238
1239
1240
1241
# File 'lib/VMwareWebService/MiqVimVm.rb', line 1238

def cfManager
  @cfManager = @invObj.getMiqCustomFieldsManager unless @cfManager
  @cfManager
end

#check_disk_space(action, ds_mor, max_disk_space_in_kb, free_space_percent) ⇒ Object



476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
# File 'lib/VMwareWebService/MiqVimVm.rb', line 476

def check_disk_space(action, ds_mor, max_disk_space_in_kb, free_space_percent)
  pct = free_space_percent.to_f.zero? ? 100 : free_space_percent
  required_snapshot_space = ((max_disk_space_in_kb * 1024) * (pct.to_f / 100.to_f)).to_i

  # Determine the free space on the datastore used for snapshots
  ds_summary    = @invObj.getMoProp_local(ds_mor, "summary")
  ds_name       = ds_summary.fetch_path('summary', 'name')
  ds_free_space = ds_summary.fetch_path('summary', 'freeSpace').to_i

  # Log results so we can reference if needed.
  if free_space_percent.to_f.zero?
    $log.info "Snapshot #{action} pre-check skipped for Datastore <#{ds_name}> due to Percentage:<#{free_space_percent}>.  Space Free:<#{ds_free_space}>  Disk size:<#{required_snapshot_space}>" if $log
    return
  end

  if ds_free_space < required_snapshot_space
    raise MiqException::MiqVimVmSnapshotError, "Snapshot #{action} aborted.  Datastore <#{ds_name}> does not have enough free space.  Space Free:<#{ds_free_space}>  Required:<#{required_snapshot_space}>  Disk Percentage Used:<#{free_space_percent}>"
  else
    $log.info "Snapshot #{action} pre-check OK.  Datastore <#{ds_name}> has enough free space.  Space Free:<#{ds_free_space}>  Required:<#{required_snapshot_space}>  Disk Percentage Used:<#{free_space_percent}>" if $log
  end
end

#cloneVM(name, folder, pool = nil, host = nil, datastore = nil, powerOn = false, template = false, transform = nil, config = nil, customization = nil, disk = nil, wait = true) ⇒ Object



257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
# File 'lib/VMwareWebService/MiqVimVm.rb', line 257

def cloneVM(name, folder,
    pool = nil, host = nil, datastore = nil,
    powerOn = false, template = false, transform = nil,
    config = nil, customization = nil, disk = nil, wait = true)

  fmor  = (folder.kind_of?(Hash) ? folder['MOR'] : folder)
  pmor  = (pool.kind_of?(Hash) ? pool['MOR'] : pool)    if pool
  hmor  = (host.kind_of?(Hash) ? host['MOR'] : host)    if host
  dsmor = (datastore.kind_of?(Hash) ? datastore['MOR'] : datastore) if datastore

  cspec = VimHash.new('VirtualMachineCloneSpec') do |cs|
    cs.powerOn          = powerOn.to_s
    cs.template         = template.to_s
    cs.config           = config    if config
    cs.customization    = customization if customization
    cs.location = VimHash.new('VirtualMachineRelocateSpec') do |csl|
      csl.datastore   = dsmor   if dsmor
      csl.host        = hmor    if hmor
      csl.pool        = pmor    if pmor
      csl.disk        = disk    if disk
      csl.transform   = transform if transform
    end
  end
  cloneVM_raw(fmor, name, cspec, wait)
end

#cloneVM_raw(folder, name, spec, wait = true) ⇒ Object



241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
# File 'lib/VMwareWebService/MiqVimVm.rb', line 241

def cloneVM_raw(folder, name, spec, wait = true)
  $vim_log.info "MiqVimVm(#{@invObj.server}, #{@invObj.username}).cloneVM_raw: calling cloneVM_Task" if $vim_log
  taskMor = @invObj.cloneVM_Task(@vmMor, folder, name, spec)
  $vim_log.info "MiqVimVm(#{@invObj.server}, #{@invObj.username}).cloneVM_raw: returned from cloneVM_Task" if $vim_log
  $vim_log.debug "MiqVimVm::cloneVM_raw: taskMor = #{taskMor}" if $vim_log

  if wait
    rv = waitForTask(taskMor)
    $vim_log.debug "MiqVimVm::cloneVM_raw: rv = #{rv}" if $vim_log
    return rv
  end

  $vim_log.debug "MiqVimVm::cloneVM_raw - no wait: taskMor = #{taskMor}" if $vim_log
  taskMor
end

#connectDevice(dev, connect = true, onStartup = false) ⇒ Object



664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
# File 'lib/VMwareWebService/MiqVimVm.rb', line 664

def connectDevice(dev, connect = true, onStartup = false)
  raise "connectDevice: device #{dev['deviceInfo']['label']} is not a removable device" unless @invObj.hasProp?(dev, "connectable")

  vmConfigSpec = VimHash.new("VirtualMachineConfigSpec") do |vmcs|
    vmcs.deviceChange = VimArray.new("ArrayOfVirtualDeviceConfigSpec") do |vmcs_vca|
      vmcs_vca << VimHash.new("VirtualDeviceConfigSpec") do |vdcs|
        vdcs.operation = VirtualDeviceConfigSpecOperation::Edit
        vdcs.device = @invObj.deepClone(dev)
        vdcs.device.connectable.startConnected = connect.to_s if onStartup
        vdcs.device.connectable.connected = connect.to_s
      end
    end
  end

  $vim_log.info "MiqVimVm(#{@invObj.server}, #{@invObj.username}).connectDevice: calling reconfigVM_Task" if $vim_log
  taskMor = @invObj.reconfigVM_Task(@vmMor, vmConfigSpec)
  $vim_log.info "MiqVimVm(#{@invObj.server}, #{@invObj.username}).connectDevice: returned from reconfigVM_Task" if $vim_log
  waitForTask(taskMor)
end

#connectionStateObject



168
169
170
171
172
# File 'lib/VMwareWebService/MiqVimVm.rb', line 168

def connectionState
  runtime = getProp("runtime.connectionState")
  raise "Failed to retrieve property 'runtime.connectionState' for VM MOR: <#{@vmMor}>" if runtime.nil?
  runtime["runtime"]["connectionState"]
end

#createEvmSnapshot(desc, quiesce = "false", wait = true, free_space_percent = 100) ⇒ Object



352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
# File 'lib/VMwareWebService/MiqVimVm.rb', line 352

def createEvmSnapshot(desc, quiesce = "false", wait = true, free_space_percent = 100)
  hasEvm    = hasSnapshot?(EVM_SNAPSHOT_NAME, true)
  hasCh     = hasSnapshot?(CH_SNAPSHOT_NAME, false)
  hasVcb    = hasSnapshot?(VCB_SNAPSHOT_NAME, false)
  hasNetApp = hasSnapshot?(NETAPP_SNAPSHOT_NAME, false)

  if hasEvm || hasCh || hasVcb
    raise MiqException::MiqVimVmSnapshotError, "VM has EVM and consolidate helper snapshots" if hasEvm && hasCh
    raise MiqException::MiqVimVmSnapshotError, "VM already has an EVM snapshot"              if hasEvm
    raise MiqException::MiqVimVmSnapshotError, "VM already has an VCB snapshot"              if hasVcb
    raise MiqException::MiqVimVmSnapshotError, "VM already has a NetApp snapshot"            if hasNetApp
    raise MiqException::MiqVimVmSnapshotError, "VM has a consolidate helper snapshot"
  end
  createSnapshot(EVM_SNAPSHOT_NAME, desc, false, quiesce, wait, free_space_percent)
end

#createSnapshot(name, desc, memory, quiesce, wait = true, free_space_percent = 100) ⇒ Object



388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
# File 'lib/VMwareWebService/MiqVimVm.rb', line 388

def createSnapshot(name, desc, memory, quiesce, wait = true, free_space_percent = 100)
  $vim_log.debug "MiqVimVm::createSnapshot(#{name}, #{desc}, #{memory}, #{quiesce})" if $vim_log
  cs = connectionState
  raise "MiqVimVm(#{@invObj.server}, #{@invObj.username}).createSnapshot: VM is not connected, connectionState = #{cs}" if cs != "connected"
  snapshot_free_space_check('create', free_space_percent)
  $vim_log.info "MiqVimVm(#{@invObj.server}, #{@invObj.username}).createSnapshot: calling createSnapshot_Task" if $vim_log
  taskMor = @invObj.createSnapshot_Task(@vmMor, name, desc, memory, quiesce)
  $vim_log.info "MiqVimVm(#{@invObj.server}, #{@invObj.username}).createSnapshot: returned from createSnapshot_Task" if $vim_log
  $vim_log.debug "MiqVimVm::createSnapshot: taskMor = #{taskMor}" if $vim_log

  if wait
    snMor = waitForTask(taskMor)
    $vim_log.warn "MiqVimVm::createSnapshot: snMor = #{snMor}" if $vim_log
    return snMor
  end

  $vim_log.debug "MiqVimVm::createSnapshot - no wait: taskMor = #{taskMor}" if $vim_log
  taskMor
end

#destroyObject



304
305
306
307
308
309
# File 'lib/VMwareWebService/MiqVimVm.rb', line 304

def destroy
  $vim_log.info "MiqVimVm(#{@invObj.server}, #{@invObj.username}).destroy: calling destroy_Task" if $vim_log
  taskMor = @invObj.destroy_Task(@vmMor)
  $vim_log.info "MiqVimVm(#{@invObj.server}, #{@invObj.username}).destroy: returned from destroy_Task" if $vim_log
  waitForTask(taskMor)
end

#devicesByFilter(filter) ⇒ Object



660
661
662
# File 'lib/VMwareWebService/MiqVimVm.rb', line 660

def devicesByFilter(filter)
  (@invObj.applyFilter(@devices, filter))
end

#disableMiqAlarmObject



1084
1085
1086
1087
1088
1089
1090
1091
# File 'lib/VMwareWebService/MiqVimVm.rb', line 1084

def disableMiqAlarm
  @cacheLock.synchronize(:SH) do
    raise "disableMiqAlarm: MiqAlarm not configured for VM #{@dsPath}" unless (aMor = getMiqAlarm_locked)
    $vim_log.info "MiqVimVm(#{@invObj.server}, #{@invObj.username}).disableMiqAlarm: calling reconfigureAlarm" if $vim_log
    @invObj.reconfigureAlarm(aMor, @miqAlarmSpecDisabled)
    $vim_log.info "MiqVimVm(#{@invObj.server}, #{@invObj.username}).disableMiqAlarm: returned from reconfigureAlarm" if $vim_log
  end
end

#disk_space_per_datastore(devices, snapshot_path_mor) ⇒ Object



498
499
500
501
502
503
504
505
506
# File 'lib/VMwareWebService/MiqVimVm.rb', line 498

def disk_space_per_datastore(devices, snapshot_path_mor)
  # Add up the provision size of the disks.  Skip independent disk.
  devices.each_with_object(Hash.new { |h, k| h[k] = 0 }) do |dev, hsh|
    next unless dev.xsiType == 'VirtualDisk'
    next if dev.fetch_path('backing', 'diskMode').to_s.include?('independent_')
    ds_mor = snapshot_path_mor ? snapshot_path_mor : dev.fetch_path('backing', 'datastore')
    hsh[ds_mor] += dev.capacityInKB.to_i
  end
end

#enableMiqAlarmObject



1093
1094
1095
1096
1097
1098
1099
1100
# File 'lib/VMwareWebService/MiqVimVm.rb', line 1093

def enableMiqAlarm
  @cacheLock.synchronize(:SH) do
    raise "enableMiqAlarm: MiqAlarm not configured for VM #{@dsPath}" unless (aMor = getMiqAlarm_locked)
    $vim_log.info "MiqVimVm(#{@invObj.server}, #{@invObj.username}).enableMiqAlarm: calling reconfigureAlarm" if $vim_log
    @invObj.reconfigureAlarm(aMor, @miqAlarmSpecEnabled)
    $vim_log.info "MiqVimVm(#{@invObj.server}, #{@invObj.username}).enableMiqAlarm: returned from reconfigureAlarm" if $vim_log
  end
end

#extraConfigObject

extraConfig based methods



1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
# File 'lib/VMwareWebService/MiqVimVm.rb', line 1124

def extraConfig
  return @extraConfig unless @extraConfig.nil?

  @extraConfig = {}
  vmh = getProp("config.extraConfig")
  if vmh['config'] && vmh['config']['extraConfig']
    vmh['config']['extraConfig'].each do |ov|
      # Fixes issue where blank values come back as VimHash objects
      value = ov['value'].kind_of?(VimHash) ? VimString.new("", nil, "xsd:string") : ov['value']
      @extraConfig[ov['key']] = value
    end
  end
  @extraConfig
end

#getCfg(snap = nil) ⇒ Object

Configuration methods.



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
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
# File 'lib/VMwareWebService/MiqVimVm.rb', line 535

def getCfg(snap = nil)
  mor = snap ? getSnapMor(snap) : @vmMor
  cfgProps = @invObj.getMoProp(mor, "config")
  raise MiqException::MiqVimError, "Failed to retrieve configuration information for VM" if cfgProps.nil?
  cfgProps = cfgProps["config"]

  cfgHash = {
    'displayname'          => cfgProps['name'],
    'guestos'              => cfgProps['guestId'].downcase.chomp("guest"),
    'uuid.bios'            => cfgProps['uuid'],
    'uuid.location'        => cfgProps['locationId'],
    'memsize'              => cfgProps['hardware']['memoryMB'],
    'cpu_cores_per_socket' => cfgProps['hardware']['numCoresPerSocket'],
    'numvcpu'              => cfgProps['hardware']['numCPU'],
    'config.version'       => cfgProps['version'],
  }

  controllerKeyHash = {}

  1.upto(2) do |_i|
    cfgProps['hardware']['device'].each do |dev|
      case dev.xsiType
      when 'VirtualIDEController'
        tag = "ide#{dev['busNumber']}"
        dev['tag'] = tag
        controllerKeyHash[dev['key']] = dev

      when 'VirtualLsiLogicController', 'VirtualLsiLogicSASController', 'ParaVirtualSCSIController'
        tag = "scsi#{dev['busNumber']}"
        dev['tag'] = tag
        controllerKeyHash[dev['key']] = dev
        cfgHash["#{tag}.present"] = "true"
        cfgHash["#{tag}.virtualdev"] = "lsilogic"

      when 'VirtualBusLogicController'
        tag = "scsi#{dev['busNumber']}"
        dev['tag'] = tag
        controllerKeyHash[dev['key']] = dev
        cfgHash["#{tag}.present"] = "true"
        cfgHash["#{tag}.virtualdev"] = "buslogic"

      when 'VirtualDisk'
        controller_tag = controllerKeyHash.fetch_path(dev['controllerKey'], 'tag')
        next if controller_tag.nil?
        tag = "#{controller_tag}:#{dev['unitNumber']}"
        cfgHash["#{tag}.present"] = "true"
        cfgHash["#{tag}.devicetype"] = "disk"
        cfgHash["#{tag}.filename"] = dev['backing']['fileName']
        cfgHash["#{tag}.mode"] = dev['backing']['diskMode']
      when "VirtualCdrom"
        controller_tag = controllerKeyHash.fetch_path(dev['controllerKey'], 'tag')
        next if controller_tag.nil?
        tag = "#{controller_tag}:#{dev['unitNumber']}"
        cfgHash["#{tag}.present"] = "true"
        if dev['backing']['fileName'].nil?
          cfgHash["#{tag}.devicetype"] = "cdrom-raw"
          cfgHash["#{tag}.filename"] = dev['backing']['deviceName']
        else
          cfgHash["#{tag}.devicetype"] = "cdrom-image"
          cfgHash["#{tag}.filename"] = dev['backing']['fileName']
        end
        cfgHash["#{tag}.startconnected"] = dev['connectable']['startConnected']
      when "VirtualFloppy"
        tag = "floppy#{dev['unitNumber']}"
        cfgHash["#{tag}.present"] = "true"
        if dev['backing']['fileName'].nil?
          cfgHash["#{tag}.filename"] = dev['backing']['deviceName']
        else
          cfgHash["#{tag}.filename"] = dev['backing']['fileName']
        end
        cfgHash["#{tag}.startconnected"] = dev['connectable']['startConnected']
      when "VirtualPCNet32", "VirtualE1000"
        tag = "ethernet#{dev['unitNumber'].to_i - 1}"
        cfgHash["#{tag}.present"] = "true"
        cfgHash["#{tag}.networkname"] = dev['backing']['deviceName']
        cfgHash["#{tag}.generatedaddress"] = dev['macAddress']
        cfgHash["#{tag}.startconnected"] = dev['connectable']['startConnected']
        cfgHash["#{tag}.type"] = dev['deviceInfo']['label']
      end
    end
  end

  cfgHash
end

#getDeviceByBacking(backingFile, hardware = nil) ⇒ Object

Returns the device details associated with the given backing file.



940
941
942
943
944
945
946
947
948
949
# File 'lib/VMwareWebService/MiqVimVm.rb', line 940

def getDeviceByBacking(backingFile, hardware = nil)
  hardware ||= getHardware

  hardware["device"].to_a.each do |dev|
    next if dev.xsiType != "VirtualDisk"
    next if dev["backing"]["fileName"] != backingFile
    return dev
  end
  nil
end

#getDeviceByLabel(device_label, hardware = nil) ⇒ Object



951
952
953
954
# File 'lib/VMwareWebService/MiqVimVm.rb', line 951

def getDeviceByLabel(device_label, hardware = nil)
  hardware ||= getHardware
  hardware["device"].to_a.detect { |dev| dev["deviceInfo"]["label"] == device_label }
end

#getDeviceKeysByBacking(backingFile, hardware = nil) ⇒ Object

Returns the [controllerKey, key] pair for the virtul device associated with the given backing file.



930
931
932
933
934
# File 'lib/VMwareWebService/MiqVimVm.rb', line 930

def getDeviceKeysByBacking(backingFile, hardware = nil)
  dev = getDeviceByBacking(backingFile, hardware)
  return [nil, nil] if dev.nil?
  [dev["controllerKey"], dev["key"]]
end

#getDeviceKeysByLabel(device_label, hardware = nil) ⇒ Object



956
957
958
959
# File 'lib/VMwareWebService/MiqVimVm.rb', line 956

def getDeviceKeysByLabel(device_label, hardware = nil)
  dev = getDeviceByLabel(device_label, hardware)
  dev.values_at("controllerKey", "key", "unitNumber") unless dev.nil?
end

#getExtraConfigAttributes(attributes) ⇒ Object



1139
1140
1141
1142
1143
# File 'lib/VMwareWebService/MiqVimVm.rb', line 1139

def getExtraConfigAttributes(attributes)
  rh = {}
  attributes.each { |a| rh[a] = extraConfig[a] }
  (rh)
end

#getHardwareObject



627
628
629
# File 'lib/VMwareWebService/MiqVimVm.rb', line 627

def getHardware
  getProp("config.hardware").try(:fetch_path, "config", "hardware") || {}
end

#getMemoryObject



636
637
638
# File 'lib/VMwareWebService/MiqVimVm.rb', line 636

def getMemory
  getProp("summary.config.memorySizeMB")["summary"]["config"]["memorySizeMB"].to_i
end

#getMiqAlarmObject

Public accessor



1076
1077
1078
1079
1080
1081
1082
# File 'lib/VMwareWebService/MiqVimVm.rb', line 1076

def getMiqAlarm
  aMor = nil
  @cacheLock.synchronize(:SH) do
    aMor = getMiqAlarm_locked
  end
  (aMor)
end

#getNumCPUsObject



648
649
650
# File 'lib/VMwareWebService/MiqVimVm.rb', line 648

def getNumCPUs
  getProp("summary.config.numCpu")["summary"]["config"]["numCpu"].to_i
end

#getProp(path = nil) ⇒ Object



1256
1257
1258
# File 'lib/VMwareWebService/MiqVimVm.rb', line 1256

def getProp(path = nil)
  @invObj.getMoProp(@vmMor, path)
end

#getRemoteDisplayVncAttributesObject



1214
1215
1216
1217
# File 'lib/VMwareWebService/MiqVimVm.rb', line 1214

def getRemoteDisplayVncAttributes
  attrs = getExtraConfigAttributes(RemoteDisplayVncAttributes)
  removeExtraConfigPrefix(attrs, RemoteDisplayVncAttributePrefix)
end

#getScsiControllers(hardware = nil) ⇒ Object



631
632
633
634
# File 'lib/VMwareWebService/MiqVimVm.rb', line 631

def getScsiControllers(hardware = nil)
  hardware ||= getHardware()
  hardware["device"].to_a.select { |dev| VIRTUAL_SCSI_CONTROLLERS.include?(dev.xsiType) }
end

#getSnapMor(snMor) ⇒ Object



518
519
520
521
522
523
524
525
526
527
528
529
# File 'lib/VMwareWebService/MiqVimVm.rb', line 518

def getSnapMor(snMor)
  unless snMor.respond_to?(:vimType)
    $vim_log.debug "MiqVimVm::getSnapMor converting #{snMor} to MOR" if $vim_log
    @cacheLock.synchronize(:SH) do
      raise "getSnapMor: VM #{@dsPath} has no snapshots" unless (sni = snapshotInfo_locked(true))
      raise "getSnapMor: snapshot #{snMor} not found" unless (snObj = sni['ssMorHash'][snMor])
      snMor = snObj['snapshot']
    end
    $vim_log.debug "MiqVimVm::getSnapMor new MOR: #{snMor}" if $vim_log
  end
  (snMor)
end

#getVmSafeAttributesObject



1189
1190
1191
1192
# File 'lib/VMwareWebService/MiqVimVm.rb', line 1189

def getVmSafeAttributes
  attrs = getExtraConfigAttributes(VmSafeAttributes)
  removeExtraConfigPrefix(attrs, VmSafeAttributePrefix)
end

#hasSnapshot?(name, refresh = false) ⇒ Boolean

Returns:

  • (Boolean)


368
369
370
371
372
373
# File 'lib/VMwareWebService/MiqVimVm.rb', line 368

def hasSnapshot?(name, refresh = false)
  @cacheLock.synchronize(:SH) do
    return false unless (si = snapshotInfo_locked(refresh))
    return !searchSsTree(si['rootSnapshotList'], 'name', name).nil?
  end
end

#init(vmh) ⇒ Object

def initialize



52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
# File 'lib/VMwareWebService/MiqVimVm.rb', line 52

def init(vmh)
  @vmh                    = vmh
  @name                   = vmh['summary']['config']['name']
  @uuid                   = vmh['summary']['config']['uuid']
  @vmMor                  = vmh['summary']['vm']
  @dsPath                 = vmh['summary']['config']['vmPathName']
  @hostSystem             = vmh['summary']['runtime']['host']
  @devices                = vmh['config']['hardware']['device']   if vmh['config'] && vmh['config']['hardware']
  @devices ||= []
  @annotation       = vmh['summary']['config']['annotation']  if vmh['summary']['config']
  @localPath              = @invObj.localVmPath(@dsPath)
  @miqAlarmName           = "#{MIQ_ALARM_PFX}-#{@uuid}"

  @customValues     = {}
  if vmh['availableField'] && vmh['summary']['customValue']
    kton = {}
    vmh['availableField'].each { |af| kton[af['key']] = af['name'] }
    vmh['summary']['customValue'].each { |cv| @customValues[kton[cv['key']]] = cv['value'] }
  end

  @datacenterName         = nil
  @miqAlarmMor            = nil
  @snapshotInfo           = nil
end

#logUserEvent(msg) ⇒ Object

Utility Methods.



1252
1253
1254
# File 'lib/VMwareWebService/MiqVimVm.rb', line 1252

def logUserEvent(msg)
  @invObj.logUserEvent(@vmMor, msg)
end

#markAsTemplateObject

Template flag operations.



178
179
180
181
182
# File 'lib/VMwareWebService/MiqVimVm.rb', line 178

def markAsTemplate
  $vim_log.info "MiqVimVm(#{@invObj.server}, #{@invObj.username}).markAsTemplate: calling markAsTemplate" if $vim_log
  @invObj.markAsTemplate(@vmMor)
  $vim_log.info "MiqVimVm(#{@invObj.server}, #{@invObj.username}).markAsTemplate: returned from markAsTemplate" if $vim_log
end

#markAsVm(pool, host = nil) ⇒ Object



184
185
186
187
188
189
190
191
# File 'lib/VMwareWebService/MiqVimVm.rb', line 184

def markAsVm(pool, host = nil)
  hmor = nil
  hmor = (host.kind_of?(Hash) ? host['MOR'] : host) if host
  pmor = (pool.kind_of?(Hash) ? pool['MOR'] : pool)
  $vim_log.info "MiqVimVm(#{@invObj.server}, #{@invObj.username}).markAsVm: calling markAsVirtualMachine" if $vim_log
  @invObj.markAsVirtualMachine(@vmMor, pmor, hmor)
  $vim_log.info "MiqVimVm(#{@invObj.server}, #{@invObj.username}).markAsVm: returned from markAsVirtualMachine" if $vim_log
end

#migrate(host, pool = nil, priority = "defaultPriority", state = nil) ⇒ Object

VM Migration.



201
202
203
204
205
206
207
208
209
210
# File 'lib/VMwareWebService/MiqVimVm.rb', line 201

def migrate(host, pool = nil, priority = "defaultPriority", state = nil)
  hmor = (host.kind_of?(Hash) ? host['MOR'] : host)
  pool = (pool.kind_of?(Hash) ? pool['MOR'] : pool) if pool

  $vim_log.info "MiqVimVm(#{@invObj.server}, #{@invObj.username}).migrate: calling migrateVM_Task, vm=<#{@vmMor.inspect}>, host=<#{hmor.inspect}>, pool=<#{pool.inspect}>, priority=<#{priority.inspect}>, state=<#{state.inspect}>" if $vim_log
  taskMor = @invObj.migrateVM_Task(@vmMor, pool, hmor, priority, state)
  $vim_log.info "MiqVimVm(#{@invObj.server}, #{@invObj.username}).migrate: returned from migrateVM_Task" if $vim_log
  $vim_log.debug "MiqVimVm::migrate: taskMor = #{taskMor}" if $vim_log
  waitForTask(taskMor)
end

#miqAlarmEnabled?Boolean

Returns:

  • (Boolean)


1112
1113
1114
1115
1116
1117
1118
# File 'lib/VMwareWebService/MiqVimVm.rb', line 1112

def miqAlarmEnabled?
  @cacheLock.synchronize(:SH) do
    return(false) unless (alarmMor = getMiqAlarm_locked)
    props = @invObj.getMoProp(alarmMor, "info.enabled")
    return(props['info.enabled'] == 'true')
  end
end

#miqAlarmSpecDisabledObject

Only called from initialize.



994
995
996
997
998
# File 'lib/VMwareWebService/MiqVimVm.rb', line 994

def miqAlarmSpecDisabled
  alarmSpec = @miqAlarmSpecEnabled.clone
  alarmSpec.enabled = "false"
  (alarmSpec)
end

#pollTask(tmor) ⇒ Object



1264
1265
1266
# File 'lib/VMwareWebService/MiqVimVm.rb', line 1264

def pollTask(tmor)
  @invObj.pollTask(tmor, self.class.to_s)
end

#poweredOff?Boolean

Returns:

  • (Boolean)


160
161
162
# File 'lib/VMwareWebService/MiqVimVm.rb', line 160

def poweredOff?
  powerState == "poweredOff"
end

#poweredOn?Boolean

Returns:

  • (Boolean)


156
157
158
# File 'lib/VMwareWebService/MiqVimVm.rb', line 156

def poweredOn?
  powerState == "poweredOn"
end

#powerStateObject



152
153
154
# File 'lib/VMwareWebService/MiqVimVm.rb', line 152

def powerState
  getProp("runtime.powerState")["runtime"]["powerState"]
end

#rebootGuestObject



134
135
136
137
138
# File 'lib/VMwareWebService/MiqVimVm.rb', line 134

def rebootGuest
  $vim_log.info "MiqVimVm(#{@invObj.server}, #{@invObj.username}).rebootGuest: calling rebootGuest" if $vim_log
  @invObj.rebootGuest(@vmMor)
  $vim_log.info "MiqVimVm(#{@invObj.server}, #{@invObj.username}).rebootGuest: returned from rebootGuest" if $vim_log
end

#reconfig(vmConfigSpec) ⇒ Object

def getCfg



620
621
622
623
624
625
# File 'lib/VMwareWebService/MiqVimVm.rb', line 620

def reconfig(vmConfigSpec)
  $vim_log.info "MiqVimVm(#{@invObj.server}, #{@invObj.username}).reconfig: calling reconfigVM_Task" if $vim_log
  taskMor = @invObj.reconfigVM_Task(@vmMor, vmConfigSpec)
  $vim_log.info "MiqVimVm(#{@invObj.server}, #{@invObj.username}).reconfig: returned from reconfigVM_Task" if $vim_log
  waitForTask(taskMor)
end

#refreshObject



77
78
79
# File 'lib/VMwareWebService/MiqVimVm.rb', line 77

def refresh
  init(@invObj.refreshVirtualMachine(@vmMor))
end

#releaseObject Also known as: release_orig

Called when client is finished using this MiqVimVm object. The server will delete its reference to the object, so the server-side object csn be GC’d



86
87
88
# File 'lib/VMwareWebService/MiqVimVm.rb', line 86

def release
  # @invObj.releaseObj(self)
end

#relocateVM(host, pool = nil, datastore = nil, disk_move_type = nil, transform = nil, priority = "defaultPriority", disk = nil) ⇒ Object



220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
# File 'lib/VMwareWebService/MiqVimVm.rb', line 220

def relocateVM(host, pool = nil, datastore = nil, disk_move_type = nil, transform = nil, priority = "defaultPriority", disk = nil)
  pmor  = (pool.kind_of?(Hash) ? pool['MOR'] : pool)    if pool
  hmor  = (host.kind_of?(Hash) ? host['MOR'] : host)    if host
  dsmor = (datastore.kind_of?(Hash) ? datastore['MOR'] : datastore) if datastore

  rspec = VimHash.new('VirtualMachineRelocateSpec') do |rsl|
    rsl.datastore    = dsmor          if dsmor
    rsl.disk         = disk           if disk
    rsl.diskMoveType = disk_move_type if disk_move_type
    rsl.host         = hmor           if hmor
    rsl.pool         = pmor           if pmor
    rsl.transform    = transform      if transform
  end

  $vim_log.info "MiqVimVm(#{@invObj.server}, #{@invObj.username}).relocate: calling relocateVM_Task, vm=<#{@vmMor.inspect}>, host=<#{hmor.inspect}>, pool=<#{pool.inspect}>, datastore=<#{dsmor.inspect}>, priority=<#{priority.inspect}>" if $vim_log
  taskMor = @invObj.relocateVM_Task(@vmMor, rspec, priority)
  $vim_log.info "MiqVimVm(#{@invObj.server}, #{@invObj.username}).relocate: returned from relocateVM_Task" if $vim_log
  $vim_log.debug "MiqVimVm::relocate: taskMor = #{taskMor}" if $vim_log
  waitForTask(taskMor)
end

#remoteDisplayVncEnabled?Boolean

Returns:

  • (Boolean)


1229
1230
1231
1232
# File 'lib/VMwareWebService/MiqVimVm.rb', line 1229

def remoteDisplayVncEnabled?
  return false unless (ve = extraConfig['RemoteDisplay.vnc.enabled'])
  ve.casecmp("true") == 0
end

#removeAllSnapshots(free_space_percent = 100) ⇒ Object

def removeSnapshotByDescription



432
433
434
435
436
437
438
439
440
# File 'lib/VMwareWebService/MiqVimVm.rb', line 432

def removeAllSnapshots(free_space_percent = 100)
  $vim_log.debug "MiqVimVm::removeAllSnapshots" if $vim_log
  $vim_log.info "MiqVimVm(#{@invObj.server}, #{@invObj.username}).removeAllSnapshots: calling removeAllSnapshots_Task" if $vim_log
  snapshot_free_space_check('remove_all', free_space_percent)
  taskMor = @invObj.removeAllSnapshots_Task(@vmMor)
  $vim_log.info "MiqVimVm(#{@invObj.server}, #{@invObj.username}).removeAllSnapshots: returned from removeAllSnapshots_Task" if $vim_log
  $vim_log.debug "MiqVimVm::removeAllSnapshots: taskMor = #{taskMor}" if $vim_log
  waitForTask(taskMor)
end

#removeDiskByFile(backingFile, deleteBacking = false) ⇒ Object

Remove the virtual disk device associated with the given backing file. The backingFile must be the datastore path to the vmdk in question. If deleteBacking is true, the backing file will be deleted, otherwise the disk will be logically removed from the VM and the backing file will remain in place.



827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
# File 'lib/VMwareWebService/MiqVimVm.rb', line 827

def removeDiskByFile(backingFile, deleteBacking = false)
  raise "removeDiskByFile: false setting for deleteBacking not yet supported" if deleteBacking == false
  controllerKey, key = getDeviceKeysByBacking(backingFile)
  raise "removeDiskByFile: no virtual device associated with: #{backingFile}" unless key
  $vim_log.debug "MiqVimVm::MiqVimVm: backingFile = #{backingFile}" if $vim_log
  $vim_log.debug "MiqVimVm::MiqVimVm: controllerKey = #{controllerKey}, key = #{key}" if $vim_log

  vmConfigSpec = VimHash.new("VirtualMachineConfigSpec") do |vmcs|
    vmcs.deviceChange = VimArray.new("ArrayOfVirtualDeviceConfigSpec") do |vmcs_vca|
      vmcs_vca << VimHash.new("VirtualDeviceConfigSpec") do |vdcs|
        vdcs.operation = VirtualDeviceConfigSpecOperation::Remove
        if deleteBacking
          vdcs.fileOperation = VirtualDeviceConfigSpecFileOperation::Destroy
        else
          vdcs.fileOperation = VirtualDeviceConfigSpecFileOperation::Replace
        end
        vdcs.device = VimHash.new("VirtualDisk") do |vDev|
          vDev.key      = key
          vDev.capacityInKB = 0
          vDev.controllerKey  = controllerKey
          vDev.connectable = VimHash.new("VirtualDeviceConnectInfo") do |con|
            con.allowGuestControl = "false"
            con.startConnected    = "true"
            con.connected     = "true"
          end
          vDev.backing = VimHash.new("VirtualDiskFlatVer2BackingInfo") do |bck|
            bck.diskMode    = VirtualDiskMode::Independent_persistent
            bck.split     = "false"
            bck.thinProvisioned = "false"
            bck.writeThrough  = "false"
            bck.fileName    = backingFile
            begin
                dsn = @invObj.path2dsName(@dsPath)
                bck.datastore = @invObj.dsName2mo(dsn)
              rescue
                bck.datastore = nil
              end
          end unless deleteBacking
        end
      end
    end
  end

  $vim_log.info "MiqVimVm(#{@invObj.server}, #{@invObj.username}).removeDiskByFile: calling reconfigVM_Task" if $vim_log
  taskMor = @invObj.reconfigVM_Task(@vmMor, vmConfigSpec)
  $vim_log.info "MiqVimVm(#{@invObj.server}, #{@invObj.username}).removeDiskByFile: returned from reconfigVM_Task" if $vim_log
  waitForTask(taskMor)
end

#removeExtraConfigPrefix(hash, prefix) ⇒ Object



1175
1176
1177
1178
1179
1180
# File 'lib/VMwareWebService/MiqVimVm.rb', line 1175

def removeExtraConfigPrefix(hash, prefix)
  hash.each_with_object({}) do |(k, v), rh|
    k = k[prefix.length + 1..-1]
    rh[k] = v
  end
end

#removeMiqAlarmObject



1102
1103
1104
1105
1106
1107
1108
1109
1110
# File 'lib/VMwareWebService/MiqVimVm.rb', line 1102

def removeMiqAlarm
  @cacheLock.synchronize(:SH) do
    return unless (aMor = getMiqAlarm_locked)
    $vim_log.info "MiqVimVm(#{@invObj.server}, #{@invObj.username}).removeMiqAlarm: calling removeAlarm" if $vim_log
    @invObj.removeAlarm(aMor)
    $vim_log.info "MiqVimVm(#{@invObj.server}, #{@invObj.username}).removeMiqAlarm: returned from removeAlarm" if $vim_log
    @miqAlarmMor = nil
  end
end

#removeSnapshot(snMor, subTree = "false", wait = true, free_space_percent = 100) ⇒ Object

def createSnapshot



408
409
410
411
412
413
414
415
416
417
418
# File 'lib/VMwareWebService/MiqVimVm.rb', line 408

def removeSnapshot(snMor, subTree = "false", wait = true, free_space_percent = 100)
  $vim_log.warn "MiqVimVm::removeSnapshot(#{snMor}, #{subTree})" if $vim_log
  snMor = getSnapMor(snMor)
  snapshot_free_space_check('remove', free_space_percent)
  $vim_log.warn "MiqVimVm(#{@invObj.server}, #{@invObj.username}).removeSnapshot: calling removeSnapshot_Task: snMor [#{snMor}] subtree [#{subTree}]" if $vim_log
  taskMor = @invObj.removeSnapshot_Task(snMor, subTree)
  $vim_log.warn "MiqVimVm(#{@invObj.server}, #{@invObj.username}).removeSnapshot: returned from removeSnapshot_Task: snMor [#{snMor}]" if $vim_log
  $vim_log.debug "MiqVimVm::removeSnapshot: taskMor = #{taskMor}" if $vim_log
  return taskMor unless wait
  waitForTask(taskMor)
end

#removeSnapshotByDescription(description, refresh = false, subTree = "false", wait = true, free_space_percent = 100) ⇒ Object

def removeSnapshot



420
421
422
423
424
425
426
427
428
429
430
# File 'lib/VMwareWebService/MiqVimVm.rb', line 420

def removeSnapshotByDescription(description, refresh = false, subTree = "false", wait = true, free_space_percent = 100)
  mor = nil
  @cacheLock.synchronize(:SH) do
    return false unless (si = snapshotInfo_locked(refresh))
    sso = searchSsTree(si['rootSnapshotList'], 'description', description)
    return false if sso.nil?
    mor = sso['snapshot']
  end
  removeSnapshot(mor, subTree, wait, free_space_percent)
  true
end

#renameSnapshot(snMor, name, desc) ⇒ Object

def revertToCurrentSnapshot



461
462
463
464
465
466
467
# File 'lib/VMwareWebService/MiqVimVm.rb', line 461

def renameSnapshot(snMor, name, desc)
  $vim_log.debug "MiqVimVm::renameSnapshot(#{snMor}, #{name}, #{desc})" if $vim_log
  snMor = getSnapMor(snMor)
  $vim_log.info "MiqVimVm(#{@invObj.server}, #{@invObj.username}).renameSnapshot: calling renameSnapshot" if $vim_log
  @invObj.renameSnapshot(snMor, name, desc)
  $vim_log.info "MiqVimVm(#{@invObj.server}, #{@invObj.username}).renameSnapshot: returned from renameSnapshot" if $vim_log
end

#renameVM(newName) ⇒ Object



212
213
214
215
216
217
218
# File 'lib/VMwareWebService/MiqVimVm.rb', line 212

def renameVM(newName)
  $vim_log.info "MiqVimVm(#{@invObj.server}, #{@invObj.username}).renameVM: calling rename_Task, vm=<#{@vmMor.inspect}>, newName=<#{newName}>" if $vim_log
  task_mor = @invObj.rename_Task(@vmMor, newName)
  $vim_log.info "MiqVimVm(#{@invObj.server}, #{@invObj.username}).renameVM: returned from rename_Task" if $vim_log
  $vim_log.debug "MiqVimVm::renameVM: taskMor = #{task_mor}" if $vim_log
  waitForTask(task_mor)
end

#reset(wait = true) ⇒ Object

def suspend



126
127
128
129
130
131
132
# File 'lib/VMwareWebService/MiqVimVm.rb', line 126

def reset(wait = true)
  $vim_log.info "MiqVimVm(#{@invObj.server}, #{@invObj.username}).reset: calling resetVM_Task" if $vim_log
  taskMor = @invObj.resetVM_Task(@vmMor)
  $vim_log.info "MiqVimVm(#{@invObj.server}, #{@invObj.username}).reset: returned from resetVM_Task" if $vim_log
  return taskMor unless wait
  waitForTask(taskMor)
end

#resetCdObject



722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
# File 'lib/VMwareWebService/MiqVimVm.rb', line 722

def resetCd
  raise "MiqVimVmMod.resetCd: No previous CD state" unless @cdSave

  vmConfigSpec = VimHash.new("VirtualMachineConfigSpec") do |vmcs|
    vmcs.deviceChange = VimArray.new("ArrayOfVirtualDeviceConfigSpec") do |vmcs_vca|
      vmcs_vca << VimHash.new("VirtualDeviceConfigSpec") do |vdcs|
        vdcs.operation = VirtualDeviceConfigSpecOperation::Edit
        vdcs.device = @cdSave
      end
    end
  end

  $vim_log.info "MiqVimVm(#{@invObj.server}, #{@invObj.username}).resetCd: calling reconfigVM_Task" if $vim_log
  taskMor = @invObj.reconfigVM_Task(@vmMor, vmConfigSpec)
  $vim_log.info "MiqVimVm(#{@invObj.server}, #{@invObj.username}).resetCd: returned from reconfigVM_Task" if $vim_log
  waitForTask(taskMor)
end

#revertToCurrentSnapshotObject

def revertToSnapshot



452
453
454
455
456
457
458
459
# File 'lib/VMwareWebService/MiqVimVm.rb', line 452

def revertToCurrentSnapshot
  $vim_log.debug "MiqVimVm::revertToCurrentSnapshot" if $vim_log
  $vim_log.info "MiqVimVm(#{@invObj.server}, #{@invObj.username}).revertToCurrentSnapshot: calling revertToCurrentSnapshot_Task" if $vim_log
  taskMor = @invObj.revertToCurrentSnapshot_Task(@vmMor)
  $vim_log.info "MiqVimVm(#{@invObj.server}, #{@invObj.username}).revertToCurrentSnapshot: returned from revertToCurrentSnapshot_Task" if $vim_log
  $vim_log.debug "MiqVimVm::revertToCurrentSnapshot: taskMor = #{taskMor}" if $vim_log
  waitForTask(taskMor)
end

#revertToSnapshot(snMor) ⇒ Object

def removeAllSnapshots



442
443
444
445
446
447
448
449
450
# File 'lib/VMwareWebService/MiqVimVm.rb', line 442

def revertToSnapshot(snMor)
  $vim_log.debug "MiqVimVm::revertToSnapshot(#{snMor})" if $vim_log
  snMor = getSnapMor(snMor)
  $vim_log.info "MiqVimVm(#{@invObj.server}, #{@invObj.username}).revertToSnapshot: calling revertToSnapshot_Task" if $vim_log
  taskMor = @invObj.revertToSnapshot_Task(snMor)
  $vim_log.info "MiqVimVm(#{@invObj.server}, #{@invObj.username}).revertToSnapshot: returned from revertToSnapshot_Task" if $vim_log
  $vim_log.debug "MiqVimVm::revertToSnapshot: taskMor = #{taskMor}" if $vim_log
  waitForTask(taskMor)
end

#searchSsTree(ssObj, key, value) ⇒ Object



375
376
377
378
379
380
381
382
383
384
385
386
# File 'lib/VMwareWebService/MiqVimVm.rb', line 375

def searchSsTree(ssObj, key, value)
  ssObj = [ssObj] unless ssObj.kind_of?(Array)
  ssObj.each do |sso|
    if value.kind_of?(Regexp)
      return sso if value =~ sso[key]
    else
      return sso if sso[key] == value
    end
    sso['childSnapshotList'].each { |csso| s = searchSsTree(csso, key, value); return s unless s.nil? }
  end
  nil
end

#setCustomField(name, value) ⇒ Object



1243
1244
1245
1246
# File 'lib/VMwareWebService/MiqVimVm.rb', line 1243

def setCustomField(name, value)
  fk = cfManager.getFieldKey(name, @vmMor.vimType)
  cfManager.setField(@vmMor, fk, value)
end

#setExtraConfigAttributes(hash) ⇒ Object



1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
# File 'lib/VMwareWebService/MiqVimVm.rb', line 1145

def setExtraConfigAttributes(hash)
  raise "setExtraConfigAttributes: no attributes specified" if !hash.kind_of?(Hash) || hash.empty?

  vmConfigSpec = VimHash.new("VirtualMachineConfigSpec") do |vmcs|
    vmcs.extraConfig = VimArray.new("ArrayOfOptionValue") do |vmcs_eca|
      hash.each do |k, v|
        vmcs_eca << VimHash.new("OptionValue") do |ov|
          ov.key   = k.to_s
          ov.value = VimString.new(v.to_s, nil, "xsd:string")
        end
      end
    end
  end

  $vim_log.info "MiqVimVm(#{@invObj.server}, #{@invObj.username}).setExtraConfigAttributes: calling reconfigVM_Task" if $vim_log
  taskMor = @invObj.reconfigVM_Task(@vmMor, vmConfigSpec)
  $vim_log.info "MiqVimVm(#{@invObj.server}, #{@invObj.username}).setExtraConfigAttributes: returned from reconfigVM_Task" if $vim_log
  waitForTask(taskMor)

  @extraConfig = nil
  hash
end

#setMemory(memMB) ⇒ Object



640
641
642
643
644
645
646
# File 'lib/VMwareWebService/MiqVimVm.rb', line 640

def setMemory(memMB)
  vmConfigSpec = VimHash.new("VirtualMachineConfigSpec") { |cs| cs.memoryMB = memMB }
  $vim_log.info "MiqVimVm(#{@invObj.server}, #{@invObj.username}).setMemory: calling reconfigVM_Task" if $vim_log
  taskMor = @invObj.reconfigVM_Task(@vmMor, vmConfigSpec)
  $vim_log.info "MiqVimVm(#{@invObj.server}, #{@invObj.username}).setMemory: returned from reconfigVM_Task" if $vim_log
  waitForTask(taskMor)
end

#setNumCPUs(numCPUs) ⇒ Object



652
653
654
655
656
657
658
# File 'lib/VMwareWebService/MiqVimVm.rb', line 652

def setNumCPUs(numCPUs)
  vmConfigSpec = VimHash.new("VirtualMachineConfigSpec") { |cs| cs.numCPUs = numCPUs }
  $vim_log.info "MiqVimVm(#{@invObj.server}, #{@invObj.username}).setNumCPUs: calling reconfigVM_Task" if $vim_log
  taskMor = @invObj.reconfigVM_Task(@vmMor, vmConfigSpec)
  $vim_log.info "MiqVimVm(#{@invObj.server}, #{@invObj.username}).setNumCPUs: returned from reconfigVM_Task" if $vim_log
  waitForTask(taskMor)
end

#setRemoteDisplayVncAttributes(hash) ⇒ Object



1219
1220
1221
1222
1223
1224
1225
1226
1227
# File 'lib/VMwareWebService/MiqVimVm.rb', line 1219

def setRemoteDisplayVncAttributes(hash)
  attrs = addExtraConfigPrefix(hash, RemoteDisplayVncAttributePrefix)
  attrs.each do |k, v|
    raise "setRemoteDisplayVncAttributes: unrecognized attribute: #{k[RemoteDisplayVncAttributePrefix.length + 1..-1]}" unless RemoteDisplayVncAttributes.include?(k)
    raise "setRemoteDisplayVncAttributes: RemoteDisplay.vnc.key cannot be set" if k == "RemoteDisplay.vnc.key"
    raise "setRemoteDisplayVncAttributes: RemoteDisplay.vnc.password cannot be longer than 8 characters" if k == "RemoteDisplay.vnc.password" && v.to_s.length > 8
  end
  setExtraConfigAttributes(attrs)
end

#setVmSafeAttributes(hash) ⇒ Object



1194
1195
1196
1197
1198
1199
1200
# File 'lib/VMwareWebService/MiqVimVm.rb', line 1194

def setVmSafeAttributes(hash)
  attrs = addExtraConfigPrefix(hash, VmSafeAttributePrefix)
  attrs.keys.each do |k|
    raise "setVmSafeAttributes: unrecognized attribute: #{k[VmSafeAttributePrefix.length + 1..-1]}" unless VmSafeAttributes.include?(k)
  end
  setExtraConfigAttributes(attrs)
end

#shutdownGuestObject



140
141
142
143
144
# File 'lib/VMwareWebService/MiqVimVm.rb', line 140

def shutdownGuest
  $vim_log.info "MiqVimVm(#{@invObj.server}, #{@invObj.username}).shutdownGuest: calling shutdownGuest" if $vim_log
  @invObj.shutdownGuest(@vmMor)
  $vim_log.info "MiqVimVm(#{@invObj.server}, #{@invObj.username}).shutdownGuest: returned from shutdownGuest" if $vim_log
end

#snapshot_directory_mor(config) ⇒ Object



508
509
510
511
512
513
514
515
516
# File 'lib/VMwareWebService/MiqVimVm.rb', line 508

def snapshot_directory_mor(config)
  if @invObj.apiVersion.to_i >= 5
    redoNotWithParent = config.fetch_path('config', 'extraConfig').detect { |ec| ec['key'] == 'snapshot.redoNotWithParent' }
    return nil if redoNotWithParent.nil? || redoNotWithParent['value'].to_s.downcase != "true"
  end
  snapshot_path = config.fetch_path('config', 'files', 'snapshotDirectory')
  dsn = @invObj.path2dsName(snapshot_path)
  @invObj.dsName2mo_local(dsn)
end

#snapshot_free_space_check(action, free_space_percent = 100) ⇒ Object

def renameSnapshot



469
470
471
472
473
474
# File 'lib/VMwareWebService/MiqVimVm.rb', line 469

def snapshot_free_space_check(action, free_space_percent = 100)
  config = @invObj.getMoProp_local(@vmMor, "config")
  disk_space_per_datastore(@devices, snapshot_directory_mor(config)).each do |ds_mor, disk_space_in_kb|
    check_disk_space(action, ds_mor, disk_space_in_kb, free_space_percent)
  end
end

#snapshotInfo(_refresh = false) ⇒ Object

Public accessor



344
345
346
347
348
349
350
# File 'lib/VMwareWebService/MiqVimVm.rb', line 344

def snapshotInfo(_refresh = false)
  sni = nil
  @cacheLock.synchronize(:SH) do
    sni = @invObj.dupObj(snapshotInfo_locked)
  end
  (sni)
end

#snapshotInfo_locked(refresh = false) ⇒ Object

Snapshot methods.



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
# File 'lib/VMwareWebService/MiqVimVm.rb', line 315

def snapshotInfo_locked(refresh = false)
  raise "snapshotInfo_locked: cache lock not held" unless @cacheLock.sync_locked?
  return(@snapshotInfo) if @snapshotInfo && !refresh

  begin
      @cacheLock.sync_lock(:EX) if (unlock = @cacheLock.sync_shared?)

      unless (ssp = @invObj.getMoProp_local(@vmMor, "snapshot"))
        @snapshotInfo = nil
        return(nil)
      end

      ssObj = ssp["snapshot"]
      ssMorHash = {}
      rsl = ssObj['rootSnapshotList']
      rsl = [rsl] unless rsl.kind_of?(Array)
      rsl.each { |rs| @invObj.snapshotFixup(rs, ssMorHash) }
      ssObj['ssMorHash'] = ssMorHash
      @snapshotInfo = ssObj
    ensure
      @cacheLock.sync_unlock if unlock
    end

  (@snapshotInfo)
end

#standbyGuestObject



146
147
148
149
150
# File 'lib/VMwareWebService/MiqVimVm.rb', line 146

def standbyGuest
  $vim_log.info "MiqVimVm(#{@invObj.server}, #{@invObj.username}).standbyGuest: calling standbyGuest" if $vim_log
  @invObj.standbyGuest(@vmMor)
  $vim_log.info "MiqVimVm(#{@invObj.server}, #{@invObj.username}).standbyGuest: returned from standbyGuest" if $vim_log
end

#start(wait = true) ⇒ Object

Power state methods.



102
103
104
105
106
107
108
# File 'lib/VMwareWebService/MiqVimVm.rb', line 102

def start(wait = true)
  $vim_log.info "MiqVimVm(#{@invObj.server}, #{@invObj.username}).start: calling powerOnVM_Task" if $vim_log
  taskMor = @invObj.powerOnVM_Task(@vmMor)
  $vim_log.info "MiqVimVm(#{@invObj.server}, #{@invObj.username}).start: returned from powerOnVM_Task" if $vim_log
  return taskMor unless wait
  waitForTask(taskMor)
end

#stop(wait = true) ⇒ Object

def start



110
111
112
113
114
115
116
# File 'lib/VMwareWebService/MiqVimVm.rb', line 110

def stop(wait = true)
  $vim_log.info "MiqVimVm(#{@invObj.server}, #{@invObj.username}).stop: calling powerOffVM_Task" if $vim_log
  taskMor = @invObj.powerOffVM_Task(@vmMor)
  $vim_log.info "MiqVimVm(#{@invObj.server}, #{@invObj.username}).stop: returned from powerOffVM_Task" if $vim_log
  return taskMor unless wait
  waitForTask(taskMor)
end

#suspend(wait = true) ⇒ Object

def stop



118
119
120
121
122
123
124
# File 'lib/VMwareWebService/MiqVimVm.rb', line 118

def suspend(wait = true)
  $vim_log.info "MiqVimVm(#{@invObj.server}, #{@invObj.username}).suspend: calling suspendVM_Task" if $vim_log
  taskMor = @invObj.suspendVM_Task(@vmMor)
  $vim_log.info "MiqVimVm(#{@invObj.server}, #{@invObj.username}).suspend: returned from suspendVM_Task" if $vim_log
  return taskMor unless wait
  waitForTask(taskMor)
end

#suspended?Boolean

Returns:

  • (Boolean)


164
165
166
# File 'lib/VMwareWebService/MiqVimVm.rb', line 164

def suspended?
  powerState == "suspended"
end

#template?Boolean

Returns:

  • (Boolean)


193
194
195
# File 'lib/VMwareWebService/MiqVimVm.rb', line 193

def template?
  getProp("config.template")["config"]["template"] == "true"
end

#unregisterObject

def testCancel(tmor)

fault = VimHash.new('RequestCanceled') do |mf|
  mf.faultMessage = VimHash.new('LocalizableMessage') do |lm|
    lm.key = "EVM"
    lm.message = "EVM test fault message"
  end
end
@invObj.setTaskState(tmor, 'error', nil, fault)
# desc = VimHash.new('LocalizableMessage') do |lm|
#     lm.key = "EVM"
#     lm.message = "EVM test task description"
# end
# @invObj.setTaskDescription(tmor, desc)

end



298
299
300
301
302
# File 'lib/VMwareWebService/MiqVimVm.rb', line 298

def unregister
  $vim_log.info "MiqVimVm(#{@invObj.server}, #{@invObj.username}).unregister: calling unregisterVM" if $vim_log
  @invObj.unregisterVM(@vmMor)
  $vim_log.info "MiqVimVm(#{@invObj.server}, #{@invObj.username}).unregister: returned from unregisterVM" if $vim_log
end

#vixVmxSpecObject



1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
# File 'lib/VMwareWebService/MiqVimVm.rb', line 1290

def vixVmxSpec
  #
  # For VDDK 1.1 and later, this is the preferred form for the vmxspec.
  #
  "moref=#{@vmMor}"
  #
  # For pre 1.1 versions of VDDK, this vmxspec must be used.
  #
  # return "#{@invObj.dsRelativePath(@dsPath)}?dcPath=#{datacenterName}&dsName=#{@invObj.path2dsName(@dsPath)}"
end

#vmsafeEnabled?Boolean

Returns:

  • (Boolean)


1202
1203
1204
1205
# File 'lib/VMwareWebService/MiqVimVm.rb', line 1202

def vmsafeEnabled?
  return false unless (ve = extraConfig['vmsafe.enable'])
  ve.casecmp("true") == 0
end

#waitForTask(tmor) ⇒ Object

def getProp



1260
1261
1262
# File 'lib/VMwareWebService/MiqVimVm.rb', line 1260

def waitForTask(tmor)
  @invObj.waitForTask(tmor, self.class.to_s)
end