Skip to content

Implement schema option for PsDscAdapter #563

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

Open
wants to merge 7 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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"
}
}
}
20 changes: 20 additions & 0 deletions powershell-adapter/Tests/powershellgroup.resource.tests.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -345,4 +345,24 @@ Describe 'PowerShell adapter resource tests' {
$res = $r | ConvertFrom-Json
$res.actualState.HashTableProp.Name | Should -Be 'DSCv3'
}

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
}

# Rebuild the cache file first
dsc resource list --adapter Microsoft.DSC/PowerShell | Out-Null

$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
}
91 changes: 64 additions & 27 deletions powershell-adapter/psDscAdapter/powershell.resource.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@
# Licensed under the MIT License.
[CmdletBinding()]
param(
[Parameter(Mandatory = $true, Position = 0, HelpMessage = 'Operation to perform. Choose from List, Get, Set, Test, Export, Validate, ClearCache.')]
[ValidateSet('List', 'Get', 'Set', 'Test', 'Export', 'Validate', 'ClearCache')]
[Parameter(Mandatory = $true, Position = 0, HelpMessage = 'Operation to perform. Choose from List, Get, Set, Test, Export, Validate, Schema, 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 @@ -56,8 +56,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 @@ -70,8 +69,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 @@ -83,7 +81,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 @@ -102,20 +100,17 @@ switch ($Operation) {
# 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 @@ -135,7 +130,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) {
Write-DscTrace -Operation Error -message 'Failed to create configuration object from provided input JSON.'
Expand Down Expand Up @@ -176,7 +171,7 @@ switch ($Operation) {
}
$result += $actualState
}

# OUTPUT json to stderr for debug, and to stdout
if ($Operation -eq 'Test') {
$result = @{ result = $result; _inDesiredState = $inDesiredState } | ConvertTo-Json -Depth 10 -Compress
Expand All @@ -187,14 +182,47 @@ switch ($Operation) {
Write-DscTrace -Operation Debug -Message "jsonOutput=$result"
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-12/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-DscTrace -Operation Error -Message 'Unsupported operation. Please use one of the following: List, Get, Set, Test, Export, Validate'
Write-DscTrace -Operation Error -Message 'Unsupported operation. Please use one of the following: List, Get, Set, Test, Export, Schema, and Validate'
}
}

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

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