1 Introduction
A plug-in is a shared library which provides a specific service in the server. Examples of services provided by plug-ins include access control, client monitoring and file system access. In general, plug-ins may be used to extend or customize server functionality. This document provides guidelines on how to design and implement a server plug-in.2 Plug-in Basics
In a standard server installation, all plug-ins are stored in the "Plugins" directory under the Helix Server install root. However, this plug-in storage location is configurable. During initialization, the server's core modules scan this directory and perform the following operations for each installed plug-in:
- Immediately after the plug-in library is loaded, the plug-in's entry point function, HXCreateInstance, is invoked.
- Next, the plug-in's GetPluginInfo() method is executed to obtain the plug-in's attributes.
- Finally, the plug-in's initialization function, InitPlugin(), is invoked.
Once the plug-in is loaded and initialized, it is able to receive requests from the server core to perform specific operations. The type of operations performed depends entirely on the interfaces implemented by the plug-in. At a minimum, every plug-in must implement the IHXPlugin interface. This interface provides the basic hooks required to enable communication between the plug-in and the server core. Plug-ins usually implement at least one other interface in addition to IHXPlugin.
The following sections describe the plug-in initialization steps in detail and provide examples on how to implement each of the required interface methods.
2.1 Defining the Plug-in Entry-point Function
We'll use a simple concrete example to illustrate the basic elements of a plug-in. For this example, we'll create a plug-in that outputs "Hello World" to the server's error log file (error.log). To start with, we'll implement the entry point function HXCreatInstance(). Below is a code segment from the plug-in's source file which defines this function:
#define INITGUID 1 //1 #include "hxcom.h" #include "hxtypes.h" //Defines standard helix type definitions #include "hxassert.h" //Defines helix assert macros #include "hxresult.h" //Defines helix return codes #include "hxplugn.h" //Defines the IHXPlugin interface #include "hxerror.h" //Defines the IHXErrorMessages interface #include "hxver.h" //Defines helix version information #include "simpleplugin.h" STDAPI ENTRYPOINT(HXCreateInstance)(IUnknown** ppPlugin) //2 { *ppPlugin = (IUnknown*)(IHXPlugin*) new SimplePlugin(); if (*ppPlugin != NULL) { (*ppPlugin)->AddRef(); //3 return HXR_OK; //4 } return HXR_OUTOFMEMORY; } STDAPI ENTRYPOINT(HXShutdown)(void) //5 { // No cleanup required. return HXR_OK; }The annotated source lines in the code segment above are explained below:
//1 The INITGUID #define is required in all server plug-ins to ensure that all interface GUIDs are defined in the plug-in library.
//2 HXCreateInstance() is the plug-in's entry point function. This function is invoked by the server core just after the plug-in library is loaded. Note that the code returns a pointer to the IHXPlugin interface which is used by the core for subsequent plug-in operations.
//3 The AddRef() function is used to increment the plug-in's reference counter (we'll discuss this in greater detail later). Note that a plug-in must increment it's reference counter anytime it returns an interface pointer.
//4 HXR_OK is the standard return code used to indicate success.
//5 HXShutdown() is the last function invoked just before the plug-in unloaded. This function should be used to complete any required cleanup and release any global resources held by the plug-in. Generally, the server core never unloads any plug-ins that are loaded on application startup.
2.2 Defining Plug-in Attributes
Once the plug-in library is loaded, the server core uses the IHXPlugin::GetPluginInfo() method to retrieve the plug-in's attributes. Following is the implementation of this function in our SimplePlugin example:
STDMETHODIMP SimplePlugin::GetPluginInfo(REF(BOOL) bLoadMultiple, REF(const char*) pszDescription, REF(const char*) pszCopyright, REF(const char*) pszMoreInfoURL, REF(ULONG32) ulVersionNumber) { bLoadMultiple = FALSE; //1 pszDescription = "Simple Plugin"; //2 pszCopyright = HXVER_COPYRIGHT; pszMoreInfoURL = HXVER_MOREINFO; ulVersionNumber = 1; return HXR_OK; }The annotated source lines in the code segment above are explained below:
1// The bLoadMultiple variable is used to indicate whether this is a multiload or non-multiload plug-in. The server core creates a separate process/thread for each non-multiload plug-in. In addition to this, only a single plug-in instance is created for non-multiload plug-ins. Multiload plug-ins are created in the streamer's address space and, as the name suggests, the plug-in may be instantiated multiple times. (See the server architecture document for a detailed description of the streamer process ). In this example, the plug-in is created as a non-multiload plug-in.
2// The pszDescription variable defines a string which provides descriptive information about a plug-in. This is displayed on the server console and output to the error log during application startup.
2.3 Exporting Plug-in Interfaces
After loading a plug-in and obtaining its attributes, the server core then tries to determine the plug-in type using the IUnknown::QueryInterface() method. This method defines all interfaces that are exported or implemented by a plug-in. Plug-in's may be classified into one of five categories based on the type of interface implemented:
- Filesystem plug-ins implement the IHXFileSystemObject interface.
- Datatype (a.k.a file format) plug-ins implement the IHXFileFormatObject interface.
- Allowance plug-ins implement the IHXPlayerConnectionAdviseSink interface.
- Live broadcast plug-ins implement the IHXBroadcastFormatObject interface.
- All other plug-ins are classified as generic plug-ins.
Following is a code segment with an implementation of the QueryInterface() method for our SimplePlugin example:
STDMETHODIMP SimplePlugin::QueryInterface(REFIID riid, void** ppvInterface) { if (IsEqualIID(riid, IID_IUnknown)) { AddRef(); *ppvInterface = (IUnknown*)this; return HXR_OK; } else if (IsEqualIID(riid, IID_IHXPlugin)) { AddRef(); *ppvInterface = (IHXPlugin*)this; //1 return HXR_OK; } *ppvInterface = NULL; return HXR_NOINTERFACE; //2 }The annotated source lines in the code segment above are explained below:
//1 Our SimplePlugin exports the IHXPlugin interface and implicitly exports the IUnknown interface as well, since every interface inherits from IUnknown. Note that the plug-in's reference counter is incremented using the AddRef() method each time an interface pointer is returned.
//2 HXR_NOINTERFACE is the standard return code used when a callee requests an interface that is not implemented by a plug-in.
2.4 Plug-in Initialization
Plug-in initialization logic is always implemented in the IHXPlugin::InitPlugin() function. In non-multiload plug-ins, the InitPlugin() method is invoked immediately after the plug-in library is loaded during server initialization. Execution of this method is delayed in multiload plug-ins. In this case, the initialization function is invoked only when an instance of the plug-in is created to service a particular request. However, multiload plug-ins can force the server core to invoke the InitPlugin() method immediately after the plug-in is loaded by implementing the IXHGenericPlugin interface and setting the bIsGeneric flag to "TRUE".
During initialization, plug-ins will usually save a pointer to the server context object (passed as argument in the InitPlugin() function). Plug-ins rely on the server context to obtain interface pointers to objects that implement core application services such as the server registry and network I/O. The following code segment provides an implementation of InitPlugin() for our SimplePlugin example:
STDMETHODIMP SimplePlugin::InitPlugin(IUnknown* pContext) { HX_RESULT rc = HXR_OK; HX_ASSERT(pContext); m_pContext = pContext; m_pContext->AddRef(); //1 IHXErrorMessages* pErrorLogger = NULL; rc = m_pContext->QueryInterface(IID_IHXErrorMessages, (void**)&pErrorLogger); //2 if (FAILED(rc)) { return rc; } pErrorLogger->Report(HXLOG_ERR, rc, 0, "Hello World", NULL); //3 HX_RELEASE(pErrorLogger); //4 return rc; }The annotated source lines in the code segment above are explained below:
//1 The plug-in stores a reference to the server context and increments the object's reference counter.
//2 The plug-in QI's the server context to obtain a reference to the error logging interface. Note that the plug-in does not explicitly increment the pErrorLogger reference counter since this is done implicitly by the QueryInterface() method.
//3 The plug-in uses the error logging interface to output "Hello World" to the server's error log file (error.log).
//4 Once the plug-in is done with the error logging interface, it decrements the object's reference counter using the HX_RELEASE macro.
2.5 Maintaining Plug-in Reference Counters
Every plug-in must implement the IUnknown::AddRef() and IUnknown::Release() methods to keep track of the number of clients using the plug-in. The AddRef() function increments the plug-in's reference counter by one each time a pointer to an interface implemented by the plug-in is requested. The Release() method is used to decrement the reference counter when the interface is no longer in use. When the reference counter is decremented to 0, the plug-in object is deleted. Below is a code segment including a standard implementation of the AddRef() and Release() methods for our SimplePlugin example. Virtually all plug-ins implement these methods the same way.
STDMETHODIMP_(ULONG32) SimplePlugin::AddRef() { return InterlockedIncrement(&m_ulRefCount); //1 } STDMETHODIMP_(ULONG32) SimplePlugin::Release() { if (InterlockedDecrement(&m_ulRefCount) > 0) //1 { return m_ulRefCount; } delete this; return 0; }Note:
//1 The InterlockedIncrement() and InterlockedDecrement() functions ensure that the reference counters is incremented (or decremented) atomically.
2.6 Plug-in Object Constructor and Destructor
Now that we've covered all methods associated with interfaces implemented by our simple plug-in, we can move on to the last two methods required to complete this plug-in -- the plug-in object's constructor and destructor. The code segment below provides a sample implementation of these methods for the SimplePlugin class:
SimplePlugin::SimplePlugin() : m_ulRefCount(0) //Reference counter-- an unsigned integer(UINT32) ,m_pContext(NULL) //Server context-- stored as an IUnknown* { } SimplePlugin::~SimplePlugin() { HX_RELEASE(m_pContext); //All references held by an object must be //released when the object is destroyed. //This is typically done using the HX_RELEASE //macro. }
2.7 Tying It All Together
Finally, we have all the pieces required to build a complete server plug-in! If you have installed and built the helix server source successfully, you can build the plug-in example described in this document and install it on your server. To get detailed information on how to use the helix build system, please review the ribosome documentation available at http://ribosome.helixcommunity.org/2002/devdocs. A high-level description of the steps required to build the SimplePlugin on Unix-based platforms is provided below:
- Create a directory under your helix server source root (e.g. <SRC_ROOT>/server/simpleplugin).
- Copy the sample code segments provided above into a source file (e.g. simpleplugin.cpp).
- Create the plug-in's header file (e.g. simpleplugin.h). A sample header file is provided in Appendix A of this document.
- Create a Umakefil and setup your build environment as described in the ribosome document. A sample Umakefil is provided in Appendix B of this document.
- On Windows, some additional libraries are needed. Create a file called win32.pcf in your simpleplugin directory, and copy and paste the following code into it. PCF files contain information used by Umake to customize builds for specific platforms.
project.AddSystemLibraries("version.lib", "wsock32.lib", "kernel32.lib", "user32.lib", "advapi32.lib")
- To build the plug-in, run 'umake -t debug' then 'make' (On Windows, it might be 'nmake').
- Copy the shared library from the "dbg" directory into the server's "Plugins" directory, and start the server.
3 Plug-in Design Considerations
- Server plug-ins should be designed to support an asynchronous execution model since the server performs many operations asynchronously. No assumptions should be made about the order in which plug-in functions will be invoked.
- Whenever possible, plug-ins should create dynamic strings using either IHXBuffer objects or the NEW_FAST_TEMP_STR macro.
- Use the common class factory (IHXCommonClassFactory) to create helix objects. The following code segment illustrates how to create an IHXBuffer object using the common class factory:
IHXBuffer* pMyBuffer = NULL; pMyClassFactory->CreateInstance(CLSID_IHXBuffer, (void**)&pMyBuffer);
Plug-ins may obtain a reference to an object implementing the IHXCommonClassFactory interface via the server context. For example:IHXCommonClassFactory* pMyClassFactory = NULL; pServerContext->QueryInterface(IID_IHXCommonClassFactory, (void**)&pMyClassFactory);
- Allowance plug-ins can significantly affect server performance because a new instance of the plug-in is created for each client connection handled by the server. Use of allowance plug-ins should therefore be limited. When used, it is highly recommended that developers design allowance plug-ins to run as multiload plug-ins.
4 Real-World Plug-in Examples
The example presented in this document contains all the essential elements of a plug-in. However, it is highly simplified and provides no useful functionality. The following plug-ins included in the helix server source distribution may provide more realistic examples:
- FileSystem plug-in: adminfs in <helix_source_root>/server/fs/adminfs
- Allowance plug-in: svrbascauth in <helix_source_root>/server/access/auth/bascauth
- Broadcast plug-in: qtbcplin in <helix_source_root>/server/transport/rtp/recv
Appendix A: Sample Header File
#ifndef _SIMPLEPLUGIN_H_ #define _SIMPLEPLUGIN_H_ class SimplePlugin : public IHXPlugin { public: SimplePlugin(); virtual ~SimplePlugin(); /* * IUnknown methods */ STDMETHOD(QueryInterface) (THIS_ REFIID riid, void** ppvObj); STDMETHOD_(ULONG32,AddRef) (THIS); STDMETHOD_(ULONG32,Release) (THIS); /* * IHXPlugin methods */ STDMETHOD(InitPlugin) (THIS_ IUnknown* pContext); STDMETHOD(GetPluginInfo) (THIS_ REF(BOOL) bLoadMultiple, REF(const char*) pszDescription, REF(const char*) pszCopyright, REF(const char*) pszMoreInfoURL, REF(ULONG32) ulVersionNumber); private: ULONG32 m_ulRefCount; IUnknown* m_pContext; }; #endif // ndef _SIMPLEPLUGIN_H_
Appendix B: Sample Plug-in Umakefil
UmakefileVersion(2,0) CPPSuffixRule() project.AddModuleIncludes( 'common/include' ,'common/runtime/pub' ,'common/dbgtool/pub' ) project.AddModuleLibraries( "common/dbgtool[debuglib]" ,"common/container[contlib]" ) project.AddSources('simpleplugin.cpp') project.AddExportedFunctions('RMACreateInstance', 'RMAShutdown') SetupDefines() DLLTarget('simpleplugin') DependTarget()