An In-Depth Look at WMI and Instrumentation, Part I

Introduction

WMI stands for Windows Management Instrumentation and, as the name indicates,is about managing your IT infrastructure. Applications are used to solvespecific business needs or ease existing pains in an enterprise. One step inthe process of acquiring enterprise-wide applications is the cost benefitanalysis. What are the costs of acquiring this application and what are thebenefits. Costs are distinguished between one-time costs and ongoing costs.Even though one-time costs can be quite high, it is really the ongoing costswhich are under high scrutiny. Ongoing costs typically exceed the one-timecosts by far and hit IT budgets hard. This involves training IT staff tohave the necessary skills to install, maintain and troubleshoot theapplication. This also involves proactively monitoring the application socertain SLA's (Service Level Agreements) are met. Almost every IT departmentneeds to guarantee certain service levels to their internal customers. Thisis important to them; they need to know that they can rely on the fact that theapplication is available and functioning when required. The last thing youwant is to introduce a new finance system and, when you need to bookreceivables, it is not available and your business is impacted. This alsoinvolves troubleshooting applications when they are down and getting it upwithin guaranteed time frames. Application downtimes hit the organizationtwofold. For one, the business is impacted because it cannot perform acertain function. On the other hand, you have expensive resources looking forthe root cause like a needle in a hay stack. Applications are still veryhard to troubleshoot; 90% of the time is spent identifying the root causeand the remaining 10% fixing it. Often it happens that IT staff is fixingthe symptoms of a problem instead of the root cause, mostly due to the factthat it is hard to identify the real root cause.

This is not a new challenge. But "maintainability", which encompasses allthe things stated above, is an important application characteristic intoday's world. Every IT department has a say when it comes to acquiring newenterprise applications. And besides performance and scalability, they willinquire in more and more detail about how easy it is to maintain yourapplication, how easy it is to get proactively notified about applicationissues with suggested resolutions, and how easy it is to troubleshoot yourapplication.

 

Windows Management Instrumentation to the rescue

This is where WMI comes into play. It provides a consistent programmaticaccess to management information in the enterprise. It uses the typicalprovider and consumer concept where you have on one side componentsproviding this management information while on the other side managementapplications can subscribe and consume it. Management applications alsodon't have to go out and find these providers and their information. WMIprovides a WMI store which gives access to all the providers and all theclasses and objects these providers provide. This makes it very easy formanagement applications to discover all the information available and thenread and consume this management information. WMI is Microsoft'simplementation of WEBM (Web-Based Enterprise Management) Initiative. WBEMdefines a set of standards deployed to provide a unified management ofenterprise computing environments. You can find more information about WBEMhere.

WBEM itself uses a standardized data model to describe manageableobjects like systems, applications, services, networks, etc. This is theCommon Information Model (CIM) and you can find more information about it here. The WMI data model is extending the CIM data model. WMI is acomponent of the Windows OS and is included out-of-the-box on Windows 2000,Windows XP and Windows 2003. It is located in the "windows\system32\wbem"folder. It can be downloaded for earlier versions of Windows from here (with a number of other WMI tools). WMI also provides a rich programming interface including VB, C++,scripting languages and the .NET framework itself.

 

A WMI architecture overview

The WMI architecture consists of three layers. Layer one contains the managedobjects and providers which provide rich management information. Managedobjects are logical or physical components in the enterprise which aremanaged. Providers are COM or .NET components which monitor the managedobjects and expose real time information about them to WMI. Any managedapplication can provide one or multiple managed objects and a provider byproviding the necessary components so information is available to WMI.

Layer two is the WMI infrastructure which is provided by the Windows OSitself. The WMI infrastructure consists of the "Windows ManagementInstrumentation" service and the WMI repository (store). TheWindows Management Instrumentation service is the intermediary between theproviders, the consumers and the WMI store. Providers can placeinformation through it into the WMI repository, consumers can query the WMIstore for available information, and the WMI service can pass informationdirectly between providers and consumers.

Layer three consists of the management applications, the applications which areinteracting with WMI to find information about managed objects. Managementapplications gather information to analyze it and provide a comprehensiveand accurate view of what is happening to these managed objects. Operatorscan use this raw or processed information to make decisions, take actionsand resolve items. Microsoft's implementation of such a managementapplication is Microsoft Operations Manager 2005 (which we cover later inthe article).

 

A look at the WMI data model

Each managed object is represented through a WMI class stored in the WMIschema. A WMI class can have properties, system properties, methods andqualifiers. System properties are defined by the WMI infrastructure, forexample the class name, the list of classes this class is inherited from,etc. The properties are information you can store in an instance of thisclass. The methods are actions you can perform on a class instance. Methodshave in-parameters and out-parameters, the method return code being theout-parameter with the name "ResultValue". Qualifiers provide qualifyinginformation about the class, the property or the method (each has a list ofqualifiers). For example "Abstract" for abstract classes, "Constructor" tomark a method as constructor, "Destructor" to mark a method as destructor,"In" and "Out" to mark method parameters as in or out, etc. A list ofstandard and WMI specific qualifiers can be found here.

