Class: MiqVimVm

Inherits:
Object
  • Object
show all
Includes:
MiqVimVdlVcConnectionMod, VMwareWebService::Logging
Defined in:
lib/VMwareWebService/MiqVimVm.rb

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 MiqVimVdlVcConnectionMod

#vdlVcConnection

Methods included from VMwareWebService::Logging

#logger

Constructor Details

#initialize(invObj, vmh) ⇒ MiqVimVm

Returns a new instance of MiqVimVm.



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

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.



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

def annotation
  @annotation
end

#customValuesObject (readonly)

Returns the value of attribute customValues.



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

def customValues
  @customValues
end

#devicesObject (readonly)

Returns the value of attribute devices.



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

def devices
  @devices
end

#dsPathObject (readonly)

Returns the value of attribute dsPath.



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

def dsPath
  @dsPath
end

#hostSystemObject (readonly)

Returns the value of attribute hostSystem.



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

def hostSystem
  @hostSystem
end

#invObjObject (readonly)

Returns the value of attribute invObj.



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

def invObj
  @invObj
end

#localPathObject (readonly)

Returns the value of attribute localPath.



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

def localPath
  @localPath
end

#nameObject (readonly)

Returns the value of attribute name.



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

def name
  @name
end

#uuidObject (readonly)

Returns the value of attribute uuid.



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

def uuid
  @uuid
end

#vmhObject (readonly)

Returns the value of attribute vmh.



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

def vmh
  @vmh
end

#vmMorObject (readonly)

Returns the value of attribute vmMor.



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

def vmMor
  @vmMor
end

Instance Method Details

#acquireMksTicketObject



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

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

#acquireTicket(ticketType) ⇒ Object

def acquireMksTicket



1297
1298
1299
1300
1301
1302
# File 'lib/VMwareWebService/MiqVimVm.rb', line 1297

def acquireTicket(ticketType)
  logger.info "MiqVimVm(#{@invObj.server}, #{@invObj.username}).acquireTicket: calling acquireTicket"
  rv = @invObj.acquireTicket(@vmMor, ticketType)
  logger.info "MiqVimVm(#{@invObj.server}, #{@invObj.username}).acquireTicket: returned from acquireTicket"
  (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/



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
806
807
808
809
810
811
# File 'lib/VMwareWebService/MiqVimVm.rb', line 750

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

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

#addExtraConfigPrefix(hash, prefix) ⇒ Object



1190
1191
1192
1193
1194
1195
# File 'lib/VMwareWebService/MiqVimVm.rb', line 1190

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

#addMiqAlarmObject

Public accessor



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

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

#attachIsoToCd(isoPath, cd = nil) ⇒ Object

def connectDevice



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
708
709
710
711
712
713
# File 'lib/VMwareWebService/MiqVimVm.rb', line 677

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

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

#available_scsi_buses(hardware = nil) ⇒ Object

def available_scsi_units



937
938
939
940
941
942
943
944
945
946
# File 'lib/VMwareWebService/MiqVimVm.rb', line 937

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.



901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
# File 'lib/VMwareWebService/MiqVimVm.rb', line 901

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
    device = Array(scsi_controller["device"])
    next if device.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| device.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.



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

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

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



469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
# File 'lib/VMwareWebService/MiqVimVm.rb', line 469

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



250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
# File 'lib/VMwareWebService/MiqVimVm.rb', line 250

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



234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
# File 'lib/VMwareWebService/MiqVimVm.rb', line 234

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

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

  logger.debug "MiqVimVm::cloneVM_raw - no wait: taskMor = #{taskMor}"
  taskMor
end

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



657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
# File 'lib/VMwareWebService/MiqVimVm.rb', line 657

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

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

#connectionStateObject



161
162
163
164
165
# File 'lib/VMwareWebService/MiqVimVm.rb', line 161

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



345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
# File 'lib/VMwareWebService/MiqVimVm.rb', line 345

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



381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
# File 'lib/VMwareWebService/MiqVimVm.rb', line 381

def createSnapshot(name, desc, memory, quiesce, wait = true, free_space_percent = 100)
  logger.debug "MiqVimVm::createSnapshot(#{name}, #{desc}, #{memory}, #{quiesce})"
  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)
  logger.info "MiqVimVm(#{@invObj.server}, #{@invObj.username}).createSnapshot: calling createSnapshot_Task"
  taskMor = @invObj.createSnapshot_Task(@vmMor, name, desc, memory, quiesce)
  logger.info "MiqVimVm(#{@invObj.server}, #{@invObj.username}).createSnapshot: returned from createSnapshot_Task"
  logger.debug "MiqVimVm::createSnapshot: taskMor = #{taskMor}"

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

  logger.debug "MiqVimVm::createSnapshot - no wait: taskMor = #{taskMor}"
  taskMor
