Skip to content

Commit

Permalink
Merge pull request #210 from PlagueHO/Issue-209
Browse files Browse the repository at this point in the history
Improve xNetAdapterName Resource to handle already renamed adapters - Fixes #209
  • Loading branch information
PlagueHO committed Jun 4, 2017
2 parents 9427a60 + 544052a commit 20c090a
Show file tree
Hide file tree
Showing 11 changed files with 309 additions and 141 deletions.
8 changes: 8 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,14 @@

## Unreleased

- Find-NetworkAdapter:
- Fixed to return null if exception thrown.
- Allowed passing no selection parameters.
- MSFT_xNetAdapterName:
- Fixed bug in Get-TargetResource when Name is the only adapter selector parameter.
- Improved verbose logging.
- More improvements to verbose logging.

## 4.1.0.0

- Added integration test to test for conflicts with other common resource kit modules.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@ $localizedData = Get-LocalizedData `
#>
function Get-TargetResource
{
[CmdletBinding()]
[OutputType([System.Collections.Hashtable])]
param
(
Expand Down Expand Up @@ -109,15 +110,25 @@ function Get-TargetResource
)

Write-Verbose -Message ( @("$($MyInvocation.MyCommand): "
$($LocalizedData.GettingNetAdapterNameMessage)
$($LocalizedData.GettingNetAdapterNameMessage -f $NewName)
) -join '')

$null = $PSBoundParameters.Remove('Name')
$null = $PSBoundParameters.Remove('NewName')

$adapter = Find-NetworkAdapter `
@PSBoundParameters `
-ErrorAction Stop
-Name $NewName `
-ErrorAction SilentlyContinue

if (-not $adapter)
{
Write-Verbose -Message ( @( "$($MyInvocation.MyCommand): "
$($LocalizedData.FindNetAdapterMessage)
) -join '')

$null = $PSBoundParameters.Remove('NewName')

$adapter = Find-NetworkAdapter `
@PSBoundParameters `
-ErrorAction Stop
}

