Monday, March 12, 2012

Monitoring SCVMM New-SCVirtualMachine Jobs

I see this question frequently in the SCVMM forum. 
A job was started and I attempted to perform some action and the VM is not ready.  One way SCVMM lets you handle things like this is through JobGroups.  But not all cmdlets support JobGroups and instead you ( as the coder ) must ‘do the right thing.’
In the forums I have made a feeble attempt to relate monitoring WMI / CIM job status to monitoring the SCVMM job progress.
Well, I had a need to write a VM deployment script, so I thought that I would tackle this topic once and for all.  As it is different than WMI jobs.
In the WMI / CIM world you send off a command and get a response back.  Usually within that is the ReturnValue.  If this is ‘0’ then the task is done, if this is ‘4096’ then the task is running, if it is anything else something went wrong.
In PowerShell we are so very used to getting an object back that we rarely take the time to actually look at it, or the process behind it.  We get the object back and we move on.
And this is not always a good thing to be doing.  There are cases where need to make sure that whatever we asked to happen actually finished before we move on.
Using the New-SCVirtualMachine cmdlet will pretty quickly give you a VM object back.  But if you then turn to the Job console in the GUI you will see that there is a bunch of stuff happening.  How do you know when this is complete?
$vm = New-SCVirtualMachine <…>
Well, lets take a look at that object we get back from New-SCVirtualMachine.
VMCPath                             : C:\Users\Public\VMs\ViewRds1\Virtual Machines\FD4E85BB-A9EC-4E20-9A45-7BC94B2189D5.xml
MarkedAsTemplate                    : False
OwnerSid                            :
VMId                                : FD4E85BB-A9EC-4E20-9A45-7BC94B2189D5
VMResourceGroup                     :
VMConfigResource                    :
VMConfigResourceStatus              : ClusterResourceStateUnknown
VMResource                          :
VMResourceStatus                    : ClusterResourceStateUnknown
DiskResources                       : {}
UnsupportedReason                   : Success (0)
RefresherErrors                     : {}
VirtualMachineState                 : PowerOff
HostGroupPath                       : All Hosts\ViewRds1
TotalSize                           : 8497528832
MemoryAssignedMB                    : 1024
MemoryAvailablePercentage           :
DynamicMemoryDemandMB               :
DynamicMemoryStatus                 :
AllocatedGPU                        :
HasPassthroughDisk                  : False
Status                              : UnderCreation
HasSavedState                       : False
StatusString                        : Creating...
StartAction                         : NeverAutoTurnOnVM
StopAction                          : SaveVM
RunGuestAccount                     :
DelayStart                          : 0
CPUUtilization                      : 0
PerfCPUUtilization                  : 0
PerfMemory                          : 0
PerfDiskBytesRead                   : 0
PerfDiskBytesWrite                  : 0
PerfNetworkBytesRead                : 0
PerfNetworkBytesWrite               : 0
VirtualizationPlatform              : HyperV
ComputerNameString                  : ViewRds1.pvs.brianeh.local
CreationSource                      : ViewRdsHost
IsUndergoingLiveMigration           : False
SourceObjectType                    : VM Template
OperatingSystemShutdownEnabled      : True
TimeSynchronizationEnabled          : True
DataExchangeEnabled                 : True
HeartbeatEnabled                    : True
BackupEnabled                       : True
ExcludeFromPRO                      : False
FailedJobID                         : 875de483-5160-4e66-8884-ec29885a2ebb
CheckpointLocation                  :
SelfServiceUserRole                 :
PassThroughDisks                    : {}
ComputerTier                        :
UpgradeDomain                       :
SCApplications                      : {}
LastRestoredVMCheckpoint            :
ComplianceStatus                    :
IsFaultTolerant                     : False
DeploymentErrorInfo                 :
ServiceDeploymentErrorMessage       :
DeploymentState                     : Undeployed
TieredPerfData                      : e26928de-370b-4751-9c7e-020b09647bc1
Location                            : C:\Users\Public\VMs\ViewRds1
CreationTime                        : 2/15/2012 11:08:55 AM
OperatingSystem                     : 64-bit edition of Windows Server 2008 R2 Enterprise
HasVMAdditions                      : False
VMAddition                          : Not Detected
NumLockEnabled                      : False
CPUCount                            : 2
IsHighlyAvailable                   : False
LimitCPUFunctionality               : False
LimitCPUForMigration                : False
Memory                              : 1024
DynamicMemoryEnabled                : True
DynamicMemoryMaximumMB              : 8096
DynamicMemoryBufferPercentage       : 20
MemoryWeight                        : 5000
VirtualVideoAdapterEnabled          : False
MonitorMaximumCount                 :
MonitorResolutionMaximum            :
BootOrder                           : {CD, IdeHardDrive, PxeBoot, Floppy}
ComputerName                        : ViewRds1.pvs.brianeh.local
UseHardwareAssistedVirtualization   : False
SANStatus                           : {DeployVMMultipleVolumeOnVMDisk (1212)}
CostCenter                          :
QuotaPoint                          : 1
IsTagEmpty                          : False
Tag                                 : (none)
CustomProperties                    : {, , , ...}
CustomProperty                      : {}
UndoDisksEnabled                    : False
CPUType                             : 3.60 GHz Xeon (2 MB L2 cache)
ExpectedCPUUtilization              : 20
DiskIO                              : 0
NetworkUtilization                  : 0
RelativeWeight                      : 100
CPUReserve                          : 0
CPUMax                              : 100
VirtualDVDDrives                    : {ViewRds1}
VirtualHardDisks                    : {ViewRdsTempl.vhd}
VirtualDiskDrives                   : {ViewRds1}
ShareSCSIBus                        : False
VirtualNetworkAdapters              : {ViewRds1}
VirtualFloppyDrive                  : ViewRds1
VirtualCOMPorts                     : {COM1, COM2}
VirtualSCSIAdapters                 : {ViewRds1}
CapabilityProfile                   :
CapabilityProfileCompatibilityState : Compatible
VMCheckpoints                       : {}
HostId                              : fa18d24c-7cbb-4244-999b-1dd26d7d2969
HostType                            : VMHost
HostName                            : threel6.pvs.brianeh.local
VMHost                              : threel6.pvs.brianeh.local
LibraryServer                       :
Cloud                               :
LibraryGroup                        :
GrantedToList                       : {}
UserRoleID                          : 75700cd5-893e-4f68-ada7-50ef4668acc6
UserRole                            : Administrator
Owner                               : PVS\Administrator
ObjectType                          : VM
Accessibility                       : Public
Name                                : ViewRds1
IsViewOnly                          : False
Description                         :
AddedTime                           : 2/15/2012 11:08:55 AM
ModifiedTime                        : 2/15/2012 11:15:12 AM
Enabled                             : True
MostRecentTask                      : Create virtual machine
ServerConnection                    : Microsoft.SystemCenter.VirtualMachineManager.Remoting.ServerConnection
ID                                  : e269288b-370b-4751-9c7e-020b09647bc1
MarkedForDeletion                   : False
IsFullyCached                       : True
ServicingWindows                    : {}
I highlighted a couple items that are important to avoiding sending a command before an existing one is finished.
Now, it gives us this MostRecentTask, lets look at that.
Name                 : Create virtual machine
Description          : Create virtual machine
Progress             : 32 %
Status               : Running
CmdletName           : New-SCVirtualMachine
ErrorInfo            : Success (0)
StartTime            : 2/15/2012 11:08:54 AM
EndTime              :
Owner                : PVS\Administrator
ErrorInfo            : Success (0)
AdditionalMessages   : {}
ResultName           : ViewRds1
ResultObjectTypeName : Virtual Machine
IsStoppable          : True
IsRestartable        : False
If you notice, this is the actual Create Virtual Machine job.  This gives you a quick link direct to the current long running task.
You also have the cmdlet that invoked the job. 
One thing to be aware of is that this MostRecentTask reference has a life to it.  At some point in the future, this reference will be NULL as the last job has aged and there is no reason to keep the reference any longer.
Now, you could monitor that MostRecentTask for completion.  Or you could monitor the status of the VM itself.
$vm.MostRecentTask.Status = Completed
or cast it to a new object to get the job itself and then query the job;
$job = $vm.MostRecentTask
Get-SCJob $job
As a recent forum user put it:
A simple line of:
ifelse { [string]($vm.MostRecentTask | select "Status") -match "Running" {
  "Skip this VM, it is already running a job"
}

Should handle what I need.

No comments: