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



33
34
35
36
37
38
39
40
41
42
43
44
45
# File 'lib/VMwareWebService/MiqVimVm.rb', line 33

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.



29
30
31
# File 'lib/VMwareWebService/MiqVimVm.rb', line 29

def annotation
  @annotation
end

#customValuesObject (readonly)

Returns the value of attribute customValues.



29
30
31
# File 'lib/VMwareWebService/MiqVimVm.rb', line 29

def customValues
  @customValues
end

#devicesObject (readonly)

Returns the value of attribute devices.



29
30
31
# File 'lib/VMwareWebService/MiqVimVm.rb', line 29

def devices
  @devices
end

#dsPathObject (readonly)

Returns the value of attribute dsPath.



29
30
31
# File 'lib/VMwareWebService/MiqVimVm.rb', line 29

def dsPath
  @dsPath
end

#hostSystemObject (readonly)

Returns the value of attribute hostSystem.



29
30
31
# File 'lib/VMwareWebService/MiqVimVm.rb', line 29

def hostSystem
  @hostSystem
end

#invObjObject (readonly)

Returns the value of attribute invObj.



29
30
31
# File 'lib/VMwareWebService/MiqVimVm.rb', line 29

def invObj
  @invObj
end

#localPathObject (readonly)

Returns the value of attribute localPath.



29
30
31
# File 'lib/VMwareWebService/MiqVimVm.rb', line 29

def localPath
  @localPath
end

#nameObject (readonly)

Returns the value of attribute name.



29
30
31
# File 'lib/VMwareWebService/MiqVimVm.rb', line 29

def name
  @name
end

#uuidObject (readonly)

Returns the value of attribute uuid.



29
30
31
# File 'lib/VMwareWebService/MiqVimVm.rb', line 29

def uuid
  @uuid
end

#vmhObject (readonly)

Returns the value of attribute vmh.



29
30
31
# File 'lib/VMwareWebService/MiqVimVm.rb', line 29

def vmh
  @vmh
end

#vmMorObject (readonly)

Returns the value of attribute vmMor.



29
30
31
# File 'lib/VMwareWebService/MiqVimVm.rb', line 29

def vmMor
  @vmMor
end

Instance Method Details

#acquireMksTicketObject



1235
1236
1237
1238
1239
1240
# File 'lib/VMwareWebService/MiqVimVm.rb', line 1235

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



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

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/



744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
# File 'lib/VMwareWebService/MiqVimVm.rb', line 744

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



1135
1136
1137
1138
1139
1140
# File 'lib/VMwareWebService/MiqVimVm.rb', line 1135

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

#addMiqAlarmObject

Public accessor



1005
1006
1007
1008
1009
1010
1011
# File 'lib/VMwareWebService/MiqVimVm.rb', line 1005

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

#attachIsoToCd(isoPath, cd = nil) ⇒ Object

def connectDevice



671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
# File 'lib/VMwareWebService/MiqVimVm.rb', line 671

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



902
903
904
905
906
907
908
909
910
911
# File 'lib/VMwareWebService/MiqVimVm.rb', line 902

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.



867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
# File 'lib/VMwareWebService/MiqVimVm.rb', line 867

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.



1205
1206
1207
1208
# File 'lib/VMwareWebService/MiqVimVm.rb', line 1205

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

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



463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
# File 'lib/VMwareWebService/MiqVimVm.rb', line 463

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



244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
# File 'lib/VMwareWebService/MiqVimVm.rb', line 244

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



228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
# File 'lib/VMwareWebService/MiqVimVm.rb', line 228

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



651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
# File 'lib/VMwareWebService/MiqVimVm.rb', line 651

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



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

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



339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
# File 'lib/VMwareWebService/MiqVimVm.rb', line 339

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



375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
# File 'lib/VMwareWebService/MiqVimVm.rb', line 375

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.debug "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



291
292
293
294
295
296
# File 'lib/VMwareWebService/MiqVimVm.rb', line 291

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



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

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

#disableMiqAlarmObject