end

#destroyObject



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

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

#devicesByFilter(filter) ⇒ Object



653
654
655
# File 'lib/VMwareWebService/MiqVimVm.rb', line 653

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

#disableMiqAlarmObject



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

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

#disk_space_per_datastore(devices, snapshot_path_mor) ⇒ Object



491
492
493
494
495
496
497
498
499
# File 'lib/VMwareWebService/MiqVimVm.rb', line 491

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



1115
1116
1117
1118
1119
1120
1121
1122
# File 'lib/VMwareWebService/MiqVimVm.rb', line 1115

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

#extraConfigObject

extraConfig based methods



1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
# File 'lib/VMwareWebService/MiqVimVm.rb', line 1146

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.



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
606
607
608
609
610
611
# File 'lib/VMwareWebService/MiqVimVm.rb', line 528

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.



962
963
964
965
966
967
968
969
970
971
# File 'lib/VMwareWebService/MiqVimVm.rb', line 962

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



973
974
975
976
# File 'lib/VMwareWebService/MiqVimVm.rb', line 973

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.



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

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



978
979
980
981
# File 'lib/VMwareWebService/MiqVimVm.rb', line 978

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

#getExtraConfigAttributes(attributes) ⇒ Object



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

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

#getHardwareObject



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

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

#getMemoryObject



629
630
631
# File 'lib/VMwareWebService/MiqVimVm.rb', line 629

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

#getMiqAlarmObject

Public accessor



1098
1099
1100
1101
1102
1103
1104
# File 'lib/VMwareWebService/MiqVimVm.rb', line 1098

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

#getNumCPUsObject



641
642
643
# File 'lib/VMwareWebService/MiqVimVm.rb', line 641

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

#getProp(path = nil) ⇒ Object



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

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

#getRemoteDisplayVncAttributesObject



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

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

#getScsiControllers(hardware = nil) ⇒ Object



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

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

#getSnapMor(snMor) ⇒ Object



511
512
513
514
515
516
517
518
519
520
521
522
# File 'lib/VMwareWebService/MiqVimVm.rb', line 511

def getSnapMor(snMor)
  unless snMor.respond_to?(:vimType)
    logger.debug "MiqVimVm::getSnapMor converting #{snMor} to MOR"
    @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
    logger.debug "MiqVimVm::getSnapMor new MOR: #{snMor}"
  end
  (snMor)
end

#getVmSafeAttributesObject



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

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

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

Returns:

  • (Boolean)


361
362
363
364
365
366
# File 'lib/VMwareWebService/MiqVimVm.rb', line 361

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



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

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.



1274
1275
1276
# File 'lib/VMwareWebService/MiqVimVm.rb', line 1274

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

#markAsTemplateObject

Template flag operations.



171
172
173
174
175
# File 'lib/VMwareWebService/MiqVimVm.rb', line 171

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

