Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement schema option for PsDscAdapter #563

Open
wants to merge 10 commits into
base: main
Choose a base branch
from
1 change: 1 addition & 0 deletions .vscode/settings.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
"./y2j/Cargo.toml"
],
"rust-analyzer.showUnlinkedFileNotification": true,
"powershell.codeFormatting.preset": "OTBS",
"json.schemas": [
{
"fileMatch": ["**/*.dsc.resource.json"],
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
{
"$schema": "https://raw.githubusercontent.com/PowerShell/DSC/main/schemas/2024/04/bundled/resource/manifest.json",
"type": "TestClassResource/TestClassResource",
"description": "Manage test class",
"tags": [
"Windows"
],
"version": "0.1.0",
"schema": {
"command": {
"executable": "pwsh",
"args": [
"-NoLogo",
"-NonInteractive",
"-NoProfile",
"-Command",
"$Input | ./psDscAdapter/powershell.resource.ps1 Schema"
],
"input": "stdin"
}
}
}
17 changes: 17 additions & 0 deletions powershell-adapter/Tests/powershellgroup.resource.tests.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -325,4 +325,21 @@ Describe 'PowerShell adapter resource tests' {
"$TestDrive/tracing.txt" | Should -Not -FileContentMatchExactly 'Constructing Get-DscResource cache'
}
}

It "Verify that Schema operation works on PS class-based resource" {
BeforeDiscovery {
$resourceManifest = Resolve-Path -Path (Join-Path $PSScriptRoot 'TestClassResource' 'testclassresource.dsc.resource.json')
$dest = Split-Path -Path ((Get-Command dsc).Source) -Parent
$script:file = Copy-Item -Path $resourceManifest -Destination $dest -Force -PassThru
}

$r = dsc resource schema --resource TestClassResource/TestClassResource
$properties = $r | ConvertFrom-Json
$properties.required | Should -Not -BeNullOrEmpty
$properties.properties.PSObject.properties.Name.Contains('BaseProperty') | Should -BeTrue
}
}

