SQL Server 2012 复制组件发现提供程序

Microsoft.SQLServer.2012.ReplicationComponentDiscovery (DataSourceModuleType)

此模块类型用于发现 SQL Server 2012 复制组件的实例

Element properties:

TypeDataSourceModuleType
IsolationAny
AccessibilityInternal
RunAsMicrosoft.SQLServer.SQLDiscoveryAccount
OutputTypeSystem.Discovery.Data

Member Modules:

ID Module Type TypeId RunAs 
DS DataSource Microsoft.Windows.TimedScript.DiscoveryProvider Default

Overrideable Parameters:

IDParameterTypeSelectorDisplay NameDescription
IntervalSecondsint$Config/IntervalSeconds$间隔(秒)将运行发现的轮询间隔(秒)。
SyncTimestring$Config/SyncTime$同步时间要执行初始发现的时间
TimeoutSecondsint$Config/TimeoutSeconds$超时(秒)

Source Code:

<DataSourceModuleType ID="Microsoft.SQLServer.2012.ReplicationComponentDiscovery" Accessibility="Internal" RunAs="SQL!Microsoft.SQLServer.SQLDiscoveryAccount">
<Configuration>
<xsd:element xmlns:xsd="http://www.w3.org/2001/XMLSchema" name="IntervalSeconds" type="xsd:integer"/>
<xsd:element xmlns:xsd="http://www.w3.org/2001/XMLSchema" name="SyncTime" type="xsd:string"/>
<xsd:element xmlns:xsd="http://www.w3.org/2001/XMLSchema" name="NetworkName" type="xsd:string"/>
<xsd:element xmlns:xsd="http://www.w3.org/2001/XMLSchema" name="SQLConnectionString" type="xsd:string"/>
<xsd:element xmlns:xsd="http://www.w3.org/2001/XMLSchema" name="SQLInstanceName" type="xsd:string"/>
<xsd:element xmlns:xsd="http://www.w3.org/2001/XMLSchema" name="TimeoutSeconds" type="xsd:int"/>
</Configuration>
<OverrideableParameters>
<OverrideableParameter ID="IntervalSeconds" ParameterType="int" Selector="$Config/IntervalSeconds$"/>
<OverrideableParameter ID="SyncTime" ParameterType="string" Selector="$Config/SyncTime$"/>
<OverrideableParameter ID="TimeoutSeconds" ParameterType="int" Selector="$Config/TimeoutSeconds$"/>
</OverrideableParameters>
<ModuleImplementation>
<Composite>
<MemberModules>
<DataSource ID="DS" TypeID="Windows!Microsoft.Windows.TimedScript.DiscoveryProvider">
<IntervalSeconds>$Config/IntervalSeconds$</IntervalSeconds>
<SyncTime>$Config/SyncTime$</SyncTime>
<ScriptName>DiscoverSQL2012ReplicationComponents.vbs</ScriptName>
<Arguments>$MPElement$ $Target/Id$ $Config/NetworkName$ $Config/SQLConnectionString$ $Config/SQLInstanceName$ $Target/Property[Type="SQL!Microsoft.SQLServer.DBEngine"]/TcpPort$</Arguments>
<ScriptBody><Script>'#Include File:Initialize.vbs

Option Explicit
SetLocale("en-us")

Function Quit()
WScript.Quit()
End Function

Function IsValidObject(ByVal oObject)
IsValidObject = False

If IsObject(oObject) Then
If Not oObject Is Nothing Then
IsValidObject = True
End If
End If
End Function

Function MomCreateObject(ByVal sProgramId)
Dim oError
Set oError = New Error

On Error Resume Next
Set MomCreateObject = CreateObject(sProgramId)
oError.Save
On Error GoTo 0

If oError.Number &lt;&gt; 0 Then ThrowScriptError "Unable to create automation object '" &amp; sProgramId &amp; "'", oError
End Function
'#Include File:SQL2012Constants.vbs

Const SQL_VERSION = "2012"
Const SQL_VERSION_NUMBER = "11"
Const SQL_WMI_NAMESPACE = "ComputerManagement11"

