Verify Windows Service State Probe Action

Microsoft.SQLServer.2008.VerifyWindowsServiceState (ProbeActionModuleType)

Element properties:

TypeProbeActionModuleType
IsolationAny
AccessibilityInternal
RunAsMicrosoft.SQLServer.SQLProbeAccount
InputTypeSystem.BaseData
OutputTypeSystem.PropertyBagData

Member Modules:

ID Module Type TypeId RunAs 
PA ProbeAction Microsoft.Windows.ScriptPropertyBagProbe Default

Overrideable Parameters:

IDParameterTypeSelectorDisplay NameDescription
ServiceUnavailableTimeint$Config/ServiceUnavailableTime$Service Unavailable Time (sec)

Source Code:

<ProbeActionModuleType ID="Microsoft.SQLServer.2008.VerifyWindowsServiceState" Accessibility="Internal" RunAs="SQL!Microsoft.SQLServer.SQLProbeAccount">
<Configuration>
<xsd:element xmlns:xsd="http://www.w3.org/2001/XMLSchema" name="ServiceName" type="xsd:string"/>
<xsd:element xmlns:xsd="http://www.w3.org/2001/XMLSchema" name="ServiceUnavailableTime" type="xsd:integer"/>
<xsd:element xmlns:xsd="http://www.w3.org/2001/XMLSchema" name="CheckStartupType" type="xsd:string"/>
<xsd:element xmlns:xsd="http://www.w3.org/2001/XMLSchema" name="StartMode" type="xsd:string"/>
<xsd:element xmlns:xsd="http://www.w3.org/2001/XMLSchema" name="State" type="xsd:string"/>
</Configuration>
<OverrideableParameters>
<OverrideableParameter ID="ServiceUnavailableTime" ParameterType="int" Selector="$Config/ServiceUnavailableTime$"/>
</OverrideableParameters>
<ModuleImplementation>
<Composite>
<MemberModules>
<ProbeAction ID="PA" TypeID="Windows!Microsoft.Windows.ScriptPropertyBagProbe">
<ScriptName>GetSQL2008DBEngineWinServState.js</ScriptName>
<Arguments>"$Config/ServiceName$" "$Config/CheckStartupType$" "$Config/ServiceUnavailableTime$" "$Config/StartMode$" "$Config/State$"</Arguments>
<ScriptBody><Script>var SQL_WMI_NAMESPACE = "ComputerManagement10";//#Include File:Common.js

var DEBUG = false;
var ManagementGroupName = "$Target/ManagementGroup/Name$";
var ManagementGroupID = "$Target/ManagementGroup/Id$";

