Skip to content

Commit

Permalink
Merge pull request #183 from alemonmk/master
Browse files Browse the repository at this point in the history
Consul: new package params, au improvements
  • Loading branch information
flcdrg authored Aug 18, 2024
2 parents 31492ff + 3778d35 commit 29e8b8a
Show file tree
Hide file tree
Showing 4 changed files with 144 additions and 115 deletions.
16 changes: 13 additions & 3 deletions consul/consul.nuspec
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,19 @@ Consul is a tool for service discovery and configuration. Consul is distributed,
Uses NSSM as the service wrapper. More info at: https://nssm.cc/

#### Package Parameters
The package parameters can be set - https://www.consul.io/docs/agent/options.html
These parameters can be passed to the installer with the use of `-params`.
For example: `-params '-config-file="%PROGRAMDATA%\consul\dsc-config\default.json"'`.
The package parameters can be set -

* `/noservice` - Disables installation of Windows service
* `/apiaddr` - Sets environment variable `CONSUL_HTTP_ADDR` for easy execute commands on remote agent

These parameters can be passed to the installer with the use of `--params`.
For example: `--params="'/noservice /apiaddr=http://10.0.0.1:8500'"`.

#### Installer Arguments
Consul agent runtime options can also be set via `--ia`: https://developer.hashicorp.com/consul/docs/agent/config/cli-flags

