-
Notifications
You must be signed in to change notification settings - Fork 34
/
Copy pathpsDscAdapter.psm1
561 lines (475 loc) · 21.6 KB
/
psDscAdapter.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
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
$script:CurrentCacheSchemaVersion = 2
function Write-DscTrace {
param(
[Parameter(Mandatory = $false)]
[ValidateSet('Error', 'Warn', 'Info', 'Debug', 'Trace')]
[string]$Operation = 'Debug',
[Parameter(Mandatory = $true, ValueFromPipeline = $true)]
[string]$Message
)
$trace = @{$Operation.ToLower() = $Message } | ConvertTo-Json -Compress
$host.ui.WriteErrorLine($trace)
}
function Import-PSDSCModule {
$m = Get-Module PSDesiredStateConfiguration -ListAvailable | Sort-Object -Descending | Select-Object -First 1
$PSDesiredStateConfiguration = Import-Module $m -Force -PassThru
}
function Get-DSCResourceModules {
$listPSModuleFolders = $env:PSModulePath.Split([IO.Path]::PathSeparator)
$dscModulePsd1List = [System.Collections.Generic.HashSet[System.String]]::new()
foreach ($folder in $listPSModuleFolders) {
if (!(Test-Path $folder)) {
continue
}
foreach ($moduleFolder in Get-ChildItem $folder -Directory) {
$addModule = $false
foreach ($psd1 in Get-ChildItem -Recurse -Filter "$($moduleFolder.Name).psd1" -Path $moduleFolder.fullname -Depth 2) {
$containsDSCResource = select-string -LiteralPath $psd1 -pattern '^[^#]*\bDscResourcesToExport\b.*'
if ($null -ne $containsDSCResource) {
$dscModulePsd1List.Add($psd1) | Out-Null
}
}
}
}
return $dscModulePsd1List
}
function Add-AstMembers {
param(
$AllTypeDefinitions,
$TypeAst,
$Properties
)
foreach ($TypeConstraint in $TypeAst.BaseTypes) {
$t = $AllTypeDefinitions | Where-Object { $_.Name -eq $TypeConstraint.TypeName.Name }
if ($t) {
Add-AstMembers $AllTypeDefinitions $t $Properties
}
}
foreach ($member in $TypeAst.Members) {
$property = $member -as [System.Management.Automation.Language.PropertyMemberAst]
if (($property -eq $null) -or ($property.IsStatic)) {
continue;
}
$skipProperty = $true
$isKeyProperty = $false
foreach ($attr in $property.Attributes) {
if ($attr.TypeName.Name -eq 'DscProperty') {
$skipProperty = $false
foreach ($attrArg in $attr.NamedArguments) {
if ($attrArg.ArgumentName -eq 'Key') {
$isKeyProperty = $true
break
}
}
}
}
if ($skipProperty) {
continue;
}
[DscResourcePropertyInfo]$prop = [DscResourcePropertyInfo]::new()
$prop.Name = $property.Name
$prop.PropertyType = $property.PropertyType.TypeName.Name
$prop.IsMandatory = $isKeyProperty
$Properties.Add($prop)
}
}
function FindAndParseResourceDefinitions {
[CmdletBinding(HelpUri = '')]
param(
[Parameter(Mandatory = $true)]
[string]$filePath,
[Parameter(Mandatory = $true)]
[string]$moduleVersion
)
if (-not (Test-Path $filePath)) {
return
}
if (".psm1", ".ps1" -notcontains ([System.IO.Path]::GetExtension($filePath))) {
return
}
"Loading resources from file '$filePath'" | Write-DscTrace -Operation Trace
#TODO: Ensure embedded instances in properties are working correctly
[System.Management.Automation.Language.Token[]] $tokens = $null
[System.Management.Automation.Language.ParseError[]] $errors = $null
$ast = [System.Management.Automation.Language.Parser]::ParseFile($filePath, [ref]$tokens, [ref]$errors)
foreach ($e in $errors) {
$e | Out-String | Write-DscTrace -Operation Error
}
$typeDefinitions = $ast.FindAll(
{
$typeAst = $args[0] -as [System.Management.Automation.Language.TypeDefinitionAst]
return $typeAst -ne $null;
},
$false);
$resourceList = [System.Collections.Generic.List[DscResourceInfo]]::new()
foreach ($typeDefinitionAst in $typeDefinitions) {
foreach ($a in $typeDefinitionAst.Attributes) {
if ($a.TypeName.Name -eq 'DscResource') {
$DscResourceInfo = [DscResourceInfo]::new()
$DscResourceInfo.Name = $typeDefinitionAst.Name
$DscResourceInfo.ResourceType = $typeDefinitionAst.Name
$DscResourceInfo.FriendlyName = $typeDefinitionAst.Name
$DscResourceInfo.ImplementationDetail = 'ClassBased'
$DscResourceInfo.Module = $filePath
$DscResourceInfo.Path = $filePath
#TODO: ModuleName, Version and ParentPath should be taken from psd1 contents
$DscResourceInfo.ModuleName = [System.IO.Path]::GetFileNameWithoutExtension($filePath)
$DscResourceInfo.ParentPath = [System.IO.Path]::GetDirectoryName($filePath)
$DscResourceInfo.Version = $moduleVersion
$DscResourceInfo.Properties = [System.Collections.Generic.List[DscResourcePropertyInfo]]::new()
Add-AstMembers $typeDefinitions $typeDefinitionAst $DscResourceInfo.Properties
$resourceList.Add($DscResourceInfo)
}
}
}
return $resourceList
}
function LoadPowerShellClassResourcesFromModule {
[CmdletBinding(HelpUri = '')]
param(
[Parameter(Mandatory = $true)]
[PSModuleInfo]$moduleInfo
)
"Loading resources from module '$($moduleInfo.Path)'" | Write-DscTrace -Operation Trace
if ($moduleInfo.RootModule) {
if (".psm1", ".ps1" -notcontains ([System.IO.Path]::GetExtension($moduleInfo.RootModule)) -and
(-not $moduleInfo.NestedModules)) {
"RootModule is neither psm1 nor ps1 '$($moduleInfo.RootModule)'" | Write-DscTrace -Operation Trace
return [System.Collections.Generic.List[DscResourceInfo]]::new()
}
$scriptPath = Join-Path $moduleInfo.ModuleBase $moduleInfo.RootModule
}
else {
$scriptPath = $moduleInfo.Path;
}
$Resources = FindAndParseResourceDefinitions $scriptPath $moduleInfo.Version
if ($moduleInfo.NestedModules) {
foreach ($nestedModule in $moduleInfo.NestedModules) {
$resourcesOfNestedModules = LoadPowerShellClassResourcesFromModule $nestedModule
if ($resourcesOfNestedModules) {
$Resources.AddRange($resourcesOfNestedModules)
}
}
}
return $Resources
}
<# public function Invoke-DscCacheRefresh
.SYNOPSIS
This function caches the results of the Get-DscResource call to optimize performance.
.DESCRIPTION
This function is designed to improve the performance of DSC operations by caching the results of the Get-DscResource call.
By storing the results, subsequent calls to Get-DscResource can retrieve the cached data instead of making a new call each time.
This can significantly speed up operations that need to repeatedly access DSC resources.
.EXAMPLE
Invoke-DscCacheRefresh -Module "PSDesiredStateConfiguration"
#>
function Invoke-DscCacheRefresh {
[CmdletBinding(HelpUri = '')]
param(
[Parameter(ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true)]
[Object[]]
$Module
)
$refreshCache = $false
$cacheFilePath = if ($IsWindows) {
# PS 6+ on Windows
Join-Path $env:LocalAppData "dsc\PSAdapterCache.json"
}
else {
# PS 6+ on Linux/Mac
Join-Path $env:HOME ".dsc" "PSAdapterCache.json"
}
if (Test-Path $cacheFilePath) {
"Reading from Get-DscResource cache file $cacheFilePath" | Write-DscTrace
$cache = Get-Content -Raw $cacheFilePath | ConvertFrom-Json
if ($cache.CacheSchemaVersion -ne $script:CurrentCacheSchemaVersion) {
$refreshCache = $true
"Incompatible version of cache in file '" + $cache.CacheSchemaVersion + "' (expected '" + $script:CurrentCacheSchemaVersion + "')" | Write-DscTrace
}
else {
$dscResourceCacheEntries = $cache.ResourceCache
if ($dscResourceCacheEntries.Count -eq 0) {
# if there is nothing in the cache file - refresh cache
$refreshCache = $true
"Filtered DscResourceCache cache is empty" | Write-DscTrace
}
else {
"Checking cache for stale entries" | Write-DscTrace
foreach ($cacheEntry in $dscResourceCacheEntries) {
$cacheEntry.LastWriteTimes.PSObject.Properties | ForEach-Object {
if (Test-Path $_.Name) {
$file_LastWriteTime = (Get-Item $_.Name).LastWriteTime
# Truncate DateTime to seconds
$file_LastWriteTime = $file_LastWriteTime.AddTicks( - ($file_LastWriteTime.Ticks % [TimeSpan]::TicksPerSecond));
$cache_LastWriteTime = [DateTime]$_.Value
# Truncate DateTime to seconds
$cache_LastWriteTime = $cache_LastWriteTime.AddTicks( - ($cache_LastWriteTime.Ticks % [TimeSpan]::TicksPerSecond));
if (-not ($file_LastWriteTime.Equals($cache_LastWriteTime))) {
"Detected stale cache entry '$($_.Name)'" | Write-DscTrace
$refreshCache = $true
break
}
}
else {
"Detected non-existent cache entry '$($_.Name)'" | Write-DscTrace
$refreshCache = $true
break
}
}
if ($refreshCache) { break }
}
if (-not $refreshCache) {
"Checking cache for stale PSModulePath" | Write-DscTrace
$m = $env:PSModulePath -split [IO.Path]::PathSeparator | % { Get-ChildItem -Directory -Path $_ -Depth 1 -ea SilentlyContinue }
$hs_cache = [System.Collections.Generic.HashSet[string]]($cache.PSModulePaths)
$hs_live = [System.Collections.Generic.HashSet[string]]($m.FullName)
$hs_cache.SymmetricExceptWith($hs_live)
$diff = $hs_cache
"PSModulePath diff '$diff'" | Write-DscTrace
if ($diff.Count -gt 0) {
$refreshCache = $true
}
}
}
}
}
else {
"Cache file not found '$cacheFilePath'" | Write-DscTrace
$refreshCache = $true
}
if ($refreshCache) {
'Constructing Get-DscResource cache' | Write-DscTrace
# create a list object to store cache of Get-DscResource
[dscResourceCacheEntry[]]$dscResourceCacheEntries = [System.Collections.Generic.List[Object]]::new()
$DscResources = [System.Collections.Generic.List[DscResourceInfo]]::new()
$dscResourceModulePsd1s = Get-DSCResourceModules
if ($null -ne $dscResourceModulePsd1s) {
$modules = Get-Module -ListAvailable -Name ($dscResourceModulePsd1s)
$processedModuleNames = @{}
foreach ($mod in $modules) {
if (-not ($processedModuleNames.ContainsKey($mod.Name))) {
$processedModuleNames.Add($mod.Name, $true)
# from several modules with the same name select the one with the highest version
$selectedMod = $modules | Where-Object Name -EQ $mod.Name
if ($selectedMod.Count -gt 1) {
"Found $($selectedMod.Count) modules with name '$($mod.Name)'" | Write-DscTrace -Operation Trace
$selectedMod = $selectedMod | Sort-Object -Property Version -Descending | Select-Object -First 1
}
[System.Collections.Generic.List[DscResourceInfo]]$r = LoadPowerShellClassResourcesFromModule -moduleInfo $selectedMod
if ($r) {
$DscResources.AddRange($r)
}
}
}
}
foreach ($dscResource in $DscResources) {
$moduleName = $dscResource.ModuleName
# fill in resource files (and their last-write-times) that will be used for up-do-date checks
$lastWriteTimes = @{}
Get-ChildItem -Recurse -File -Path $dscResource.ParentPath -Include "*.ps1", "*.psd1", "*.psm1", "*.mof" -ea Ignore | % {
$lastWriteTimes.Add($_.FullName, $_.LastWriteTime)
}
$dscResourceCacheEntries += [dscResourceCacheEntry]@{
Type = "$moduleName/$($dscResource.Name)"
DscResourceInfo = $dscResource
LastWriteTimes = $lastWriteTimes
}
}
[dscResourceCache]$cache = [dscResourceCache]::new()
$cache.ResourceCache = $dscResourceCacheEntries
$m = $env:PSModulePath -split [IO.Path]::PathSeparator | % { Get-ChildItem -Directory -Path $_ -Depth 1 -ea SilentlyContinue }
$cache.PSModulePaths = $m.FullName
$cache.CacheSchemaVersion = $script:CurrentCacheSchemaVersion
# save cache for future use
# TODO: replace this with a high-performance serializer
"Saving Get-DscResource cache to '$cacheFilePath'" | Write-DscTrace
$jsonCache = $cache | ConvertTo-Json -Depth 90
New-Item -Force -Path $cacheFilePath -Value $jsonCache -Type File | Out-Null
}
return $dscResourceCacheEntries
}
# Convert the INPUT to a dscResourceObject object so configuration and resource are standardized as much as possible
function Get-DscResourceObject {
param(
[Parameter(Mandatory = $true, ValueFromPipeline = $true)]
$jsonInput
)
# normalize the INPUT object to an array of dscResourceObject objects
$inputObj = $jsonInput | ConvertFrom-Json
$desiredState = [System.Collections.Generic.List[Object]]::new()
$inputObj.resources | ForEach-Object -Process {
$desiredState += [dscResourceObject]@{
name = $_.name
type = $_.type
properties = $_.properties
}
}
return $desiredState
}
# Get the actual state using DSC Get method from any type of DSC resource
function Invoke-DscOperation {
param(
[Parameter(Mandatory)]
[ValidateSet('Get', 'Set', 'Test', 'Export')]
[string]$Operation,
[Parameter(Mandatory, ValueFromPipeline = $true)]
[dscResourceObject]$DesiredState,
[Parameter(Mandatory)]
[dscResourceCacheEntry[]]$dscResourceCache
)
$osVersion = [System.Environment]::OSVersion.VersionString
'OS version: ' + $osVersion | Write-DscTrace
$psVersion = $PSVersionTable.PSVersion.ToString()
'PowerShell version: ' + $psVersion | Write-DscTrace
# get details from cache about the DSC resource, if it exists
$cachedDscResourceInfo = $dscResourceCache | Where-Object Type -EQ $DesiredState.type | ForEach-Object DscResourceInfo | Select-Object -First 1
# if the resource is found in the cache, get the actual state
if ($cachedDscResourceInfo) {
# formated OUTPUT of each resource
$addToActualState = [dscResourceObject]@{}
# set top level properties of the OUTPUT object from INPUT object
$DesiredState.psobject.properties | ForEach-Object -Process {
if ($_.TypeNameOfValue -EQ 'System.String') { $addToActualState.$($_.Name) = $DesiredState.($_.Name) }
}
# workaround: script based resources do not validate Get parameter consistency, so we need to remove any parameters the author chose not to include in Get-TargetResource
switch ([dscResourceType]$cachedDscResourceInfo.ImplementationDetail) {
'ClassBased' {
try {
# load powershell class from external module
$resource = GetTypeInstanceFromModule -modulename $cachedDscResourceInfo.ModuleName -classname $cachedDscResourceInfo.Name
$dscResourceInstance = $resource::New()
$ValidProperties = $cachedDscResourceInfo.Properties.Name
if ($DesiredState.properties) {
# set each property of $dscResourceInstance to the value of the property in the $desiredState INPUT object
$DesiredState.properties.psobject.properties | ForEach-Object -Process {
# handle input objects by converting them to a hash table
if ($_.Value -is [System.Management.Automation.PSCustomObject]) {
Write-DscTrace -Message "The object is a PSCustomObject"
$_.Value.psobject.properties | ForEach-Object -Begin {
$propertyHash = @{}
} -Process {
$propertyHash[$_.Name] = $_.Value
} -End {
$dscResourceInstance.$($_.Name) = $propertyHash
}
}
else {
$dscResourceInstance.$($_.Name) = $_.Value
}
}
}
switch ($Operation) {
'Get' {
$Result = @{}
$raw_obj = $dscResourceInstance.Get()
$ValidProperties | ForEach-Object { $Result[$_] = $raw_obj.$_ }
$addToActualState.properties = $Result
}
'Set' {
$dscResourceInstance.Set()
}
'Test' {
$Result = $dscResourceInstance.Test()
$addToActualState.properties = [psobject]@{'InDesiredState' = $Result }
}
'Export' {
$t = $dscResourceInstance.GetType()
$methods = $t.GetMethods() | Where-Object { $_.Name -eq 'Export' }
$method = foreach ($mt in $methods) {
if ($mt.GetParameters().Count -eq 0) {
$mt
break
}
}
if ($null -eq $method) {
"Export method not implemented by resource '$($DesiredState.Type)'" | Write-DscTrace -Operation Error
exit 1
}
$resultArray = @()
$raw_obj_array = $method.Invoke($null, $null)
foreach ($raw_obj in $raw_obj_array) {
$Result_obj = @{}
$ValidProperties | ForEach-Object { $Result_obj[$_] = $raw_obj.$_ }
$resultArray += $Result_obj
}
$addToActualState = $resultArray
}
}
}
catch {
'Exception: ' + $_.Exception.Message | Write-DscTrace -Operation Error
exit 1
}
}
Default {
'Resource ImplementationDetail not supported: ' + $cachedDscResourceInfo.ImplementationDetail | Write-DscTrace -Operation Error
exit 1
}
}
"Output: $($addToActualState | ConvertTo-Json -Depth 10 -Compress)" | Write-DscTrace -Operation Trace
return $addToActualState
}
else {
$dsJSON = $DesiredState | ConvertTo-Json -Depth 10
'Can not find type "' + $DesiredState.type + '" for resource "' + $dsJSON + '". Please ensure that Get-DscResource returns this resource type.' | Write-DscTrace -Operation Error
exit 1
}
}
# GetTypeInstanceFromModule function to get the type instance from the module
function GetTypeInstanceFromModule {
param(
[Parameter(Mandatory = $true)]
[string] $modulename,
[Parameter(Mandatory = $true)]
[string] $classname
)
$instance = & (Import-Module $modulename -PassThru) ([scriptblock]::Create("'$classname' -as 'type'"))
return $instance
}
# cached resource
class dscResourceCacheEntry {
[string] $Type
[psobject] $DscResourceInfo
[PSCustomObject] $LastWriteTimes
}
class dscResourceCache {
[int] $CacheSchemaVersion
[string[]] $PSModulePaths
[dscResourceCacheEntry[]] $ResourceCache
}
# format expected for configuration output
class dscResourceObject {
[string] $name
[string] $type
[psobject] $properties
}
# dsc resource types
enum dscResourceType {
ScriptBased
ClassBased
Binary
Composite
}
class DscResourcePropertyInfo {
[string] $Name
[string] $PropertyType
[bool] $IsMandatory
[System.Collections.Generic.List[string]] $Values
}
# dsc resource type (settable clone)
class DscResourceInfo {
[dscResourceType] $ImplementationDetail
[string] $ResourceType
[string] $Name
[string] $FriendlyName
[string] $Module
[string] $ModuleName
[string] $Version
[string] $Path
[string] $ParentPath
[string] $ImplementedAs
[string] $CompanyName
[System.Collections.Generic.List[DscResourcePropertyInfo]] $Properties
}