function EscapeConnStringValue(connStringValue) {
return '"' + connStringValue.replace(/"/g, '""') + '"';
}

function EscapeWQLString(wqlString) {
return wqlString.replace(/'/g, "\\'");
}

function BuildConnectionString(server, database) {
var dataSource = BuildServerName(server);
return "Data Source=" + EscapeConnStringValue(dataSource) + ";Initial Catalog=" + EscapeConnStringValue(database) + ";Integrated Security=SSPI";
}

function BuildConnectionStringWithPort(server, database, tcpPort) {

var dataSource = server;
if ((tcpPort != "") &amp;&amp; (tcpPort != "0")) {
dataSource = dataSource + "," + tcpPort;
}
return "Data Source=" + EscapeConnStringValue(dataSource) + ";Initial Catalog=" + EscapeConnStringValue(database) + ";Integrated Security=SSPI";
}

function ConcatinateServerName(server, tcpPort) {
var dataSource = server;
if ((tcpPort != "") &amp;&amp; (tcpPort != "0")) {
dataSource = dataSource + "," + tcpPort;
}
return dataSource;
}
function BuildServerName(strServer) {
var tcp = "";
var ip = "";
var pathArray = strServer.split("\\");
var instanceName = "MSSQLSERVER";
if (pathArray.length &gt; 1) {
instanceName = pathArray[1];
}

var serverName = strServer;

var oWMI = new WMIProvider("root\\Microsoft\\SqlServer\\" + SQL_WMI_NAMESPACE);
var oQuery = oWMI.ExecQuery("SELECT * FROM ServerNetworkProtocolProperty WHERE ProtocolName = 'Tcp' AND InstanceName = '" + EscapeWQLString(instanceName) + "' AND PropertyName = 'ListenOnAllIPs'");

if (oQuery.Count &gt; 0) {
var e = new Enumerator(oQuery);
e.moveFirst();
var isListenAll = e.item();
if (isListenAll.PropertyNumVal == 1) {
oQuery = oWMI.ExecQuery("SELECT * FROM ServerNetworkProtocolProperty WHERE ProtocolName = 'Tcp' AND InstanceName = '" + EscapeWQLString(instanceName) + "' AND IPAddressName = 'IPAll' AND (PropertyName = 'TcpPort' OR PropertyName = 'TcpDynamicPorts') AND PropertyStrVal != ''");
if (oQuery.Count &gt; 0) {
e = new Enumerator(oQuery);
e.moveFirst();
tcp = e.item().PropertyStrVal;
if ((tcp != "0") &amp;&amp; (tcp != "")) {
serverName = serverName + "," + tcp;
}
}
}
else {
oQuery = oWMI.ExecQuery("SELECT * FROM ServerNetworkProtocolProperty WHERE ProtocolName = 'Tcp' AND InstanceName = '" + EscapeWQLString(instanceName) + "' AND IPAddressName != '' AND PropertyName = 'Enabled' AND PropertyNumVal = 1");
if (oQuery.Count &gt; 0) {
var ipAddressName = oQuery.ItemIndex(0).IPAddressName;
oQuery = oWMI.ExecQuery("SELECT * FROM ServerNetworkProtocolProperty WHERE ProtocolName = 'Tcp' AND InstanceName = '" + EscapeWQLString(instanceName) + "' AND IPAddressName = '" + EscapeWQLString(ipAddressName) + "' AND (PropertyName = 'TcpPort' OR PropertyName = 'TcpDynamicPorts') AND PropertyStrVal != ''");
if (oQuery.Count &gt; 0) {
var e = new Enumerator(oQuery);
e.moveFirst();
tcp = e.item().PropertyStrVal;
}
oQuery = oWMI.ExecQuery("SELECT * FROM ServerNetworkProtocolProperty WHERE ProtocolName = 'Tcp' AND InstanceName = '" + EscapeWQLString(instanceName) + "' AND IPAddressName = '" + EscapeWQLString(ipAddressName) + "' AND PropertyName = 'IpAddress' AND PropertyStrVal != ''");
if (oQuery.Count &gt; 0) {
var e = new Enumerator(oQuery);
e.moveFirst();
ip = e.item().PropertyStrVal;
}
if (ip != "") {
serverName = ip;
}
if (tcp != "") {
serverName = serverName + "," + tcp;
}
}
}
}
return serverName;
}

function CheckConnectionTarget (dbConnection, serverName, instanceName) {
var destinationTestQuery = "select SERVERPROPERTY('MachineName') as ServerName, @@servicename as InstanceName";
var queryResult = dbConnection.ExecuteQuery(destinationTestQuery);
queryResult.MoveFirst();
if (!queryResult.EOF) {
var queryServerName = queryResult("ServerName").Value.toUpperCase();
var queryInstanceName = queryResult("InstanceName").Value.toUpperCase();
var serverNameWithoutDomain = serverName;
var dotPosition = serverName.indexOf(".");
if (dotPosition &gt; -1) {
serverNameWithoutDomain = serverName.substring(0, dotPosition);
}
if (serverNameWithoutDomain.toUpperCase() == queryServerName &amp;&amp; instanceName.toUpperCase() == queryInstanceName) {
return;
}
}
throw new Exception("Connection target check failed: connected to " + serverName + "\\" + instanceName + ", but got " + queryServerName + "\\" + queryInstanceName + ".");
};

function SmartConnect (serverName, databaseName, tcpPort, machineName, instanceName) {
var dbMasterConnection;
var connectionString;
//try to use SQL server browser
connectionString = BuildConnectionStringWithPort(serverName, databaseName, "");
try {
dbMasterConnection = new ADODB(connectionString, "sqloledb", 10);
CheckConnectionTarget(dbMasterConnection, machineName, instanceName);
} catch (e) {
//use original tcp port and try to connect again
connectionString = BuildConnectionStringWithPort(serverName, databaseName, tcpPort);
try {
dbMasterConnection = new ADODB(connectionString, "sqloledb", 10);
CheckConnectionTarget(dbMasterConnection, machineName, instanceName);
} catch (eInt) {
//get fresh tcp port and try to connect again
connectionString = BuildConnectionString(serverName, databaseName);
dbMasterConnection = new ADODB(connectionString, "sqloledb", 30);
CheckConnectionTarget(dbMasterConnection, machineName, instanceName);
}
}
return dbMasterConnection;
};

Function.prototype.setAlias = function (name) {
this.getAlias = function () {
return name;
};
};
Error.prototype.toString = function () {
if (this.message) {
var parts = [];
parts.push(this.message);
parts.push('\n');

if (this.number) {
parts.push("Error Number : ");
parts.push(this.number);
parts.push('\n');
parts.push("Error Code : ");
parts.push(this.number &amp; 0xFFFF);
parts.push('\n');
parts.push("Win32 Facility : ");
parts.push((this.number &gt;&gt; 16 &amp; 0x1FFF));
parts.push('\n');
}
if (this.description) {
parts.push("Error Description : ");
parts.push(this.description);
}
parts.push('\n');
return parts.join('');
}
else {
return this.toString();
}
};
var Exception = function (message, innerException) {
arguments.callee.setAlias('Exception.constructor');
this.message = message;
this.innerException = innerException;

var parts = [];
var collectArguments = function (caller) {
parts.push('(');
for (var i = 0; i &lt; caller.length; i++) {
if (typeof (caller[i]) != 'undefined') {
parts.push(caller[i] === null ? 'null' : (typeof (caller[i].toString) === 'undefined' ? 'object' : caller[i].toString()));
parts.push(',');
}
}
parts.pop();
parts.push(')');
parts.push(',\n');
};
var collectCallStack = function (caller) {
arguments.callee.setAlias('Exception.collectCallStack');
parts.push(caller.callee.getAlias ? caller.callee.getAlias() : 'anonymous');
collectArguments(caller);
var nextCaller = caller.caller;
if (nextCaller)
collectCallStack(nextCaller);
};
collectCallStack(arguments);
this.callStack = parts.join('');

this.toString = function () {
arguments.callee.setAlias('Exception.toStringFull');
var parts = [];
parts.push(this.message);
parts.push('\n');
if (this.innerException) {

parts.push('Inner exception: \n');
parts.push("Error Number : ");
parts.push(this.innerException.number);
parts.push('\n');
parts.push("Error Code : ");
parts.push(this.innerException.number &amp; 0xFFFF);
parts.push('\n');
parts.push("Win32 Facility : ");
parts.push((this.innerException.number &gt;&gt; 16 &amp; 0x1FFF));
parts.push('\n');
parts.push("Error Description : ");
parts.push(this.innerException.description);
parts.push('\n');
}
parts.push('Call stack:');
parts.push(this.callStack);
return parts.join('');;
};
};
var OpsMgrAPI = function () {
arguments.callee.setAlias('MOMAPI.constructor');
var scriptAPI;
try {
scriptAPI = new ActiveXObject('MOM.ScriptAPI');
}
catch (e) {
throw new Exception("Application cannot create MOM.ScriptAPI ActiveX object.", e);
}
this.ScriptAPI = scriptAPI;
};
var MessageType = {
Error: 1,
Warning: 2,
Information: 4
};
var Logger = function () {
arguments.callee.setAlias('Logger.constructor');
var opsMgrAPI = new OpsMgrAPI();

this.LogError = function (eventId, message) {
arguments.callee.setAlias('Logger.LogError');
opsMgrAPI.ScriptAPI.LogScriptEvent("Management Group: " + ManagementGroupName + ". Script: " + WScript.ScriptName, eventId, MessageType.Error, message);
};
this.LogError2 = function (instanceName, eventId, message) {
arguments.callee.setAlias('Logger.LogError2');
opsMgrAPI.ScriptAPI.LogScriptEvent("Management Group: " + ManagementGroupName + ". Script: " + WScript.ScriptName + ". Instance: " + instanceName, eventId, MessageType.Error, message);
};
this.LogWarning = function (eventId, message) {
arguments.callee.setAlias('Logger.LogWarning');
opsMgrAPI.ScriptAPI.LogScriptEvent("Management Group: " + ManagementGroupName + ". Script: " + WScript.ScriptName, eventId, MessageType.Warning, message);
};
this.LogInformation = function (eventId, message) {
arguments.callee.setAlias('Logger.LogInformation');
opsMgrAPI.ScriptAPI.LogScriptEvent("Management Group: " + ManagementGroupName + ". Script: " + WScript.ScriptName, eventId, MessageType.Information, message);
};
this.LogDebug = function (eventId, message) {
if (DEBUG) {
arguments.callee.setAlias('Logger.LogDebug');
opsMgrAPI.ScriptAPI.LogScriptEvent("Management Group: " + ManagementGroupName + ". Script: " + WScript.ScriptName, eventId, MessageType.Information, message);
}
};
this.LogCustomInfo = function (param1, eventId, message) {
arguments.callee.setAlias('Logger.LogCustomInfo');
opsMgrAPI.ScriptAPI.LogScriptEvent(param1, eventId, MessageType.Information, message);
};
};
var ADODB = function (connectionString, provider, connectionTimeout) {
arguments.callee.setAlias('ADODB.constructor');
if (!connectionString)
throw new Exception("Connection string cannot be null or empty string");
this.provider = provider ? provider : "sqloledb";
this.connectionTimeout = connectionTimeout ? connectionTimeout : 30;

var connection;
try {
connection = new ActiveXObject("ADODB.Connection");
}
catch (e) {
throw new Exception("Can't create ActiveXObject 'ADODB.Connection'", e);
}

connection.Provider = this.provider;
connection.ConnectionTimeout = this.connectionTimeout;
connection.ConnectionString = connectionString;
try {
connection.Open();
}
catch (e) {
throw new Exception("Can't connect to SQL Server. Connection string : '" + connectionString + "'", e);
}

this.ExecuteQuery = function (query) {
arguments.callee.setAlias('ADODB.ExecuteQuery');
var dbSet;
try {
dbSet = connection.Execute(query);
}
catch (e) {
throw new Exception("Can't execute query '" + query + "'", e);
}
return dbSet;
};
this.Close = function () {
arguments.callee.setAlias('ADODB.Close');
try {
if (connection) {
connection.Close();
}
}
catch (e) {
throw new Exception("Can't close connection.", e);
}
};
};
var Registry = function () {
arguments.callee.setAlias('Registry.constructor');
var registry;
try {
registry = new ActiveXObject("WScript.Shell");
}
catch (e) {
throw new Exception("Can't create ActiveXObject 'WScript.Shell'", e);
}

this.Write = function (key, value, type) {
arguments.callee.setAlias('Registry.Write');
try {
if (type) {
registry.RegWrite(key, value, type);
}
else {
registry.RegWrite(key, value);
}
}
catch (e) {
throw new Exception("Can't write value '" + value.toString() + "' by registry key '" + key.toString() + "'.", e);
}
};
this.Read = function (key) {
arguments.callee.setAlias('Registry.Read');
var value;
try {
value = registry.RegRead(key);
}
catch (e) {
throw new Exception("Can't read value from registry key '" + key.toString() + "'.", e);
}
return value;
};
this.IsKeyExists = function (key) {
arguments.callee.setAlias('Registry.IsKeyExists');
var result = false;
try {
value = registry.RegRead(key);
result = true;
}
catch (e) {
result = false;
}
return result;
};
this.Delete = function (key) {
arguments.callee.setAlias('Registry.Delete');
var value;
try {
value = registry.RegDelete(key);
}
catch (e) {
throw new Exception("Can't delete registry key '" + key.toString() + "'.", e);
}
return value;
};
};
var WMIProvider = function (wmiNamespace, computerName) {
arguments.callee.setAlias('WMIProvider.constructor');
this.wmiNamespace = wmiNamespace;
this.computerName = (!computerName) ? computerName : ".";
var SWbemLocator;
try {
SWbemLocator = new ActiveXObject("WbemScripting.SWbemLocator");
}
catch (e) {
throw new Exception("Cannot create 'WbemScripting.SWbemLocator' object.", e);
}
this.SWbemLocator = SWbemLocator;

var wmiService;
try {
wmiService = this.SWbemLocator.ConnectServer(this.computerName, this.wmiNamespace);
}
catch (e) {
throw new Exception("Cannot connect to WMI of computer '" + this.computerName + "' by namespace '" + this.wmiNamespace + "'.", e);
}
this.WMIService = wmiService;

this.ExecQuery = function (query) {
arguments.callee.setAlias('WMIProvider.ExecQuery');
var result = null;
try {
result = this.WMIService.ExecQuery(query, "WQL", 0x0);
}
catch (e) {
throw new Exception("Cannot execute WMI query '" + query + "'.", e);
}
return result;
};
};
//#Include File:GetSQL2008DBEngineWinServState.js
///
var ServiceUnavailableStartTime = "ServiceUnavailableStartTime";
var IsServiceUnavailable = "ServiceUnavailable";
var RunnningServiceState = "Running";
var AutoStartMode = "Auto";

function GetServiceUnavailableRegistryKey(ServiceName) {
arguments.callee.setAlias('GetRegistryKeyForService');
key = "";
var opsMgrAPI = new OpsMgrAPI();
var registryKey = opsMgrAPI.ScriptAPI.GetScriptStateKeyPath(ManagementGroupID);
key = "HKEY_LOCAL_MACHINE\\" + registryKey + "\\" + ServiceName + "\\";
return key;
}

function ResetServiceState(ServiceName) {
arguments.callee.setAlias('ResetServiceState');
var regPath = GetServiceUnavailableRegistryKey(ServiceName);
var regKey = regPath + ServiceUnavailableStartTime;
var registry = new Registry();
if (registry.IsKeyExists(regKey)) {
registry.Delete(regKey);
}
var regKey1 = regPath + IsServiceUnavailable;
if (registry.IsKeyExists(regKey1)) {
registry.Delete(regKey1);
}
}

function GetServiceUnavailableStartTime(ServiceName) {
arguments.callee.setAlias('GetServiceUnavailableStartTime');
var regKey = GetServiceUnavailableRegistryKey(ServiceName) + ServiceUnavailableStartTime;
var ServiceUnavailableTime = 0;
var registry = new Registry();
if (registry.IsKeyExists(regKey)) {
ServiceUnavailableTime = registry.Read(regKey);
}
else {
var dateObj = new Date();
ServiceUnavailableTime = parseInt(dateObj.getTime() / 1000);
registry.Write(regKey, ServiceUnavailableTime);
}
return ServiceUnavailableTime;
}

function MaskServiceAsUnavailable(ServiceName) {
arguments.callee.setAlias('MaskServiceAsUnavailable');
var regKey = GetServiceUnavailableRegistryKey(ServiceName) + IsServiceUnavailable;
var registry = new Registry();
if (!registry.IsKeyExists(regKey)) {
registry.Write(regKey, "1");
}
}


function ReturnServiceStateToOpsMgr(serviceState) {
var opsMgrAPI = new OpsMgrAPI();
logger.LogDebug(EVENT_ID, "Return to OpsMgr state of service = " + serviceState);
var propertyBag = opsMgrAPI.ScriptAPI.CreatePropertyBag();
propertyBag.AddValue("ServiceState", serviceState);
opsMgrAPI.ScriptAPI.AddItem(propertyBag);
opsMgrAPI.ScriptAPI.ReturnItems();
}

function IsServiceRunningState(CheckStartupType, StartMode, State) {

if ((CheckStartupType == "true" &amp;&amp; StartMode != AutoStartMode) || State == RunnningServiceState) {
return true;
}
return false;
}

function Main(ServiceName, CheckStartupType, ServiceUnavailableTime, StartMode, State) {
arguments.callee.setAlias('Main');
try {
if (!IsServiceRunningState(CheckStartupType, StartMode, State)) {
logger.LogDebug(EVENT_ID, "ServiceName = " + ServiceName + "; Service is not running...");
var ServiceUnavailableStartTime = GetServiceUnavailableStartTime(ServiceName);
var dateObj = new Date();
currentTime = parseInt(dateObj.getTime() / 1000);
if ((currentTime - ServiceUnavailableStartTime) &gt;= ServiceUnavailableTime) {
MaskServiceAsUnavailable(ServiceName);
ReturnServiceStateToOpsMgr("NotRunning")
}
else {
ReturnServiceStateToOpsMgr("Running")
}
}
else {
logger.LogDebug(EVENT_ID, "ServiceName = " + ServiceName + "; Service is running...");
ResetServiceState(ServiceName);
ReturnServiceStateToOpsMgr("Running")
}
}
catch (e) {
throw new Exception("Script '" + WScript.ScriptName + "' failed.", e);
}
}


var EVENT_ID = 4000;
var PARAMETER_CHECK_FAILED_EVENT_ID = 4002;
var logger = new Logger();
logger.LogDebug(EVENT_ID, "Start...")
if (WScript.Arguments.Count() != 5)
WScript.Quit();

var ServiceName = WScript.Arguments(0);
var CheckStartupType = WScript.Arguments(1);
var ServiceUnavailableTime = WScript.Arguments(2);
var StartMode = WScript.Arguments(3);
var State = WScript.Arguments(4);

if (CheckStartupType == null || CheckStartupType == "")
{
CheckStartupType = "true";
}
else if (CheckStartupType != "false" &amp;&amp; CheckStartupType != "true")
{
logger.LogError(PARAMETER_CHECK_FAILED_EVENT_ID, "CheckStartupType must be 'true' or 'false'.");
WScript.Quit();
}

ServiceUnavailableTime = parseInt(ServiceUnavailableTime);
if (ServiceUnavailableTime &lt; 0)
{
logger.LogError(PARAMETER_CHECK_FAILED_EVENT_ID, "ServiceUnavailableTime must be a non-negative integer.");
WScript.Quit();
}


logger.LogDebug(EVENT_ID, "ServiceName = " + ServiceName + "; CheckStartupType = " + CheckStartupType + "; ServiceUnavailableTime = " + ServiceUnavailableTime + "; StartMode = " + StartMode + "; State = " + State);

try {
Main(ServiceName, CheckStartupType, ServiceUnavailableTime, StartMode, State);
}
catch (e) {
logger.LogError(EVENT_ID, e.toString());
}
logger.LogDebug(EVENT_ID, "End...")
</Script></ScriptBody>
<TimeoutSeconds>300</TimeoutSeconds>
</ProbeAction>
</MemberModules>
<Composition>
<Node ID="PA"/>
</Composition>
</Composite>
</ModuleImplementation>
<OutputType>System!System.PropertyBagData</OutputType>
<InputType>System!System.BaseData</InputType>
</ProbeActionModuleType>