30
Operating System Windows Management Instrumentation Provider Programming White Paper Abstract This paper presents an overview of the Microsoft® Windows® Management Instrumentation (WMI) Providers API. The Windows Management Instrumentation is an implementation of the Distributed Management Task Force (DMTF) Web- Based Enterprise Management (WBEM) initiative that provides standards for accessing and sharing management information in an enterprise environment.

WMI Provider Programming - ITwelzel.bizgwise.itwelzel.biz/Microsoft/Windows 2000 Server... · Web viewWMI facilitates these communications by providing a common programming interface

  • Upload
    others

  • View
    5

  • Download
    0

Embed Size (px)

Citation preview

Page 1: WMI Provider Programming - ITwelzel.bizgwise.itwelzel.biz/Microsoft/Windows 2000 Server... · Web viewWMI facilitates these communications by providing a common programming interface

Operating System

Windows Management InstrumentationProvider Programming

White Paper

Abstract

This paper presents an overview of the Microsoft® Windows® Management Instrumentation (WMI) Providers API. The Windows Management Instrumentation is an implementation of the Distributed Management Task Force (DMTF) Web-Based Enterprise Management (WBEM) initiative that provides standards for accessing and sharing management information in an enterprise environment.

Page 2: WMI Provider Programming - ITwelzel.bizgwise.itwelzel.biz/Microsoft/Windows 2000 Server... · Web viewWMI facilitates these communications by providing a common programming interface

© 1999 Microsoft Corporation. All rights reserved.The information contained in this document represents the current view of Microsoft Corporation on the issues discussed as of the date of publication. Because Microsoft must respond to changing market conditions, it should not be interpreted to be a commitment on the part of Microsoft, and Microsoft cannot guarantee the accuracy of any information presented after the date of publication.This White Paper is for informational purposes only. MICROSOFT MAKES NO WARRANTIES, EXPRESS OR IMPLIED, IN THIS DOCUMENT.Microsoft, Active Directory, ActiveX, IntelliMirror, Jscript,Visual Basic, Windows, and Windows NT are either registered trademarks or trademarks of Microsoft Corporation.Other product or company names mentioned herein may be the trademarks of their respective owners.Microsoft Corporation • One Microsoft Way • Redmond, WA 98052-6399 • USA12/99

Page 3: WMI Provider Programming - ITwelzel.bizgwise.itwelzel.biz/Microsoft/Windows 2000 Server... · Web viewWMI facilitates these communications by providing a common programming interface

INTRODUCTION.................................................................................1Windows Management Instrumentation Technology 1

WMI ARCHITECTURE OVERVIEW.......................................................3

PROGRAMMING BASICS FOR WMI PROVIDERS..................................6Provider Primary Interfaces 7Registering a Provider 8Initializing a Provider 9Making Calls to WMI 10Unloading a Provider 11Abrupt Termination of Providers 12Client Impersonation by Providers 13Registering Providers 14High-Performance API Providers 16

PROVIDER FRAMEWORK.................................................................18Provider Code Generator 18Compiling a Framework Provider 21Error Handling for Framework Providers 21Upgrading Framework Providers 22

CONCLUSION..................................................................................25

For More Information......................................................................26

CONTENTS

Page 4: WMI Provider Programming - ITwelzel.bizgwise.itwelzel.biz/Microsoft/Windows 2000 Server... · Web viewWMI facilitates these communications by providing a common programming interface

The Windows® Management Instrumentation (WMI) technology is the Microsoft® implementation of the Distributed Management Task Force (DMTF) Web-Based Enterprise Management (WBEM) initiative that extends the Common Information Model (CIM) to represent management objects in Windows-based management environments. The Common Information Model, also a DMTF standard, is an extensible data model for logically organizing management objects in a consistent, unified manner in a managed environment.

Based on the Common Information Model, WBEM is a DMTF initiative and technology that establishes management infrastructure standards and provides a standardized way to access information from various hardware and software management systems in an enterprise environment. Using WBEM standards, developers can create tools and technologies that reduce the complexity and costs of enterprise management. By providing such standards, WBEM contributes to industry-wide efforts to lower total cost of ownership (TCO). TCO refers to the administrative costs associated with computer hardware and software purchases, deployment and configuration, hardware and software updates, training, maintenance, and technical support.

WBEM provides a point of integration through which data from management sources can be accessed, and it complements and extends existing management protocols and instrumentation such as Simple Network Management Protocol (SNMP), Desktop Management Interface (DMI), and Common Management Information Protocol (CMIP).

The WBEM initiative results from the cooperative efforts of Microsoft, BMC Software, Cisco Systems, Compaq Computer, and Intel, as well as many other member companies active in the DMTF.

This paper presents a brief overview of WMI (the Microsoft implementation of the WBEM standard) and its architecture and goes on to provide detailed information about the WMI provider interfaces and aspects of programming WMI providers.

Windows Management Instrumentation TechnologyThe Windows Management Instrumentation (WMI) technology is a management infrastructure that supports the syntax of CIM, the Managed Object Format (MOF), and a common programming interface. The MOF syntax defines the structure and contents of the CIM schema in human and machine-readable form. Windows Management Instrumentation offers a powerful set of services, including query-based information retrieval and event notification. These services and the management data are accessed through a Component Object Model (COM) programming interface. The WMI scripting interface also provides scripting support.

The WMI technology provides:

Access to monitor, command, and control any managed object through a common, unifying set of interfaces, regardless of the underlying instrumentation mechanism. WMI is an access mechanism.

A consistent model of Windows 2000 operating system operation, configuration, and

WMI Provider Programming 1

INTRODUCTION

Page 5: WMI Provider Programming - ITwelzel.bizgwise.itwelzel.biz/Microsoft/Windows 2000 Server... · Web viewWMI facilitates these communications by providing a common programming interface

status.

A COM Application Programming Interface (API) that supplies a single point of access for all management information.

Interoperability with other Windows 2000 management services. This approach can simplify the process of creating integrated, well-architected management solutions.

A flexible, extensible architecture. Developers can extend the information model to cover new devices, applications, and so on, by writing code modules called WMI providers, described later in this document.

Extensions to the Windows Driver Model (WDM) to capture instrumentation data and events from device drivers and kernel-side components.

A powerful event architecture. This allows management information changes to be identified, aggregated, compared, and associated with other management information. These changes can also be forwarded to local or remote management applications.

