-
Notifications
You must be signed in to change notification settings - Fork 0
/
Utils.psm1
447 lines (411 loc) · 13.8 KB
/
Utils.psm1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
<#
.SYNOPSIS
Contains common objects, functions and variables.
.NOTES
File name: lib.psm1
#>
#requires -Version 5.1
using namespace System
using namespace System.Text
using namespace System.Collections.Generic
using namespace System.Security.AccessControl
function Set-AppSettingsConfig {
<#
.SYNOPSIS
Set or add an <add> node typically in a web.config file based on
a key with a given value.
.PARAMETER Key
The key of the <add> node.
.PARAMETER Value
The value of the <add> node.
.PARAMETER XmlDocument
The XML representation of the file.
.PARAMETER DocumentPath
The path to the document.
.PARAMETER Force
If the <add> node exists, overwrite its value.
#>
[CmdletBinding()]
param (
[Parameter(Mandatory=$true, Position=0)]
[ValidateNotNullOrEmpty()]
[string]$Key,
[Parameter(Mandatory=$true, Position=1)]
[string]$Value,
[Parameter(Mandatory=$true)]
[ValidateNotNull()]
[xml]$XmlDocument,
[Parameter(Mandatory=$true)]
[ValidateNotNullOrEmpty()]
[string]$DocumentPath,
[Switch]$Force
)
$addNode = $XmlDocument.SelectSingleNode("//add[@key=""$Key""]")
if ($addNode -eq $null) {
$addElement = $XmlDocument.CreateElement("add")
$addElement.SetAttribute("key", $Key)
$addElement.SetAttribute("value", $Value)
$XmlDocument.configuration.appSettings.AppendChild($addElement)
$XmlDocument.Save($DocumentPath)
} elseif ($addNode -ne $null -and $Force) {
$addNode.Attributes["value"].Value = $Value
$XmlDocument.Save($DocumentPath)
}
}
function Set-IISNodeSetting {
<#
.SYNOPSIS
Sets a IISNode property in the web.config of the specified node application.
.PARAMETER Name
The name of the property to set.
.PARAMETER Value
The value to set to the property.
.PARAMETER Application
The name of the node application.
#>
[CmdletBinding()]
param (
[Parameter(Mandatory=$true, Position=0)]
[ValidateNotNullOrEmpty()]
[string]$Name,
[Parameter(Mandatory=$true, Position=1)]
[ValidateNotNullOrEmpty()]
[string]$Value,
[Parameter(Mandatory=$true)]
[ValidateNotNullOrEmpty()]
[ValidateSet("Auth", "SCIM", "GraphQL", "Hooks")]
[string]$Application
)
$nodeAppName = $Application.ToLower()
$wfgenFolder = [io.path]::Combine("C:\", "inetpub", "wwwroot", "wfgen")
$nodeAppConfigPath = [io.path]::Combine($wfgenFolder, $nodeAppName, "web.config")
$nodeAppConfig = [xml](Get-Content $nodeAppConfigPath)
$nodeAppConfig.
configuration["system.webServer"].
iisnode.Attributes[$Name].Value = $Value
$nodeAppConfig.Save($nodeAppConfigPath)
}
function Enable-IISNodeOption {
<#
.SYNOPSIS
Enables a special option for iisnode that needs custom code.
.DESCRIPTION
Some options are hard to generalized without asking for XML input from
the user of the container because almost everything comes down to XML
when configuring iisnode. Therefore, this function will expose some options
and hide the underlying required XML.
.PARAMETER Name
The name of the option to enable.
.PARAMETER ApplicationName
The name of the node application to enable the option on.
#>
[CmdletBinding()]
param(
[Parameter(Mandatory=$true, Position=0)]
[ValidateNotNullOrEmpty()]
[ValidateSet("ExposeLogs")]
[string]$Name,
[Parameter(Mandatory=$true)]
[ValidateNotNullOrEmpty()]
[Alias("Application")]
[string]$ApplicationName
)
$nodeAppName = $ApplicationName.ToLower()
$wfgenFolder = [io.path]::Combine("C:\", "inetpub", "wwwroot", "wfgen")
$nodeAppConfigPath = [io.path]::Combine($wfgenFolder, $nodeAppName, "web.config")
$nodeAppConfig = [xml](Get-Content $nodeAppConfigPath)
switch ($Name.ToLower()) {
"exposelogs" {
$iisnodeAddSegment = $nodeAppConfig.
configuration["system.webServer"].
security.
requestFiltering.
hiddenSegments.
SelectSingleNode("//add[@segment=""iisnode""]")
$iisnodeLogsRewriteRule = $nodeAppConfig.
configuration["system.webServer"].
rewrite.
SelectSingleNode("//rule[@name=""LogFile""]")
if ($iisnodeAddSegment) {
$iisnodeAddSegment.ParentNode.RemoveChild($iisnodeAddSegment)
}
if (-not $iisnodeLogsRewriteRule) {
$logsRewriteRule = $nodeAppConfig.CreateElement("rule")
$match = $nodeAppConfig.CreateElement("match")
$logsRewriteRule.SetAttribute("name", "LogFile")
$logsRewriteRule.SetAttribute("patternSyntax", "ECMAScript")
$logsRewriteRule.SetAttribute("stopProcessing", "true")
$match.SetAttribute("url", "iisnode")
$logsRewriteRule.AppendChild($match)
$nodeAppConfig.
configuration["system.webServer"].
rewrite.
rules.
PrependChild($logsRewriteRule)
$nodeAppConfig.Save($nodeAppConfigPath)
}
}
}
}
function Get-EnvVar {
<#
.SYNOPSIS
Get an env var based on its name.
.PARAMETER Name
The name of the env var.
.PARAMETER TryAzureAppServices
Tries to recover the env var by name. If it does not exist,
tries to recover the env var by prefixing an Azure App Services
specific string.
.PARAMETER TryFile
Tries to recover the env var by name. If it does not exist,
tries to recover the env var by suffixing the env var name by _FILE
and then retrieves the value from the path indicated in the env var value.
.OUTPUTS
Returns the value of the environement variable or null.
#>
[CmdletBinding()]
[OutputType([string])]
param (
[Parameter(Mandatory=$true, Position=0)]
[string]$Name,
[string]$DefaultValue,
[switch]$TryAzureAppServices,
[switch]$TryFile
)
$isDefaultValueBound = $PSBoundParameters.ContainsKey("DefaultValue")
$getValue = { param ([string]$EnvName)
$value = [Environment]::GetEnvironmentVariable($EnvName)
if ($TryFile) {
$nameFile = $EnvName + "_FILE"
$valueFile = [Environment]::GetEnvironmentVariable($nameFile)
if ($value -and $valueFile) {
Script:Write-Error "$EnvName and $nameFile are mutually exclusive."
if ($PSBoundParameters.ErrorAction -eq "Stop" -or $ErrorActionPreference -eq "Stop") {
exit 1
}
} elseif ($valueFile) {
return (Get-Content $valueFile -Raw -Encoding UTF8).Trim()
}
}
return $value
}
$valueOrDefault = { param ($Value)
if ($isDefaultValueBound -and ([string]::IsNullOrEmpty($Value))) {
return $DefaultValue
}
return $Value
}
if ($TryAzureAppServices) {
$prefixedName = "APPSETTING_$Name"
$value = & $getValue -EnvName $Name
if ($value) {
return $value
}
return & $valueOrDefault -Value (& $getValue -EnvName $prefixedName)
}
return & $valueOrDefault -Value (& $getValue -EnvName $Name)
}
function Join-Path {
<#
.SYNOPSIS
Overrides the Join-Path standard function to add PowerShell 6 feature
of arbitrary number of path elements.
.DESCRIPTION
In PowerShell 6, one can pass an arbitrary number of path elements to
the function so that all the elements can be combined into one path.
.PARAMETER Path
The path elements to be combined into one.
.OUTPUTS
A path represented as a string in which all path elements have been
combined.
#>
[CmdletBinding()]
[OutputType([string])]
param (
[Parameter(Mandatory=$true, ValueFromPipeline=$true, Position=0)]
[ValidateNotNullOrEmpty()]
[string[]]$Path
)
begin {
$allPath = [List[string]]::new()
}
process {
$allPath.AddRange($Path)
}
end {
return [io.path]::Combine($allPath)
}
}
function Write-Error {
<#
.SYNOPSIS
Writes a message to the error output.
.DESCRIPTION
This is a simplified version of the standard Write-Output function
that only writes a message to the standard error stream without a
stack trace.
.PARAMETER Message
The message to be sent in the error stream.
#>
param (
[Parameter(Mandatory=$true, ValueFromPipeline=$true, Position=0)]
[ValidateNotNull()]
[AllowEmptyString()]
[string]$Message
)
process {
[Console]::ForegroundColor = "red"
[Console]::Error.WriteLine($Message)
[Console]::ResetColor()
}
}
function New-RetryPolicy {
<#
.SYNOPSIS
Creates a retry policy to use with other functions. A retry policy gives
a description of how many retries it should take and how much time to wait
between retries.
.PARAMETER RetryCount
The maximum number of retries to take.
.PARAMETER IntervalMilliseconds
Time between retries.
.PARAMETER CatchException
A list of exceptions to catch that will trigger another retry.
#>
[CmdletBinding()]
[OutputType([PSCustomObject])]
param (
[int]$RetryCount = 3,
[int]$IntervalMilliseconds = 200,
$CatchException = @()
)
process {
return [PSCustomObject]@{
PSTypeName = "Advantys.WorkflowGen.Docker.RetryPolicy"
Retry = $RetryCount
Exceptions = $CatchException
Interval = $IntervalMilliseconds
}
}
}
function Invoke-Block {
<#
.SYNOPSIS
Invoke a block of code with a specific policy.
.PARAMETER Block
The ScriptBlock to execute.
.PARAMETER PolicyDefinition
The policy to apply while executing the block.
.PARAMETER ErrorMessage
Message to display when the policy is not fulfilled.
#>
[CmdletBinding()]
[OutputType([Object], [Void])]
param (
[Parameter(Mandatory=$true, ValueFromPipeline=$true, Position=0)]
[scriptblock]$Block,
[Parameter(Mandatory=$true, ValueFromPipeline=$true, Position=1)]
[ValidateNotNull()]
[Alias("Policy")]
[PSTypeName("Advantys.WorkflowGen.Docker.RetryPolicy")]$PolicyDefinition
)
process {
$retryCount = 0
while ($retryCount -lt $PolicyDefinition.Retry) {
try {
return $Block.InvokeReturnAsIs()
} catch [Exception] {
$exception = $_.Exception
$exceptionMatching = $PolicyDefinition.Exceptions `
| ForEach-Object -Begin { $acc = $false } -Process {
$acc = $acc -or $exception -is $_
} -End { $acc }
if (-not $exceptionMatching) {
throw $_.Exception
}
}
$retryCount += 1
Start-Sleep -Milliseconds $PolicyDefinition.Interval
}
Microsoft.Powershell.Utility\Write-Error "Policy enforcement on script block failed."
}
}
function Invoke-OnPlatform {
<#
.SYNOPSIS
Executes a scriptblock on a specific platform.
.DESCRIPTION
This command is useful for a multi-platform script.
.PARAMETER Windows
Block to execute on Windows platforms only.
.PARAMETER Linux
Block to execute on Unix platforms only including Linux and MacOS.
.PARAMETER ArgumentList
A list of arguments to pass to the scriptblock.
.OUTPUTS
Outputs anything that the scriptblock returns.
#>
[CmdletBinding()]
param(
[Parameter(ValueFromPipelineByPropertyName=$true)]
[scriptblock]$Windows = {},
[Parameter(ValueFromPipelineByPropertyName=$true)]
[scriptblock]$Linux = {},
[object[]]$ArgumentList = @()
)
if ($PSVersionTable.PSVersion.Major -le 5 -or $IsWindows) {
return & $Windows $ArgumentList
} elseif ($IsLinux) {
return & $Linux $ArgumentList
} else {
Microsoft.Powershell.Utility\Write-Error "Unsupported platform."
}
}
function Test-Error {
<#
.SYNOPSIS
Test if the $LASTEXITCODE is 0. Dispays an error message if not.
.DESCRIPTION
By default, this method will write to the error output with Write-Error.
.PARAMETER ErrorMessage
The message to write to the error output.
.PARAMETER Throw
Instead of writing to the error output, throws the error message.
.PARAMETER Exit
Exits with the last error code if it is not 0.
#>
[CmdletBinding(DefaultParameterSetName="Default")]
param (
[string]$ErrorMessage = "",
[Parameter(Mandatory=$true, ParameterSetName="Throw")]
[switch]$Throw,
[Parameter(Mandatory=$true, ParameterSetName="Exit")]
[switch]$Exit,
[int[]]$AdditionalSuccessCodes = @()
)
$successCodes = @(0) + $AdditionalSuccessCodes
if ($LASTEXITCODE -notin $successCodes) {
$code = $LASTEXITCODE
if ($Throw) {
throw $ErrorMessage
} elseif ($Exit) {
Script:Write-Error $ErrorMessage
exit $code
} else {
Microsoft.Powershell.Utility\Write-Error $ErrorMessage
}
}
}
Export-ModuleMember -Function @(
"Get-EnvVar",
"Invoke-Block",
"Set-AppSettingsConfig",
"Set-IISNodeSetting",
"Join-Path",
"Write-Error",
"New-RetryPolicy",
"Test-Error",
"Invoke-OnPlatform",
"Enable-IISNodeOption"
)