#markAsVm(pool, host = nil) ⇒ Object



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

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)
  logger.info "MiqVimVm(#{@invObj.server}, #{@invObj.username}).markAsVm: calling markAsVirtualMachine"
  @invObj.markAsVirtualMachine(@vmMor, pmor, hmor)
  logger.info "MiqVimVm(#{@invObj.server}, #{@invObj.username}).markAsVm: returned from markAsVirtualMachine"
end

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

VM Migration.



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

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

  logger.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}>"
  taskMor = @invObj.migrateVM_Task(@vmMor, pool, hmor, priority, state)
  logger.info "MiqVimVm(#{@invObj.server}, #{@invObj.username}).migrate: returned from migrateVM_Task"
  logger.debug "MiqVimVm::migrate: taskMor = #{taskMor}"
  waitForTask(taskMor)
end

#miqAlarmEnabled?Boolean

Returns:

  • (Boolean)


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

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.



1016
1017
1018
1019
1020
# File 'lib/VMwareWebService/MiqVimVm.rb', line 1016

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

#pollTask(tmor) ⇒ Object



1286
1287
1288
# File 'lib/VMwareWebService/MiqVimVm.rb', line 1286

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

#poweredOff?Boolean

Returns:

  • (Boolean)


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

def poweredOff?
  powerState == "poweredOff"
end

#poweredOn?Boolean

Returns:

  • (Boolean)


149
150
151
# File 'lib/VMwareWebService/MiqVimVm.rb', line 149

def poweredOn?
  powerState == "poweredOn"
end

#powerStateObject



145
146
147
# File 'lib/VMwareWebService/MiqVimVm.rb', line 145

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

#rebootGuestObject



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

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

#reconfig(vmConfigSpec) ⇒ Object

def getCfg



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

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

#refreshObject



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

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

#releaseObject

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



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

def release
  # @invObj.releaseObj(self)
end

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



213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
# File 'lib/VMwareWebService/MiqVimVm.rb', line 213

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

  logger.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}>"
  taskMor = @invObj.relocateVM_Task(@vmMor, rspec, priority)
  logger.info "MiqVimVm(#{@invObj.server}, #{@invObj.username}).relocate: returned from relocateVM_Task"
  logger.debug "MiqVimVm::relocate: taskMor = #{taskMor}"
  waitForTask(taskMor)
end

#remoteDisplayVncEnabled?Boolean

Returns:

  • (Boolean)


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

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

#removeAllSnapshots(free_space_percent = 100) ⇒ Object

def removeSnapshotByDescription



425
426
427
428
429
430
431
432
433
# File 'lib/VMwareWebService/MiqVimVm.rb', line 425

def removeAllSnapshots(free_space_percent = 100)
  logger.debug "MiqVimVm::removeAllSnapshots"
  logger.info "MiqVimVm(#{@invObj.server}, #{@invObj.username}).removeAllSnapshots: calling removeAllSnapshots_Task"
  snapshot_free_space_check('remove_all', free_space_percent)
  taskMor = @invObj.removeAllSnapshots_Task(@vmMor)
  logger.info "MiqVimVm(#{@invObj.server}, #{@invObj.username}).removeAllSnapshots: returned from removeAllSnapshots_Task"
  logger.debug "MiqVimVm::removeAllSnapshots: taskMor = #{taskMor}"
  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.



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
862
863
864
865
866
867
# File 'lib/VMwareWebService/MiqVimVm.rb', line 820

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
  logger.debug "MiqVimVm::MiqVimVm: backingFile = #{backingFile}"
  logger.debug "MiqVimVm::MiqVimVm: controllerKey = #{controllerKey}, key = #{key}"

  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

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

#removeExtraConfigPrefix(hash, prefix) ⇒ Object



1197
1198
1199
1200
1201
1202
# File 'lib/VMwareWebService/MiqVimVm.rb', line 1197

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

#removeMiqAlarmObject



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

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

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

def createSnapshot



401
402
403
404
405
406
407
408
409
410
411
# File 'lib/VMwareWebService/MiqVimVm.rb', line 401

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

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

def removeSnapshot



