ps/Modules/Alkami.PowerShell.Services/Public/Restart-Nag.ps1
2023-05-30 22:51:22 -07:00

72 lines
2.4 KiB
PowerShell

function Restart-Nag {
<#
.SYNOPSIS
Checks Running Jobs and Restarts Nag When Safe to Do So
.PARAMETER threshold
Alias: Minutes
The number of minutes in the future to check for scheduled jobs
.PARAMETER forceRecycle
Alias: Force
Force recycle even if jobs are running or scheduled within the cutoff time
#>
[CmdletBinding()]
Param(
[Parameter(Mandatory = $false)]
[Alias("Minutes")]
[int]$threshold = 5,
[Parameter(Mandatory = $false)]
[Alias("Force")]
[switch]$forceRecycle
)
$canRecycle = $false
$hostName = Get-Host
$logLead = (Get-LogLeadName);
$skipJobCheck = $forceRecycle.IsPresent
$userName = Get-ChildItem env:USERNAME
$nagService = Get-Service | Where-Object {$_.Name -match "Alkami.Nag"}
# If the Nag service isn't found or is disabled, warn and return
if ($null -eq $nagService) {
Write-Warning ("$logLead : The Alkami Nag Service could not be located")
return
} elseif ($nagService.StartType -eq "Disabled") {
Write-Warning ("$logLead : The Alkami Nag Service is disabled and cannot be restarted")
return
} elseif ($userName.Value -match "ANONYMOUS") {
Write-Warning ("$logLead : Anonymous users cannot query the database. This function cannot be executed under the current user context")
return
} elseif ($hostName.Name -match "Chocolatey_PSHost" -and !$skipJobCheck) {
Write-Warning ("$logLead : You can't run this from Chocolatey without the -Force flag because we don't know if this is a local or remote session")
return
}
# If the Nag Service is already stopped, we don't need to check if we can shut it down
if ($nagService.Status -eq [System.ServiceProcess.ServiceControllerStatus]::Stopped) {
$skipJobCheck = $true
}
if (!$skipJobCheck) {
$canRecycle = Test-AreCriticalNagJobsRunning $threshold
} else {
Write-Verbose ("$logLead : Force Recycle Flag Passed or Service Was Already Stopped")
$canRecycle = $true
}
if ($canRecycle) {
# Recycle the service
Write-Output "$logLead : Recycling Nag Service"
Stop-AlkamiService -ServiceName $nagService.Name -Seconds 45
Start-Service -name $nagService.name
} else {
# Warn that we cannot recycle the service
Write-Warning ("$logLead : Cannot recycle {0} due to running or scheduled jobs" -f $nagService.Name)
}
}