1051
1052
1053
1054
1055
1056
1057
1058
# File 'lib/VMwareWebService/MiqVimVm.rb', line 1051

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



485
486
487
488
489
490
491
492
493
# File 'lib/VMwareWebService/MiqVimVm.rb', line 485

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



1060
1061
1062
1063
1064
1065
1066
1067
# File 'lib/VMwareWebService/MiqVimVm.rb', line 1060

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



1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
# File 'lib/VMwareWebService/MiqVimVm.rb', line 1091

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.



522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
# File 'lib/VMwareWebService/MiqVimVm.rb', line 522

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

#getDeviceKeysByBacking(backingFile, hardware = nil) ⇒ Object

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



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

def getDeviceKeysByBacking(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["controllerKey"], dev["key"]])
  end
  ([nil, nil])
end

#getExtraConfigAttributes(attributes) ⇒ Object



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

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

#getHardwareObject



614
615
616
# File 'lib/VMwareWebService/MiqVimVm.rb', line 614

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

#getMemoryObject



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

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

#getMiqAlarmObject

Public accessor



1043
1044
1045
1046
1047
1048
1049
# File 'lib/VMwareWebService/MiqVimVm.rb', line 1043

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

#getNumCPUsObject



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

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

#getProp(path = nil) ⇒ Object



1223
1224
1225
# File 'lib/VMwareWebService/MiqVimVm.rb', line 1223

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

#getRemoteDisplayVncAttributesObject



1181
1182
1183
1184
# File 'lib/VMwareWebService/MiqVimVm.rb', line 1181

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

#getScsiControllers(hardware = nil) ⇒ Object



618
619
620
621
# File 'lib/VMwareWebService/MiqVimVm.rb', line 618

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

#getSnapMor(snMor) ⇒ Object



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

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



1156
1157
1158
1159
# File 'lib/VMwareWebService/MiqVimVm.rb', line 1156

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

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

Returns:

  • (Boolean)


355
356
357
358
359
360
# File 'lib/VMwareWebService/MiqVimVm.rb', line 355

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



47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
# File 'lib/VMwareWebService/MiqVimVm.rb', line 47

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.



1219
1220
1221
# File 'lib/VMwareWebService/MiqVimVm.rb', line 1219

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

#markAsTemplateObject

Template flag operations.



173
174
175
176
177
# File 'lib/VMwareWebService/MiqVimVm.rb', line 173

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



179
180
181
182
183
184
185
186
# File 'lib/VMwareWebService/MiqVimVm.rb', line 179

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.



196
197
198
199
200
201
202
203
204
205
# File 'lib/VMwareWebService/MiqVimVm.rb', line 196

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)


1079
1080
1081
1082
1083
1084
1085
# File 'lib/VMwareWebService/MiqVimVm.rb', line 1079

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.



961
962
963
964
965
# File 'lib/VMwareWebService/MiqVimVm.rb', line 961

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

#pollTask(tmor) ⇒ Object



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

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

#poweredOff?Boolean

Returns:

  • (Boolean)


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

def poweredOff?
  powerState == "poweredOff"
end

#poweredOn?Boolean

Returns:

  • (Boolean)


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

def poweredOn?
  powerState == "poweredOn"
end

#powerStateObject



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

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

#rebootGuestObject



129
130
131
132
133
# File 'lib/VMwareWebService/MiqVimVm.rb', line 129

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



607
608
609
610
611
612
# File 'lib/VMwareWebService/MiqVimVm.rb', line 607

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



72
73
74
# File 'lib/VMwareWebService/MiqVimVm.rb', line 72

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



81
82
83
# File 'lib/VMwareWebService/MiqVimVm.rb', line 81

def release
  # @invObj.releaseObj(self)
end

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



207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
# File 'lib/VMwareWebService/MiqVimVm.rb', line 207

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)


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

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

#removeAllSnapshots(free_space_percent = 100) ⇒ Object

def removeSnapshotByDescription



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

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.



814
815
816
817
818
819
820
821
822
823
824
825
826
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
# File 'lib/VMwareWebService/MiqVimVm.rb', line 814

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



