Hyper-V WMI Introduction

It will be really difficult to under Hyper-V programming model without understanding WMI. I will briefly describe the WMI concepts that were used in our samples.

WMI borrowed Relational Database concept and applied to the object world. There are many similarities between Relational Database and WMI.

WMI CIM Studio is a visual tool that allows you to explore the WMI objects. The tool can be downloaded from:

https://www.microsoft.com/downloads/details.aspx?FamilyID=6430f853-1120-48db-8cc5-f2abdc3ed314&displaylang=en

Namespace

 

Virtualization is one of the WMI namespaces that defined on Windows 2008. From CIM Studio, we will see other namespaces as well.

 

Just like programming against a backend SQL Server database, we can’t do anything else before we establish a connection to the database that we want to program against.

In WMI, we need to make such connection as well. Here is how we make connections to the Virtualization namespace:

VBScript

 

set objWMIService = GetObject("winmgmts:\\" & computer & "\root\virtualization")

C#

 ManagementScope scope = new ManagementScope(@"root\virtualization", null);

WMI Objects

Schema

 

As in SQL relational database, tables are defined with schema, WMI classes are also defined with schema. WMI also introduced inheritance concept in its class definition. Children class can inherent property and method defined in their parents.

 

 

(Diagram 1)

For example, StartService and StopService methods are defined in CIM_Service class. They are also visible in Msvm_VirtualSystemManagementService, Msvm_ImageManagementService and Msvm_VirtualSystemManagementService classes. CIM classes are more like C# abstraction classes.

Hyper-V schema definition file can be found on your Hyper-V host machine at: %windir%\system32\WindowsVirtualization.mof.

Properties

 

Properties of WMI objects describe characteristics of WMI objects. A property is a named value pair.

Type

 

Property value types are CIM typed. See the following link for a complete list of CIM types.

https://msdn.microsoft.com/en-us/library/aa386309(VS.85).aspx

 

Modification

 

It depends on each provider implementation, some providers implement Put method, which allows modifying object properties directly.

Most Hyper-V classes don’t support modifying properties directly. The following will not change the VM friendly name:

computer = "."

set objWMIService = GetObject("winmgmts:\\" & computer & "\root\virtualization")

set computer= objWMIService.ExecQuery("SELECT * FROM Msvm_ComputerSystem where ElementName='Win2008'").ItemIndex(0)

computer.ElementName = "My Computer"

computer.Put_

 

In the case above, we need to use “ModifyVirtualSystem” method modify VM name. Here is the link to the MSDN sample code:

https://msdn.microsoft.com/en-us/library/cc136809(VS.85).aspx

 

Methods

 

Parameters

 

Methods that are defined with WMI objects takes [in] parameters and produce [out] parameters and a return value.

  
 uint32 ModifyVirtualSystem
 (
 [in]   CIM_ComputerSystem REF ComputerSystem,
 [in]   string SystemSettingData,
 [out]  CIM_VirtualSystemSettingData REF ModifiedSettingData,
 [out]  CIM_ConcreteJob REF Job
 );

 

ModifyVirtualSystem method takes following parameters as inputs:

1. Object path that is pointing to CIM_ComputerSystem object.

2. Msvm_VirtualSystemSettingData that is in a Unicode string in Xml format.

 

Output parameters:

1. ModifiedSettingData contains a path in Unicode string that is pointing to an CIM_VirtualSystemSettingData

2. Job contains a path in Unicode string that is pointing to CIM_ConcreteJob object

The method is an unsynchronized operation. The Job object in the output is used for pulling operation complete state.

The return value uint32 is returned in “RetureValue” of method out parameter. The return value indicates if the method was executed successfully.

 

Operation Impacts

 

An execution a WMI method may have impacts on computer system resources. It really depends on provides’ implementation.

When we call methods that are defined in Msvm_ImageManagementService object, we will interact with host file system to perform Virtual Hard Disk file operations. When we call the methods that are defined in Msvm_VirtualSwitchManagementService, we will interact with the host networking stack to performance network configuration activities, etc.

The detail impacts of Hyper-V methods will be posted when we discuss each individual method.

 

Relationships

In relational database, we construct table relationships with primary keys and foreign keys. In the many to many relationships, we create a link table as the diagram shows.

(Diagram 2)

The relationships help us to retrieve related information in table2 from table1.

In WMI, we use the similar concept to build object trees. In between two objects, we use a association object to link them up. The main purpose of this association object is to help us to navigate from one object to other. It’s all about how to retrieve information that was structured in object world.

(Diagram 3)

Here is an association object when we view it from WMI CIM Studio:

(Diagram 4)

Object Path

In Relational data base, primary keys uniquely identify an entity (table row). In WMI, an object path is the unique identifiers for each object. An object path consists of object schema path (WMI class path) and key instance values.

WMI Class Path

Key Value

Key Value

\\MyMachine\root\virtualization:Msvm_SettingsDefineState.

ManagedElement="\\MyMachine\root\virtualization:Msvm_ComputerSystem.CreationClassName="Msvm_ComputerSystem\",Name=\"A2E571D2-6237-460C-8413-CB246C55E029",

SettingData="\\MyMachine\root\virtualization:Msvm_VirtualSystemSettingData.InstanceID="Microsoft:A2E571D2-6237-460C-8413-CB246C55E029"

Queries

WQL is a subset of SQL. For complete reference, please visit:

https://msdn.microsoft.com/en-us/library/aa394606(VS.85).aspx

The queries that we used in our samples are

· Simple select statement

· WMI ASSOCIATORS OF

· WMI REFERENCES OF

Select Statement

As you might have noticed, we use the select statement in AddVirtualSystemResources (https://msdn.microsoft.com/en-us/library/cc160705(VS.85).aspx)

  
 query = Format1("select * from Msvm_ComputerSystem where ElementName = '{0}'", vmElementName) 

But when we query Msvm_SyntheticEthernetPortSettingData default definition object, we traversed the following objects by using ASSOCIATORS and REFERENCES queries.

(Diagram 5)

You might wonder I can use the following shortcut to get it working, why bother with the object traversing:

  
 select * from Msvm_SyntheticEthernetPortSettingData where InstanceID like '%default' 

Yes, you could retrieve the Msvm_SyntheticEthernetPortSettingData definition object this way, but it’s not recommended.

ASSOCIATORS OF

ASSOCIATORS OF is one of the two special queries was not part of the ANSI SQL queries.

As you can see the (Diagram 2) above, this query allows us to retrieve object2 from object1 based on their associations.

In AddVirtualSystemResources VBScript sample, we use following query to get Msvm_AllocationCapabilities object.

 
 query = Format1("ASSOCIATORS OF {{0}} WHERE resultClass = Msvm_AllocationCapabilities", poolResource.Path_.Path) 

poolResource.Path_.Path points to Synthetic Ethernet object instance that is defined in Msvm_ResourcePool. As you can see in (Diagram 5) , we will get Msvm_AllocationCapabilities object after this query.

C# System.Management assembly introduced a wrapper (Syntax sugar) around this query. In our sample code at https://msdn.microsoft.com/en-us/library/cc723869(VS.85).aspx, we query Msvm_AllocationCapabilities as following:

 
 ManagementObjectCollection allocationCapabilities = poolResource.GetRelated("Msvm_AllocationCapabilities"); 

REFERENCES OF

In (Diagram 2) above, REFERENCES OF will bring us to the Association object.

In AddVirtualSystemResources VBScript sample, we use following query to get Msvm_SettingsDefineCapabilities object.

 
 query = Format1("REFERENCES  OF {{0}} WHERE resultClass = Msvm_SettingsDefineCapabilities", capbility.Path_.Path) 
 

The reason for us to get Msvm_SettingsDefineCapabilities because ValueRole(or ValueRange) property that is defined in this association class:

ValueRole

ValueRange

Associated with Msvm_SyntheticEthernetPortSettingData

0(Point)

0(Default)

Microsoft:Definition\6A45335D-4C3A-44B7-B61F-C9808BBDF8ED\Default

3(Supported)

1(Minimum)

Microsoft:Definition\6A45335D-4C3A-44B7-B61F-C9808BBDF8ED\Minimum

3(Supported)

2(Maximum)

Microsoft:Definition\6A45335D-4C3A-44B7-B61F-C9808BBDF8ED\Maximum

3(Supported)

3(Increment)

Microsoft:Definition\\6A45335D-4C3A-44B7-B61F-C9808BBDF8ED\\Increment

Please also reference to MSDN REMARK section at https://msdn.microsoft.com/en-us/library/cc136891(VS.85).aspx for meaning of these values.

Once we find Msvm_SettingsDefineCapabilities with ValueRole = 0 or Value Range = 0, then we find Msvm_SyntheticEthernetPortSettingData default object instance.

This is a second query that C# System.Management assembly has an API wrapper. In our sample code at https://msdn.microsoft.com/en-us/library/cc723869(VS.85).aspx, here is how we retrieve Msvm_SettingsDefineCapabilities object:

 
 ManagementObjectCollection settingDatas = allocationCapability.GetRelationships("Msvm_SettingsDefineCapabilities"); 

 

Events

A WMI event is fired when a WMI object state changed. Hyper-V WMI provider creates a __InstanceOperationEvent object when a Hyper-V object state changed. In the following dialog from CIM Studio, it shows four different kinds of events maybe generated.

Most Hyper-V operations are synchronized operations. Most of these methods provide a Job object allow you to pull the operation status in a while loop. We can also monitor operation status by listening object instance creation events; but it’s trickier since an operation may create many events.

The following VBScript sample codes will allow us monitor all Hyper-V WMI object creation events. The program will display WMI object relative path for each object that is created.

To run the program, simply copy the following codes and save it as eventmon.vbs; then run it from command line prompt as: cscript eventmon.vbs

 
 Option Explicit
 dim fileSystem
 dim objWMIService
 Main() 
 
  '------------------------------------------------- 
  ' The Main
  '------------------------------------------------- 
 Sub Main() 
 dim objArgs, computer, eventQuery, wmiSink
     set fileSystem = Wscript.CreateObject("Scripting.FileSystemObject") 
     computer = "." 
     set objWMIService = GetObject("winmgmts:\\" & computer & "\root\virtualization") 
     eventQuery = "Select * from __instancecreationevent within 10" 
     Set wmiSink = WScript.CreateObject("WbemScripting.SWbemSink", "SINK_") 
     objWMIService.ExecNotificationQueryAsync wmiSink, eventQuery
     WriteLog "Listening for the WMI events..." 
     While(True) 
         Wscript.Sleep(1000) 
     Wend
 End Sub
  '------------------------------------------------- 
  ' Sink call back function
  '------------------------------------------------- 
 Sub SINK_OnObjectReady(wmiObject, wmiAsyncContext) 
     dim p
     for each p in wmiObject.Properties_ 
         if p.Name = "TargetInstance" then
             WriteLog p.Value.Path_.RelPath
         end if
     next
 End Sub
  '----------------------------------------------------------------- 
  ' Create the console log files. 
  '----------------------------------------------------------------- 
 Sub WriteLog(line) 
     Dim fileStream
    Set fileStream = fileSystem.OpenTextFile("WMIEvent.log", 8, true, -1) 
     WScript.Echo line
     fileStream.WriteLine line
     fileStream.Close
 
 End Sub

Here is a sample output when creating a new VM from Hyper-V Manager Console:

WMI and Relational Database Comparison

WMI

Relational Database

Schema

Classes

Tables

Properties

Columns

Keys

Primary Keys

Keys

Foreign Keys

Path

Three part names. machineName.databaseName.tablename

Child class inherits the ancestor’s properties and methods.

Relational database doesn’t have inheritance concept.

Object Entities

Instances of the class

Rows

Relationships

Association

The other table in M:M relationships

References

The linked table in M:M relationships

Query Language

WQL

SQL

ASSOCIATOR

Join

REFERENCES

Join

Function Executions

Methods

Store Proc, .Net functions

Data Types

CIM data types

SQL data types

Meta Info

WMI uses classes to define objects. Classes are schema information about the WMI.

SQL system tables defines the entire database objects

 

Hyper-V Object Properties can be Modified with Put

 

Class

Property

Msvm_VirtualSwitch

ElementName

ScopeOfResidence

Msvm_SwitchPort.

ElementName

ScopeOfResidence

VMQOffloadWeight

ChimneyOffloadWeight

AllowMacSpoofing

Msvm_InternalEthernetPort

ElementName

Msvm_VLANEndpointSettingData

AccessVLAN

NativeVLAN

PruneEligibleVLANList

TrunkedVLANList

Msvm_VLANEndpoint

DesiredEndpointMode

 

DMTF

Virtualization schema is an industry wide collaboration efforts, here are DMTF’s standard if you are interested:

  • DSP1042, System Virtualization Profile
  • DSP1057, Virtual System Profile
  • DSP1059, Generic Device Resource Virtualization Profile
  • DSP1041, Resource Allocation Profile
  • DSP1043, Allocation Capabilities Profile

Comments

  • Anonymous
    January 01, 2003
    Howdie, wooohoo, this article rocks. Thanks for the great information! Peter Forster MVP Virtual Machine Austria

  • Anonymous
    January 01, 2003
    Tx for sharing this information, it's pricless...

  • Anonymous
    December 19, 2008
    Thanks for this article. It gives me a heads on WMI programming for Hyper-V which I was not able to find elsewhere. Regards, Sam

  • Anonymous
    December 01, 2010
    great stuff, thanks for sharing this with us ;-) Regards Ramazan