This is exactly the same as in the .NET framework with the exception thatyou define these WMI classes through WMI and store them in the WMIrepository. You can group classes together into namespaces, like yournamespaces in .NET. Each provider typically creates its own namespace, forexample "root\enterpriseminds". The root namespace is called "Root" and allother namespaces are children of it. Each namespace can have one or multipleclasses and child namespaces. The picture on the left shows a sample (pleasenote this is an abbreviated view usi
ng the sample application attached to the second part of this article to demonstrate this namespace andclass hierarchy).

On top you see the Root namespace which has two classes. System classesalways start with two underscores. The Root namespace has aspnet, cimv2,default and directory child namespaces. In the picture you can see that thecimv2 namespace has two system classes followed with a number of Win32classes implemented by it.

The class Win32_DefragAnalysis, for example, provides a defrag analysis andreturns all the information back to the WMI consumer. The namespace cimv2 iswhere you find all classes provided by Windows itself. All classes providedby IIS are in the microsoftiisv2 namespace. You can create your ownnamespaces as needed, e.g. root\mycompany.

 Like in .NET, you cannot instantiate abstract classes. All otherclasses can have class instances, actual objects which hold data(information). Class instances can be static or dynamic. Static classinstances are stored in the WMI repository and the WMI service queries itdirectly from the WMI store. Dynamic class instances are provided in realtime by underlying providers. Classes which provide dynamic class instancesare marked with the Dynamic qualifier and also have a Provider qualifierwhich specifies the name of the provider. Providers (or rather, the information aboutproviders) are stored in the WMI store as static class instances of theclass __Win32Provider. The provider named in a Provider qualifier needs tohave a __Win32Provider class instance so WMI knows the class ID and otherrelated information it needs to communicate with the dynamic provider.Almost all classes defined in the cimv2 and microsoftiisv2 namespace aredynamic.

WMI provides class instances (objects) and events. Both are defined as WMIclasses in the WMI repository. The difference is that consumers have toactively query for class instances while they can subscribe to events; assoon as an event is available the consumer gets notified about it. More onthat later in this article.

 

The .NET framework support for WMI

The .NET framework has comprehensive support for WMI but still haslimitations. The System.Management namespace provides the classes needed tointeract with WMI. The types in this namespace are used to query for WMIclasses and class instances, find all the namespaces in the WMI store, etc.There is a complete section in this article dedicated to these classes. TheSystem.Management.Instrumentation namespace provides the classes andattributes which makes it very easy to register classes in the WMI store,provide dynamic class instances, and raise WMI events. The next section inthis article explains those types and attributes. The .NET implementation ofWMI has the following major limitations:

  • WMI classes defined through managed providers cannot implement methodsor qualifiers. However, it is possible to call methods of classes definedthrough unmanaged code.
  • Properties defined through managed providers areread-only for consumers.
  • WMI classes defined through managed providers are always markedwith the Dynamic qualifier.

Hopefully future versions of the .NET framework will remove thoselimitations. But the .NET framework makes it very easy to define WMIclasses, raise WMI events and provide dynamic WMI class instances.

 

A look at the System.Management.Instrumentation namespace