A rich query language that enables detailed queries of the information model.

A scriptable API which developers can use to create management applications. The scripting API supports several languages, including Microsoft Visual Basic®; Visual Basic for Applications; Visual Basic, Scripting Edition (VBSript); Microsoft JScript® development software. Besides VBScript and JScript, developers can use any scripting language implementation that supports Microsoft ActiveX® scripting technologies with this API (for example, a Perl scripting engine). Additionally, you can use the Windows Script Host or Microsoft Internet Explorer to write scripts using this interface. Windows Script Host, like Internet Explorer, serves as a controller engine of ActiveX scripting engines. Windows Script Host supports scripts written in VBScript, and JScript.

The WMI technology architecture consists of the following:

A management infrastructure. This includes the CIM Object Manager, which provides applications with uniform access to management data and a central storage area for management data called the CIM Object Manager repository.

WMI Providers. These function as intermediaries between the CIM Object Manager and managed objects. Using the WMI APIs, providers supply the CIM Object Manager with data from managed objects, handle requests on behalf of management applications, and generate event notifications.

The management infrastructure consists of CIM Object Manager and the CIM Object Manager repository. Applications depend on the Object Manager to handle the interface between management applications and data providers. WMI facilitates these communications by providing a common programming interface to Windows management services using COM. This COM API supplies event notification and query processing services, and can be used in several programming language environments such as C and C++. The CIM Object Manager repository holds the CIM and extension

WMI Provider Programming 2

WMI ARCHITECTURE OVERVIEW

Page 6: WMI Provider Programming - ITwelzel.bizgwise.itwelzel.biz/Microsoft/Windows 2000 Server... · Web viewWMI facilitates these communications by providing a common programming interface

schemas, and data information or data source details. CIM Object Manager uses the schema data in this repository when servicing requests from management applications for managed objects.

Managed objects are either physical or logical enterprise components that are modeled using CIM. For example, a managed object can be hardware such as a cable, or software such as a database application. Management applications can access managed objects through CIM Object Manager.

Management applications are applications or Windows 2000 services that use or process information originating from managed objects. Management applications can access managed object information by making a request to CIM Object Manager through one of the methods in the WMI API.

WMI providers are standard COM and Distributed Component Object Model (DCOM) servers that function as mediators between managed objects and the CIM Object Manager. If the CIM Object Manager receives a request from a management application for data that is not available from the CIM Object Manager repository or for event notifications that are not supported by the CIM Object Manager, it forwards the request to a WMI provider. Providers supply data and event notifications for managed objects that are specific to their particular domain. Figure 1 illustrates the three layer model WMI uses, which consists of providers, the CIM Object Manager, and consumers of WMI information.

Figure 1. Model that WMI uses

To implement a provider, you should use one of the following supported server types:

Microsoft Windows 2000 services, local or remote. Standard executables (.exe files), local or remote. In-process dynamic-link libraries (DLLs).

Note that local or remote Windows 2000 services and standard executables are recommended server types.

WMI Provider Programming 3

Page 7: WMI Provider Programming - ITwelzel.bizgwise.itwelzel.biz/Microsoft/Windows 2000 Server... · Web viewWMI facilitates these communications by providing a common programming interface

WMI ships with built-in providers (or standard providers) that supply data from sources such as the system registry. The built-in providers include:

Active Directory Provider—Acts as a gateway to all the information stored in the Active Directory™ service. Allows information from both WMI and Active Directory to be accessed using a single API.

Windows Installer Provider—Allows complete control of Windows Installer and installation of software through WMI. Also supplies information about any application installed with Windows Installer.

Performance Counter Provider—Exposes the raw performance counter information used to compute the performance values shown in the System Monitor tool. Any performance counters installed on a system will automatically be visible through this provider. Supported by Windows 2000.

Registry Provider—Allows Registry keys to be created, read, and written. WMI events can be generated when specified Registry keys are modified

SNMP Provider—Acts as a gateway to systems and devices that use the Simple Network Management Protocol (SNMP) for management. SNMP MIB object variables can be read and written. SNMP traps can be automatically mapped to WMI events.

Event Log Provider—provides access to data and event notifications from the Windows 2000 Event Log.

Win32 Provider—Provides information about the operating system, computer system, peripheral devices, file systems and security information.

WDM Provider—Supplies low level Windows Driver Model driver information for user input devices, storage devices, network interfaces, and communications ports.

View Provider—Allows new aggregated classes to be built up from existing classes. Source classes can be filtered for only the information of interest, information from multiple classes can be combined into a single class and data from multiple machines can be aggregated into a single view.

The WMI technology also provides support for third party custom providers. Custom providers can be used to service requests related to managed objects that are environment-specific. Providers typically use the MOF language to define and create classes. Providers use the WMI API to access the CIM Object Manager repository, and to respond to CIM Object Manager requests made initially by applications.

Additional technical papers on WMI are available on the Microsoft Web site.

The next sections present an overview of the WMI provider interfaces and programming guidelines.

WMI providers are categorized according to the types of requests that they service. The most common providers are instance providers. Instance providers supply instances of a given class and support one or more of the following asynchronous operations:

Instance retrieval

WMI Provider Programming 4

PROGRAMMING BASICS FOR WMI PROVIDERS

Page 8: WMI Provider Programming - ITwelzel.bizgwise.itwelzel.biz/Microsoft/Windows 2000 Server... · Web viewWMI facilitates these communications by providing a common programming interface

Enumeration Modification Deletion Query processing

Class providers can support the same asynchronous operations as instance operations. However, class providers supply class definitions rather than instances of a class. Because the operations supported by class providers can negatively impact system performance, they should only be implemented when absolutely required.

Class providers can be implemented as pull or push providers; instance providers can only be implemented as pull providers. Pull providers maintain their own data, generating it dynamically when necessary. Push providers rely on WMI to maintain their data in the Common Information Model (CIM) repository.

Property providers can support the retrieval and modification of individual property values.

Method providers implement the methods of one or more classes. Having a single provider support both methods and instances can be convenient.

Event providers deliver event notifications to WMI from a data source, such as the system registry or a Simple Network Management Protocol (SNMP) device. Then, WMI forwards the events to the appropriate consumers.

Event consumer providers are used by permanent event consumers to supply the appropriate physical destination for particular events.

Providers typically perform the following tasks:

Register with WMI. All types of providers are required to complete the registration process.

