Skip to main content

sdl-healthcheck as Windows Service

This post describes how to convert the 'sdl-healthcheck' application to a Windows Service.

SDL-healthcheck is a Java application that creates a webservice around the SDL Web microservices in order to provide monitoring (heart beat) checks on them. Mark van der Wal wrote the application and provided startup and stop Shell scripts.

My requirement was to have the same application installable and executable as Windows Service.

Therefore, I had to wrap the Java application inside a service container and provide start, stop hooks for the service. I know that SDL Web Content Delivery microservices are also Java applications using Spring Boot, so my approach was to use the same mechanism to make the Java application run as Windows Service.

The service container used is 'procrun.exe' daemon from Apache Commons. Depending on the arguments passed to it, it can perform different Windows Service functionality such as install, remove service, start/stop service.

I ended up hacking together the installService PowerShell scripts from the CD microservices and they look like the ones below. One trick was to provide a StopClass and StopParams to the service. If a service should finish gracefully, then it should be programmed to do so. But I saw Mark was simply killing the process on his stop.sh script, so I ended up just calling java.lang.System.exit() method. This ensues the services stops when it is requested to do so.

installService.ps1

$jvmoptions = "-Xrs", "-Xms48m", "-Xmx128m", "-Dfile.encoding=UTF-8"

$currentFolder = Get-Location
$name="SDLHealthcheck"
$displayName="SDL Healthcheck"
$description="SDL Healthcheck"
$dependsOn=""
$path=$PSScriptRoot
cd $path\..
$rootFolder = Get-Location
$procrun="procrun.exe"
$application=$path + "\" + $procrun
$fullPath=$path + "\" + $procrun

$arguments = @()
$arguments += "//IS//" + $name
$arguments += "--DisplayName=" + $displayName
$arguments += "--Description=" + $description
$arguments += "--Install=" + $fullPath
$arguments += "--Jvm=auto"
$arguments += "--Startup=auto"
$arguments += "--LogLevel=Info"
$arguments += "--StartMode=jvm"
$arguments += "--StartPath=" + $rootFolder
$arguments += "--StartClass=org.springframework.boot.loader.JarLauncher"
$arguments += "--StartParams=start"
$arguments += "--StopMode=jvm"
$arguments += "--StopClass=java.lang.System"
$arguments += "--StopParams=exit"

$classpath = ".\bin\*;.\lib\*;.\addons\*;.\config"
foreach ($folder in Get-ChildItem -path $rootFolder -recurse | ?{ $_.PSIsContainer } | Resolve-Path -relative | Where { $_ -match 'services*' })
{
    $classpath = $folder + ";" + $folder + "\*;" + $classpath
}
$arguments += "--Classpath=" + $classpath

# Check script is launched with Administrator permissions
$isAdministrator = ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")
if ($isAdministrator -eq $False) {
    $Host.UI.WriteErrorLine("ERROR: Please ensure script is launched with Administrator rights")
    Exit
}

Try {
    Write-Host "Installing '$name' as windows service..." -ForegroundColor Green
    if (Get-Service $name -ErrorAction SilentlyContinue) {
        Write-Warning "Service '$name' already exists in system."
    } else {
        & $application $arguments
        Start-Sleep -s 3

        if (Get-Service $name -ErrorAction SilentlyContinue) {
            Write-Host "Service '$name' successfully installed." -ForegroundColor Green
        } else {
            $Host.UI.WriteErrorLine("ERROR: Unable to create the service '" + $name + "'")
            Exit
        }
    }

    if ((Get-Service $name -ErrorAction SilentlyContinue).Status -ne "Running") {
        Write-Host "Starting service '$name'..." -ForegroundColor Green
        & sc.exe start $name
    } else {
        Write-Host "Service '$name' already started." -ForegroundColor Green
    }
} Finally {
    cd $currentFolder
}



uninstallService.ps1

The following script will stop the service and then remove it:

function waitServiceStop {
    param (
        [string]$svcName
    )
    $svc = Get-Service $svcName
    # Wait for 30s
    $svc.WaitForStatus('Stopped', '00:00:30')
    if ($svc.Status -ne 'Stopped') {
        $Host.UI.WriteErrorLine("ERROR: Not able to stop service " + $serviceName)
    } else {
        Write-Host "Service '$serviceName' is stopped." -ForegroundColor Green
    }
}


# Check script is launched with Administrator permissions
$isAdministrator = ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")
if ($isAdministrator -eq $False) {
    $Host.UI.WriteErrorLine("ERROR: Please ensure script is launched with Administrator rights")
    Exit
}

$currentFolder = Get-Location
$defaultServiceName="SDLHealthcheck"

try {
    $scriptPath=$PSScriptRoot
    cd $scriptPath\.. 
    $rootFolder = Get-Location

    $serviceName = $defaultServiceName

    if (-Not (Get-Service $serviceName -ErrorAction SilentlyContinue)) {
        $Host.UI.WriteErrorLine("ERROR: There is no service with name " + $serviceName)
        Exit
    }

    Write-Host "Stopping service '$serviceName'..." -ForegroundColor Green
    & sc.exe stop $serviceName
    waitServiceStop $serviceName

    Write-Host "Removing service '$serviceName'..." -ForegroundColor Green
    & sc.exe delete $serviceName
    if (-Not (Get-Service $serviceName -ErrorAction SilentlyContinue)) {
        Write-Host "Service '$serviceName' successfully removed." -ForegroundColor Green
    }
} Finally {
    cd $currentFolder
}




Comments

Popular posts from this blog

Running sp_updatestats on AWS RDS database

Part of the maintenance tasks that I perform on a MSSQL Content Manager database is to run stored procedure sp_updatestats . exec sp_updatestats However, that is not supported on an AWS RDS instance. The error message below indicates that only the sa  account can perform this: Msg 15247 , Level 16 , State 1 , Procedure sp_updatestats, Line 15 [Batch Start Line 0 ] User does not have permission to perform this action. Instead there are several posts that suggest using UPDATE STATISTICS instead: https://dba.stackexchange.com/questions/145982/sp-updatestats-vs-update-statistics I stumbled upon the following post from 2008 (!!!), https://social.msdn.microsoft.com/Forums/sqlserver/en-US/186e3db0-fe37-4c31-b017-8e7c24d19697/spupdatestats-fails-to-run-with-permission-error-under-dbopriveleged-user , which describes a way to wrap the call to sp_updatestats and execute it under a different user: create procedure dbo.sp_updstats with execute as 'dbo' as...

I Have Gone Dark

Maybe it's the Holidays, but my mood has gone pretty dark. That is, regarding the look and feel of my computer and Tridion CME, of course. What I did was to dim the lights on the operating system, so I installed Placebo themes for Windows 7 . I went for the Ashtray look -- great name :) My VM looks now like this: But, once you change the theme on Windows, you should 'match' the theme of your applications. Some skin easily, some not. The Office suite has an in-built scheme, which can be set to Black , but it doesn't actually dim the ribbon tool bars -- it looks quite weird. Yahoo Messenger is skinnable, but you can't change the big white panels where you actually 'chat'. Skype is not skinnable at all. For Chrome, there are plenty of grey themes. Now i'm using Pro Grey . But then I got into changing the theme of websites. While very few offer skinnable interfaces (as GMail does), I had to find a way to darken the websites... Enter Stylish -- a pl...

REL Standard Tag Library

The RSTL is a library of REL tags providing standard functionality such as iterating collections, conditionals, imports, assignments, XML XSLT transformations, formatting dates, etc. RSTL distributable is available on my Google Code page under  REL Standard Tag Library . Always use the latest JAR . This post describes each RSTL tag in the library explaining its functionality, attributes and providing examples. For understanding the way expressions are evaluated, please read my post about the  Expression Language used by REL Standard Tag Library . <c:choose> / <c:when> / <c:otherwise> Syntax:     <c:choose>         <c:when test="expr1">             Do something         </c:when>         <c:when test="expr2">             Do something else         </c:when...