413
414
415
416
417
418
419
420
421
422
423
# File 'lib/VMwareWebService/MiqVimVm.rb', line 413

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



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

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

#renameVM(newName) ⇒ Object



205
206
207
208
209
210
211
# File 'lib/VMwareWebService/MiqVimVm.rb', line 205

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

#reset(wait = true) ⇒ Object

def suspend



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

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

#resetCdObject



715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
# File 'lib/VMwareWebService/MiqVimVm.rb', line 715

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

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

#resizeDisk(backingFile, newSizeInKb) ⇒ Object

def removeDiskByFile



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

def resizeDisk(backingFile, newSizeInKb)
  disk = getDeviceByBacking(backingFile)
  raise "resizeDisk: no virtual device associated with: #{backingFile}" unless disk
  raise "resizeDisk: cannot reduce the size of a disk" unless newSizeInKb >= Integer(disk.capacityInKB)
  logger.debug "MiqVimVm::resizeDisk: backingFile = #{backingFile} current size = #{device.capacityInKB} newSize = #{newSizeInKb} KB"

  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 = VimHash.new("VirtualDisk") do |vDev|
          vDev.backing       = disk.backing
          vDev.capacityInKB  = newSizeInKb
          vDev.controllerKey = disk.controllerKey
          vDev.key           = disk.key
          vDev.unitNumber    = disk.unitNumber
        end
      end
    end
  end

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

#revertToCurrentSnapshotObject

def revertToSnapshot



445
446
447
448
449
450
451
452
# File 'lib/VMwareWebService/MiqVimVm.rb', line 445

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

#revertToSnapshot(snMor) ⇒ Object

def removeAllSnapshots



435
436
437
438
439
440
441
442
443
# File 'lib/VMwareWebService/MiqVimVm.rb', line 435

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

#searchSsTree(ssObj, key, value) ⇒ Object



368
369
370
371
372
373
374
375
376
377
378
379
# File 'lib/VMwareWebService/MiqVimVm.rb', line 368

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



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

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

#setExtraConfigAttributes(hash) ⇒ Object



1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
# File 'lib/VMwareWebService/MiqVimVm.rb', line 1167

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

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

  @extraConfig = nil
  hash
end

#setMemory(memMB) ⇒ Object



633
634
635
636
637
638
639
# File 'lib/VMwareWebService/MiqVimVm.rb', line 633

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

#setNumCPUs(numCPUs) ⇒ Object



645
646
647
648
649
650
651
# File 'lib/VMwareWebService/MiqVimVm.rb', line 645

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

#setRemoteDisplayVncAttributes(hash) ⇒ Object



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

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



1216
1217
1218
1219
1220
1221
1222
# File 'lib/VMwareWebService/MiqVimVm.rb', line 1216

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



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

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

#snapshot_directory_mor(config) ⇒ Object



501
502
503
504
505
506
507
508
509
# File 'lib/VMwareWebService/MiqVimVm.rb', line 501

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



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

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



337
338
339
340
341
342
343
# File 'lib/VMwareWebService/MiqVimVm.rb', line 337

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.



308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
# File 'lib/VMwareWebService/MiqVimVm.rb', line 308

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



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

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

#start(wait = true) ⇒ Object

Power state methods.



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

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

#stop(wait = true) ⇒ Object

def start



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

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

#suspend(wait = true) ⇒ Object

def stop



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

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

#suspended?Boolean

Returns:

  • (Boolean)


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

def suspended?
  powerState == "suspended"
end

#template?Boolean

Returns:

  • (Boolean)


186
187
188
# File 'lib/VMwareWebService/MiqVimVm.rb', line 186

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



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

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

#vixVmxSpecObject



1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
# File 'lib/VMwareWebService/MiqVimVm.rb', line 1312

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)


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

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

#waitForTask(tmor) ⇒ Object

def getProp



1282
1283
1284
# File 'lib/VMwareWebService/MiqVimVm.rb', line 1282

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