Implement the IWbemProviderInit interface to perform initialization. All types of providers are required to support initialization.

Implement a primary interface. Most providers are required to implement a primary interface to support the features that are specific to the type of provider. Only push providers are exempt from having to implement a primary interface.

Support a request from WMI to unload. All pure providers (providers that operate only as providers) are required to unload when asked to do so by WMI. Non-pure providers (providers that can also operate as clients) do not have to respond to an unload request. However, such providers place an additional load on WMI by performing private operations not related to their role as providers. This should only be done if strictly necessary. Providers specify whether they are pure or non-pure in the registration process.

Provider Primary InterfacesProviders implement a primary interface that supports the type of functionality specific to their role. The following table lists primary interfaces by provider type.

WMI Provider Programming 5

Page 9: WMI Provider Programming - ITwelzel.bizgwise.itwelzel.biz/Microsoft/Windows 2000 Server... · Web viewWMI facilitates these communications by providing a common programming interface

Provider Primary interface

Class provider IwbemServices (asynchronous methods only)

Instance provider IWbemServices (asynchronous methods only)

Property provider IWbemPropertyProvider

Method provider IWbemServices (ExecMethodAsync only)

Event provider IWbemEventProvider

Event consumer provider IWbemEventConsumerProvider

As an option, event providers can also implement IWbemEventProviderQuerySink. This interface is most useful for providers that supply events of multiple types and that need to perform as many internal optimizations as possible.

Because IWbemServices is also used by applications and providers to request services of WMI, it contains many methods that are irrelevant to certain types of providers. Class, instance, and method providers are typically concerned with fewer than six IWbemServices methods. These providers can supply a stub implementation that returns WBEM_E_PROVIDER_NOT_CAPABLE for all of the other methods that do not support their feature set. This is illustrated in the following code sample.

HRESULT STDMETHODCALLTYPE PutClassAsync( IWbemClassObject __RPC_FAR *pObject, long lFlags, IWbemContext __RPC_FAR *pCtx, IWbemObjectSink __RPC_FAR *pResponseHandler) {return WBEM_E_PROVIDER_NOT_CAPABLE;};Class and instance providers can support zero or more of the following features by supplying a complete implementation of the corresponding IWbemServices method.

Feature Class Provider Method Instance Provider Method

Data retrieval GetObjectAsync GetObjectAsync

Data modification PutClassAsync PutInstanceAsync

Data deletion DeleteClassAsync DeleteInstanceAsync

Data enumeration CreateClassEnumAsync CreateInstanceEnumAsync

Query processing ExecQueryAsync ExecQueryAsync

Note that both provider types implement only the asynchronous variety of methods. There is no support in the Windows 2000 operating system for providers that implement the synchronous methods of IWbemServices.

The target data for a class provider is a class definition; the data for an instance provider is an instance of a class. Class and instance providers inform WMI of their feature set as part of the registration process.

Method providers fully implement a set of methods for a Common Information Management (CIM) object in their primary interface, ExecMethodAsync. All of the other

WMI Provider Programming 6

Page 10: WMI Provider Programming - ITwelzel.bizgwise.itwelzel.biz/Microsoft/Windows 2000 Server... · Web viewWMI facilitates these communications by providing a common programming interface

methods return WBEM_E_NOT_IMPLEMENTED.

A single provider can act simultaneously as a class, instance, and method provider by proper registration and implementation of all relevant methods.

Property, event, and event consumer providers implement all of the methods in their primary interface.

Note  Class providers that are designed as simple push providers only implement IWbemProviderInit; they do not implement a primary interface. This is because push providers use WMI to support their operations.

Registering a ProviderProviders register with WMI to publish information about the data and operations that they support and their physical implementation. WMI uses this information to load and initialize the provider and to determine the right provider for a particular client request. All types of providers follow the same procedure for registration. Neither WMI nor the provider needs to be running during the registration process. To register with WMI, a provider must execute the following steps.

1. Register with the Component Object Model (COM) by creating registry entries if necessary. This process applies to all COM servers and is unrelated to WMI.

2. Create a Managed Object Format (MOF) file that contains the following two instances:

An instance of the __Win32Provider class to describe the physical implementation of the provider.

An instance of a class derived either directly or indirectly from __ProviderRegistration to describe the logical implementation of the provider. For more information on provider registration see the corresponding section for a particular type of provider.

3. Place the .mof file into a permanent directory, typically the provider's installation directory.

4. Locate the following registry key: HKLM\SOFTWARE\Microsoft\WBEM. This key contains a REG_SZ value named "MOF Self-Install Directory."

5. Copy the .mof file into the directory named by the registry key value. Placing the .mof file into this directory ensures that it is compiled either right away (if WMI is currently running) or the next time that WMI is started. When WMI compiles the .mof file, it will move the file to the good or bad subdirectories depending on whether the .mof file was compiled with or without errors. Refer to the mofcomp.log file in the %systemroot%\system32\wbem\logs for related messages.

6. Locate the following registry key:HKLM\SOFTWARE\Microsoft\WBEM\CIMOM. This key contains a REG_MULTI_SZ value named "Autorecover MOFs (recovered)" that contains a list of paths to various .mof files.

WMI Provider Programming 7

Page 11: WMI Provider Programming - ITwelzel.bizgwise.itwelzel.biz/Microsoft/Windows 2000 Server... · Web viewWMI facilitates these communications by providing a common programming interface

Add the full path to the permanent location of the .mof file to the end of this list. This ensures that the .mof file will be recompiled if a problem occurs.

For testing purposes, a registration .mof file can be immediately compiled using the MOF Compiler instead of the preceding steps.

During installation, some providers place their .mof files in a temporary location such as C:\Wbem\Mof before copying them to their permanent location. Do not include the path to this temporary location in the list of paths described in step 6. Because WMI deletes all temporary copies of .mof files after they have been compiled, always use the path to the permanent copy.

Initializing a ProviderIWbemProviderInit and IWbemProviderInitSink are two interfaces involved in the initialization of all providers. IWbemProviderInit is implemented by providers and called by Windows Management Instrumentation (WMI) to begin initialization. When WMI determines that a provider's services are needed, it loads the provider and calls its IWbemProviderInit::Initialize method.

IWbemProviderInitSink is implemented by WMI and called by providers to report initialization status. Because Initialize should return after only a few seconds and initialization can sometimes take longer, providers can report interim status.

