Udostępnij za pośrednictwem


How to Create a Group

Applies To: Operations Manager 2007 R2, Operations Manager 2007 SP1, System Center Operations Manager 2007

In Operations Manager 2007, groups are logical collections of objects, such as Windows-based computers, hard disks, or instances of Microsoft SQL Server. Groups are used to delegate authority, scope access to specific areas of the Operations Console, and override the default settings of Management Packs.

To create a group, you need to specify a name for the group and the Management Pack that the group will be added to. Next, you specify the type of objects (such as Windows computers) to add to the group. Then you specify the configuration for the group's data source, which dynamically discovers objects to include in the group based on specified criteria.

The following code example creates a group of SQL Server 2005 databases. In the CreateDiscoveryConfiguration method in the code example, the criteria that specifies which objects will be in the group is created. This example specifies that all instances of objects with a Monitoring Class equal to Microsoft.SQLServer.2005.Database will be included in the group.

using Microsoft.EnterpriseManagement;
using Microsoft.EnterpriseManagement.Common;
using Microsoft.EnterpriseManagement.Configuration;
using Microsoft.EnterpriseManagement.Monitoring;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Text;
using System.Xml;

namespace SDKSamples
{
    class Program
    {
        static void Main(string[] args)
        {
            ManagementGroup mg;

            mg = new ManagementGroup("localhost");

            try
            {
                CreateGroup(mg);
                Console.WriteLine("Successfully created the group.");
            }
            catch (MonitoringException error)
            {
                Console.WriteLine("Error: " + error.Message);
            }
        }

        // ---------------------------------------------------------------------
        private static void CreateGroup(ManagementGroup mg)
        {
            ManagementPackClass groupClass;
            ManagementPackDiscovery groupDiscovery;
            ManagementPack testManagementPack;
            MonitoringRelationshipClass relationshipClass;
            ManagementPackDiscoveryRelationship discoveryRelationship;

            testManagementPack = mg.GetManagementPacks("Test.Management.Pack")[0];

            groupClass = new ManagementPackClass(testManagementPack,
                "Samples.GroupsSample.AllDatabasesGroup",
                ManagementPackAccessibility.Public);
            groupClass.Singleton = true;
            groupClass.Base = mg.GetMonitoringClass(SystemMonitoringClass.InstanceGroup);
            groupClass.DisplayName = "SampleGroup";

            groupDiscovery = new ManagementPackDiscovery(testManagementPack,
                "Samples.GroupsSample.AllDatabasesGroup.Discovery");
            groupDiscovery.Remotable = true;

            discoveryRelationship = new ManagementPackDiscoveryRelationship();

            relationshipClass = mg.GetMonitoringRelationshipClass(
                SystemMonitoringRelationshipClass.InstanceGroupContainsEntities);

            discoveryRelationship.TypeID = relationshipClass;

            groupDiscovery.DiscoveryRelationshipCollection.Add(discoveryRelationship);
            groupDiscovery.Target = groupClass;
            
            groupDiscovery.DataSource = new ManagementPackDataSourceModule(
                groupDiscovery, "GroupPopulationDataSource");
            groupDiscovery.DataSource.TypeID = 
                (ManagementPackDataSourceModuleType)mg.GetMonitoringModuleTypes(
                "Microsoft.SystemCenter.GroupPopulator")[0];
            groupDiscovery.DataSource.Configuration = CreateDiscoveryConfiguration(mg,
                testManagementPack,
                groupClass.Name,
                "Microsoft.SQLServer.2005.Database");

            testManagementPack.AcceptChanges();

        }