Const SQL_FULLTEXTSEARCH_SERVICENAME = "MSSQLFDLauncher"
Const SQL_FULLTEXTSEARCH_SERVICECLUSTERNAME = "SQL Full-text Filter Daemon Launcher"

Const SQL_DBENGINE_CLASS = "$MPElement[Name='Microsoft.SQLServer.2012.DBEngine']$"
Const SQL_DATABASE_CLASS = "$MPElement[Name='Microsoft.SQLServer.2012.Database']$"
Const SQL_AGENTJOB_CLASS = "$MPElement[Name='Microsoft.SQLServer.2012.AgentJob']$"
Const SQL_REPLICATION_DISTRIBUTOR_CLASS = "$MPElement[Name='Microsoft.SQLServer.2012.Distributor']$"
Const SQL_DISTRIBUTOR_CONTAINS_DATABASE_RELATIONSHIP = "$MPElement[Name='Microsoft.SQLServer.2012.DistributorContainsDatabase']$"
Const SQL_REPLICATION_PUBLISHER_CLASS = "$MPElement[Name='Microsoft.SQLServer.2012.Publisher']$"
Const SQL_REPLICATION_SUBSCRIBER_CLASS = "$MPElement[Name='Microsoft.SQLServer.2012.Subscriber']$"
Const SQL_REPLICATION_PUBLICATION_CLASS = "$MPElement[Name='Microsoft.SQLServer.2012.Publication']$"
Const SQL_REPLICATION_SUBSCRIPTION_CLASS = "$MPElement[Name='Microsoft.SQLServer.2012.Subscription']$"
Const SQL_DATABASE_ERROR_USER_POLICY_CLASS = "$MPElement[Name='Microsoft.SQLServer.2012.DatabaseErrorUserPolicy']$"
Const SQL_DATABASE_WARNING_USER_POLICY_CLASS = "$MPElement[Name='Microsoft.SQLServer.2012.DatabaseWarningUserPolicy']$"
Const SQL_USERPOLICY_DEFAULT_CATEGORY_NAME = "&lt;Default&gt;"
'#Include File:Error.vbs

Class Error
Private m_lNumber
Private m_sSource
Private m_sDescription
Private m_sHelpContext
Private m_sHelpFile

Public Sub Save()
m_lNumber = Err.Number
m_sSource = Err.Source
m_sDescription = Err.Description
m_sHelpContext = Err.HelpContext
m_sHelpFile = Err.HelpFile
End Sub

Public Sub Raise()
Err.Raise m_lNumber, m_sSource, m_sDescription, m_sHelpFile, m_sHelpContext
End Sub

Public Sub Clear()
m_lNumber = 0
m_sSource = ""
m_sDescription = ""
m_sHelpContext = ""
m_sHelpFile = ""
End Sub

Public Default Property Get Number()
Number = m_lNumber
End Property
Public Property Get Source()
Source = m_sSource
End Property
Public Property Get Description()
Description = m_sDescription
End Property
Public Property Get HelpContext()
HelpContext = m_sHelpContext
End Property
Public Property Get HelpFile()
HelpFile = m_sHelpFile
End Property
End Class

Function ThrowScriptErrorNoAbort(ByVal sMessage, ByVal oErr)
On Error Resume Next
Dim oAPITemp
Set oAPITemp = MOMCreateObject("MOM.ScriptAPI")
oAPITemp.LogScriptEvent WScript.ScriptName, 4001, 1, sMessage &amp; ". " &amp; oErr.Description
End Function

Function ThrowScriptError(Byval sMessage, ByVal oErr)
On Error Resume Next
ThrowScriptErrorNoAbort sMessage, oErr
Quit()
End Function

Sub HandleError(customMessage)
Dim localLogger
If Not (Err.number = 0) Then
Set localLogger = new ScriptLogger
localLogger.LogFormattedError(customMessage)
Wscript.Quit 0
End If
End Sub

Function HandleErrorContinue(customMessage)
Dim localLogger
HandleErrorContinue = False
If Not (Err.number = 0) Then
Set localLogger = new ScriptLogger
localLogger.LogFormattedError(customMessage)
Err.Clear
HandleErrorContinue = True
End If
End Function

'#Include File:ConnectionString.vbs