WMI passes the following as input parameters to IWbemProviderInit::Initialize:

If the provider has requested per-user initialization by setting the PerUserInitialization property in the __Win32Provider class to TRUE, the name of the logical user.

A set of flags that currently must be zero. The name of the namespace. The name of the locale.

WMI also passes pointers to three interfaces:

IWbemServices IWbemContext IWbemProviderInitSink

The IWbemServices and IWbemContext interfaces can be used to make requests to WMI either during the initialization process or later. If the provider needs to use any of these pointers after returning from the Initialize call, it must call AddRef to increment the reference count for that pointer.

The initialization process of some providers can involve other providers. Providers that are dependent upon information from another provider are known as dependent providers. WMI defines some special rules for dependent providers:

Dependent requests must reuse the IWbemContext pointer that was passed to Initialize. Non-dependent requests must not reuse this pointer. This means that any calls into

WMI Provider Programming 8

Page 12: WMI Provider Programming - ITwelzel.bizgwise.itwelzel.biz/Microsoft/Windows 2000 Server... · Web viewWMI facilitates these communications by providing a common programming interface

WMI made during initialization must reuse the IWbemContext pointer that was passed in from WMI. Failure to do so can result in deadlock.

Dependent providers must make requests to WMI by using one of the following two strategies: The dependent request can be made with the thread that was received from

WMI. The dependent request can be made with a new thread created by the provider.

Before making the request, the provider records it in an internal data structure and returns the call.

Dependent providers must always return the thread that was received from WMI, either through the dependent request or by returning from Initialize.

Under no circumstances will a provider be allowed to block a thread received from WMI. The danger in not carefully handling the threads that are delivered by WMI is that it is possible for a provider to acquire all of the threads in the WMI thread pool and block them, resulting in a deadlocked system.

Note: In-process providers that must connect to WMI separately from the initialization process must use the CLSID_WbemAdministrativeLocator class identifier to access IWbemLocator in the CoCreateInstance call.

IWbemLocator *pLoc = 0; DWORD dwRes = CoCreateInstance(CLSID_WbemAdministrativeLocator, 0, CLSCTX_INPROC_SERVER, IID_IWbemLocator, (LPVOID *) &pLoc);

Making Calls to WMIProviders can call methods implemented by Windows Management Instrumentation from within their method implementations. When a provider calls the WMI implementation of an IWbemServices method from within its own implementation of the same method, there are special considerations. These considerations are important regardless of whether the provider calls the synchronous or asynchronous version of the method.

Each IWbemServices method that a provider can implement has a pCtx parameter, a pointer to an IWbemContext interface implementation. When WMI calls the provider, it passes a valid pointer in this parameter. Providers must always pass this same pointer in any calls to WMI that they make while servicing requests. Neglecting to set pCtx appropriately can cause WMI to start an infinite loop.

For example, the following code shows the correct way to call the WMI implementation of GetObject from within its implementation of GetObjectAsync.STDMETHODIMP CClassProv::GetObjectAsync (BSTR ObjectPath, long lFlags, IWbemContext *pCtx, IWbemObjectSink *pHandler){ IWbemClassObject *pclObj = NULL;

hr = m_pNamespace->GetObject( _bstr_t(L"AClass"), 0, pCtx, &pclObj, NULL ); RELEASE( pclObj ); return pHandler->SetStatus(0, hr, NULL, NULL);}

Instance, class, and property providers must not issue any calls to WMI requesting the

WMI Provider Programming 9

Page 13: WMI Provider Programming - ITwelzel.bizgwise.itwelzel.biz/Microsoft/Windows 2000 Server... · Web viewWMI facilitates these communications by providing a common programming interface

modification of data while servicing a read request. The only providers that are exceptions to this rule are push providers. These types of providers are class providers that store their data in the CIM repository and rely on WMI to handle requests from clients. While servicing a read request, a push provider can update the CIM repository, but it must set the lFlags parameter to WBEM_FLAG_OWNER_UPDATE in the appropriate IWbemServices call.

Event providers must not make any class changes while servicing a call. They also cannot issue any event-related calls, such as modifying an event filter.

Unloading a ProviderWindows Management Instrumentation unloads a provider when it determines that it is no longer needed. When a provider is idle for more than a specific amount of time, WMI will begin the process of unloading the provider. The minimum amount of time a provider will remain active is determined by a property named ClearAfter in instances of classes that are derived from the WMI system class __CacheControl in the \Root namespace. Each of these derived classes control provider unloading for a specific type of provider. Listed below are the classes that control provider unloading:

__EventConsumerProviderCacheControl

__EventProviderCacheControl

__EventSinkCacheControl

__ObjectProviderCacheControl

__PropertyProviderCacheControl

You can change the minimum amount of time that WMI will allow a provider to remain inactive by editing the ClearAfter property in cache control instance for a specific type of provider. For example, if you want to want to limit the amount of time a property provider can remain idle you could use WMI CIM Studio to edit an instance of the class __PropertyProviderCacheControl in the Root namespace. You can use the interval editor to set the value of the ClearAfter property to a new value.

In future versions, WMI will use the UnloadTimeout property of the provider's __Win32Provider instance. Therefore, providers should set this property to five minutes or less.

To unload a provider, WMI calls the Release method of the provider's primary interface. For example, WMI calls IWbemServices::Release for a class provider and IWbemPropertyProvider::Release for a property provider. When Release is called, a pure provider (a provider that has set the Pure property of its Win32Provider instance to TRUE) is required to release all of the interface pointers that it currently holds against WMI. Typically, providers hold pointers to the IWbemServices and IWbemContext interfaces supplied to them in IWbemProviderInit::Initialize. A pure provider exists only to service requests and cannot take on the role of a client application.

Non-pure providers can transition to the role of client application after WMI has asked it

WMI Provider Programming 10

Page 14: WMI Provider Programming - ITwelzel.bizgwise.itwelzel.biz/Microsoft/Windows 2000 Server... · Web viewWMI facilitates these communications by providing a common programming interface

to unload. Non-pure providers set the Pure property to False. Such providers also independently act as clients, but because they cannot be unloaded, they increase system overhead.

Abrupt Termination of ProvidersWhen the WinMgmt service is stopped by the user (either explicitly, or during system shutdown), any providers (instance, class, event, and so on) that are still loaded at the time will not be released. Also, an in-process provider's DllCanUnloadNow entry point will not be called. Moreover, if an in-process provider is in the middle of a method call at the time of the shutdown, the executing thread can be terminated in the middle of the call.