        // ---------------------------------------------------------------------
        private static string CreateDiscoveryConfiguration(
            ManagementGroup mg,
            ManagementPack groupMp,
            string groupTypeName,
            string className
            )
        {
            /*
            Here is the XML document that is being created in this function. 
            <RuleId>$MPElement$</RuleId>
            <GroupInstanceId>$MPElement[Name="Samples.GroupsSample.AllDatabasesGroup"]$</GroupInstanceId>
            <MembershipRules>
                <MembershipRule>
                    <MonitoringClass>$MPElement[Name="MicrosoftSQLServer2005Discovery6050000!Microsoft.SQLServer.2005.Database"]$</MonitoringClass>
                    <RelationshipClass>$MPElement[Name="MicrosoftSystemCenterInstanceGroupLibrary6050000!Microsoft.SystemCenter.InstanceGroupContainsEntities"]$</RelationshipClass>
                </MembershipRule>
            </MembershipRules>
            */

            XmlDocument document = new XmlDocument();
            XmlElement rootElement = document.CreateElement("Configuration");
            XmlElement ruleIdElement;
            XmlElement groupInstanceElement;
            XmlElement membershipRulesElement;
            XmlElement membershipRuleElement;
            XmlElement membershipClassElement;
            XmlElement membershipRelationshipElement;

            document.AppendChild(rootElement);

            ruleIdElement = document.CreateElement("RuleId");
            membershipRulesElement = document.CreateElement("MembershipRules");
            membershipRuleElement = document.CreateElement("MembershipRule");
            membershipClassElement = document.CreateElement("MonitoringClass");
            membershipRelationshipElement = document.CreateElement("RelationshipClass");
            groupInstanceElement = document.CreateElement("GroupInstanceId");

            ruleIdElement.InnerText = "$MPElement$";
            groupInstanceElement.InnerText = string.Format(@"$MPElement[Name=""{0}""]$", groupTypeName);
            membershipClassElement.InnerText = GetClassReference(mg, groupMp, className);
            membershipRelationshipElement.InnerText = GetMPElementReference(mg,
                groupMp,
                mg.GetMonitoringRelationshipClass(SystemMonitoringRelationshipClass.InstanceGroupContainsEntities));

            rootElement.AppendChild(ruleIdElement);
            rootElement.AppendChild(groupInstanceElement);
            rootElement.AppendChild(membershipRulesElement);
            membershipRulesElement.AppendChild(membershipRuleElement);
            membershipRuleElement.AppendChild(membershipClassElement);
            membershipRuleElement.AppendChild(membershipRelationshipElement);

            return (rootElement.InnerXml);
        }

        // ---------------------------------------------------------------------
        private static string GetMPElementReference(
            ManagementGroup mg,
            ManagementPack groupMp,
            ManagementPackElement element
            )
        {
            string formatString = @"$MPElement[Name=""{0}!{1}""]$";
            string mpAlias = string.Empty;

            mpAlias = GetMPAlias(groupMp, element);

            return (string.Format(formatString, mpAlias, element.Name));
        }

        // ---------------------------------------------------------------------
        private static string GetClassReference(
            ManagementGroup mg,
            ManagementPack groupMp,
            string className
            )
        {
            ReadOnlyCollection<MonitoringClass> monitoringClasses;

            monitoringClasses = mg.GetMonitoringClasses(className);

            if (monitoringClasses.Count == 0)
            {
                throw new ApplicationException("The specified class was not found");
            }

            if (monitoringClasses.Count > 1)
            {
                throw new ApplicationException("Multiple classes with the specified name were found");
            }

            return (GetMPElementReference(mg, groupMp, monitoringClasses[0]));
        }

        // ---------------------------------------------------------------------
        private static string GetMPAlias(
            ManagementPack groupMp,
            ManagementPackElement element
            )
        {
            ManagementPack elementMp = element.GetManagementPack();
            string mpAlias = string.Empty;
            bool addRefRequired = true;

            if (elementMp.Id == groupMp.Id)
            {
                // The type is defined in the same MP as the new override MP.
                // No need to add a dependency.
                addRefRequired = false;
                return (string.Empty);
            }

            foreach (KeyValuePair<string, ManagementPackReference> existingMPRef in groupMp.References)
            {
                if (existingMPRef.Value.KeyToken == elementMp.KeyToken &&
                    existingMPRef.Value.Version == elementMp.Version &&
                    existingMPRef.Value.Name == elementMp.Name)
                {
                    addRefRequired = false;
                    mpAlias = existingMPRef.Key;
                }
            }

            if (addRefRequired)
            {
                ManagementPackReference mpRef = new ManagementPackReference(elementMp);

                mpAlias = elementMp.Name + elementMp.Version.ToString();
                mpAlias = mpAlias.Replace(".", "");

                groupMp.References.Add(mpAlias, mpRef);
            }

            return (mpAlias);
        }
    }
}
Imports Microsoft.EnterpriseManagement
Imports Microsoft.EnterpriseManagement.Common
Imports Microsoft.EnterpriseManagement.Configuration
Imports Microsoft.EnterpriseManagement.Monitoring
Imports System
Imports System.Collections.Generic
Imports System.Collections.ObjectModel
Imports System.Text
Imports System.Xml

