Proveedor de trabajos de larga ejecución del Agente SQL 2008

Microsoft.SQLServer.2008.AgentLongRunningJobs (DataSourceModuleType)

Element properties:

TypeDataSourceModuleType
IsolationAny
AccessibilityInternal
RunAsMicrosoft.SQLServer.SQLProbeAccount
OutputTypeSystem.PropertyBagData

Member Modules:

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

Overrideable Parameters:

IDParameterTypeSelectorDisplay NameDescription
IntervalSecondsint$Config/IntervalSeconds$Intervalo (s)
SyncTimestring$Config/SyncTime$Hora de sincronización
TimeoutSecondsint$Config/TimeoutSeconds$Tiempo de espera (s)

Source Code:

<DataSourceModuleType ID="Microsoft.SQLServer.2008.AgentLongRunningJobs" Accessibility="Internal" RunAs="SQL!Microsoft.SQLServer.SQLProbeAccount">
<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="ConnectionString" 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.PropertyBagProvider">
<IntervalSeconds>$Config/IntervalSeconds$</IntervalSeconds>
<SyncTime>$Config/SyncTime$</SyncTime>
<ScriptName>GetSQL2008LongRunningJobs.vbs</ScriptName>
<Arguments>$Config/ConnectionString$ $Target/Host/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: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:GetSQL2008LongRunningJobs.vbs
'Copyright (c) Microsoft Corporation. All rights reserved.

Const SQL_MONITORING_CONNECT_FAILURE = -1
Const SQL_MONITORING_QUERY_FAILURE = -2
Const SQL_MONITORING_SUCCESS = 0

Dim SCRIPT_SQL
SCRIPT_SQL = "SET NOCOUNT ON" &amp; VbCrLf &amp;_
"DECLARE @job_activity TABLE (" &amp; VbCrLf &amp;_
"[session_id] [int] NOT NULL," &amp; VbCrLf &amp;_
"[job_id] [uniqueidentifier] NOT NULL," &amp; VbCrLf &amp;_
"[job_name] [sysname] COLLATE SQL_Latin1_General_CP1_CS_AS NOT NULL," &amp; VbCrLf &amp;_
"[run_requested_date] [datetime] NULL," &amp; VbCrLf &amp;_
"[run_requested_source] [sysname] COLLATE SQL_Latin1_General_CP1_CS_AS NULL," &amp; VbCrLf &amp;_
"[queued_date] [datetime] NULL," &amp; VbCrLf &amp;_
"[start_execution_date] [datetime] NULL," &amp; VbCrLf &amp;_
"[last_executed_step_id] [int] NULL," &amp; VbCrLf &amp;_
"[last_exectued_step_date] [datetime] NULL," &amp; VbCrLf &amp;_
"[stop_execution_date] [datetime] NULL," &amp; VbCrLf &amp;_
"[next_scheduled_run_date] [datetime] NULL," &amp; VbCrLf &amp;_
"[job_history_id] [int] NULL," &amp; VbCrLf &amp;_
"[message] [nvarchar](1024) COLLATE SQL_Latin1_General_CP1_CS_AS NULL," &amp; VbCrLf &amp;_
"[run_status] [int] NULL," &amp; VbCrLf &amp;_
"[operator_id_emailed] [int] NULL," &amp; VbCrLf &amp;_
"[operator_id_netsent] [int] NULL," &amp; VbCrLf &amp;_
"[operator_id_paged] [int] NULL," &amp; VbCrLf &amp;_
"[execution_time_minutes] [int] NULL )" &amp; VbCrLf &amp;_
"INSERT INTO @job_activity" &amp; VbCrLf &amp;_
"([session_id]" &amp; VbCrLf &amp;_
",[job_id]" &amp; VbCrLf &amp;_
",[job_name]" &amp; VbCrLf &amp;_
",[run_requested_date]" &amp; VbCrLf &amp;_
",[run_requested_source]" &amp; VbCrLf &amp;_
",[queued_date]" &amp; VbCrLf &amp;_
",[start_execution_date]" &amp; VbCrLf &amp;_
",[last_executed_step_id]" &amp; VbCrLf &amp;_
",[last_exectued_step_date]" &amp; VbCrLf &amp;_
",[stop_execution_date]" &amp; VbCrLf &amp;_
",[next_scheduled_run_date]" &amp; VbCrLf &amp;_
",[job_history_id]" &amp; VbCrLf &amp;_
",[message]" &amp; VbCrLf &amp;_
",[run_status]" &amp; VbCrLf &amp;_
",[operator_id_emailed]" &amp; VbCrLf &amp;_
",[operator_id_netsent]" &amp; VbCrLf &amp;_
",[operator_id_paged])" &amp; VbCrLf &amp;_
"EXECUTE [msdb].[dbo].[sp_help_jobactivity]" &amp; VbCrLf &amp;_
"SELECT" &amp; VbCrLf &amp;_
"[ja].[job_id]" &amp; VbCrLf &amp;_
",[ja].[job_name]" &amp; VbCrLf &amp;_
",[originating_server]" &amp; VbCrLf &amp;_
",DATEDIFF(minute, [start_execution_date], GETDATE()) AS [execution_time_minutes]" &amp; VbCrLf &amp;_
"FROM @job_activity [ja]" &amp; VbCrLf &amp;_
"JOIN [msdb].[dbo].[sysjobs_view] [sjv] ON [sjv].[job_id] = [ja].[job_id]" &amp; VbCrLf &amp;_
"WHERE [start_execution_date] IS NOT NULL AND [run_status] IS NULL"


