Debian Codegraph @

ansible_collections/community/windows/plugins/modules/win_nssm.ps1

raw
1 #!powershell
2
3 # Copyright: (c) 2015, George Frank <[email protected]>
4 # Copyright: (c) 2015, Adam Keech <[email protected]>
5 # Copyright: (c) 2015, Hans-Joachim Kliemeck <[email protected]>
6 # Copyright: (c) 2019, Kevin Subileau (@ksubileau)
7 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
8
9 #Requires -Module Ansible.ModuleUtils.Legacy
10 #Requires -Module Ansible.ModuleUtils.ArgvParser
11 #Requires -Module Ansible.ModuleUtils.CommandUtil
12
13 $ErrorActionPreference = "Stop"
14
15 $start_modes_map = @{
16 "auto" = "SERVICE_AUTO_START"
17 "delayed" = "SERVICE_DELAYED_AUTO_START"
18 "manual" = "SERVICE_DEMAND_START"
19 "disabled" = "SERVICE_DISABLED"
20 }
21
22 $params = Parse-Args -arguments $args -supports_check_mode $true
23 $check_mode = Get-AnsibleParam -obj $params -name "_ansible_check_mode" -type "bool" -default $false
24 $diff_mode = Get-AnsibleParam -obj $params -name "_ansible_diff" -type "bool" -default $false
25
26 $name = Get-AnsibleParam -obj $params -name "name" -type "str" -failifempty $true
27 $state_options = "present", "absent", "started", "stopped", "restarted"
28 $state = Get-AnsibleParam -obj $params -name "state" -type "str" -default "present" -validateset $state_options -resultobj $result
29 $display_name = Get-AnsibleParam -obj $params -name 'display_name' -type 'str'
30 $description = Get-AnsibleParam -obj $params -name 'description' -type 'str'
31
32 $application = Get-AnsibleParam -obj $params -name "application" -type "path"
33 $appDirectory = Get-AnsibleParam -obj $params -name "working_directory" -aliases "app_directory", "chdir" -type "path"
34 $appArguments = Get-AnsibleParam -obj $params -name "arguments" -aliases "app_parameters_free_form"
35
36 $stdoutFile = Get-AnsibleParam -obj $params -name "stdout_file" -type "path"
37 $stderrFile = Get-AnsibleParam -obj $params -name "stderr_file" -type "path"
38
39 $executable = Get-AnsibleParam -obj $params -name "executable" -type "path" -default "nssm.exe"
40
41 $app_env = Get-AnsibleParam -obj $params -name "app_environment" -type "dict"
42
43 $app_rotate_bytes = Get-AnsibleParam -obj $params -name "app_rotate_bytes" -type "int" -default 104858
44 $app_rotate_online = Get-AnsibleParam -obj $params -name "app_rotate_online" -type "int" -default 0 -validateset 0, 1
45 $app_stop_method_console = Get-AnsibleParam -obj $params -name "app_stop_method_console" -type "int"
46 $app_stop_method_skip = Get-AnsibleParam -obj $params -name "app_stop_method_skip" -type "int" -validateset 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15
47
48 $startMode = Get-AnsibleParam -obj $params -name "start_mode" -type "str" -default "auto" -validateset $start_modes_map.Keys -resultobj $result
49 $dependencies = Get-AnsibleParam -obj $params -name "dependencies" -type "list"
50 $user = Get-AnsibleParam -obj $params -name "username" -type "str" -aliases "user"
51 $password = Get-AnsibleParam -obj $params -name "password" -type "str"
52
53 $result = @{
54 changed = $false
55 }
56 $diff_text = $null
57
58 function Invoke-NssmCommand {
59 [CmdletBinding()]
60 param(
61 [Parameter(Mandatory = $true, ValueFromRemainingArguments = $true)]
62 [string[]]$arguments
63 )
64
65 $command = Argv-ToString -arguments (@($executable) + $arguments)
66 $result = Run-Command -command $command
67
68 $result.arguments = $command
69
70 return $result
71 }
72
73 function Get-NssmServiceStatus {
74 [CmdletBinding()]
75 param(
76 [Parameter(Mandatory = $true)]
77 [string]$service
78 )
79
80 return Invoke-NssmCommand -arguments @("status", $service)
81 }
82
83 function Get-NssmServiceParameter {
84 [CmdletBinding()]
85 param(
86 [Parameter(Mandatory = $true)]
87 [string]$service,
88 [Parameter(Mandatory = $true)]
89 [Alias("param")]
90 [string]$parameter,
91 [Parameter(Mandatory = $false)]
92 [string]$subparameter
93 )
94
95 $arguments = @("get", $service, $parameter)
96 if ($subparameter -ne "") {
97 $arguments += $subparameter
98 }
99 return Invoke-NssmCommand -arguments $arguments
100 }
101
102 function Set-NssmServiceParameter {
103 [CmdletBinding()]
104 param(
105 [Parameter(Mandatory = $true)]
106 [string]$service,
107 [Parameter(Mandatory = $true)]
108 [string]$parameter,
109 [Parameter(Mandatory = $true, ValueFromRemainingArguments = $true)]
110 [Alias("value")]
111 [string[]]$arguments
112 )
113
114 return Invoke-NssmCommand -arguments (@("set", $service, $parameter) + $arguments)
115 }
116
117 function Reset-NssmServiceParameter {
118 [CmdletBinding()]
119 param(
120 [Parameter(Mandatory = $true)]
121 [string]$service,
122 [Parameter(Mandatory = $true)]
123 [Alias("param")]
124 [string]$parameter
125 )
126
127 return Invoke-NssmCommand -arguments @("reset", $service, $parameter)
128 }
129
130 function Update-NssmServiceParameter {
131 <#
132 .SYNOPSIS
133 A generic cmdlet to idempotently set a nssm service parameter.
134 .PARAMETER service
135 [String] The service name
136 .PARAMETER parameter
137 [String] The name of the nssm parameter to set.
138 .PARAMETER arguments
139 [String[]] Target value (or list of value) or array of arguments to pass to the 'nssm set' command.
140 .PARAMETER compare
141 [scriptblock] An optionnal idempotency check scriptblock that must return true when
142 the current value is equal to the desired value. Usefull when 'nssm get' doesn't return
143 the same value as 'nssm set' takes in argument, like for the ObjectName parameter.
144 #>
145 [CmdletBinding(SupportsShouldProcess = $true)]
146 param(
147 [Parameter(Mandatory = $true)]
148 [string]$service,
149
150 [Parameter(Mandatory = $true)]
151 [string]$parameter,
152
153 [Parameter(Mandatory = $true, ValueFromRemainingArguments = $true)]
154 [AllowEmptyString()]
155 [AllowNull()]
156 [Alias("value")]
157 [string[]]$arguments,
158
159 [Parameter()]
160 [scriptblock]$compare = { param($actual, $expected) @(Compare-Object -ReferenceObject $actual -DifferenceObject $expected).Length -eq 0 }
161 )
162
163 if ($null -eq $arguments) { return }
164 $arguments = @($arguments | Where-Object { $_ -ne '' })
165
166 $nssm_result = Get-NssmServiceParameter -service $service -parameter $parameter
167
168 if ($nssm_result.rc -ne 0) {
169 $result.nssm_error_cmd = $nssm_result.arguments
170 $result.nssm_error_log = $nssm_result.stderr
171 Fail-Json -obj $result -message "Error retrieving $parameter for service ""$service"""
172 }
173
174 $current_values = @($nssm_result.stdout.split("`n`r") | Where-Object { $_ -ne '' })
175
176 if (-not $compare.Invoke($current_values, $arguments)) {
177 if ($PSCmdlet.ShouldProcess($service, "Update '$parameter' parameter")) {
178 if ($arguments.Count -gt 0) {
179 $nssm_result = Set-NssmServiceParameter -service $service -parameter $parameter -arguments $arguments
180 }
181 else {
182 $nssm_result = Reset-NssmServiceParameter -service $service -parameter $parameter
183 }
184
185 if ($nssm_result.rc -ne 0) {
186 $result.nssm_error_cmd = $nssm_result.arguments
187 $result.nssm_error_log = $nssm_result.stderr
188 Fail-Json -obj $result -message "Error setting $parameter for service ""$service"""
189 }
190 }
191
192 $script:diff_text += "-$parameter = $($current_values -join ', ')`n+$parameter = $($arguments -join ', ')`n"
193 $result.changed_by = $parameter
194 $result.changed = $true
195 }
196 }
197
198 function Test-NssmServiceExist {
199 [CmdletBinding()]
200 param(
201 [Parameter(Mandatory = $true)]
202 [string]$service
203 )
204
205 return [bool](Get-Service -Name $service -ErrorAction SilentlyContinue)
206 }
207
208 function Invoke-NssmStart {
209 [CmdletBinding()]
210 param(
211 [Parameter(Mandatory = $true)]
212 [string]$service
213 )
214
215 $nssm_result = Invoke-NssmCommand -arguments @("start", $service)
216
217 if ($nssm_result.rc -ne 0) {
218 $result.nssm_error_cmd = $nssm_result.arguments
219 $result.nssm_error_log = $nssm_result.stderr
220 Fail-Json -obj $result -message "Error starting service ""$service"""
221 }
222 }
223
224 function Invoke-NssmStop {
225 [CmdletBinding()]
226 param(
227 [Parameter(Mandatory = $true)]
228 [string]$service
229 )
230
231 $nssm_result = Invoke-NssmCommand -arguments @("stop", $service)
232
233 if ($nssm_result.rc -ne 0) {
234 $result.nssm_error_cmd = $nssm_result.arguments
235 $result.nssm_error_log = $nssm_result.stderr
236 Fail-Json -obj $result -message "Error stopping service ""$service"""
237 }
238 }
239
240 function Start-NssmService {
241 [CmdletBinding(SupportsShouldProcess = $true)]
242 param(
243 [Parameter(Mandatory = $true)]
244 [string]$service
245 )
246
247 $currentStatus = Get-NssmServiceStatus -service $service
248
249 if ($currentStatus.rc -ne 0) {
250 $result.nssm_error_cmd = $currentStatus.arguments
251 $result.nssm_error_log = $currentStatus.stderr
252 Fail-Json -obj $result -message "Error starting service ""$service"""
253 }
254
255 if ($currentStatus.stdout -notlike "*SERVICE_RUNNING*") {
256 if ($PSCmdlet.ShouldProcess($service, "Start service")) {
257 switch -wildcard ($currentStatus.stdout) {
258 "*SERVICE_STOPPED*" { Invoke-NssmStart -service $service }
259
260 "*SERVICE_CONTINUE_PENDING*" { Invoke-NssmStop -service $service; Invoke-NssmStart -service $service }
261 "*SERVICE_PAUSE_PENDING*" { Invoke-NssmStop -service $service; Invoke-NssmStart -service $service }
262 "*SERVICE_PAUSED*" { Invoke-NssmStop -service $service; Invoke-NssmStart -service $service }
263 "*SERVICE_START_PENDING*" { Invoke-NssmStop -service $service; Invoke-NssmStart -service $service }
264 "*SERVICE_STOP_PENDING*" { Invoke-NssmStop -service $service; Invoke-NssmStart -service $service }
265 }
266 }
267
268 $result.changed_by = "start_service"
269 $result.changed = $true
270 }
271 }
272
273 function Stop-NssmService {
274 [CmdletBinding(SupportsShouldProcess = $true)]
275 param(
276 [Parameter(Mandatory = $true)]
277 [string]$service
278 )
279
280 $currentStatus = Get-NssmServiceStatus -service $service
281
282 if ($currentStatus.rc -ne 0) {
283 $result.nssm_error_cmd = $currentStatus.arguments
284 $result.nssm_error_log = $currentStatus.stderr
285 Fail-Json -obj $result -message "Error stopping service ""$service"""
286 }
287
288 if ($currentStatus.stdout -notlike "*SERVICE_STOPPED*") {
289 if ($PSCmdlet.ShouldProcess($service, "Stop service")) {
290 Invoke-NssmStop -service $service
291 }
292
293 $result.changed_by = "stop_service"
294 $result.changed = $true
295 }
296 }
297
298 Function ConvertTo-NormalizedUser {
299 [CmdletBinding()]
300 param (
301 [Parameter(Mandatory = $true)]
302 [String]$InputObject
303 )
304
305 $systemSid = [System.Security.Principal.SecurityIdentifier]'S-1-5-18'
306
307 # Try to get the SID from the raw value or with LocalSystem (what services consider to be SYSTEM).
308 try {
309 $sid = New-Object -TypeName System.Security.Principal.SecurityIdentifier -ArgumentList $InputObject
310 }
311 catch [ArgumentException] {
312 if ($InputObject -eq "LocalSystem") {
313 $sid = $systemSid
314 }
315 }
316
317 if (-not $sid) {
318 $candidates = @(if ($InputObject.Contains('\')) {
319 $nameSplit = $InputObject.Split('\', 2)
320
321 if ($nameSplit[0] -eq '.') {
322 # If the domain portion is . try using the hostname then falling back to just the username.
323 # Usually the hostname just works except when running on a DC where it's a domain account
324 # where looking up just the username should work.
325 , @($env:COMPUTERNAME, $nameSplit[1])
326 $nameSplit[1]
327 }
328 else {
329 , $nameSplit
330 }
331 }
332 else {
333 $InputObject
334 })
335
336 $sid = for ($i = 0; $i -lt $candidates.Length; $i++) {
337 $candidate = $candidates[$i]
338 $ntAccount = New-Object -TypeName System.Security.Principal.NTAccount -ArgumentList $candidate
339 try {
340 $ntAccount.Translate([System.Security.Principal.SecurityIdentifier])
341 break
342 }
343 catch [System.Security.Principal.IdentityNotMappedException] {
344 if ($i -eq ($candidates.Length - 1)) {
345 throw
346 }
347 continue
348 }
349 }
350 }
351
352 if ($sid -eq $systemSid) {
353 "LocalSystem"
354 }
355 else {
356 $sid.Translate([System.Security.Principal.NTAccount]).Value
357 }
358 }
359
360 if ($state -ne 'absent') {
361 if ($null -eq $application) {
362 Fail-Json -obj $result -message "The application parameter must be defined when the state is not absent."
363 }
364
365 if (-not (Test-Path -LiteralPath $application -PathType Leaf)) {
366 Fail-Json -obj $result -message "The application specified ""$application"" does not exist on the host."
367 }
368
369 if ($null -eq $appDirectory) {
370 $appDirectory = (Get-Item -LiteralPath $application).DirectoryName
371 }
372
373 if ($user) {
374 $user = ConvertTo-NormalizedUser -InputObject $user
375 if (
376 $user -in @(
377 (ConvertTo-NormalizedUser -InputObject 'S-1-5-18'), # SYSTEM
378 (ConvertTo-NormalizedUser -InputObject 'S-1-5-19'), # LOCAL SERVICE
379 (ConvertTo-NormalizedUser -InputObject 'S-1-5-20') # NETWORK SERVICE
380 )
381 ) {
382 # These accounts have no password (NSSM expects nothing)
383 $password = ""
384 }
385 elseif ($user.EndsWith('$')) {
386 # While a gMSA doesn't have a password NSSM will fail with no password so we set a dummy value. The service
387 # still starts up properly with this so SCManager handles this nicely.
388 $password = "gsma_password"
389 }
390 elseif (-not $password) {
391 # Any other account requires a password here.
392 Fail-Json -obj $result -message "User without password is informed for service ""$name"""
393 }
394 }
395 }
396
397
398 $service_exists = Test-NssmServiceExist -service $name
399
400 if ($state -eq 'absent') {
401 if ($service_exists) {
402 if (-not $check_mode) {
403 if ((Get-Service -Name $name).Status -ne "Stopped") {
404 $nssm_result = Invoke-NssmStop -service $name
405 }
406
407 $nssm_result = Invoke-NssmCommand -arguments @("remove", $name, "confirm")
408
409 if ($nssm_result.rc -ne 0) {
410 $result.nssm_error_cmd = $nssm_result.arguments
411 $result.nssm_error_log = $nssm_result.stderr
412 Fail-Json -obj $result -message "Error removing service ""$name"""
413 }
414 }
415
416 $diff_text += "-[$name]"
417 $result.changed_by = "remove_service"
418 $result.changed = $true
419 }
420 }
421 else {
422 $diff_text_added_prefix = ''
423 if (-not $service_exists) {
424 if (-not $check_mode) {
425 $nssm_result = Invoke-NssmCommand -arguments @("install", $name, $application)
426
427 if ($nssm_result.rc -ne 0) {
428 $result.nssm_error_cmd = $nssm_result.arguments
429 $result.nssm_error_log = $nssm_result.stderr
430 Fail-Json -obj $result -message "Error installing service ""$name"""
431 }
432 $service_exists = $true
433 }
434
435 $diff_text_added_prefix = '+'
436 $result.changed_by = "install_service"
437 $result.changed = $true
438 }
439
440 $diff_text += "$diff_text_added_prefix[$name]`n"
441
442 # We cannot configure a service that was created above in check mode as it won't actually exist
443 if ($service_exists) {
444 $common_params = @{
445 service = $name
446 WhatIf = $check_mode
447 }
448
449 Update-NssmServiceParameter -parameter "Application" -value $application @common_params
450 Update-NssmServiceParameter -parameter "DisplayName" -value $display_name @common_params
451 Update-NssmServiceParameter -parameter "Description" -value $description @common_params
452
453 Update-NssmServiceParameter -parameter "AppDirectory" -value $appDirectory @common_params
454
455
456 if ($null -ne $appArguments) {
457 $singleLineParams = ""
458 if ($appArguments -is [array]) {
459 $singleLineParams = Argv-ToString -arguments $appArguments
460 }
461 else {
462 $singleLineParams = $appArguments.ToString()
463 }
464
465 $result.nssm_app_parameters = $appArguments
466 $result.nssm_single_line_app_parameters = $singleLineParams
467
468 Update-NssmServiceParameter -parameter "AppParameters" -value $singleLineParams @common_params
469 }
470
471
472 Update-NssmServiceParameter -parameter "AppStdout" -value $stdoutFile @common_params
473 Update-NssmServiceParameter -parameter "AppStderr" -value $stderrFile @common_params
474
475 # set app environment, only do this for now when explicitly requested by caller to
476 # avoid breaking playbooks which use another / custom scheme for configuring app_env
477 if ($null -ne $app_env) {
478 # note: convert app_env dictionary to list of strings in the form key=value and pass that a long as value
479 $app_env_str = $app_env.GetEnumerator() | ForEach-Object { "$($_.Name)=$($_.Value)" }
480
481 # note: this is important here to make an empty envvar set working properly (in the sense that appenv is reset)
482 if ($null -eq $app_env_str) {
483 $app_env_str = ''
484 }
485
486 Update-NssmServiceParameter -parameter "AppEnvironmentExtra" -value $app_env_str @common_params
487 }
488
489 ###
490 # Setup file rotation so we don't accidentally consume too much disk
491 ###
492
493 #set files to overwrite
494 Update-NssmServiceParameter -parameter "AppStdoutCreationDisposition" -value 2 @common_params
495 Update-NssmServiceParameter -parameter "AppStderrCreationDisposition" -value 2 @common_params
496
497 #enable file rotation
498 Update-NssmServiceParameter -parameter "AppRotateFiles" -value 1 @common_params
499
500 #don't rotate until the service restarts
501 Update-NssmServiceParameter -parameter "AppRotateOnline" -value $app_rotate_online @common_params
502
503 #both of the below conditions must be met before rotation will happen
504 #minimum age before rotating
505 Update-NssmServiceParameter -parameter "AppRotateSeconds" -value 86400 @common_params
506
507 #minimum size before rotating
508 Update-NssmServiceParameter -parameter "AppRotateBytes" -value $app_rotate_bytes @common_params
509
510 Update-NssmServiceParameter -parameter "DependOnService" -arguments $dependencies @common_params
511 if ($user) {
512 # Use custom compare callback to test only the username (and not the password)
513 Update-NssmServiceParameter -parameter "ObjectName" -arguments @($user, $password) -compare {
514 param($actual, $expected)
515
516 $actualUser = ConvertTo-NormalizedUser -InputObject $actual[0]
517 $expectedUser = ConvertTo-NormalizedUser -InputObject $expected[0]
518
519 $actualUser -eq $expectedUser
520 } @common_params
521 }
522 $mappedMode = $start_modes_map.$startMode
523 Update-NssmServiceParameter -parameter "Start" -value $mappedMode @common_params
524 if ($state -in "stopped", "restarted") {
525 Stop-NssmService @common_params
526 }
527
528 if ($state -in "started", "restarted") {
529 Start-NssmService @common_params
530 }
531
532 # Added per users` requests
533 if ($null -ne $app_stop_method_console) {
534 Update-NssmServiceParameter -parameter "AppStopMethodConsole" -value $app_stop_method_console @common_params
535 }
536
537 if ($null -ne $app_stop_method_skip) {
538 Update-NssmServiceParameter -parameter "AppStopMethodSkip" -value $app_stop_method_skip @common_params
539 }
540 }
541 }
542
543 if ($diff_mode -and $result.changed -eq $true) {
544 $result.diff = @{
545 prepared = $diff_text
546 }
547 }
548
549 Exit-Json $result