Namespace SDKSamples
    Class Program

        Public Overloads Shared Function Main(ByVal args() As String) As Integer
            Dim mg As ManagementGroup

            mg = New ManagementGroup("localhost")

            Try
                CreateGroup(mg)
                Console.WriteLine("Successfully created the group.")
            Catch e As MonitoringException
                Console.WriteLine("Error: " & e.Message)
            End Try
        End Function 'Main


        ' ---------------------------------------------------------------------
        Private Shared Sub CreateGroup(ByVal mg As ManagementGroup)
            Dim groupClass As ManagementPackClass
            Dim groupDiscovery As ManagementPackDiscovery
            Dim testManagementPack As ManagementPack
            Dim relationshipClass As MonitoringRelationshipClass
            Dim discoveryRelationship As ManagementPackDiscoveryRelationship

            testManagementPack = mg.GetManagementPacks("Test.Management.Pack")(0)

            groupClass = New ManagementPackClass(testManagementPack, "Samples.GroupsSample.AllDatabasesGroup", ManagementPackAccessibility.Public)
            groupClass.Singleton = True
            groupClass.Base = mg.GetMonitoringClass(SystemMonitoringClass.InstanceGroup)
            groupClass.DisplayName = "SampleGroup"

            groupDiscovery = New ManagementPackDiscovery(testManagementPack, "Samples.GroupsSample.AllDatabasesGroup.Discovery")
            groupDiscovery.Remotable = True

            discoveryRelationship = New ManagementPackDiscoveryRelationship()

            relationshipClass = mg.GetMonitoringRelationshipClass(SystemMonitoringRelationshipClass.InstanceGroupContainsEntities)

            discoveryRelationship.TypeID = relationshipClass

            groupDiscovery.DiscoveryRelationshipCollection.Add(discoveryRelationship)
            groupDiscovery.Target = groupClass

            groupDiscovery.DataSource = New ManagementPackDataSourceModule(groupDiscovery, "GroupPopulationDataSource")
            groupDiscovery.DataSource.TypeID = CType(mg.GetMonitoringModuleTypes("Microsoft.SystemCenter.GroupPopulator")(0), ManagementPackDataSourceModuleType)
            groupDiscovery.DataSource.Configuration = CreateDiscoveryConfiguration(mg, testManagementPack, groupClass.Name, "Microsoft.SQLServer.2005.Database")

            testManagementPack.AcceptChanges()
        End Sub 'CreateGroup


        ' ---------------------------------------------------------------------
        Private Shared Function CreateDiscoveryConfiguration(ByVal mg As ManagementGroup, ByVal groupMp As ManagementPack, ByVal groupTypeName As String, ByVal className As String) As String
            '
            ' Here is the XML document that is being created in this function. 
            ' <RuleId>$MPElement$</RuleId>
            ' <GroupInstanceId>$MPElement[Name="Samples.GroupsSample.AllDatabasesGroup"]$</GroupInstanceId>
            ' <MembershipRules>
            '    <MembershipRule>
            '       <MonitoringClass>$MPElement[Name="MicrosoftSQLServer2005Discovery6050000!Microsoft.SQLServer.2005.Database"]$</MonitoringClass>
            '          <RelationshipClass>$MPElement[Name="MicrosoftSystemCenterInstanceGroupLibrary6050000!Microsoft.SystemCenter.InstanceGroupContainsEntities"]$</RelationshipClass>
            '    </MembershipRule>
            ' </MembershipRules>
            '

            Dim document As New XmlDocument()
            Dim rootElement As XmlElement = document.CreateElement("Configuration")
            Dim ruleIdElement As XmlElement
            Dim groupInstanceElement As XmlElement
            Dim membershipRulesElement As XmlElement
            Dim membershipRuleElement As XmlElement
            Dim membershipClassElement As XmlElement
            Dim membershipRelationshipElement As XmlElement

            document.AppendChild(rootElement)

            ruleIdElement = document.CreateElement("RuleId")
            membershipRulesElement = document.CreateElement("MembershipRules")
            membershipRuleElement = document.CreateElement("MembershipRule")
            membershipClassElement = document.CreateElement("MonitoringClass")
            membershipRelationshipElement = document.CreateElement("RelationshipClass")
            groupInstanceElement = document.CreateElement("GroupInstanceId")

            ruleIdElement.InnerText = "$MPElement$"
            groupInstanceElement.InnerText = String.Format("$MPElement[Name=""{0}""]$", groupTypeName)

            membershipClassElement.InnerText = GetClassReference(mg, groupMp, className)
            membershipRelationshipElement.InnerText = GetMPElementReference(mg, groupMp, mg.GetMonitoringRelationshipClass(SystemMonitoringRelationshipClass.InstanceGroupContainsEntities))

            rootElement.AppendChild(ruleIdElement)
            rootElement.AppendChild(groupInstanceElement)
            rootElement.AppendChild(membershipRulesElement)
            membershipRulesElement.AppendChild(membershipRuleElement)
            membershipRuleElement.AppendChild(membershipClassElement)
            membershipRuleElement.AppendChild(membershipRelationshipElement)

            Return rootElement.InnerXml
      End Function 'CreateDiscoveryConfiguration


        ' ---------------------------------------------------------------------
        Private Shared Function GetMPElementReference(ByVal mg As ManagementGroup, ByVal groupMp As ManagementPack, ByVal element As ManagementPackElement) As String
            Dim formatString As String = "$MPElement[Name=""{0}!{1}""]$"
            Dim mpAlias As String = String.Empty

            mpAlias = GetMPAlias(groupMp, element)

            Return String.Format(formatString, mpAlias, element.Name)
        End Function 'GetMPElementReference


        ' ---------------------------------------------------------------------
        Private Shared Function GetClassReference(ByVal mg As ManagementGroup, ByVal groupMp As ManagementPack, ByVal className As String) As String

            Dim monitoringClasses As ReadOnlyCollection(Of MonitoringClass)

            monitoringClasses = mg.GetMonitoringClasses(className)

            If monitoringClasses.Count = 0 Then
                Throw New ApplicationException("The specified class was not found")
            End If

            If monitoringClasses.Count > 1 Then
                Throw New ApplicationException("Multiple classes with the specified name were found")
            End If

            Return GetMPElementReference(mg, groupMp, monitoringClasses(0))
        End Function 'GetClassReference


        ' ---------------------------------------------------------------------
        Private Shared Function GetMPAlias(ByVal groupMp As ManagementPack, ByVal element As ManagementPackElement) As String
            Dim elementMp As ManagementPack = element.GetManagementPack()
            Dim mpAlias As String = String.Empty
            Dim addRefRequired As Boolean = True

            If elementMp.Id = groupMp.Id Then
                ' The type is defined in the same MP as the new override MP.
                ' No need to add a dependency.
                addRefRequired = False
                Return String.Empty
            End If

            Dim existingMPRef As KeyValuePair(Of String, ManagementPackReference)
            For Each existingMPRef In groupMp.References

                If existingMPRef.Value.KeyToken = elementMp.KeyToken And _
                   existingMPRef.Value.Version = elementMp.Version And _
                   existingMPRef.Value.Name = elementMp.Name Then
                    addRefRequired = False
                    mpAlias = existingMPRef.Key
                End If
            Next

            If addRefRequired Then
                Dim mpRef As New ManagementPackReference(elementMp)

                mpAlias = elementMp.Name + elementMp.Version.ToString()
                mpAlias = mpAlias.Replace(".", "")

                groupMp.References.Add(mpAlias, mpRef)
            End If

            Return mpAlias
        End Function 'GetMPAlias

    End Class 'Program
End Namespace 'SDKSamples