'Start of Main
'-----------------------------------------------------------------------------------------------
call Main()

Sub Main()

Dim objParameters, sConnectionString, sTcpPort
Dim oAPI, oBag

Set objParameters = WScript.Arguments

If objParameters.Count &lt;&gt; 2 Then
Quit()
End If

sConnectionString= objParameters(0)
sTcpPort= objParameters(1)

Set objParameters = Nothing

Set oAPI = MOMCreateObject("MOM.ScriptAPI")
Set oBag = oAPI.CreatePropertyBag()

If CheckLongRunningJobs(oBag, sConnectionString, sTcpPort) = 0 Then
Call oAPI.Return(oBag)
Else
Quit()
End If

End Sub
'End of Main
'-----------------------------------------------------------------------------------------------


Function WMIExecQuery(ByVal sNamespace, ByVal sQuery)
'
' WMIExecQuery :: Executes the WMI query and returns the result set.
'
'
Dim oWMI, oQuery, nInstanceCount
Dim e
Set e = New Error
On Error Resume Next
Set oWMI = GetObject(sNamespace)
e.Save
On Error Goto 0
If IsEmpty(oWMI) Then
ThrowScriptError "Unable to open WMI Namespace '" &amp; sNamespace &amp; "'. Check to see if the WMI service is enabled and running, and ensure this WMI namespace exists.", e
End If

On Error Resume Next
Set oQuery = oWMI.ExecQuery(sQuery)
e.Save
On Error Goto 0
If IsEmpty(oQuery) Or e.Number &lt;&gt; 0 Then
ThrowScriptError "The Query '" &amp; sQuery &amp; "' returned an invalid result set. Please check to see if this is a valid WMI Query.", e
End If

'Determine if we queried a valid WMI class - Count will return 0 or empty
On Error Resume Next
nInstanceCount = oQuery.Count
e.Save
On Error Goto 0
If e.Number &lt;&gt; 0 Then
ThrowScriptError "The Query '" &amp; sQuery &amp; "' did not return any valid instances. Please check to see if this is a valid WMI Query.", e
End If

Set WMIExecQuery = oQuery

End Function

Function CheckLongRunningJobs (ByRef oBag, ByVal sConnectionString, ByVal sTcpPort)


Dim cnADOConnection
Dim strProv
Dim strQuery
Dim rsSQLLongRunningJobs
Dim bFail
Dim nDuration
Dim maxDuration
Dim e
Set e = New Error

'on error resume next

Set cnADOConnection = MomCreateObject("ADODB.Connection")
cnADOConnection.Provider = "sqloledb"
cnADOConnection.ConnectionTimeout = 3
strProv = BuildConnectionStringWithPort(sConnectionString, "msdb", sTcpPort)

e.Clear
On Error Resume Next
cnADOConnection.Open strProv
e.Save
On Error Goto 0
If e.Number &lt;&gt; 0 Then
e.Clear
strProv = BuildConnectionString(sConnectionString, "msdb")
On Error Resume Next
cnADOConnection.Open strProv
e.Save
On Error Goto 0
If e.Number &lt;&gt; 0 Then
'Error event in here
CheckLongRunningJobs = SQL_MONITORING_CONNECT_FAILURE
Exit Function
End If
End If

strQuery = SCRIPT_SQL

Err.Clear
Set rsSQLLongRunningJobs = cnADOConnection.Execute(strQuery)
If 0 &lt;&gt; Err.number Then
CheckLongRunningJobs = SQL_MONITORING_QUERY_FAILURE
Exit Function
End If

If 0 = rsSQLLongRunningJobs.State Then
' No records returned, recordset is likely closed.
Exit Function
End If

maxDuration = 0
Do
bFail = True
Err.Clear
if rsSQLLongRunningJobs.EOF then
if 0 &lt;&gt; Err.number then Exit Do
bFail = False
Exit Do
End If
If 0 &lt;&gt; Err.number Then Exit Do

nDuration = Int(rsSQLLongRunningJobs("execution_time_minutes").Value)
Call oBag.AddValue(rsSQLLongRunningJobs("job_name").Value,CDbl(nDuration))

If maxDuration &lt; nDuration Then
maxDuration = nDuration
End If

Err.Clear
rsSQLLongRunningJobs.MoveNext
If 0 &lt;&gt; Err.number then Exit Do
Loop

Call oBag.AddValue("MaxJobDuration", CDbl(maxDuration))


If bFail Then
' Throw
End if

Set cnADOConnection = Nothing
Set rsSQLLongRunningJobs = Nothing


CheckLongRunningJobs = SQL_MONITORING_SUCCESS

End Function

</Script></ScriptBody>
<TimeoutSeconds>$Config/TimeoutSeconds$</TimeoutSeconds>
</DataSource>
</MemberModules>
<Composition>
<Node ID="DS"/>
</Composition>
</Composite>
</ModuleImplementation>
<OutputType>System!System.PropertyBagData</OutputType>
</DataSourceModuleType>