For example: `--ia='-config-file ""%PROGRAMDATA%\consul\dsc-config\default.json/"" -client 10.0.0.1'`
Or better, drop a `config.hcl` into `%PROGRAMDATA%\consul\config` with your configuration.
</description><releaseNotes><![CDATA[### 1.19.1 (July 11, 2024)
SECURITY:
Expand Down
204 changes: 108 additions & 96 deletions consul/tools/chocolateyInstall.ps1
Original file line number Diff line number Diff line change
@@ -1,107 +1,119 @@
if (Test-Path Function:\au_GetLatest) {
return
# Defaults
$toolsPath = Split-Path -Parent $MyInvocation.MyCommand.Definition
$packageParameters = Get-PackageParameters

# Download and unzip consul
$package = @{
PackageName = 'consul'
Url = 'https://releases.hashicorp.com/consul/1.19.1/consul_1.19.1_windows_386.zip'
Url64bit = 'https://releases.hashicorp.com/consul/1.19.1/consul_1.19.1_windows_amd64.zip'
UnzipLocation = $toolsPath
Checksum = '5e6cc24d3219c1c331f9b39ade2961b9948c86e254a214751b921b4027f168a5'
Checksum64 = 'a33bed52d6004c956b5b9a1fa6659477a32db14a07d37425f9ed96a6b1eaeae2'
ChecksumType = 'sha256'
}
Install-ChocolateyZipPackage @package

# Defaults
$serviceName = "consul"
$binariesPath = Split-Path -parent $MyInvocation.MyCommand.Definition
$toolsPath = Split-Path -Parent $MyInvocation.MyCommand.Definition
$wrapperExe = "$env:ChocolateyInstall\bin\nssm.exe"
$serviceInstallationDirectory = "$env:PROGRAMDATA\consul"
$serviceLogDirectory = "$serviceInstallationDirectory\logs"
$serviceConfigDirectory = "$serviceInstallationDirectory\config"
$serviceDataDirectory = "$serviceInstallationDirectory\data"

$packageParameters = $env:chocolateyPackageParameters
if (-not ($packageParameters)) {
$packageParameters = ""
Write-Debug "No Package Parameters Passed in"
# Install Env CONSUL_HTTP_ADDR
if ($packageParameters["apiaddr"] -ne "") {
Install-ChocolateyEnvironmentVariable "CONSUL_HTTP_ADDR" $packageParameters["apiaddr"]
}

# Create Service Directories
Write-Host "Creating $serviceLogDirectory"
New-Item -ItemType directory -Path "$serviceLogDirectory" -ErrorAction SilentlyContinue | Out-Null
Write-Host "Creating $serviceConfigDirectory"
New-Item -ItemType directory -Path "$serviceConfigDirectory" -ErrorAction SilentlyContinue | Out-Null

# Unzip and move Consul
Get-ChocolateyUnzip -fileFullPath $(Join-Path $binariesPath "consul_$($env:ChocolateyPackageVersion)_windows_386.zip") -fileFullPath64 $(Join-Path $binariesPath "consul_$($env:ChocolateyPackageVersion)_windows_amd64.zip") -destination "$toolsPath"

# Create event log source
# User -Force to avoid "A key at this path already exists" exception. Overwrite not an issue since key is not further modified
$registryPath = 'HKLM:\SYSTEM\CurrentControlSet\services\eventlog\Application'
New-Item -Path $registryPath -Name consul -Force | Out-Null
# Set EventMessageFile value
Set-ItemProperty $registryPath\consul EventMessageFile "C:\Windows\Microsoft.NET\Framework64\v2.0.50727\EventLogMessages.dll" | Out-Null

# Set up task scheduler for log rotation
$logrotate = ('%SYSTEMROOT%\System32\forfiles.exe /p \"{0}\" /s /m *.* /c \"cmd /c Del @path\" /d -7' -f "$serviceLogDirectory")
SchTasks.exe /Create /SC DAILY /TN ""ConsulLogrotate"" /TR ""$($logrotate)"" /ST 09:00 /F | Out-Null

# Set up task scheduler for log rotation. Only works for Powershell 4 or Server 2012R2 so this block can replace
# using SchTasks.exe for registering services once machines have retired the older version of PS or upgraded to 2012R2
#$command = ('$now = Get-Date; dir "{0}" | where {{$_.LastWriteTime -le $now.AddDays(-7)}} | del -whatif' -f $serviceLogDirectory)
#$action = New-ScheduledTaskAction -Execute 'Powershell.exe' -Argument "-NoProfile -WindowStyle Hidden -command $($command)"
#$trigger = New-ScheduledTaskTrigger -Daily -At 9am
#Register-ScheduledTask -Action $action -Trigger $trigger -TaskName "ConsulLogrotate" -Description "Log rotation for consul"

#Uninstall service if it already exists. Stops the service first if it's running
$service = Get-Service $serviceName -ErrorAction SilentlyContinue
if ($service) {
Write-Host "Uninstalling existing service"
if($service.Status -ne "Stopped" -and $service.Status -ne "Stopping") {
Write-Host "Stopping consul process ..."
$service.Stop();
# Default to install with Windows service
if (-not ($packageParameters["noservice"])) {
$serviceName = "consul"
$wrapperExe = "$env:ChocolateyInstall\bin\nssm.exe"
$serviceInstallationDirectory = "$env:PROGRAMDATA\consul"
$serviceLogDirectory = "$serviceInstallationDirectory\logs"
$serviceConfigDirectory = "$serviceInstallationDirectory\config"
$serviceDataDirectory = "$serviceInstallationDirectory\data"
$installArguments = $env:chocolateyInstallArguments
if (-not ($installArguments)) {
$installArguments = ""
}

$service.WaitForStatus("Stopped", (New-TimeSpan -Minutes 1));
if($service.Status -ne "Stopped") {
throw "$serviceName could not be stopped within the allotted timespan. Stop the service and try again."
# Create Service Directories
Write-Host "Creating $serviceLogDirectory"
New-Item -ItemType directory -Path "$serviceLogDirectory" -ErrorAction SilentlyContinue | Out-Null
Write-Host "Creating $serviceConfigDirectory"
New-Item -ItemType directory -Path "$serviceConfigDirectory" -ErrorAction SilentlyContinue | Out-Null

# Create event log source
# User -Force to avoid "A key at this path already exists" exception. Overwrite not an issue since key is not further modified
$registryPath = 'HKLM:\SYSTEM\CurrentControlSet\services\eventlog\Application'
New-Item -Path $registryPath -Name consul -Force | Out-Null
# Set EventMessageFile value
Set-ItemProperty $registryPath\consul EventMessageFile "C:\Windows\Microsoft.NET\Framework64\v2.0.50727\EventLogMessages.dll" | Out-Null

# Set up task scheduler for log rotation
$logrotate = ('%SYSTEMROOT%\System32\forfiles.exe /p \"{0}\" /s /m *.* /c \"cmd /c Del @path\" /d -7' -f "$serviceLogDirectory")
SchTasks.exe /Create /SC DAILY /TN ""ConsulLogrotate"" /TR ""$($logrotate)"" /ST 09:00 /F | Out-Null

# Set up task scheduler for log rotation. Only works for Powershell 4 or Server 2012R2 so this block can replace
# using SchTasks.exe for registering services once machines have retired the older version of PS or upgraded to 2012R2
#$command = ('$now = Get-Date; dir "{0}" | where {{$_.LastWriteTime -le $now.AddDays(-7)}} | del -whatif' -f $serviceLogDirectory)
#$action = New-ScheduledTaskAction -Execute 'Powershell.exe' -Argument "-NoProfile -WindowStyle Hidden -command $($command)"
#$trigger = New-ScheduledTaskTrigger -Daily -At 9am
#Register-ScheduledTask -Action $action -Trigger $trigger -TaskName "ConsulLogrotate" -Description "Log rotation for consul"

#Uninstall service if it already exists. Stops the service first if it's running
$service = Get-Service $serviceName -ErrorAction SilentlyContinue
if ($service) {
Write-Host "Uninstalling existing service"
if ($service.Status -ne "Stopped" -and $service.Status -ne "Stopping") {
Write-Host "Stopping consul process ..."
$service.Stop();
}

$service.WaitForStatus("Stopped", (New-TimeSpan -Minutes 1));
if ($service.Status -ne "Stopped") {
throw "$serviceName could not be stopped within the allotted timespan. Stop the service and try again."
}

$service = Get-WmiObject -Class Win32_Service -Filter "Name='$serviceName'"
$service.delete() | Out-Null
}

$service = Get-WmiObject -Class Win32_Service -Filter "Name='$serviceName'"
$service.delete() | Out-Null
}

Write-Host "Installing service: $serviceName"
# Install the service
& $wrapperExe install $serviceName $(Join-Path $toolsPath "consul.exe") "agent -ui -config-dir=$serviceConfigDirectory -data-dir=$serviceDataDirectory $packageParameters" | Out-Null
& $wrapperExe set $serviceName AppEnvironmentExtra GOMAXPROCS=$env:NUMBER_OF_PROCESSORS | Out-Null
& $wrapperExe set $serviceName ObjectName NetworkService | Out-Null
& $wrapperExe set $serviceName AppStdout "$serviceLogDirectory\consul-output.log" | Out-Null
& $wrapperExe set $serviceName AppStderr "$serviceLogDirectory\consul-error.log" | Out-Null
& $wrapperExe set $serviceName AppRotateBytes 10485760 | Out-Null
& $wrapperExe set $serviceName AppRotateFiles 1 | Out-Null
& $wrapperExe set $serviceName AppRotateOnline 1 | Out-Null

Write-Verbose "Service installed"

# When nssm fully supports Rotate/Post Event hooks
# $command = ('$now = Get-Date; dir "{0}" | where {{$_.LastWriteTime -le $now.AddDays(-7)}} | del -whatif' -f $serviceLogDirectory)
# $action = ("Powershell.exe -NoProfile -WindowStyle Hidden -command '$({{0}})'" -f $command)
# & $wrapperExe set consul AppEvents "Rotate/Post" $action | Out-Null

# Restart service on failure natively via Windows sc. There is a memory leak if service restart is performed via NSSM
# The NSSM configuration will set the default behavior of NSSM to stop the service if
# consul fails (for example, unable to resolve cluster) and end the nssm.exe and consul.exe process.
# The sc configuration will set Recovery under the Consul service properties such that a new instance will be started on failure,
# spawning new nssm.exe and consul.exe processes. In short, nothing changed from a functionality perspective (the service will
# still attempt to restart on failure) but this method kills the nssm.exe process thus avoiding memory hog.
& $wrapperExe set $serviceName AppExit Default Exit | Out-Null
Write-Verbose "sc failure"
cmd.exe /c "sc failure $serviceName reset= 0 actions= restart/60000" | Out-Null

Write-Verbose "Stop service"
# Let this call to Get-Service throw if the service does not exist
$service = Get-Service $serviceName
if($service.Status -ne "Stopped" -and $service.Status -ne "Stopping") {
$service.Stop()
}
Write-Host "Installing service: $serviceName"
# Install the service
& $wrapperExe install $serviceName $(Join-Path $toolsPath "consul.exe") "agent -ui -config-dir=$serviceConfigDirectory -data-dir=$serviceDataDirectory $installArguments" | Out-Null
& $wrapperExe set $serviceName AppEnvironmentExtra GOMAXPROCS=$env:NUMBER_OF_PROCESSORS | Out-Null
& $wrapperExe set $serviceName ObjectName NetworkService | Out-Null
& $wrapperExe set $serviceName AppStdout "$serviceLogDirectory\consul-output.log" | Out-Null
& $wrapperExe set $serviceName AppStderr "$serviceLogDirectory\consul-error.log" | Out-Null
& $wrapperExe set $serviceName AppRotateBytes 10485760 | Out-Null
& $wrapperExe set $serviceName AppRotateFiles 1 | Out-Null
& $wrapperExe set $serviceName AppRotateOnline 1 | Out-Null

Write-Verbose "Service installed"

# When nssm fully supports Rotate/Post Event hooks
# $command = ('$now = Get-Date; dir "{0}" | where {{$_.LastWriteTime -le $now.AddDays(-7)}} | del -whatif' -f $serviceLogDirectory)
# $action = ("Powershell.exe -NoProfile -WindowStyle Hidden -command '$({{0}})'" -f $command)
# & $wrapperExe set consul AppEvents "Rotate/Post" $action | Out-Null

# Restart service on failure natively via Windows sc. There is a memory leak if service restart is performed via NSSM
# The NSSM configuration will set the default behavior of NSSM to stop the service if
# consul fails (for example, unable to resolve cluster) and end the nssm.exe and consul.exe process.
# The sc configuration will set Recovery under the Consul service properties such that a new instance will be started on failure,
# spawning new nssm.exe and consul.exe processes. In short, nothing changed from a functionality perspective (the service will
# still attempt to restart on failure) but this method kills the nssm.exe process thus avoiding memory hog.
& $wrapperExe set $serviceName AppExit Default Exit | Out-Null
Write-Verbose "sc failure"
cmd.exe /c "sc failure $serviceName reset= 0 actions= restart/60000" | Out-Null

Write-Verbose "Stop service"
# Let this call to Get-Service throw if the service does not exist
$service = Get-Service $serviceName
if ($service.Status -ne "Stopped" -and $service.Status -ne "Stopping") {
$service.Stop()
}

Write-Verbose "Wait for service to stop"
$service.WaitForStatus("Stopped", (New-TimeSpan -Minutes 1));
Write-Verbose "Wait for service to stop"
$service.WaitForStatus("Stopped", (New-TimeSpan -Minutes 1));

Write-Verbose "Start service"
Start-Service $serviceName
Write-Verbose "Start service"
Start-Service $serviceName

Write-Host "Installed service: $serviceName"
Write-Host "Installed service: $serviceName"
}
18 changes: 11 additions & 7 deletions consul/tools/chocolateyUninstall.ps1
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
if (Test-Path env:CONSUL_HTTP_ADDR) {
Uninstall-ChocolateyEnvironmentVariable "CONSUL_HTTP_ADDR"
}

$service = Get-Service "consul" -ErrorAction SilentlyContinue

if ($service) {
Expand All @@ -8,11 +12,11 @@ if ($service) {

$service = Get-WmiObject -Class Win32_Service -Filter "Name='consul'"
$service.delete() | Out-Null
}

SchTasks.exe /Delete /F /TN "ConsulLogrotate" 2>&1 | Out-Null

SchTasks.exe /Delete /F /TN "ConsulLogrotate" 2>&1 | Out-Null

Write-Host "Removing C:\ProgramData\consul\ ..."
takeown /f "C:\ProgramData\consul\" /a /r /d Y | Out-Null
icacls "C:\ProgramData\consul" /grant administrators:F /t | Out-Null
Remove-Item -Path "C:\ProgramData\consul\" -Force -Recurse -ErrorAction SilentlyContinue | Out-Null
Write-Host "Removing C:\ProgramData\consul\ ..."
takeown /f "C:\ProgramData\consul\" /a /r /d Y | Out-Null
icacls "C:\ProgramData\consul" /grant administrators:F /t | Out-Null
Remove-Item -Path "C:\ProgramData\consul\" -Force -Recurse -ErrorAction SilentlyContinue | Out-Null
}
21 changes: 12 additions & 9 deletions consul/update.ps1
Original file line number Diff line number Diff line change
@@ -1,15 +1,18 @@
Import-Module chocolatey-au

function global:au_SearchReplace {
@{ }
@{
'tools\chocolateyinstall.ps1' = @{
"(\t*Url\s*=\s*)('.*')" = "`$1'$($Latest.Url32)'"
"(\t*Url64bit\s*=\s*)('.*')" = "`$1'$($Latest.Url64)'"
"(\t*Checksum\s*=\s*)('.*')" = "`$1'$($Latest.Checksum32)'"
"(\t*Checksum64\s*=\s*)('.*')" = "`$1'$($Latest.Checksum64)'"
}
}
}

. ../_scripts/GitHub.ps1

function global:au_BeforeUpdate() {
Get-RemoteFiles -Purge -NoSuffix
}

function global:au_GetLatest {
# This repo has releases for the cli tool as well as VS Code vsix
$release = Get-GitHubLatestRelease "hashicorp/consul"
Expand All @@ -25,9 +28,9 @@ function global:au_GetLatest {
}

$Latest = @{
Version = $version
Url32 = "https://releases.hashicorp.com/consul/$version/consul_$($version)_windows_386.zip"
Url64 = "https://releases.hashicorp.com/consul/$version/consul_$($version)_windows_amd64.zip"
Version = $version
Url32 = "https://releases.hashicorp.com/consul/$version/consul_$($version)_windows_386.zip"
Url64 = "https://releases.hashicorp.com/consul/$version/consul_$($version)_windows_amd64.zip"
ReleaseNotes = $release.body.Replace("# ", "## ") # Increase heading levels
}
return $Latest
Expand All @@ -37,4 +40,4 @@ function global:au_AfterUpdate ($Package) {
Update-ReleaseNotes $Package
}

update
update

0 comments on commit 29e8b8a

Please sign in to comment.