If WMI shuts down while a provider is loaded, some of the routines that normally handle cleanup (the object's destructor and DllCanUnloadNow) are not called. Except in most unusual circumstances, the only routine guaranteed to be called is the DLL entry point (DllMain). This situation makes provider cleanup more difficult.

Because it is possible that WMI will shut down in the middle of a call, providers must make sure that they do not leave their data sources in an inconsistent state. For read-only providers, this is generally not a problem. Providers with write capabilities, however, may want to implement some sort of transactioning to allow a safe rollback after an abrupt termination.

When WMI exits, the operating system will automatically release all memory allocated to an in-process provider and will close most resources held by the provider (file handles, window handles, mutexes, and so on). The provider does not need to take any specific action to make this happen.

Certain types of resources are not automatically released by the operating system; an example would be a socket or a database connection. Such resources may need to be manually cleaned up by the provider. One place to perform this sort of cleanup is DllMain—the DLL entry point function that is called (once) when the DLL is being unloaded.

Cleanup code can be added directly into DllMain, executing it in response to DLL_PROCESS_DETACH. This can be somewhat difficult to arrange, especially in programming environments such as MFC or ATL. See Microsoft Support for the article, "How to Provide Your Own DllMain in an MFC Regular DLL."

An alternate approach is to put the cleanup code in the destructor of a global class. Global objects are not allocated on the heap and are automatically destroyed during DLL unload. The following code sample provides an example.

class CMyCleanup{ ~CMyCleanup() { CloseHandle(m_hOpenFile); CloseDatabaseConnection(g_hDatabase); }} g_Cleanup;

WMI Provider Programming 11

Page 15: WMI Provider Programming - ITwelzel.bizgwise.itwelzel.biz/Microsoft/Windows 2000 Server... · Web viewWMI facilitates these communications by providing a common programming interface

There are many restrictions as to what can be done in the cleanup code with either approach. Neither threads nor any DLLs that are not implicitly linked, may be accessed in any way; COM calls cannot be made under any circumstances. For more information, see "Win32 Q & A" Microsoft Systems Journal (March 1996 and September 1996).

Note that out-of-process providers do not experience any of these problems, because they are not killed when WMI shuts down, but they will be released after a COM timeout. Providers for whom cleanup and termination robustness issues are more important than performance may want to consider making themselves out-of-process.

Client Impersonation by ProvidersThe following section applies only to Microsoft Windows NT- and Windows  2000-based systems running Windows Management Instrumentation (WMI) SDK version 1.1 or later. It does not apply to the original WBEM SDK 1.0 release, nor does it apply to the Windows 95 or Windows 98 operating systems.

In the Windows NT and Windows 2000-based environment, WMI typically runs as an administrative service at a high security level (the LocalServer security context). This approach gives it the means to access privileged information. When WMI calls a provider for information, it passes its security identifier (SID) to the provider, enabling the provider to access information at the same high security level.

When a WMI application is launched, it is given the security context of the user who launched it. This is typically a lower security level than LocalServer, so the user may not have permission to access all of the information available to WMI. When the user application asks for dynamic information, WMI passes the user's SID to the corresponding providers. If the provider is written appropriately, it will attempt to access information with the user's SID, rather than its own. In this way, the provider can return only the information that the user is permitted to obtain. This process is called impersonation, because the provider is impersonating the client.

For impersonation to succeed, several conditions must be met.

The user application must call WMI with a DCOM connection security level of RPC_C_IMP_LEVEL_IMPERSONATE or RPC_C_IMP_LEVEL_DELEGATE.

The appropriate dynamic provider must be registered with WMI as an impersonation provider.

The impersonation provider must switch to the security level of the user application before accessing privileged information.

The provider must correctly handle error conditions if access to this information is denied.

Registering ProvidersRegistering Class and Instance Providers Class and instance providers register with WMI by creating an instance of the __Win32Provider class and an instance of either the __ClassProviderRegistration or __InstanceProviderRegistration class. The __Win32Provider instance describes the

WMI Provider Programming 12

Page 16: WMI Provider Programming - ITwelzel.bizgwise.itwelzel.biz/Microsoft/Windows 2000 Server... · Web viewWMI facilitates these communications by providing a common programming interface

provider's physical implementation, while the __ClassProviderRegistration and __InstanceProviderRegistration instances describe the provider's feature set.

Many of the properties of the __ClassProviderRegistration and __InstanceProviderRegistration classes are inherited from the superclass, __ObjectProviderRegistration. The __ObjectProviderRegistration class contains the InteractionType property to indicate whether the provider is a pull or push provider; several Boolean values for indicating support for particular features; and an array of strings to indicate query support. For example, an instance provider might use the following registration instances.

instance of __Win32Provider as $P{ Name="TestProv"; CLSID="{A41602A4-C038-11d1-AEB6-00C04FB68820}";};

instance of __InstanceProviderRegistration{ Provider = $P; SupportsGet = TRUE; SupportsEnumeration = TRUE; QuerySupportLevels = { "WQL:UnarySelect" };};

The class itself must be tagged with two standard qualifiers, Dynamic and Provider. The Dynamic qualifier signals to WMI that it should use a provider rather than WMI to retrieve the instances. The Provider qualifier specifies the name of the provider that WMI should use.

[ dynamic, provider("TestProv")]

class TestClass{ [key] string KeyVal; string StrVal1; sint32 IntVal1; sint32 IntVal2; sint32 IntArray2[];};

WMI requires all class providers to support at least Get and Enumerate methods. In classes that lack this support, provider registration will fail. WMI provides support for any operation that a provider is missing if at all possible.

Registering a Property Provider Property providers register with WMI by creating an instance of the __Win32Provider system class and an instance of the __PropertyProviderRegistration system class. The properties that are defined by __PropertyProviderRegistration include the object path to the provider and more information about the provider's implementation.

The following MOF statements supply examples of instances that can be used to register a property provider.

instance of __Win32Provider as $P { Name = "PropProvider" ; ClsId = "{E30EC6A0-23CF-11d1-8FDE-0000F804AA5C}" ;

WMI Provider Programming 13

Page 17: WMI Provider Programming - ITwelzel.bizgwise.itwelzel.biz/Microsoft/Windows 2000 Server... · Web viewWMI facilitates these communications by providing a common programming interface

};

instance of __PropertyProviderRegistration { Provider = $P; SupportsGet = TRUE; SupportsPut = FALSE; };

Note that the __Win32Provider instance accepts the default values for the other properties, such as the TRUE value for the Pure property.

Registering a Method Provider Method providers create an instance of the __MethodProviderRegistration system class. The only property of the ____MethodProviderRegistration class is the object path to the provider's __Win32Provider instance.

The following MOF statements supply examples of instances that can be used to register a method provider.

instance of __Win32Provider as $P { Name = "MethProvider" ; ClsId = "{E30EC6A0-23CF-11d1-8FDE-0000F804AA5C}" ; };

instance of __MethodProviderRegistration { Provider = $P; };

Registering an Event Provider Event providers register with WMI by creating an instance of the __Win32Provider system class and an instance of the __EventProviderRegistration system class. The properties that are local to the __EventProviderRegistration class are the object path to the provider and a list of queries describing the events that the provider supports.

For example, consider the following __EventProviderRegistration instance.

instance of __Win32Provider as $P{ ClientLoadableCLSID = NULL; CLSID = "{AA7828C5-95F9-11d2-BB0D-00C042424242}"; DefaultMachineName = NULL; ImpersonationLevel = 0; InitializationReentrancy = 0; InitializeAsAdminFirst = FALSE; Name = "FaxEventProvider"; PerLocaleInitialization = FALSE; PerUserInitialization = FALSE; Pure = TRUE; UnloadTimeout = NULL;};

instance of __EventProviderRegistration{ Provider = $P;EventQueryList = { "SELECT * FROM FaxEvent", "SELECT * FROM __InstanceCreationEvent where TargetInstance ISA \"Win32_LogicalDisk\""};};

The first query indicates that the provider generates all event notifications for the

WMI Provider Programming 14

Page 18: WMI Provider Programming - ITwelzel.bizgwise.itwelzel.biz/Microsoft/Windows 2000 Server... · Web viewWMI facilitates these communications by providing a common programming interface

extrinsic event class FaxEvent. Because it uses the ISA operator, the second query implies that the provider generates notifications for all instance creation events for the Win32_LogicalDisk class and all of its subclasses.

When a provider registers to provide an intrinsic event, the event must apply to all instances of a class. In other words, a query cannot be written to provide instance creation events for only some of the disk drives that belong to the Win32_LogicalDisk class.

Registering an Event Consumer Provider Place the .mof file into a permanent directory, typically the provider's installation directory.

Locate the following registry key: HKLM\SOFTWARE\Microsoft\WBEM. This key contains a REG_SZ value named "MOF Self-Install Directory."

Copy the .mof file into the directory named by the registry key value. Placing the .mof file into this directory ensures that it is compiled either right away (if WMI is currently running) or the next time that WMI is started.

Locate the following registry key: HKLM\SOFTWARE\Microsoft\WBEM\CIMOM. This key contains a REG_MULTI_SZ value named "Autorecover MOFs (recovered)" that contains a list of paths to various .mof files.

Add the full path to the permanent location of the .mof file to the end of this list. This ensures that the .mof file will be recompiled if a problem occurs.

For testing purposes, a registration .mof file can be immediately compiled using the MOF Compiler instead of the preceding steps.

During installation, some providers place their .mof files in a temporary location such as C:\Wbem\Mof before copying them to their permanent location. Do not include the path to this temporary location in the list of paths described in step 6. Because WMI deletes all temporary copies of .mof files after they have been compiled, always use the path to the permanent copy.

High-Performance API ProvidersThe Windows Management Instrumentation High-Performance (HiPerf) providers greatly increase the speed at which select WMI clients can obtain information from WMI. HiPerf providers require special registration and must support several of the High-Performance interfaces.

A High-Performance provider is actually an instance provider and it is registered in the same way.

High-Performance providers must be in-process servers; they are loaded in process to either WMI itself or to a client application. When loaded in process to WMI, these providers are instantiated from a CLSID. When loaded in process to another process, the providers are instantiated from a ClientLoadable CLSID. If different values are given for these two identifiers, a provider can easily tell if it is in process to WMI or to the client

WMI Provider Programming 15

Page 19: WMI Provider Programming - ITwelzel.bizgwise.itwelzel.biz/Microsoft/Windows 2000 Server... · Web viewWMI facilitates these communications by providing a common programming interface

application. If it is in process to WMI, the provider should do any necessary client impersonation by using CoImpersonateClient. If the provider is in process to a client, by default, the provider inherits the access token of the thread it is being called on.

In either case, WMI initializes the provider by using the IWbemProviderInit interface. All HiPerf providers must implement this interface. For more information, see IWbemProviderInit and Initializing A Provider.

The provider framework is a set of classes that can be used to create a Windows Management Instrumentation instance and/or method provider. The resulting provider is dynamic, supplying its instances on demand rather than storing them in the CIM repository. Providers created with the provider framework are modeled as pull providers.

Using the framework classes and the methods that they expose can cut development time significantly because they eliminate the need to become proficient with the COM. All of the communication with COM is handled by the provider framework. The provider framework is a layer between the providers and the CIM Object Manager.

Developers can create a provider with the framework by either manually writing code or taking advantage of an application wizard called the Provider Code Generator. The Provider Code Generator is included with the WMI CIM Studio application that ships with the WMI SDK. The Provider Code Generator produces several files that can be compiled and built after minor customization. The end result is an operational instance and method provider for one or more classes. The Provider Code Generator supplies stub implementations of all required functions and methods in American National Standards Institute (ANSI)-based C++ and handles provider registration. Classes defined by the Provider Code Generator that expose these implementations derive from classes defined by the provider framework. The provider framework defines several classes that bridge the gap between the framework provider and WMI.

Creating a framework provider with the Provider Code Generator is fast and easy. After selecting a class or classes to support, the Provider Code Generator requests the name and location for the output files and the name for the provider. With that information, the Provider Code Generator produces several output files that can be compiled and built to produce a working provider.

For a complete working example of a framework provider, see the CReindeerProv class in the WMI SDK \Samples\Vc\FrameworkProv folder.

Provider Code GeneratorThe Provider Code Generator is a wizard that is available in the Windows Management Instrumentation Common Information Model (CIM) Studio application included with the WMI SDK. The Provider Code Generator uses the functions of the provider framework to produce a customizable instance provider that can be fully functional with minimum effort on the developer's part. The provider framework frees developers from having to be knowledgeable about COM and allows them to focus on the features that are specific to their instance providers.

WMI Provider Programming 16

PROVIDER FRAMEWORK

Page 20: WMI Provider Programming - ITwelzel.bizgwise.itwelzel.biz/Microsoft/Windows 2000 Server... · Web viewWMI facilitates these communications by providing a common programming interface

The Provider Code Generator produces several files. There are C++ source and header files for each class supported by the new provider, a definition file, a MOF file that is used for registration, a makefile for building the provider, and a file that contains the entry points for the provider's DLL. These files make calls to the provider framework to handle registration, initialization, loading, and unloading.

The wizard produces the following files:

Provider Code Generator file Description

Maindll.cpp Contains code for the provider's DLL entry point and for initialization, registration, and shutdown.

<provider name>.def Standard definition file. No modification required.

<provider name>.mak Makefile for compiling and building the provider. The LIB and INCLUDE environment variables are set to the appropriate provider framework directories when the WMI SDK is installed.

<provider name>.mof Contains the instances required to register the provider with WMI. Requires modification if the provider should be registered in a namespace other than the current one or the provider does not support one of the standard features.

<base file name>.cpp Contains the provider's class implementation. Requires modification to customize the framework provider and support its specific features.

<base file name>.h Contains the provider's class definition. Requires modification if the class supports any private data or member functions.

Maindll FileThe Maindll.cpp file contains definitions of the globally unique identifier (GUID) and the class identifier (CLSID) for the framework provider DLL and implementations of the following standard functions.

Function Description

DllGetClassObject Called to create a new instance of the framework class CWbemGlueFactory.

DllCanUnloadNow Called periodically to determine whether the provider DLL can be unloaded.

DllRegisterServer Called to register the provider DLL as a COM server in the system registry.

DllUnregisterServer Called to remove registry entries for the provider DLL.

The Maindll.cpp file typically will not need to be changed. The framework provider may require additional registration or validation in the DllCanUnloadNow function.

WMI Provider Programming 17

Page 21: WMI Provider Programming - ITwelzel.bizgwise.itwelzel.biz/Microsoft/Windows 2000 Server... · Web viewWMI facilitates these communications by providing a common programming interface

Provider Code Generator Source and Header FilesFor each class supported by the framework provider, the Provider Code Generator generates one source (.cpp) file and an associated header (.h) file. The header file defines the class that the framework provider supports; a class that derives from the framework provider class. The framework provider class supplies default implementations of many of the synchronous IWbemServices methods and a set of helper functions. The framework provider's class definition is set up to support a standard constructor and destructor and the following methods:

DeleteInstance

EnumerateInstances

ExecMethod

ExecQuery

GetObject

PutInstance

The source file contains implementations of the methods defined in the header file. This file contains TO DO labels with comments to identify where to place customization code. Also included for each method is a standard comment block that lists the name of the method, a brief description, a description of the input parameters, the valid return values, and comments.

The developer usually implements the GetObject and EnumerateInstances methods, because they will not work as written. (The Provider Framework creates a set of code files that describe the provider in development. The set of files produced are only the stubs or framework necessary for the provider to work. After the provider framework creates the necessary files, the individual files need to be coded properly for the specific provider being developed. These are identified with the TO DO header in the code produced. GetObject and EnumerateInstances are methods that are created by the Provider Framework, but need to be filled in by the provider developer to work.)

The other methods are optional and may be deleted if unused. If the developer is writing a method-only provider for a static method, these two methods can be deleted as well.

Provider Code Generator MOF FileThe MOF file that is produced by the Provider Code Generator does not need to be changed, although it can be. The MOF file contains definitions of the three instances required for registration: __Win32Provider, __InstanceProviderRegistration, and __MethodProviderRegistration. Each of these instances have properties that are set to default values. Only the Name and Clsid properties of the __Win32Provider class are included in the MOF file. All of the other properties values are inherited.

The properties of the __InstanceProviderRegistration class specify whether various features are supported. The Provider Code Generator sets these properties as follows, specifying support for all possible instance provider operations:

instance of __InstanceProviderRegistration

WMI Provider Programming 18

Page 22: WMI Provider Programming - ITwelzel.bizgwise.itwelzel.biz/Microsoft/Windows 2000 Server... · Web viewWMI facilitates these communications by providing a common programming interface

{ Provider = $P; SupportsGet = TRUE; SupportsPut = TRUE; SupportsDelete = TRUE; SupportsEnumeration = TRUE; QuerySupportLevels = {"WQL:UnarySelect"};};

The WQL:UnarySelect value for the QuerySupportLevels property indicates that the provider supports query processing with the WQL SELECT statement only. WMI translates WQL statements such as ASSOCIATORS OF and REFERENCES OF into SELECT statements.

If the framework provider will not be supporting a particular feature, the MOF file should be modified. For example, if the provider does not support deleting instances, it should set SupportsDelete to FALSE. If WMI handles queries for the provider, QuerySupportLevels should be set to NULL. If you are not supporting the feature, delete it from the .mof, .h and .cpp files.

Compiling a Framework ProviderA framework provider created by the Provider Code Generator can be compiled using the .mak file that is automatically produced.

When building providers to work with the framework, see the .mak file in the FrameworkProv folder in the VC samples folder of the WMI SDK. In addition:

You must link with Msvcrt.lib (or Msvcrtd.lib for Debug builds). Ensure this by setting the /MD compiler switch. Failure to do this will result in either undefined symbols at link time, or stack and heap corruption at run time. In other words, you must never link with Libc.lib or Libcmt.lib.

For debug builds, compile as a multithreaded .dll debug configuration, and link with Framedyd.lib.

For release builds, compile as a multithreaded .dll configuration, and link with Framedyn.lib. Because release and debug memory allocators are different, never use Framedyd.lib in a release build or Framedyn.lib in a debug build.

Failure to link with Msvcrt.lib and Framedyd.lib (or Msvcrtd.lib and Framedyd.lib) will result in either undefined symbols at link time, or stack corruption at run time.

Error Handling for Framework ProvidersFramework providers that call a provider framework method should return the error or status code that the method returns unless the provider can supply more detailed information. For example, if a call to CWbemProviderGlue::GetAllInstances returns WBEM_E_OUT_OF_MEMORY, the framework provider should return WBEM_E_OUT_OF_MEMORY.

Typically, when checking for errors, framework providers should use the Succeeded and Failed macros, rather than testing for specific error codes. Providers should test for specific error codes only if they can remedy the situation in some way. For example, if a

WMI Provider Programming 19

Page 23: WMI Provider Programming - ITwelzel.bizgwise.itwelzel.biz/Microsoft/Windows 2000 Server... · Web viewWMI facilitates these communications by providing a common programming interface

provider is able to free memory, it is worth writing code to check for WBEM_E_OUT_OF_MEMORY.

As a general rule, the framework itself only throws on catastrophic errors, for example, out of memory errors or general protection faults. Well-designed providers should handle the possibility of thrown exceptions. The WMI SDK provides further details on specific methods of handling the framework exceptions.

Upgrading Framework ProvidersBackward compatibility is not supported when upgrading from WMI versions 1.1 or 1.2 to WMI version 1.5 or higher. Some of the changes will have no effect upon legacy code. Other changes will require changes in existing code. This document is provided to help you make a smooth and successful upgrade.

The following changes have been made to the framework provider. For more details on upgrading the framework providers, refer to the corresponding section in the WMI SDK documentation.

CHString ChangesCHString is now based upon Unicode rather than ANSI strings. This creates some incompatibilities with ANSI systems, most of which you will discover when you recompile your code. When passing a CHString to a function that requires an ANSI string parameter, you need to explicitly convert to an ANSI string. CHString has no LPCSTR cast. A related incompatibility arises when you use any function of the printf or scanf families, or CHString format. This incompatibility will not be apparent when you recompile your code. Consider the following code:

CHString str = "example1";printf("%s\m", str);

Though the preceding code compiles without error or warning, if you are running on an ANSI system it does not generate the correct output (it generates a one-character string). Now consider the following code that fixes this problem:

CHString str = "example1";#ifdef _UNICODE printf("%s\n", (LPCWSTR) str);#else printf("%S\n", (LPCWSTR) str);#endif

By compiling printf with a format string ("%S" or "%s") that is appropriate to your system you will get the expected output.

TSTR and WSTR ChangesMany methods now take WSTR parameters instead of TSTR or CHString parameters.

These incompatibilities become apparent when you recompile your code. The following code passes a string constant to the function:

PInstance->SetCharSplat ("example1", "EXAMPLE2");

Because "example1" is an ANSI string and a WSTR string is required by the function, you must change the call so that "example1" is passed as a WSTR string, as shown in

WMI Provider Programming 20

Page 24: WMI Provider Programming - ITwelzel.bizgwise.itwelzel.biz/Microsoft/Windows 2000 Server... · Web viewWMI facilitates these communications by providing a common programming interface

the following code:

PInstance->SetCharSplat (L"example1", "EXAMPLE2");

Consider the following code, which also is incompatible with the new function prototype:

LPCTSTR str = "example1";PInstance->SetCharSplat (str, "EXAMPLE2");

This will work when compiling for UNICODE, but will fail to compile when compiling for ANSI.

Exception Handling ChangesException handling is now enabled for the framework. Several classes now throw exceptions.

Generally speaking, the framework only throws errors on catastrophic errors, for example, out of memory or general protection faults.

You now need to make sure that if you have created instances, you also dispose of those instances when an exception is thrown. Failure to do so will result in memory leaks.

Impersonation ChangesThe framework now impersonates the connected user before making a call to the provider.

When a provider is called, it may run as an administrator with full rights or as a user with limited rights. When a service is requested (for example, deleting a file), you must ensure:

The present client has rights to that service. The request was performed successfully. Failures due to insufficient rights are caught and handled correctly.

Impersonation also raises the question of what to do if you are enumerating instances, and you are able to populate some properties but not others. In general, if you can get enough information to populate the key properties you should return the instance along with WBEM_S_PARTIAL_RESULTS.

Note that when using GetObject, returning WBEM_E_ACCESS_DENIED indicates to the client that the requested object exists. For security reasons, you may not want the client to have this information.

GetObject ChangesPreviously, GetObject was a macro in Windows.h resolving to GetObjectW or GetObjectA, depending on the UNICODE context. The framework has its own GetObject method that cannot be written as a macro. Therefore, in Fwcommon.h, the definition of GetObject has been removed (#undef GetObject). If you need the actual Win32 GetObject method, you must call GetObjectA or GetObjectW directly.

Deprecated Function ChangesA number of methods have been deprecated. One version of CWbemProviderGlue::GetEmptyInstance, all versions of

WMI Provider Programming 21

Page 25: WMI Provider Programming - ITwelzel.bizgwise.itwelzel.biz/Microsoft/Windows 2000 Server... · Web viewWMI facilitates these communications by providing a common programming interface

CWbemProviderGlue::FillInstance and several methods in the WBEMTime class have been deprecated. See Wbemtime.h for specifics. To find these methods, either check the comments in the appropriate header, or recompile and run your program using the Debug version of FrameDyd. When a deprecated function is called, you will receive an Assert.

WBEMTime and WBEMTimeSpan Changes

Both the WBEMTime class and the WBEMTimeSpan class have changed. These changes are not expected to affect existing code. If you are performing date or time arithmetic, the changes made to these methods may affect your code.For details, see Provider Framework Utility Class, in the WMI SDK. If you are not performing date or time arithmetic, these changes do not affect your code.

Calling Convention ChangesSeveral methods that previously did not have a calling convention are now specified as WINAPI. Recompiling your code fixes discrepancies.

Based on industry standards and using a datacentric approach, WMI provides a single point of access for manipulating disparate management information in a managed environment. The WMI extensible provider architecture can be used by developers as a basis for building vendor-specific management solutions for network, systems, devices, databases, and applications.

For the latest information on the Windows 2000 Server management infrastructure, check out the Microsoft Web site and the Windows 2000 Server Forum on the Microsoft Network (GO WORD: MSNTS).

For more information on Windows Management Instrumentation (WMI), check out the Microsoft Developer Network (MSDN). Also, check out the WMI SDK in the MSDN Platform SDK for more developer specific information.

For more information on the WBEM initiative and for information about the efforts of the DMTF, see the DMTF Web site.

WMI Provider Programming 22

CONCLUSIONFOR MORE INFORMATION