Function BuildConnectionString(strServer, strDatabase)
ON ERROR RESUME NEXT
Err.Clear

Dim dataSource
dataSource = BuildServerName(strServer, "")
BuildConnectionString = "Data Source=" &amp; EscapeConnStringValue(dataSource) &amp; ";Initial Catalog=" &amp; EscapeConnStringValue(strDatabase) &amp; ";Integrated Security=SSPI"
End Function

Function BuildConnectionStringWithPort(ByVal strServer, ByVal strDatabase, ByVal tcpPort)
ON ERROR RESUME NEXT
Err.Clear

Dim dataSource
dataSource = strServer
If ((tcpPort &lt;&gt; "0") And (tcpPort &lt;&gt; "")) Then
dataSource = dataSource &amp; "," &amp; tcpPort
End If
BuildConnectionStringWithPort = "Data Source=" &amp; EscapeConnStringValue(dataSource) &amp; ";Initial Catalog=" &amp; EscapeConnStringValue(strDatabase) &amp; ";Integrated Security=SSPI"
End Function

' This function should be used to escape Connection String keywords.
Function EscapeConnStringValue (ByVal strValue)
ON ERROR RESUME NEXT
Err.Clear

EscapeConnStringValue = """" + Replace(strValue, """", """""") + """"
End Function

Function EscapeWQLString (ByVal strValue)
ON ERROR RESUME NEXT
Err.Clear

EscapeWQLString = Replace(strValue, "'", "\'")
End Function

Function GetTcpPort (ByVal strServer)
ON ERROR RESUME NEXT
Err.Clear

Dim tcpPort
tcpPort = ""

Call BuildServerName(strServer, tcpPort)

GetTcpPort = tcpPort

End Function

Function BuildServerName(ByVal strServer, ByRef tcp)
ON ERROR RESUME NEXT
Err.Clear

Dim pathArray, instanceName, computerName, ip, serverName
Dim oWMI, oQuery

ip= ""