The System.Management.Instrumentation namespace provides a number ofattributes which makes it very easy to instrument your application. Firstyou add a reference to the System.Management assembly to your project. Thenyou mark your assembly so that it provides management instrumentation byapplying the InstrumentedAttribute on the assembly level. Add thefollowing line to your Assembly.cs file (and don't forget to import yournamespace with the "using" keyword).

 

[assembly:Instrumented("root/enterpriseminds")]

Specify the namespace hierarchy your WMI classes and events will appear in.The .NET framework will create this namespace for you when registering theWMI classes in the WMI store. Always start with the root namespace and usethe forward slash and not the backward slash as WMI itself does. Next definethe WMI classes and WMI events you want to expose. You can do this throughattributes or by inheriting from the Instance or BaseEvent classes provided by.NET. Here is how you define a WMI class using attributes:

 

[InstrumentationClass(InstrumentationType.Instance)]
public class InfoMessage
{
     public string Message;
     public string Guid;
     public int Type;
}

First define your .NET class (you can also use a struct) and then apply theattribute InstrumentationClass specifying the InstrumentationType asInstance, meaning you provide class instances. You can only use simple datatypes, or complex data types you also register in the WMI store. For example,you cannot use an enumeration as data type (because it is unknown to WMI),and you cannot register an enumeration. But you can create your ownMessageType class which you then also register with WMI through theInstrumentationClass attribute. Inheriting your class from the Instanceclass provided by .NET achieves the same as using the InstrumentationClassattribute.

 

public class InfoMessage : Instance
{
     public string Message;
     publicstring Guid;
     publicint Type;
} 

Every public property and public field becomes a WMI class property. Privateproperties, private fields, and all methods are ignored. The class
also getsassigned the Dynamic and Provider qualifiers. The .NET framework uses its ownWMI classes for this purpose – WMINET_InstrumentedAssembly andWMINET_ManagedAssemblyProvider. Whenever your WMI class gets registered inthe WMI store (which happens every time the WMI class to register changes)it creates a new WMINET_InstrumentedAssembly andWMINET_ManagedAssemblyProvider class instance and sets the value of theProvider qualifier of your class to the value ofWMINET_ManagedAssemblyProvider.Name. This information tells the WMI serviceand .NET framework how to find the dynamic provider, which consists of your assembly and typesrepresenting this WMI class.

You can apply the IgnoreMemberAttribute to any public property or publicfield you don't want to be registered as property in the WMI class. Toprovide an instance of the WMI class to consumers you create an instance ofyour .NET class, set its values and then call Instrumentation.Publish() topublish the class instance. From then on the object is visible to any WMIconsumer.

 

// create a new message
InfoMessage Message = new InfoMessage();

// set its properties
Message.Message = MessageText;
Message.Guid = Guid.NewGuid().ToString();
Message.Type = (int)Type;

try
{
      // publishes the message to the WMI repository
      Instrumentation.Publish(Message);
}

// we have not been able to publish the message
catch(ManagementException)
{
}

If you inherited your class from the Instance class instead of using theattribute then you have a Published property. Setting it to true publishesthe class instance. WMI classes created through managed providers aredynamic, meaning that, when your application domain gets destroyed and yourassembly unloaded, any class instance you published gets revokedautomatically. You can revoke any class instance you published by callingInstrumentation.Revoke() and passing along the same class instance (or forclasses inherited from the Instance class you set the Published property tofalse).

WMI classes are your choice if you want to publish information so consumerscan query it and get information about your application or assembly. WMIevents are your choice if you want to proactively notify consumers aboutsomething. There is not much difference in declaring and firing events. Youdefine again your .NET class or struct and apply the InstrumentationClass,but this time you set the InstrumentationType to Event.

 

[InstrumentationClass(InstrumentationType.Event)]
public class EventDetails
{
      public string Message;
      public string Guid;
      public int Type;
}

The same limitations apply as to WMI classes. Only simple data types orcomplex types which are also registered as WMI classes can be used. You canalso inherit the class from BaseEvent instead of applying the attribute.

 

public class EventDetails : BaseEvent
{
      public string Message;
      public string Guid;
      public int Type;
}

Events are not published and revoked like class instances. Events are firedat a given time and any consumer listening to this event type will receiveit. But any consumer subscribing to this event type afterwards will not getthe event. It will only get future events fired. Here is a code snippetwhich shows how to fire an event:

 

// create a new event
EventDetails Details = new EventDetails();

// set the event details
Details.Message = Message;
Details.Guid = Guid.NewGuid().ToString();
D
etails.Type = (int)Type;

try
{
      // fire the event so consumers can consume it
      Details.Fire();
}

// catch any exception and return false
catch (ManagementException)
{
}

You first create your .NET class instance, set its properties, and then callthe Fire method (if inherited from the BaseEvent class) or callInstrumentation.Fire() passing along the .NET object (if you used theattribute to declare your WMI event). This is all you need to do to publishWMI class instances and fire WMI events. Add a .NET installer so that youcan manually or even automatically register the WMI class and event in the WMI store when first loading the assembly. Here is the code snippet:

 

[RunInstaller(true)]
public class MyProviderInstaller : DefaultManagementProjectInstaller
{
}

You can manually run InstallUtil against this assembly to perform theregistration in the WMI store. It really can't get easier to instrument yourapplication.

 

A simple WMI consumer

You can do more then just write your own WMI class instance and eventprovider. You can also write your own WMI consumer which queries for availableWMI class instances and subscribes to WMI events. The needed types areresiding in the System.Management namespace. The ManagementClass lets youbind to a WMI class through the class path. WMI paths consist of the machineto query, the namespace hierarchy, followed by the class path itself. Thesyntax is as follows:

 

\<machinename>\root\<namespacename>:<classpath>

You can use a dot instead of the machine name to point to the local machine.For example, to connect to the WMI class created in the previous section, usethe path "\.\root\enterpriseminds:InfoMessage". Through the methodGetInstances() you get a collection of all class instances of this class.Class instances are represented by the ManagementObject type. TheManagementObject provides a property collection to access all the propertiesdefined by the class. The following code snippet queries for all availableclass instances of the InfoMessage class:

ManagementClass WMIClass = null;

try
{
      // bind to the WMI class
      WMIClass = new ManagementClass(@"\.\root\enterpriseminds\InfoMessage");
<o:p>
</o:p>
      // now loop through all the objectinstances
      foreach (ManagementObjectObject in WMIClass.GetInstances())
      {
            // create a new message
            InfoMessage Message = new InfoMessage();

            // read the properties out ofthe object instance
            Message.Message = Convert.ToString(Object.Properties["Message"].Value);
            Message.Type = Convert.ToInt16(Object.Properties["Type"].Value);
            Message.Guid = Convert.ToString(Object.Properties["Guid"].Value);

            // add the new message tothe list view
            ItemCollection.Add(new ListViewItem(new string[] { Message.Message,
                               Message.Type.ToString(),Message.Guid }));

            // release theunderlying COM object
        &nbsp
;  
Object.Dispose();
      }
}

// any exception happening is shown
catch (Exception e)
{
      MessageBox.Show(e.Message);
}

// release the underlying COM object
finally
{
      if (WMIClass != null)
            WMIClass.Dispose();
}

First we bind to the WMI class, then we loop through the collection of classinstances we obtain by calling GetInstances() on the ManagementClass typeand for each class instance we read from the property collection the threeproperties Message, Type and Guid. Each class instance we find gets addedto a list view. The .NET WMI types are built on top of the unmanaged WMIAPI. Therefore you should call Dispose() on each ManagementObject you getfrom GetInstances() as well as on the ManagementClass object itself. That isall you need to do to get the class instances of any WMI class.

You can perform WQL queries against the WMI store. WQL is built on top ofthe SQL language with some variations, the main difference being that you canonly query for data and not perform updates or deletes. A separate sectionof this article is dedicated to WQL. To subscribe to WMI events you use theWqlEventQuery type which creates the appropriate WQL query for you. When youcreate an instance of WqlEventQuery you pass along the event class name toquery for and an optional condition, like any SQL WHERE condition. Thecondition allows you to query for only specific events, for example allEventDetails events where the Type property is set to one InstrumentationConsumer Consumer = null;
WqlEventQuery EventQuery = null;
ManagementScope Scope = null;

try
{
     // create a event query object
     EventQuery = new WqlEventQuery("EventDetails");

     // define the search scope -which machine and namespace
     Scope = new ManagementScope(@"\.\root\enterpriseminds\EventDetails");
<o:p>
</o:p>
     // create a watcher object we use to get async notifications
     EventWatcher =new ManagementEventWatcher(Scope, EventQuery);

     // register the delegate to call when an event arrived
     EventWatcher.EventArrived += new EventArrivedEventHandler(Delegate_EventArrived);

     // start listening forevents
     EventWatcher.Start();
}

// show any exception happening
catch (Exception e)
{
      MessageBox.Show(e.Message);
}

This code snippet subscribes to EventDetails events in the"\.root\enterpriseminds" namespace. To synchronously wait for the next WMIevent call WaitForNextEvent() on the ManagementEventWatcher object. Thiscall waits till the next instance of that event is available and thenreturns. The code snippet above performs an asynchronous read by setting theevent handler to be called when an event arrives and then calling Start() onthe ManagementEventWatcher object. This allows your application to getnotified about WMI events while performing other tasks. The next codesnippet shows an example of the EventArrived event handler (of the typeEventArrivedEventHandler):

 

public void Delegate_EventArrived(object sender, EventArrivedEventArgs e)
{
      // create a new event info
      EventDetails Details = new EventDetails();

      // get the event details
      Details.Message = Convert.ToString(e.NewEvent.Properties["Message"].Value);
      Details.Type =    Convert.ToInt16(e.NewEvent.Properties["Type"].Value);
      Details.Guid = Convert.ToString(e.NewEvent.Properties["Guid"].Value);

      // now add the event to the list view
      EventCollection.Add(new ListViewItem(new string[] { Details.Message,
                          Details.Type.ToString(), Details.Guid }));
}

The EventArrivedEventArgs.NewEvent contains a reference to the received WMIevent and is of the type ManagementBaseObject. It provides access to theproperty collection of the WMI event which we use to read the event detailsand then we add the event to a list view. Finally if you do not want toreceive any further events you call Stop() on the ManagementEventWatcherobject and then Dispose() to free the underlying COM object. Here is a codesnippet:

 

// stop the event listening
EventWatcher.Stop();

// and dispose the underlying COM object
EventWatcher.Dispose();

It is also very simple to subscribe and asynchronously receive WMI events. It is also very powerful to perform that against any machine on your networkwhich has the WMI infrastructure installed, which all new Windows releasesdo. A good example would be a server application which you deploy ontomultiple servers. How do you monitor it and make sure you get notified assoon as a critical error happens? With WMI you can achieve that fairly easily.When a critical error happens, you raise a WMI event. You then write a smallapplication which subscribes to this WMI event on all the machines thisserver application is running on. And as soon as one raises an event, you candisplay it on a central console. This simple management tool could be verypowerful and helpful for monitoring your server application. Microsoftprovides such a management tool, just much more sophisticated Operations Manager 2005.

 

The attached sample application

The attached Windows form sample application provides an instrumentationprovider as well as an instrumentation consumer. The provider applicationdemonstrates how to create and publish class instances, how to revokepublished class instances and how to raise WMI events. The consumerapplication demonstrates how to subscribe and asynchronously receive WMIevents and how to query for instances of a WMI class. The providerapplication raises a WMI event when started as well as when closed. Formore details see the included readme.htm file. Please note that Windows 2000SP4, Windows XP SP2 or Windows 2003 SP1 (or KB836802 for Windows 2003) are required for subscribing to WMI events.This is due to a known bug in the WMI API.

 

A look at Microsoft Operations Manager 2005

There are a number of enterprise monitoring solutions on the market, one ofthem being Microsoft Operations Manager 2005. Microsoft IT uses MOM 2005 tomanage its 6,000 or more servers in over 200 countries. This article willbriefly explain how MOM 2005 works and how you can configure it to receiveWMI events and raise alerts to IT operators. This is a very powerful wayyou can alert IT operators about critical errors happening in yourapplication.

To install MOM 2005 launch setup and first perform the option "checkprerequisite". Select all the items under "Microsoft Operations Manager 2005components" and click Check. This will check that all the pre-requisiteslike Windows 2000 SP4 or Windows 2003, MDAC 2.8, SQL Server 2003 SP3a andthe .NET framework 1.1 are installed on the machine. After all thepre-requisites are installed, go back to the main setup screen and select theoption "Install Microsoft Operations Manager 2005". Select the typicalinstallation which will again perform a pre-requisite check. The check willpass as we already made sure that all pre-requisites are installed. Nextselect the database server to use followed by the database size which needsto be at a minimum 300 MB. If you have multiple management servers running,then you can group them in one or multiple groups. The group name cannot bechanged after the installation. Next you enter the group name to use, forexample "Development". Next you enter the Windows account to be used by anyaction performed by this management server, for example to gatherinformation from providers, install and uninstall agents, etc. Next youenter the Windows account to be used to access the MOM database server.Finally it asks whether to enable error reporting and whether to send themautomatically to Microsoft – always a good idea. When the install iscompleted you find a new start menu item under "Programs | MicrosoftOperations Manager 2005".

MOM 2005 consists of an "Administrator Console" and an "Operator Console".This separates very well the administrative tasks from the operationaltasks. Administrative tasks are installing agents at new servers to monitor,setting up new event providers like a WMI event, setting up alert rules like"email or page an operator", etc. Operative tasks are looking at the health ofmonitored servers, reacting to alerts, analyzing event and alertinformation, etc. So Operators are the IT professionals who use MOM 2005 asa
tool to look after the server and IT infrastructure they are responsiblefor. First launch the "Administrator Console" to set up MOM to receive theWMI events we are raising in our application. This shows the console tree onthe left side and the "Information Center" on the right side. Theinformation center gives you access to documentation, MOM downloads, theMOM home page, etc.

MOM utilizes so called Management Packs, which are a set of rules,providers, scripts, tasks, etc. A Management Pack encapsulates all themanagement aspects to monitor an application or infrastructure component.You can say it encapsulates all the knowledge to manage that application orcomponent. The ISV of that application or component should provide theManagement Pack, as the creators also know best how to monitor it and keep itrunning reliably. Microsoft internally mandates that all future serverproducts/releases shipped need to provide a Management Pack. MOM installsout of the box with the "Microsoft Operations Manager 2005" Management Packbut ships with a number of other Management Packs which you can import, forexample for SQL Server, Active Directory, Systems Management Server, IIS,DNS, etc. To import a Management Pack, click on the item "Management Pack" inthe console tree and select "Import/Export Management Pack" from the popupmenu. Next select that you want to import a Management Pack followed by thefolder where the Management Pack is located. Your MOM 2005 CD has a foldercalled "ManagementPacks". Browse to it and on the next screen you find allthe Management Packs available in that location. Select one or moreManagement Packs to import, for example "Microsoft SQL Server 2000" and"Microsoft Windows IIS". During the import it shows you a detailed progressscreen. When done you will see new items appearing under the "ManagementPacks" item in the console tree. For example under "Rule and Groups" you see"Microsoft Windows Internet Information Services" and "Microsoft SQLServer". Underneath you find detailed event and alert rules which arerecommended by those Microsoft product groups.

 

Creating your own Management Pack

As an ISV, it is very simple and also recommended to create your own ManagementPack and ship that with your product. That makes it much simpler for ITgroups to monitor and maintain your application. First create your own "RuleGroup" where you define all the event and alert rules around your product.Under the item "Management Packs" you find the item "Rules and Groups".Right click on it, select "Create Rule Group" from the popup menu and enterthe name and description describing your product (for example"Enterprise-Minds Instrumentation Sample"). On the following screen youenter the "Company Knowledge Base", which is really a description of theManagement Pack and the product it monitors. Click on the "Edit" button toenter the text. When you are finished it asks whether to deploy the new"Rule Group" to a group of computers. Through this option you select the group ofcomputers the rules in this "Rule Group" will apply to. Select "yes" and clickthe "Add" button to add a computer group. It shows you the list of definedcomputer groups. Double click on one if you want to see details about thecomputer group. The "Formula" tab shows the formula used to determine whichcomputers belong to the group. If you run the sample application on themachine you installed MOM 2005 on, select the computer group "MicrosoftOperations Manager 2005 Servers". After you selected one or more computergroups, click Ok to save the new "Rule Group".

Expand the newly created "Rule Group" with the plus sign in front of it.Next create a new event rule (events meaning MOM events collected). Rightclick on the item "Event Rule", select "Create Event Rule" from the popupmenu and from the list select "Alert on or Respond to Event (Event)". Firstyou select an existing event provider or create a new one. Create a newevent provider by clicking on the button "New". The provider type we use isWMI, so select "WMI Events" from the list. Next enter the name of the newprovider, for example "Enterprise-Minds WMI Event". Then you enter thenamespace the WMI class is residing in which is, in our case,"root\enterpriseminds". Next you enter the WQL query this provider executesagainst WMI, which in this case is "SELECT * FROM EventDetails". To queryonly for certain properties, list the properties instead of the star, forexample "SELECT Message, Type FROM EventDetails". This query returns any WMIevent raised by the sample application. Another way to only return certainproperties is to list the properties in the "Property list" field, forexample "Message, Type". Click "finish" to create this new provider, whichbrings you back to the "Event Rule" creation process and selects the newprovider in the drop down list.

On the next screen you could apply a filter if you don't want to receive allevents, for example only receive events where the Type property has a valueof one. Later in the article it is explained how to filter events based onthe WMI event values. Next you could define that this rule only runs oncertain days and times, the default being "process at any time". Next you cangenerate an alert by selecting the "Generate Alert" checkbox. Select aseverity of the alert which is by default "Critical Error". Later in thearticle it is explained how you can generate different alerts based on thevalues provided by the WMI event. Next you select if you want to suppressduplicate alerts, which is the default selection, and which criteria are usedto determine whether it is a duplicate alert. The default criterion used isif the alert comes from the same computer and domain. This reduces theamount of alerts an Operator has to deal with, as it is very likely that thesame alert will be raised many times till the issue is resolved. It isenough that the Operator sees one alert which keeps the noise level down.Next you define response actions which should be executed when the eventhappens, for example execute this script which may restart an application.This allows automating some of the actions to be taken when this eventhappens. Next you enter a knowledgebase which allows you to describe the issuein detail and standard troubleshooting steps to be taken. This helpsOperators to understand how to resolve an issue. Finally you give the eventrule a name, for example "Instrumentation Sample Rule".

This is all you need to do to capture WMI events and raise alerts toOperators. In order for all the changes to take effect you need to rightclick on the item "Management Packs" and select "Commit ConfigurationChange" from the popup menu. By default, changes are only committed and takeeffect after five minutes. With this you can commit the changes right away.To change this default setting, select the item "Administrator | Global Settings". Then, in the list onthe right side, select "Management Servers", double click the item you want to change and, on the "Rule Change Polling" tab of the dialog that comes up, change the time till changes are committed.

 

The IT Operator view in MOM 2005

IT Operators do not administrate MOM but rather have an operative view overall the servers and components they are responsible for. The "OperatorConsole" can be launched through the start menu "Programs | Microsoft OperationsManag
er 2005". The navigation pane on the left (same look as in Outlook2003) lets you navigate to different views, the most important being the event,alert, state and performance views. The "event" view shows you all the eventsavailable. The "alert" view shows all the alerts which have been raised tothe Operator. The "state" view provides a very quick and good overview of thehealth state of each computer. It shows all the main components monitoredand the state of each. For example it can show that the overall health ofthe machine is "critical error". But the IIS and MOM Agent are healthy andthe SQL component is the one which raised the "critical error". This helps alot to understand very quickly which components on which servers needattention. Double clicking on a server in the state view shows all thealerts for this server. Events can then be used to get a much betterunderstanding of what happened before, during, and after the time of error. Theperformance view shows performance for all the performance rules set up.

Next launch the "InstrumentationProviderForm" sample application attached tothis article. Launching it will raise an EventDetails WMI event which MOM2005 is now listening for. In the same application you can enter the eventtext, select the event type and then click the "Fire event" button to raiseadditional WMI events. Go back to the "Operator Console" and to the alertsview. You will see now an alert generated because of the WMI event fired bythe sample application. Click on the alert and you will see its details inthe lower "Alert Details" pane. In the alert details you see all the WMIevent properties MOM received. You see first the system properties like__PATH (the WMI event path), __SUPERCLASS (the class this WMI eventinherited from), etc. You then see also all the WMI event properties itself.Please take special note of the order they appear in. Later in the articlewhen we set event filters and alert severity, you can select the propertiesby number. For example, the __PATH property is the fifth one so you can choseit by the name Parameter 5, the Message property is Parameter 10 and theType property is Parameter 11. Also take special note of the value of theType property. The property is of type integer in the .NET code but it isshown here as "0 (0×0)", "1 (0×1)", etc. So MOM reads the numeric value andconverts it to a string which has in parenthesis the hexadecimal stringrepresentation of the value.

If you select the Event tab in the "Alert Details" pane then you see all theevents which raised this alert. In the alert details there is a wealth ofinformation available, such as when the alert was first and lastraised. When the issue has been resolved, the Operator right clicks on thealert, selects "Set Alert Resolution State | Resolved" and then enters adescription how it was resolved for future reference. Through that menuOperators can also set other alert statuses, such as that it has been assigned to avendor or subject matter expert, or it might require a scheduledmaintenance. When all alerts have been resolved then the health state is setback to "Success".

 

Filtering MOM events and setting alert severity levels

Let's go back into the Administrator Console and filter the MOM events,meaning we want to see only MOM events when the WMI event type is set to"Application Start" (value 0) or "Application Stop" (value 1). Open up theproperties of the "Instrumentation Sample Rule" rule, go to the tab"Criteria" and select the "Advanced" button. Remember that the Type propertyis the Parameter 11. At the bottom select Parameter 11, select the Condition"equal", and enter as value "0 (0×0)" (remember it is converted to a stringincluding the hexadecimal string representation in parenthesis). Thiscriterion would return only events of the type "Application Start". Becausewe want to have all WMI events except the "User Initiated", we select theCondition "not equals" and the Value "2 (0×2)". Click on the button "Add ToList" to add it to the criteria list. You can add multiple criteria, buteach field can only be used for one criterion. If you want to edit a criterionthen select it in the list on top and click the button Remove. This removesthe criterion but shows it in the Field/Condition/Value controls at thebottom so you can change it and then add it again.

Save the event rule and don't forget to commit the configuration changes(right click on Management Packs and select "Commit Configuration Change"from the popup menu). Go back to the sample application and manually raisethree events, setting the Type for each to "Application Start", "ApplicationStop" and "User Initiated". Go back to the Operator console and refresh theEvents view (key F5) and you see only two events. Select each and check thevalue of the Type property and you will see that the one with the value "2(0×2)" (which is "User Initiated") is not present, because it has beenfiltered. Switch to the alert view and you will see only one alert, becausewe suppress duplicates. Select the alert and select the Events tab in the"Alert Details" pane and you see the two events which raised the alert. Setthe state of the alert to resolved so we have no alerts for our nextscenario.

Now this time we want to get all events but for different values in the Typeproperty we want to raise alerts with different severity. Bring up again theproperties of the "Instrumentation Sample Rule" rule. First go to theCriteria tab and remove the filter (click on the Advanced button, select thecriterion in the list and click the Remove button). Next go to the Alert taband select the check box "Enable state alert properties". This allows us tocreate a complex rule which defines the severity on property values. Clickon the Edit button beside the "Alert severity". Click Edit to edit thedefault condition added by MOM. The new dialog allows you to create acomplex condition, and the severity level if that condition is met. SelectParameter 11 through the Parameter button on the left side. You see that itadds "AttributeValue(Parameter 11)" to the condition text box. Edit it so itsays "AttributeValue(Parameter 11) = "0 (0×0)"" and set the alert severityto "Information" through the drop down list at the bottom. This conditionsays if the event Type property is set to "Application Start" then raise aninformation alert. Go back to the condition dialog and click on the Add buttonto add another condition. Select again Parameter 11, set the condition to"AttributeValue(Parameter 11) = "1 (0×1)"" and set the severity level to"Critical Error". This condition says when the event Type property is"Application Stop" then raise a "critical error" alert. Repeat the samesteps to add a condition "AttributeValue(Parameter 11) = "2 (0×2)"" wherethe severity is set to warning. This condition says when the event Typeproperty is "User Initiated" then raise a warning alert. Close the conditiondialog, which brings you back to the alert tab on the event rule. We areraising now three different alerts, which means you also need to change thecriteria used by MOM to suppress duplicate alerts. Set the "Server role" to"MOM Agent", the "Component" to "WMI" and for the Instance you select(through the arrow on the right) "Source Computer" and then "Parameter 11".This sets the Instance value to "$Source Computer$$Parameter 11$". So onlyduplicate alerts coming
from the same machine with the same Parameter 11value (which is the event Type property) are suppressed.

Commit the configuration changes and go back to the sample application.Manually raise three events again, setting the Type for each to "ApplicationStart", "Application Stop" and "User Initiated". Go back to the OperatorConsole and you will see again three events, but you also see three differentalerts. One with the severity "information",one with the severity "warning" and one with the severity "critical error".If you raise multiple events through the sample application you will alsosee that only one alert per severity is raised.

 

Creating your Management Pack

Now that we have created our provider, rule, and alerts, we want to packagethat up into a distributable Management Pack. This allows you to distributethis Management Pack to your customers. Right click on the item "ManagementPacks" and choose "Import/Export Management Pack" from the popup menu. Nextselect the option "Export Management Packs" which brings up the list ofexisting Rule Groups. Select the Rule Group "Instrumentation Sample Rule",meaning we want to export all event rules, alert rules andperformance rules of this Rule Group. Next it allows you to select Views andTasks to export. We have not created any views or tasks so we do not selectany. Finally it asks for the name and location of the Management Pack tocreate, for example "c:\Enterprise-Minds Management Pack". The exported fileends with the extension "akm" and can be imported like any other ManagementPack (see earlier in the article). The sample application attached includesthe sample Management Pack we created in this article.

Note that you can also delete Rule Groups but only if there are no alertspresent for the rules defined in that rule group. If there are alerts present itwill show a message stating you can't delete the rule group because alerts areassociated with it. Unfortunately there is no simple way to resolve this. MOM 2005stores all information in the SQL Server database called OnePoint. Delete all the alerts fromthe following tables – AlertHistory, AlertEvent, AlertEventSuppression and Alert. Thisis very useful when you want to remove all rules, providers and alerts createdand then test if the Management Pack you created includes all information andfunctions properly. This approach is only recommended for development environments. Forproduction environments refer to the section "database grooming" in the MOM 2005documentation.

Download Source

 

Summary

WMI and Microsoft Operations Manager 2005 provide a compelling and simpleway to make available sophisticated management instrumentation for yourenterprise applications. The .NET framework makes it easy to create your ownWMI classes and events, and registers them for you in the WMI store.Exposing WMI class instances and raising WMI events is very easy. Thedeclarative style using attributes makes it especially intuitive. Also,querying the WMI store for class instances and subscribing to receive WMIevents asynchronously is fairly simple. This allows you to create your own simplemanagement tools. MOM 2005 is a very compelling management tool for your ITinfrastructure and applications. It provides sophisticated informationgathering and analyzing capabilities which gather a wealth of informationbut only alert operators to relevant information. MOM 2005 excels with itsnew Operator Console specifically targeted at the IT operator, and its new"health state" view which provides a very good overview of machine andcomponent health statuses. MOM provides many more features which are beyondthe scope of this article.

The second part of this article will dive deeper into the WMI store, classesand class instances. WMI can provide a wealth of information about amachine. The sample application for the second article will provide a "WMISystem Browser" which enables you to find Windows and hardware serialnumbers, a list of installed OS hotfixes, a list of processors with clockspeed and current processor status information, and much more. The articlewill cover how to programmatically create and edit class and class instanceinformation. If you have comments to this article, please contact me @ klaus_salchner@hotmail.com. I want to hear if you learned something new. Contact me if you havequestions about this topic or article.

 

About the author

Klaus Salchner has worked for 14 years in the industry, nine years in Europeand another five years in North America. As a Senior Enterprise Architectwith solid experience in enterprise software development, Klaus spendsconsiderable time on performance, scalability, availability,maintainability, globalization/localization and security. The projects hehas been involved in are used by more than a million users in 50 countrieson three continents.

Klaus calls Vancouver, British Columbia his home at the moment. His next biggoal is doing the New York marathon in 2005. Klaus is interested in guestspeaking opportunities or as an author for .NET magazines or Web sites. Hecan be contacted at klaus_salchner@hotmail.com or http://www.enterprise-minds.com.

Enterprise application architecture and design consulting services areavailable. If you want to hear more about it contact me! Involve me in yourprojects and I will make a difference for you. Contact me if you have an idea for an articleor research project. Also conact me if you want to co-author an article or join future research projects!

Edited by Dwight Johnson

Most Commented Articles :

Twitter Digg Delicious Stumbleupon Technorati Facebook Email

No comments yet... Be the first to leave a reply!