By David Wiseman (Administrator)Created 25 May 2012
My Rating:
Vote
Rating:
Not Rated
Views:4949
Downloads:19
Source:

Automatically Start AppFabric

Language:  PowerShell

Compatibility

Windows XP Unknown Windows 2003 Unknown
Windows 2000 No Windows NT No
Vista Unknown Windows 2008 Yes
Description

Automatically start AppFabric distributed cache service at startup with email notification


Notes

Overview

AppFabric is a distributed caching service that you can use to accelerate application performance.  You can read more about AppFabric here.
 
Although AppFabric runs as a service, the only supported way to start an AppFabric cluster or a particular host within a cluster is via PowerShell.  The purpose of this script is to start the AppFabrice caching service automatically after a reboot without any manual intervention.  The script will call the "Start-CacheCluster" command if no other hosts are running in the cluster, otherwise it will use the "Start-CacheHost" command to add the server back into the cluster.  The script will also send a notification email to let you know if the service started successfully and alert you if there was a problem starting the cache host.

Instructions

The default security policy prevents PowerShell scripts from been run, so the first step (if required) is to configure the security policy to allow the script to be run.  The following command can be used to change the execution policy.
 
Set-ExecutionPolicy RemoteSigned
 
 
 
Note: This needs to be run in an elevated (run as Administrator) powershell console.
 
Edit the config section of the script to specify your SMTP settings for email notification and save the script as  C:\StartAppFabricCacheHost.ps1
 
Open task scheduler and create a new task.  Change the task to run whether a user is logged on or not and run with highest priveleges.
 
 
  
 On the triggers tab, add a new trigger to run at startup.
 
 
 
On the actions tab configure the scheduled task to run PowerShell.exe (e.g. C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe) with the argument "C:\StartAppFabricCacheHost.ps1"
 
 
 
 You can now test that the task works by running the task manually or restarting the computer.  The AppFabric service should be started and an email notification should be delivered to your inbox.
 
Code

Line Numbers: On  Off      Plain Text
###########################Config###########################
$port = 22233 # default port of 22233 will be used to start AppFabric
$emailFrom = "noreply@wisesoft.local" # email notification sent from this address
$emailTo = "destination@wisesoft.local" #email notification sent to this address
$smtpServer = "MYSMTPHOST" # Name/IP of SMTP host used to send email notification
$MaxRetry = 3 #Max number of retry attempts if host fails to start
$RetryAfter = 10 #Retry after 10 seconds
############################################################
Import-Module DistributedCacheAdministration
Use-CacheCluster

#Get computer name
$hostname = gc env:computername 

$RetryCount = 0
# Keep trying to start AppFabric service until MaxRetry threshold is reached
while ($retryCount -le $MaxRetry) {
	if ($RetryCount -gt 0){
		"Host failed to start retry $RetryCount of $MaxRetry aftet $RetryAfter seconds..."
		# failed to start service so wait for a specified period of time before attempting retry
		Start-Sleep -s $RetryAfter
	}
	# Check if any hosts are running in the cluster
	$ActiveHostCount = (Get-CacheHost | where {$_.Status -eq "UP" -or $_.Status -eq "STARTING"} | Measure-Object).Count

	# Try to start the cache host/cluster
	try {
		IF ($ActiveHostCount -eq 0) {
			# No hosts are running in the cluster, start the cluster
			'Starting cache cluster...'
			Start-CacheCluster 
		}
		else {
			# Existing hosts are running in the cluster, start the cache host
			"Starting cache host $hostname..."
			Start-CacheHost -HostName $hostname -CachePort $port
		}
	}
	catch {
		$ErrorMsg = $_.Exception.ToString()
		$ErrorMsg
	}

	# Check the current host status (It should be "UP")
	$CurrentHostStatus = (Get-CacheHost -HostName $hostname -CachePort 22233).Status
	IF ($CurrentHostStatus -eq "UP" -or $CurrentHostStatus -eq "STARTING"){
		BREAK
	}
	$RetryCount +=1
}
# Finished starting AppFabric at this point. Generate email notification message
"Sending email notification..."

# Send either Success/Failed email notification based on status
 if ($CurrentHostStatus -ne 'UP') {
	$subject = "AppFabric Host '$HostName' failed to start"
	$NotificationMsg= "<div class='LargeErrorMsg'>AppFabric service on '$HostName' failed to start.  Status is '$CurrentHostStatus'</div><br/>
					<div class='ErrorMsg'>$ErrorMsg</div><br/>"
	$subject
 }
 else{
	$subject = "AppFabric Host '$HostName' started successfully"
	$NotificationMsg= "<div class='LargeNotification'>AppFabric service on '$HostName' started successfully.</div><br/>"
	$subject
 }

$smtp = new-object Net.Mail.SmtpClient($smtpServer)
$msg = New-Object Net.Mail.MailMessage($emailFrom,$EmailTo)
$msg.Subject = $subject

# Build HTML email body text
$body = "<html>
<head>
<head>
<style type='text/css'>
h1 {
color:#FFFFFF;
font:bold 16pt arial,sans-serif;
background-color:#204c7d;
text-align:center;
}
table {
font:8pt tahoma,arial,sans-serif;
}
body {
color:#000000;
font:8pt tahoma,arial,sans-serif;
margin:0px;
padding:0px;
}
th {
color:#FFFFFF;
font:bold 8pt tahoma,arial,sans-serif;
background-color:#204c7d;
padding-left:5px;
padding-right:5px;
}
td {
color:#000000;
font:8pt tahoma,arial,sans-serif;
border:1px solid #DCDCDC;
border-collapse:collapse;
padding-left:3px;
padding-right:3px;
}
.Warning {
background-color:#FFFF00; 
color:#2E2E2E;
}
.Critical {
background-color:#FF0000;
color:#FFFFFF;
}
.Healthy {
background-color:#458B00;
color:#FFFFFF;
}
.ErrorMsg{ 
	color:red
}
.LargeErrorMsg{
	color:red;
	font:bold 14pt arial,sans-serif;
}
.LargeNotification{
	color:Green;
	font:bold 14pt arial,sans-serif;
}
</head>
<body><h1>AppFabric service start notification</h1>
$NotificationMsg
<table><tr><th>Host</th><th>Status</th></tr>"

# HTML table generated to list each host in the cluster with the status (UP,DOWN etc)
ForEach($CacheHost in Get-CacheHost) {
	$class = switch ($CacheHost.Status) {"UP" {"Healthy"} "DOWN" {"Critical"} default {"Warning"} }
	$body += "<tr><td>{0}</td><td><span class='{1}'>{2}</span></td></tr>" -f $CacheHost.HostName,$class,$CacheHost.Status
}

$body+="</table></body></html>"
$msg.Body=$Body
$msg.IsBodyHTML=1
# Send email
$smtp.Send($msg)

 


Got a useful script? Click here to upload!


 

  Post Comment
Order By:  
User Comments
      
Be the first to post a comment!