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

Scaling Policies

This post is part of a bigger topic Autoscaling Publishers in AWS . In a previous post we talked about the Auto Scaling Groups , but we didn't go into details on the Scaling Policies. This is the purpose of this blog post. As defined earlier, the Scaling Policies define the rules according to which the group size is increased or decreased. These rules are based on instance metrics (e.g. CPU), CloudWatch custom metrics, or even CloudWatch alarms and their states and values. We defined a Scaling Policy with Steps, called 'increase_group_size', which is triggered first by the CloudWatch Alarm 'Publish_Alarm' defined earlier. Also depending on the size of the monitored CloudWatch custom metric 'Waiting for Publish', the Scaling Policy with Steps can add a difference number of instances to the group. The scaling policy sets the number of instances in group to 1 if there are between 1000 and 2000 items Waiting for Publish in the queue. It also sets the

Toolkit - Dynamic Content Queries

This post if part of a series about the  File System Toolkit  - a custom content delivery API for SDL Tridion. This post presents the Dynamic Content Query capability. The requirements for the Toolkit API are that it should be able to provide CustomMeta queries, pagination, and sorting -- all on the file system, without the use third party tools (database, search engines, indexers, etc). Therefore I had to implement a simple database engine and indexer -- which is described in more detail in post Writing My Own Database Engine . The querying logic does not make use of cache. This means the query logic is executed every time. When models are requested, the models are however retrieved using the ModelFactory and those are cached. Query Class This is the main class for dynamic content queries. It is the entry point into the execution logic of a query. The class takes as parameter a Criterion (presented below) which triggers the execution of query in all sub-criteria of a Criterio

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