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...

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...

Publish Binaries to Mapped Structure Groups

Today's TBB of the Week comes from the high demand in the field to publish binary assets to different mapped Structure Groups. By default SDL Tridion offers two ways of publishing binaries: All binaries publish to a folder defined in your Publication properties; All binaries rendered by a given template publish to a folder corresponding to a given Structure Group; In my view, both cases are terrible, over-simplified and not representing a real use-case. Nobody in the field wants all binaries in one folder and nobody separates binary locations by template. Instead, everybody wants a mapping mechanism that takes a binary and publishes it to a given folder, defined by a Structure Group, and this mapping is done using some kind of metadata. More often than not, the metadata is the TCM Folder location of the Multimedia Component. I have seen this implemented numerous times. So the solution to publish binaries to a given location implies finding a mapping from a TCM Folder to a...