Write-Verbose -Message ( @( "$($MyInvocation.MyCommand): "
$($LocalizedData.NetAdapterNameFoundMessage -f $adapter.Name)
Expand Down Expand Up @@ -180,6 +191,7 @@ function Get-TargetResource
#>
function Set-TargetResource
{
[CmdletBinding()]
param
(
[Parameter(Mandatory = $true)]
Expand Down Expand Up @@ -231,7 +243,7 @@ function Set-TargetResource
)

Write-Verbose -Message ( @( "$($MyInvocation.MyCommand): "
$($LocalizedData.SettingNetAdapterNameMessage)
$($LocalizedData.SettingNetAdapterNameMessage -f $NewName)
) -join '')

$null = $PSBoundParameters.Remove('NewName')
Expand Down Expand Up @@ -293,6 +305,7 @@ function Set-TargetResource
#>
function Test-TargetResource
{
[CmdletBinding()]
[OutputType([System.Boolean])]
param
(
Expand Down Expand Up @@ -345,32 +358,37 @@ function Test-TargetResource
)

Write-Verbose -Message ( @("$($MyInvocation.MyCommand): "
$($LocalizedData.TestingNetAdapterNameMessage)
$($LocalizedData.TestingNetAdapterNameMessage -f $NewName)
) -join '')

$null = $PSBoundParameters.Remove('NewName')
try
{
$adapter = Find-NetworkAdapter `
@PSBoundParameters `
-ErrorAction Stop
}
catch
{
$PSBoundParameters.Name = $NewName
$adapter = Find-NetworkAdapter `
@PSBoundParameters `
-ErrorAction Stop
}
if ($adapter.Name -eq $NewName)

# Can an adapter be found with the new name?
$adapterWithNewName = Find-NetworkAdapter `
-Name $NewName `
-Verbose:$Verbose `
-ErrorAction SilentlyContinue

if ($adapterWithNewName)
{
# An adapter was found matching the new name
Write-Verbose -Message ( @("$($MyInvocation.MyCommand): "
$($LocalizedData.NetAdapterNameMatchMessage -f $adapter.Name)
$($LocalizedData.NetAdapterWithNewNameExistsMessage -f $adapterWithNewName.Name)
) -join '')
return $true
}
else
{
# Find an adapter matching the parameters - throw if none can be found
Write-Verbose -Message ( @( "$($MyInvocation.MyCommand): "
$($LocalizedData.FindNetAdapterMessage)
) -join '')

$adapter = Find-NetworkAdapter `
@PSBoundParameters `
-ErrorAction Stop

# An adapter was found that needs to be changed to the new name
Write-Verbose -Message ( @("$($MyInvocation.MyCommand): "
$($LocalizedData.NetAdapterNameNotMatchMessage -f $adapter.Name,$NewName)
) -join '')
Expand Down
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
ConvertFrom-StringData @'
GettingNetAdapterNameMessage = Getting the Network Adapter Name.
NetAdapterNameFoundMessage = Network Adapter '{0}' found.
SettingNetAdapterNameMessage = Setting the Network Adapter Name.
RenamingNetAdapterNameMessage = Renaming Network Adapter '{0}' to '{1}'.
NetAdapterNameRenamedMessage = Network Adapter renamed to '{0}'.
TestingNetAdapterNameMessage = Testing the Network Adapter Name.
NetAdapterNameMatchMessage = Network Adapter Name '{0}' matches the adapter that was found.
NetAdapterNameNotMatchMessage = Network Adapter Name '{0}' does not match the adapter '{1}' that was found.
GettingNetAdapterNameMessage = Getting the network adapter Name '{0}'.
FindNetAdapterMessage = Finding network adapter matching search criteria.
NetAdapterNameFoundMessage = network adapter '{0}' found.
SettingNetAdapterNameMessage = Setting the network adapter Name '{0}'.
RenamingNetAdapterNameMessage = Renaming network adapter '{0}' to '{1}'.
NetAdapterNameRenamedMessage = network adapter renamed to '{0}'.
TestingNetAdapterNameMessage = Testing the network adapter Name '{0}'.
NetAdapterWithNewNameExistsMessage = A network adapter was found with the intended new name '{0}' of the Adapter. No rename required.
NetAdapterNameNotMatchMessage = network adapter Name '{0}' does not match the adapter '{1}' that was found. Rename required.
'@
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,7 @@ function Convert-CIDRToSubhetMask
#>
function Find-NetworkAdapter
{
[CmdletBinding()]
[OutputType([System.Collections.Hashtable])]
param
(
Expand Down Expand Up @@ -200,21 +201,28 @@ function Find-NetworkAdapter

if ($adapterFilters.Count -eq 0)
{
New-InvalidOperationException `
-Message ($LocalizedData.NetAdapterParameterError)
}

# Join all the filters together
$adapterFilterScript = '(' + ($adapterFilters -join ' -and ') + ')'
Write-Verbose -Message ( @("$($MyInvocation.MyCommand): "
$($LocalizedData.AllNetAdaptersFoundMessage)
) -join '')

$matchingAdapters = @(Get-NetAdapter |
Where-Object -FilterScript ([ScriptBlock]::Create($adapterFilterScript)))
$matchingAdapters = @(Get-NetAdapter)
}
else
{
# Join all the filters together
$adapterFilterScript = '(' + ($adapterFilters -join ' -and ') + ')'
$matchingAdapters = @(Get-NetAdapter |
Where-Object -FilterScript ([ScriptBlock]::Create($adapterFilterScript)))
}

# Were any adapters found matching the criteria?
if ($matchingAdapters.Count -eq 0)
{
New-InvalidOperationException `
-Message ($LocalizedData.NetAdapterNotFoundError)

# Return a null so that ErrorAction SilentlyContinue works correctly
return $null
}
else
{
Expand All @@ -232,13 +240,19 @@ function Find-NetworkAdapter
New-InvalidOperationException `
-Message ($LocalizedData.InvalidNetAdapterNumberError `
-f $matchingAdapters.Count,$InterfaceNumber)

# Return a null so that ErrorAction SilentlyContinue works correctly
return $null
} # if
}
else
{
New-InvalidOperationException `
-Message ($LocalizedData.MultipleMatchingNetAdapterFound `
-f $matchingAdapters.Count)

# Return a null so that ErrorAction SilentlyContinue works correctly
return $null
} # if
} # if
} # if
Expand All @@ -257,7 +271,7 @@ function Find-NetworkAdapter
MatchingAdapterCount = $matchingAdapters.Count
}

$returnValue
return $returnValue
} # Find-NetworkAdapter

Export-ModuleMember -Function `
Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
ConvertFrom-StringData @'
FindingNetAdapterMessage = Finding Network Adapters matching the parameters.
NetAdapterFoundMessage = {0} Network Adapters were found matching the parameters.
NetAdapterParameterError = At least one Network Adapter parameter must be passed.
NetAdapterNotFoundError = A Network Adapter matching the parameters was not found. Please correct the properties and try again.
FindingNetAdapterMessage = Finding network adapters matching the parameters.
AllNetAdaptersFoundMessage = Found all network adapters because no filter parameters provided.
NetAdapterFoundMessage = {0} network adapters were found matching the parameters.
NetAdapterNotFoundError = A network adapter matching the parameters was not found. Please correct the properties and try again.
MultipleMatchingNetAdapterFound = Please adjust the parameters or specify IgnoreMultipleMatchingAdapters to only use the first and try again.
InvalidNetAdapterNumberError = Network Adapter interface number {0} was specified but only {1} was found. Please correct the interface number and try again.
InvalidNetAdapterNumberError = network adapter interface number {0} was specified but only {1} was found. Please correct the interface number and try again.
'@
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ The **xNetworking** module contains the following resources:
- **xNetAdapterRDMA**: Enable or disable RDMA on a network adapter.
- **xNetAdapterLso**: Enable or disable Lso for different protocols
on a network adapter.
- **xNetAdapterName**: Rename a network interface that matches specified search parameters.

This project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/).
For more information see the [Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/)
Expand Down
80 changes: 70 additions & 10 deletions Tests/Integration/MSFT_xNetAdapterName.Integration.Tests.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -24,11 +24,11 @@ $TestEnvironment = Initialize-TestEnvironment `
# Using try/finally to always cleanup even if something awful happens.
try
{
#region Integration Tests
$ConfigFile = Join-Path -Path $PSScriptRoot -ChildPath "$($script:DSCResourceName).config.ps1"
. $ConfigFile -Verbose -ErrorAction Stop
#region Integration Tests with all parameters
Describe "$($script:DSCResourceName)_Integration using all parameters" {
$ConfigFile = Join-Path -Path $PSScriptRoot -ChildPath "$($script:DSCResourceName)_all.config.ps1"
. $ConfigFile -Verbose -ErrorAction Stop

Describe "$($script:DSCResourceName)_Integration" {
BeforeAll {
$adapterName = 'xNetworkingLBA'
New-IntegrationLoopbackAdapter -AdapterName $adapterName
Expand All @@ -37,7 +37,7 @@ try
}

#region DEFAULT TESTS
It 'should compile and apply the MOF without throwing' {
It 'Should compile and apply the MOF without throwing' {
{
# This is to pass to the Config
$configData = @{
Expand All @@ -56,31 +56,91 @@ try
)
}

& "$($script:DSCResourceName)_Config" `
& "$($script:DSCResourceName)_Config_All" `
-OutputPath $TestDrive `
-ConfigurationData $configData

Start-DscConfiguration -Path $TestDrive `
-ComputerName localhost -Wait -Verbose -Force
} | Should Not Throw
}

it 'should reapply the MOF without throwing' {
{ Start-DscConfiguration -Path $TestDrive `
-ComputerName localhost -Wait -Verbose -Force } | Should Not Throw
}

It 'Should be able to call Get-DscConfiguration without throwing' {
{ Get-DscConfiguration -Verbose -ErrorAction Stop } | Should Not throw
}
#endregion

It 'Should have set the resource and all the parameters should match' {
$current = Get-DscConfiguration | Where-Object {$_.ConfigurationName -eq "$($script:DSCResourceName)_Config_All"}
$current.Name | Should Be $newAdapterName
}

AfterAll {
# Remove Loopback Adapter
Remove-IntegrationLoopbackAdapter -AdapterName $adapterName
Remove-IntegrationLoopbackAdapter -AdapterName $newAdapterName
}
}
#endregion

#region Integration Tests with name parameter only
Describe "$($script:DSCResourceName)_Integration using name parameter only" {
$ConfigFile = Join-Path -Path $PSScriptRoot -ChildPath "$($script:DSCResourceName)_nameonly.config.ps1"
. $ConfigFile -Verbose -ErrorAction Stop

BeforeAll {
$adapterName = 'xNetworkingLBA'
New-IntegrationLoopbackAdapter -AdapterName $adapterName
$adapter = Get-NetAdapter -Name $adapterName
$newAdapterName = 'xNetworkingLBANew'
}

#region DEFAULT TESTS
It 'Should compile and apply the MOF without throwing' {
{
# This is to pass to the Config
$configData = @{
AllNodes = @(
@{
NodeName = 'localhost'
NewName = $newAdapterName
Name = $adapter.Name
}
)
}

& "$($script:DSCResourceName)_Config_NameOnly" `
-OutputPath $TestDrive `
-ConfigurationData $configData

Start-DscConfiguration -Path $TestDrive `
-ComputerName localhost -Wait -Verbose -Force
} | Should Not Throw
}

it 'should reapply the MOF without throwing' {
{Start-DscConfiguration -Path $TestDrive `
-ComputerName localhost -Wait -Verbose -Force} | Should Not Throw
{ Start-DscConfiguration -Path $TestDrive `
-ComputerName localhost -Wait -Verbose -Force } | Should Not Throw
}

It 'should be able to call Get-DscConfiguration without throwing' {
It 'Should be able to call Get-DscConfiguration without throwing' {
{ Get-DscConfiguration -Verbose -ErrorAction Stop } | Should Not throw
}
#endregion

It 'Should have set the resource and all the parameters should match' {
$current = Get-DscConfiguration | Where-Object {$_.ConfigurationName -eq "$($script:DSCResourceName)_Config"}
$current = Get-DscConfiguration | Where-Object {$_.ConfigurationName -eq "$($script:DSCResourceName)_Config_NameOnly"}
$current.Name | Should Be $newAdapterName
}

AfterAll {
# Remove Loopback Adapter
Remove-IntegrationLoopbackAdapter -AdapterName $adapterName
Remove-IntegrationLoopbackAdapter -AdapterName $newAdapterName
}
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
configuration MSFT_xNetAdapterName_Config {
configuration MSFT_xNetAdapterName_Config_All {
Import-DscResource -ModuleName xNetworking

node localhost {
Expand Down
10 changes: 10 additions & 0 deletions Tests/Integration/MSFT_xNetAdapterName_nameonly.config.ps1
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
configuration MSFT_xNetAdapterName_Config_NameOnly {
Import-DscResource -ModuleName xNetworking

node localhost {
xNetAdapterName Integration_Test {
Name = $Node.Name
NewName = $Node.NewName
}
}
}
Loading

0 comments on commit 20c090a

Please sign in to comment.