// This function configures the recovery options for a service,
// specified by name. It adds the two recovery options:
// 1) Restart the service on the first failure
// 2) Reboot the computer after the second failure.
// The procedure may be used for local or remote host.
// When used for local host TargetHost, UserName, Password parameters
// must be empty. For remote computer the parameters must be:
// TargetHost: name or IP address of the remote host, like '10.8.36.54'
// UserName: name of the user, may include domain, like 'MOON\Administrator';
// Password: the user's password.
// ServiceName: name of the service to start or stop.
// The function returns empty string on success, error description on failure.
function configure_service_recovery(TargetHost, UserName, Password,
ServiceName: string): string;
const
SECOND = 1;
MINUTE = SECOND * 60;
HOUR = MINUTE * 60;
var
ServiceMan: TNTServiceManager;
begin
Result := '';
ServiceMan := TNTServiceManager.Create(nil);
try
ServiceMan.LogonAs.UserName := UserName;
ServiceMan.LogonAs.Password := Password;
if TargetHost <> '' then ServiceMan.MachineName := '\\'+ TargetHost;
if (ServiceMan.MachineName <> '') and (ServiceMan.ConnectIPC <> 0) then
writeln('Warning: could not use the provided credentials.');
ServiceMan.ServiceName := ServiceName;
try
ServiceMan.ActiveManager := true;
ServiceMan.ActiveService := true;
ServiceMan.FailureOptions.Actions.Clear;
ServiceMan.FailureOptions.RebootMessage.Text :=
'The service '+ ServiceName + ' failed. Rebooting...';
ServiceMan.FailureOptions.ResetPeriod := 24 * HOUR;
// restart the service on a first failure
ServiceMan.FailureOptions.Actions.Add(SC_ACTION_RESTART, 2 * MINUTE * 1000);
// reboot the computer on the second failure
ServiceMan.FailureOptions.Actions.Add(SC_ACTION_REBOOT, 5 * MINUTE * 1000);
except
On e: ENTException do
begin
Result := e.message;
end;
end;
finally
ServiceMan.Free;
end;
end;
|