pathArray = Split(strServer, "\")
computerName = pathArray(0)
instanceName = "MSSQLSERVER"
if (pathArray.Count &gt; 1) Then
instanceName = pathArray(1)
End If

serverName = strServer

Set oWMI = GetObject("winmgmts:\\" &amp; computerName &amp; "\root\Microsoft\SqlServer\" &amp; SQL_WMI_NAMESPACE)
Set oQuery = oWMI.ExecQuery("SELECT * FROM ServerNetworkProtocolProperty WHERE ProtocolName = 'Tcp' AND InstanceName = '"&amp; EscapeWQLString(instanceName) &amp;"' AND PropertyName = 'ListenOnAllIPs'")

If oQuery.Count &gt;0 Then
Dim isListenAll
Set isListenAll = oQuery.ItemIndex(0)
If(isListenAll.PropertyNumVal = 1) Then
Set oQuery = oWMI.ExecQuery("SELECT * FROM ServerNetworkProtocolProperty WHERE ProtocolName = 'Tcp' AND InstanceName = '"&amp; EscapeWQLString(instanceName) &amp;"' AND IPAddressName = 'IPAll' AND (PropertyName = 'TcpPort' OR PropertyName = 'TcpDynamicPorts') AND PropertyStrVal &lt;&gt; ''")

If (oQuery.Count &gt; 0) Then
tcp = oQuery.ItemIndex(0).PropertyStrVal

If ((tcp &lt;&gt; "0") And (tcp &lt;&gt; "")) Then
serverName = serverName &amp; "," &amp; tcp
Else tcp = ""
End If
End If
Else
Set oQuery = oWMI.ExecQuery("SELECT * FROM ServerNetworkProtocolProperty WHERE ProtocolName = 'Tcp' AND InstanceName = '"&amp; EscapeWQLString(instanceName) &amp;"' AND IPAddressName &lt;&gt; '' AND PropertyName = 'Enabled' AND PropertyNumVal = 1")
If (oQuery.Count &gt; 0) Then
Dim ipAddressName
ipAddressName = oQuery.ItemIndex(0).IPAddressName
Set oQuery = oWMI.ExecQuery("SELECT * FROM ServerNetworkProtocolProperty WHERE ProtocolName = 'Tcp' AND InstanceName = '"&amp; EscapeWQLString(instanceName) &amp;"' AND IPAddressName = '"&amp; EscapeWQLString(ipAddressName) &amp;"' AND (PropertyName = 'TcpPort' OR PropertyName = 'TcpDynamicPorts') AND PropertyStrVal &lt;&gt; ''")
If (oQuery.Count &gt; 0) Then
tcp = oQuery.ItemIndex(0).PropertyStrVal
End If
Set oQuery = oWMI.ExecQuery("SELECT * FROM ServerNetworkProtocolProperty WHERE ProtocolName = 'Tcp' AND InstanceName = '"&amp; EscapeWQLString(instanceName) &amp;"' AND IPAddressName = '"&amp; EscapeWQLString(ipAddressName) &amp;"' AND PropertyName = 'IpAddress' AND PropertyStrVal &lt;&gt; ''")
If (oQuery.Count &gt; 0) Then
ip = oQuery.ItemIndex(0).PropertyStrVal
End If
If ip &lt;&gt; "" Then
serverName = ip
End If
If ((tcp &lt;&gt; "0") And (tcp &lt;&gt; "")) Then
serverName = servername &amp; "," &amp; tcp
Else tcp = ""
End If
End If
End If
End If
On Error Goto 0
BuildServerName = serverName
End Function'#Include File:SQLReplicationComponentsDiscovery.vbs

'Copyright (c) Microsoft Corporation. All rights reserved.

' Parameters that should be passed to this script
' 0 MPElement ID ($MPElement$)
' 1 Target Id for ME this rule is running against ($Target/Id$)
' 2 Computer (FQDN) that SQL instance is hosted on
' 3 SQL Connection String for the instance that the DBs are being discovered on
' 4 SQL Instance that this rule is being run for

Const SQL_DISCOVERY_CONNECT_FAILURE = -1
Const SQL_DISCOVERY_QUERY_FAILURE = -2
Const SQL_DISCOVERY_SUCCESS = 0

Dim oArgs
Set oArgs = WScript.Arguments
if oArgs.Count &lt;&gt; 6 Then
Wscript.Quit -1
End If

Dim SourceID, ManagedEntityId, TargetComputerID, InstanceName, ConnectionString, TcpPort

SourceID = oArgs(0)
ManagedEntityId = oArgs(1)
TargetComputerID = oArgs(2)
ConnectionString = oArgs(3)
InstanceName = oArgs(4)
TcpPort = oArgs(5)

Dim oAPI, oSQLDiscoveryData

Set oAPI = MOMCreateObject("MOM.ScriptAPI")
Set oSQLDiscoveryData = oAPI.CreateDiscoveryData(0, SourceID, ManagedEntityId)


If DoReplicationDiscovery(TargetComputerID, InstanceName, ConnectionString, oSQLDiscoveryData, TcpPort) &gt;= 0 Then Call oAPI.Return(oSQLDiscoveryData)

Function DoReplicationDiscovery(ByVal sTargetComputerID, ByVal sSqlInstance, ByVal sSQLConnectionString, ByVal oSQLDiscoveryData, ByVal sTcpPort)

Dim e
Dim oObjectInstance
Dim cnADOConnection
Dim cnADOConnection2
Dim strProv
Dim oResults
Dim oResults2
Dim oRel
Dim oDatabase

Set e = New Error

Set cnADOConnection = MomCreateObject("ADODB.Connection")
cnADOConnection.Provider = "sqloledb"
cnADOConnection.ConnectionTimeout = 30
strProv = BuildConnectionStringWithPort(sSQLConnectionString, "master", sTcpPort)

e.Clear
On Error Resume Next
cnADOConnection.Open strProv
e.Save
'get fresh tcp port and try to connect again
if 0 &lt;&gt; Err.number then
e.Clear
Err.Clear
strProv = BuildConnectionString(sSQLConnectionString, "master")
cnADOConnection.Open strProv
e.Save

if 0 &lt;&gt; Err.number then
'Error event in here
'g_oSQL.CreateConnectionFailureAlert sInstance, Err.number, Err.Description
DoReplicationDiscovery = SQL_DISCOVERY_CONNECT_FAILURE
Exit Function
end if
end if
On Error Goto 0

e.Clear
On Error Resume Next
Set oResults = cnADOConnection.Execute("sp_helpdistpublisher")
e.Save
On Error Goto 0

if 0 &lt;&gt; e.number then
'Error event in here
DoReplicationDiscovery = SQL_DISCOVERY_QUERY_FAILURE
Exit Function
end if

' Create the distributor object if it exists on this instance
' Remote distributors can be discovered from publishers but this is ignored for now
If oResults.Fields.Count &gt; 0 Then
Set oObjectInstance = oSQLDiscoveryData.CreateClassInstance(SQL_REPLICATION_DISTRIBUTOR_CLASS)
With oObjectInstance
.AddProperty "$MPElement[Name='Windows!Microsoft.Windows.Computer']/PrincipalName$", TargetComputerID
.AddProperty "$MPElement[Name='SQL!Microsoft.SQLServer.ServerRole']/InstanceName$", sSqlInstance
' TODO: Remove. Useless property - we already have all this information through hosting relationships.
.AddProperty "$MPElement[Name='SQL!Microsoft.SQLServer.Distributor']/DistributionServer$", BuildServerName(TargetComputerID, sSqlInstance)
.AddProperty "$MPElement[Name='System!System.Entity']/DisplayName$", BuildServerName(TargetComputerID, sSqlInstance)
End With

' Try extract additional properties if publisher is on the same instance as distributor.
' TODO: This properties should not be discovered for distributor, they're publisher's view on the distributor.
e.Clear
On Error Resume Next
Set oResults = cnADOConnection.Execute("sp_get_distributor")
e.Save
On Error Goto 0
If 0 &lt;&gt; e.Number Then
'Error event in here
DoReplicationDiscovery = SQL_DISCOVERY_QUERY_FAILURE
Exit Function
End If

If oResults(1) = True Then
With oObjectInstance
.AddProperty "$MPElement[Name='SQL!Microsoft.SQLServer.Distributor']/DistributionDBInstalled$", CBool(oResults(2))
.AddProperty "$MPElement[Name='SQL!Microsoft.SQLServer.Distributor']/IsDistributionPublisher$", CBool(oResults(3))
.AddProperty "$MPElement[Name='SQL!Microsoft.SQLServer.Distributor']/HasRemoteDistributionPublisher$", CBool(oResults(4))
End With
End If

' 'sp_helpdistributor' should be executed on the publisher but not the distributor.
' All this properties are valid for particular publisher but can vary on distributor.
' For example, distributor can have multiple distribution databases.
'
'e.Clear
'On Error Resume Next
' Set oResults = cnADOConnection.Execute("sp_helpdistributor")
' e.Save
'On Error Goto 0

'With oObjectInstance
' .AddProperty "$MPElement[Name='SQL!Microsoft.SQLServer.Distributor']/DistributionDB$", oResults(1)
' .AddProperty "$MPElement[Name='SQL!Microsoft.SQLServer.Distributor']/Directory$", oResults(2)
' .AddProperty "$MPElement[Name='SQL!Microsoft.SQLServer.Distributor']/Account$", oResults(3)
'End With

On Error Resume Next
Set oResults2 = cnADOConnection.Execute("select name from sys.databases where is_distributor = 1")
e.Save
On Error Goto 0

If e.Number = 0 And oResults2.Fields.Count &gt; 0 Then
Do While Not oResults2.EOF
Set oRel = oSQLDiscoveryData.CreateRelationshipInstance(SQL_DISTRIBUTOR_CONTAINS_DATABASE_RELATIONSHIP)
Set oDatabase = oSQLDiscoveryData.CreateClassInstance(SQL_DATABASE_CLASS)

With oDatabase
.AddProperty "$MPElement[Name='Windows!Microsoft.Windows.Computer']/PrincipalName$", TargetComputerID
.AddProperty "$MPElement[Name='SQL!Microsoft.SQLServer.ServerRole']/InstanceName$", sSqlInstance
.AddProperty "$MPElement[Name='SQL!Microsoft.SQLServer.Database']/DatabaseName$", oResults2(0)
End With
Call oSQLDiscoveryData.AddInstance(oDatabase)
oRel.Source = oObjectInstance
oRel.Target = oDatabase
Call oSQLDiscoveryData.AddInstance(oRel)
oResults2.MoveNext
Loop
End If

Call oSQLDiscoveryData.AddInstance(oObjectInstance)

End If

' Get distributor information from publisher side
' TODO: Looks like it discovers distributor as a publisher. Need more strict condition to determine publishers.
e.Clear
On Error Resume Next
Set oResults = cnADOConnection.Execute("sp_helpdistributor")
e.Save
On Error Goto 0
If e.Number = 0 And oResults.Fields.Count &gt; 0 And Not IsNull(oResults(0)) Then
' Publisher is created in case of any results returned
Set oObjectInstance = oSQLDiscoveryData.CreateClassInstance(SQL_REPLICATION_PUBLISHER_CLASS)
Dim sPublisherName : sPublisherName = BuildServerName(TargetComputerID, sSqlInstance)
With oObjectInstance
.AddProperty "$MPElement[Name='Windows!Microsoft.Windows.Computer']/PrincipalName$", TargetComputerID
.AddProperty "$MPElement[Name='SQL!Microsoft.SQLServer.ServerRole']/InstanceName$", sSqlInstance
.AddProperty "$MPElement[Name='SQL!Microsoft.SQLServer.Publisher']/Name$", sPublisherName
.AddProperty "$MPElement[Name='SQL!Microsoft.SQLServer.Publisher']/DistributionDB$", oResults(1)
.AddProperty "$MPElement[Name='SQL!Microsoft.SQLServer.Publisher']/PublisherType$", oResults(11)
' TODO: Remove. Useless property - this is publisher SQL Server instance name.
.AddProperty "$MPElement[Name='SQL!Microsoft.SQLServer.Publisher']/DataSource$", sPublisherName
.AddProperty "$MPElement[Name='SQL!Microsoft.SQLServer.Publisher']/WorkingDirectory$", oResults(2)
.AddProperty "$MPElement[Name='System!System.Entity']/DisplayName$", sPublisherName
End With
Call oSQLDiscoveryData.AddInstance(oObjectInstance)
End If

' Get subscriptions on subscriber side
' TODO: Review low-priviledge required for this to work.
'e.Clear
'On Error Resume Next
' Set oResults = cnADOConnection.Execute("exec sp_MSenumallsubscriptions @subscription_type = N'both'")
' e.Save
'On Error Goto 0
'If e.Number = 0 And Not oResults.BOF And Not oResults.EOF Then
' Subscriber is created in case of any results returned
' Set oObjectInstance = oSQLDiscoveryData.CreateClassInstance(SQL_REPLICATION_SUBSCRIBER_CLASS)
' Dim sSubscriberName : sSubscriberName = BuildServerName(TargetComputerID, sSqlInstance)
' With oObjectInstance
' .AddProperty "$MPElement[Name='Windows!Microsoft.Windows.Computer']/PrincipalName$", TargetComputerID
' .AddProperty "$MPElement[Name='SQL!Microsoft.SQLServer.ServerRole']/InstanceName$", sSqlInstance
' .AddProperty "$MPElement[Name='System!System.Entity']/DisplayName$", sSubscriberName
' End With
' Call oSQLDiscoveryData.AddInstance(oObjectInstance)
'End If

cnADOConnection.Close()
DoReplicationDiscovery = SQL_DISCOVERY_SUCCESS

End Function

' Simple function to build SQL Server connection string
Function BuildServerName(ByVal sComputerName, ByVal sInstanceName)
If sInstanceName = "MSSQLSERVER" Then
BuildServerName = sComputerName
Else
BuildServerName = sComputerName &amp; "\" &amp; sInstanceName
End If
End Function
</Script></ScriptBody>
<TimeoutSeconds>$Config/TimeoutSeconds$</TimeoutSeconds>
</DataSource>
</MemberModules>
<Composition>
<Node ID="DS"/>
</Composition>
</Composite>
</ModuleImplementation>
<OutputType>System!System.Discovery.Data</OutputType>
</DataSourceModuleType>