AfterAll {
Remove-Item -Path $file.FullName -Force -ErrorAction SilentlyContinue
}
92 changes: 64 additions & 28 deletions powershell-adapter/psDscAdapter/powershell.resource.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
[CmdletBinding()]
param(
[Parameter(Mandatory = $true, Position = 0, HelpMessage = 'Operation to perform. Choose from List, Get, Set, Test, Export, Validate.')]
[ValidateSet('List', 'Get', 'Set', 'Test', 'Export', 'Validate', 'ClearCache')]
[ValidateSet('List', 'Get', 'Set', 'Test', 'Export', 'Validate', 'Schema', 'ClearCache')]
[string]$Operation,
[Parameter(Mandatory = $false, Position = 1, ValueFromPipeline = $true, HelpMessage = 'Configuration or resource input in JSON format.')]
[string]$jsonInput = '@{}'
Expand All @@ -27,19 +27,19 @@ function Write-DscTrace {
'PSPath=' + $PSHome | Write-DscTrace
'PSModulePath=' + $env:PSModulePath | Write-DscTrace

if ($Operation -eq 'ClearCache') {
$cacheFilePath = if ($IsWindows) {
# PS 6+ on Windows
Join-Path $env:LocalAppData "dsc\PSAdapterCache.json"
$cacheFilePath = if ($IsWindows) {
# PS 6+ on Windows
Join-Path $env:LocalAppData "dsc\PSAdapterCache.json"
} else {
# either WinPS or PS 6+ on Linux/Mac
if ($PSVersionTable.PSVersion.Major -le 5) {
Join-Path $env:LocalAppData "dsc\WindowsPSAdapterCache.json"
} else {
# either WinPS or PS 6+ on Linux/Mac
if ($PSVersionTable.PSVersion.Major -le 5) {
Join-Path $env:LocalAppData "dsc\WindowsPSAdapterCache.json"
} else {
Join-Path $env:HOME ".dsc" "PSAdapterCache.json"
}
Join-Path $env:HOME ".dsc" "PSAdapterCache.json"
}
}

if ($Operation -eq 'ClearCache') {
'Deleting cache file ' + $cacheFilePath | Write-DscTrace
Remove-Item -Force -ea SilentlyContinue -Path $cacheFilePath
exit 0
Expand All @@ -53,8 +53,7 @@ if ('Validate' -ne $Operation) {
# load private functions of psDscAdapter stub module
if ($PSVersionTable.PSVersion.Major -le 5) {
$psDscAdapter = Import-Module "$PSScriptRoot/win_psDscAdapter.psd1" -Force -PassThru
}
else {
} else {
$psDscAdapter = Import-Module "$PSScriptRoot/psDscAdapter.psd1" -Force -PassThru
}

Expand All @@ -67,8 +66,7 @@ if ($jsonInput) {
$inputobj_pscustomobj = $jsonInput | ConvertFrom-Json
}
$new_psmodulepath = $inputobj_pscustomobj.psmodulepath
if ($new_psmodulepath)
{
if ($new_psmodulepath) {
$env:PSModulePath = $ExecutionContext.InvokeCommand.ExpandString($new_psmodulepath)
}
}
Expand All @@ -80,7 +78,7 @@ switch ($Operation) {

# cache was refreshed on script load
foreach ($dscResource in $dscResourceCache) {

# https://learn.microsoft.com/dotnet/api/system.management.automation.dscresourceinfo
$DscResourceInfo = $dscResource.DscResourceInfo

Expand All @@ -90,29 +88,25 @@ switch ($Operation) {
$module = Get-Module -Name $DscResourceInfo.ModuleName -ListAvailable | Sort-Object -Property Version -Descending | Select-Object -First 1
if ($module.PrivateData.PSData.DscCapabilities) {
$capabilities = $module.PrivateData.PSData.DscCapabilities
}
else {
} else {
$capabilities = @('Get', 'Set', 'Test')
}
}

# this text comes directly from the resource manifest for v3 native resources
if ($DscResourceInfo.Description) {
$description = $DscResourceInfo.Description
}
elseif ($module.Description) {
} elseif ($module.Description) {
# some modules have long multi-line descriptions. to avoid issue, use only the first line.
$description = $module.Description.split("`r`n")[0]
}
else {
} else {
$description = ''
}

# match adapter to version of powershell
if ($PSVersionTable.PSVersion.Major -le 5) {
$requireAdapter = 'Microsoft.Windows/WindowsPowerShell'
}
else {
} else {
$requireAdapter = 'Microsoft.DSC/PowerShell'
}

Expand All @@ -132,7 +126,7 @@ switch ($Operation) {
} | ConvertTo-Json -Compress
}
}
{ @('Get','Set','Test','Export') -contains $_ } {
{ @('Get', 'Set', 'Test', 'Export') -contains $_ } {
$desiredState = $psDscAdapter.invoke( { param($jsonInput) Get-DscResourceObject -jsonInput $jsonInput }, $jsonInput )
if ($null -eq $desiredState) {
$trace = @{'Debug' = 'ERROR: Failed to create configuration object from provided input JSON.' } | ConvertTo-Json -Compress
Expand Down Expand Up @@ -165,21 +159,54 @@ switch ($Operation) {
}
$result += $actualState
}

# OUTPUT json to stderr for debug, and to stdout
$result = @{ result = $result } | ConvertTo-Json -Depth 10 -Compress
$trace = @{'Debug' = 'jsonOutput=' + $result } | ConvertTo-Json -Compress
$host.ui.WriteErrorLine($trace)
return $result
}
'Schema' {
$cache = Get-Content $cacheFilePath | ConvertFrom-Json

# TODO: Validate how input is passed and remove hindden properties
$resourceInfoproperties = ($cache.ResourceCache | Where-Object { $_.Type -eq 'TestClassResource/TestClassResource' }).DscResourceInfo.Properties

$props = @{}
$resourceInfoproperties | Foreach-Object {
if ($_.IsMandatory -eq $true) {
$props[$_.Name] = [hashtable]@{
type = $_.PropertyType
description = ""
}
} else {
$props[$_.Name] = [hashtable]@{
type = @($_.PropertyType, $null)
description = ""
}
}
}

$out = [resourceProperties]@{
schema = 'http://json-schema.org/draft-04/schema#'
title = ($cache.ResourceCache | Where-Object { $_.Type -eq 'TestClassResource/TestClassResource' }).Type
type = 'object'
required = @($resourceInfoproperties | Where-Object { $_.IsMandatory -eq $true }).Name
properties = $props
additionalProperties = $false
# definitions = $null # TODO: Should we add definitions
}

$out | ConvertTo-Json -Depth 10 -Compress
}
'Validate' {
# VALIDATE not implemented

# OUTPUT
@{ valid = $true } | ConvertTo-Json
}
Default {
Write-Error 'Unsupported operation. Please use one of the following: List, Get, Set, Test, Export, Validate'
Write-Error 'Unsupported operation. Please use one of the following: List, Get, Set, Test, Export, Schema, Validate'
}
}

Expand All @@ -197,3 +224,12 @@ class resourceOutput {
[string] $requireAdapter
[string] $description
}

class resourceProperties {
[string] $schema
[string] $title
[string] $type
[string[]] $required
[hashtable] $properties
[bool] $additionalProperties
}
Loading