1142
1143
1144
1145
1146
1147
# File 'lib/VMwareWebService/MiqVimVm.rb', line 1142

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

#removeMiqAlarmObject



1069
1070
1071
1072
1073
1074
1075
1076
1077
# File 'lib/VMwareWebService/MiqVimVm.rb', line 1069

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



395
396
397
398
399
400
401
402
403
404
405
# File 'lib/VMwareWebService/MiqVimVm.rb', line 395

def removeSnapshot(snMor, subTree = "false", wait = true, free_space_percent = 100)
  $vim_log.debug "MiqVimVm::removeSnapshot(#{snMor}, #{subTree})" if $vim_log
  snMor = getSnapMor(snMor)
  snapshot_free_space_check('remove', free_space_percent)
  $vim_log.info "MiqVimVm(#{@invObj.server}, #{@invObj.username}).removeSnapshot: calling removeSnapshot_Task" if $vim_log
  taskMor = @invObj.removeSnapshot_Task(snMor, subTree)
  $vim_log.info "MiqVimVm(#{@invObj.server}, #{@invObj.username}).removeSnapshot: returned from removeSnapshot_Task" 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



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

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



448
449
450
451
452
453
454
# File 'lib/VMwareWebService/MiqVimVm.rb', line 448

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

#reset(wait = true) ⇒ Object

def suspend



121
122
123
124
125
126
127
# File 'lib/VMwareWebService/MiqVimVm.rb', line 121

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



709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
# File 'lib/VMwareWebService/MiqVimVm.rb', line 709

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



439
440
441
442
443
444
445
446
# File 'lib/VMwareWebService/MiqVimVm.rb', line 439

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



429
430
431
432
433
434
435
436
437
# File 'lib/VMwareWebService/MiqVimVm.rb', line 429

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



362
363
364
365
366
367
368
369
370
371
372
373
# File 'lib/VMwareWebService/MiqVimVm.rb', line 362

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



1210
1211
1212
1213
# File 'lib/VMwareWebService/MiqVimVm.rb', line 1210

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

#setExtraConfigAttributes(hash) ⇒ Object



1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
# File 'lib/VMwareWebService/MiqVimVm.rb', line 1112

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



627
628
629
630
631
632
633
# File 'lib/VMwareWebService/MiqVimVm.rb', line 627

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



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

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



1186
1187
1188
1189
1190
1191
1192
1193
1194
# File 'lib/VMwareWebService/MiqVimVm.rb', line 1186

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



1161
1162
1163
1164
1165
1166
1167
# File 'lib/VMwareWebService/MiqVimVm.rb', line 1161

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



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

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



495
496
497
498
499
500
501
502
503
# File 'lib/VMwareWebService/MiqVimVm.rb', line 495

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



456
457
458
459
460
461
# File 'lib/VMwareWebService/MiqVimVm.rb', line 456

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



331
332
333
334
335
336
337
# File 'lib/VMwareWebService/MiqVimVm.rb', line 331

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.



302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
# File 'lib/VMwareWebService/MiqVimVm.rb', line 302

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



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

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.



97
98
99
100
101
102
103
# File 'lib/VMwareWebService/MiqVimVm.rb', line 97

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



105
106
107
108
109
110
111
# File 'lib/VMwareWebService/MiqVimVm.rb', line 105

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



113
114
115
116
117
118
119
# File 'lib/VMwareWebService/MiqVimVm.rb', line 113

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)


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

def suspended?
  powerState == "suspended"
end

#template?Boolean

Returns:

  • (Boolean)


188
189
190
# File 'lib/VMwareWebService/MiqVimVm.rb', line 188

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



285
286
287
288
289
# File 'lib/VMwareWebService/MiqVimVm.rb', line 285

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



1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
# File 'lib/VMwareWebService/MiqVimVm.rb', line 1257

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)


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

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

#waitForTask(tmor) ⇒ Object

def getProp



1227
1228
1229
# File 'lib/VMwareWebService/MiqVimVm.rb', line 1227

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