DSCResources/cSwitchEmbeddedTeam/cSwitchEmbeddedTeam.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
# Fallback message strings in en-US
DATA localizedData
{
    # same as culture = "en-US"
ConvertFrom-StringData @'
    PacketDirectMustUseHyperVPort=Using Enable Packet Redirect on the SET team must use Hyper-V Port mode as the load balancing algorightm. This will reset the LB mode.
    NoHyperVModule=Hyper-V PowerShell Module not found.
    CheckSETMembers=Checking if SET network adapter members match or not.
    TeamMembersUpdate=SET Network Adapter members mismatch. This will be updated.
    LBUpdate=SET load balancing mode is different. It will be updated.
    TeamingModeUpdate=SET teaming mode is differet. It will be updated.
    UpdatingSETeam=Updating SET configuration as requested.
    UpdateAllowManagementOS=Updating AllowManagementOS on the VM switch associated with the SET.
    IOVcannotbeUpdated=EnableIOV cannot be updated once SET is created. Ignoring this change in configuration.
    ReservationModeCannotBeUpdated=Reservation mode cannot be updated once SET is created. Ignoring this change in configuration.
    PacketDirectCannotBeUpdated=Packet Direct cannot be updated once SET is created. Ignoring this change in configuration.
    CheckNetAdapter=Checking if network adapter specified is a part of another VM switch.
    SwitchWithNameExists=Another switch with specified name already exists. It is not recommeded to use the same name for mulitple switches.
    UsedAdapter=One of the adapters in the specified SET configuration is being used in another switch.
    CreateSET=Creating SwitchEmbeddedTeam.
    UpdateSET=Updating SwitchEmbeddedTeam.
    RemoveSET=Removing SwitchEmbeddedTeam.
    CheckSwitchExists=Checking if SET already exists.
    SETMembersDontMatch=SET members don't match. This team will be updated.
    CheckSETIOV=Checking if IOV is enabled.
    CheckSETReservationMode=Checking if reservation mode is configured as desired.
    CheckSETEnablePacketDirect=Checking if packet direct is enabled.
    CheckSETLoadBalacing=Checking if load balancing mode is configured as desired.
    CheckSETTeamingMode=Checking if SET teaming mode is configured as desired.
    SwitchConfigPresentNoAction=Switch configuration present as desired. No action needed.
    SwitchPresentRemove=Switch team is present while it should not. It will be removed.
    SwitchNotPresentCreate=Switch team does not exist. It will be created.
    SwitchNotPresentNoAction=Switch team exists. No action needed.
    SwitchNotPresent=Switch is not present.
    CheckSETAllowManagementOS=Checking if AllowManagementOS configurtion is present.
'@

}

if (Test-Path "$PSScriptRoot\$PSCulture")
{
    Import-LocalizedData LocalizedData -filename "cSwitchEmbeddedTeam.psd1" -BaseDirectory "$PSScriptRoot\$PSCulture"
}

function Get-TargetResource
{
    [CmdletBinding()]
    [OutputType([System.Collections.Hashtable])]
    param
    (
        [parameter(Mandatory)]
        [String]$Name,

        [parameter()]
        [String[]]$NetAdapterName
    )

    # Check if Hyper-V module is present for Hyper-V cmdlets
    if(!(Get-Module -ListAvailable -Name Hyper-V))
    {
        Throw $localizedData.NoHyperVModule
    }

    $SwitchTeam = Get-VMSwitchTeam -Name $Name -ErrorAction SilentlyContinue
    $Switch = Get-VMSwitch -Name $Name -ErrorAction SilentlyContinue

    $SwitchAdapter = ((Get-NetAdapter).Where({$switchTeam.NetAdapterInterfaceDescription -contains $_.InterfaceDescription})).Name

    @{
        Name              = $SwitchTeam.Name
        NetAdapterName    = $SwitchAdapter
        AllowManagementOS = $switch.AllowManagementOS
        EnablePacketDirect = $Switch.PacketDirectEnabled
        EnableIov = $switch.IovEnabled
        BandwidthReservationMode = $switch.BandwidthReservationMode
        TeamingMode = $SwitchTeam.TeamingMode
        LoadBalancingAlgorithm = $SwitchTeam.LoadBalancingAlgorithm
    }
}


function Set-TargetResource
{
    [CmdletBinding()]
    param
    (
        [parameter(Mandatory)]
        [String]$Name,

        [Parameter()]
        [ValidateNotNullOrEmpty()]
        [ValidateCount(1,8)]
        [String[]]$NetAdapterName,

        [Parameter()]
        [Boolean]$AllowManagementOS,

        [Parameter()]
        [Boolean]$EnableIov,

        [Parameter()]
        [Boolean]$EnablePacketDirect,

        [parameter()]
        [ValidateSet('SwitchIndependent')]
        [String]$TeamingMode='SwitchIndependent',

        [parameter()]
        [ValidateSet('Dynamic','HyperVPort')]
        [String]$LoadBalancingAlgorithm='Dynamic',

        [Parameter()]
        [ValidateSet('None', 'Default', 'Weight', 'Absolute')]
        [String] $BandwidthReservationMode,

        [ValidateSet("Present","Absent")]
        [String]$Ensure = "Present"
    )

    # Check if Hyper-V module is present for Hyper-V cmdlets
    if(!(Get-Module -ListAvailable -Name Hyper-V))
    {
        Throw $localizedData.NoHyperVModule
    }

    if($Ensure -eq 'Present')
    {
        $switchTeam = (Get-VMSwitchTeam -Name $Name -ErrorAction SilentlyContinue)
        if($switchTeam)
        {
            $switch = Get-VMSwitch -Name $Name -ErrorAction SilentlyContinue
            
            Write-Verbose $localizedData.CheckSETMembers
            $SwitchAdapter = ((Get-NetAdapter).Where({$switchTeam.NetAdapterInterfaceDescription -contains $_.InterfaceDescription})).Name
            $SwitchTeamMembers = Compare-Object -ReferenceObject $NetAdapterName -DifferenceObject $SwitchAdapter
            
            $TeamParameters = @{
                Name = $name
            }
            
            if($SwitchTeamMembers -ne $null)
            {
                $TeamParameters.Add('NetAdapterName',$NetAdapterName)
                $UpdateTeam = $true
                Write-Verbose $localizedData.TeamMembersUpdate
            }

            if ($switchTeam.LoadBalancingAlgorithm -ne $LoadBalancingAlgorithm) {
                $TeamParameters.Add('LoadBalancingAlgorithm',$LoadBalancingAlgorithm)
                Write-Verbose $localizedData.LBUpdate
                $UpdateTeam = $true
            }

            if ($switchTeam.TeamingMode -ne $TeamingMode) {
                $TeamParameters.Add('TeamingMode', $TeamingMode)
                Write-Verbose $localizedData.TeamingModeUpdate
                $UpdateTeam = $true
            }

            if ($UpdateTeam) {
                Write-Verbose $localizedData.UpdatingSETeam
                Set-VMSwitchTeam @TeamParameters -Verbose
            }
            
            if ($switch.AllowManagementOS -ne $AllowManagementOS) {
                Write-Verbose $localizedData.UpdateAllowManagementOS
                $switch | Set-VMSwitch -AllowManagementOS $AllowManagementOS -Verbose
            }

            if ($switch.IovEnabled -ne $EnableIov) {
                Write-Warning $localizedData.IOVcannotbeUpdated  
            } elseif ($BandwidthReservationMode -and ($switch.BandwidthReservationMode -ne $BandwidthReservationMode)) {
                Write-Warning $locallizedData.ReservationModeCannotBeUpdated  
            }

            if ($switch.PacketDirectEnabled -ne $EnablePacketDirect) {
                Write-Warning $localizedData.PacketDirectCannotBeUpdated
            }
        } else {
            Write-Verbose -Message $localizedData.CheckNetAdapter
            $VMSwitchArray = Get-VMSwitch
            Foreach ($vmSwitch in $VMSwitchArray) {
                if ($vmSwitch.Name -eq $Name) {
                    Write-Warning $localizedData.SwitchWithNameExists
                }

                $SwitchAdapter = ((Get-NetAdapter).Where({$vmSwitch.NetAdapterInterfaceDescriptions -contains $_.InterfaceDescription})).Name
                $UsedAdapter = ((Compare-Object $SwitchAdapter $NetAdapterName -IncludeEqual).Where({$_.SideIndicator -eq '=='})).InputObject
                if ($UsedAdapter) {
                    Throw $localizedData.UsedAdapter
                }
            }
            
            $parameters = @{
                Name = $Name
                NetAdapterName = $NetAdapterName
                AllowManagementOS = $AllowManagementOS
                EnablePacketDirect = $EnablePacketDirect
            }
            
            if ($EnablePacketDirect -and ($LoadBalancingAlgorithm -ne 'HyperVPort')) {
                Write-Warning $localizedData.PacketDirectMustUseHyperVPort
                $LoadBalancingAlgorithm = 'HyperVPort'
            }

            if ($NetAdapterName.Length -eq 1) {
                $parameters.Add('EnableEmbeddedTeaming',$true)
            }
            
            if ($EnableIov) {
                $parameters.Add('EnableIov',$true)
            } elseif($BandwidthReservationMode) {
                $parameters.Add('MinimumBandwidthMode',$BandwidthReservationMode)
            }

            Write-Verbose $localizedData.CreateSET
            $null = New-VMSwitch @parameters -ErrorAction Stop

            Write-Verbose $localizedData.UpdateSET
            $null = Set-VMSwitchTeam -Name $Name -TeamingMode $TeamingMode -LoadBalancingAlgorithm $LoadBalancingAlgorithm -ErrorAction Stop
        }
    }
    # Ensure is set to "Absent", remove the switch
    else
    {
        Write-Verbose $localizedData.RemoveSET
        Get-VMSwitch $Name -ErrorAction SilentlyContinue | Remove-VMSwitch -Force -ErrorAction Stop
    }
}


function Test-TargetResource
{
    [CmdletBinding()]
    [OutputType([System.Boolean])]
    param
    (
        [parameter(Mandatory)]
        [String]$Name,

        [Parameter()]
        [ValidateNotNullOrEmpty()]
        [ValidateCount(1,8)]
        [String[]]$NetAdapterName,

        [Parameter()]
        [Boolean]$AllowManagementOS,

        [Parameter()]
        [Boolean]$EnableIov,

        [Parameter()]
        [Boolean]$EnablePacketDirect,

        [parameter()]
        [ValidateSet('SwitchIndependent')]
        [String]$TeamingMode='SwitchIndependent',

        [parameter()]
        [ValidateSet('Dynamic','HyperVPort')]
        [String]$LoadBalancingAlgorithm='Dynamic',

        [Parameter()]
        [ValidateSet('None', 'Default', 'Weight', 'Absolute')]
        [String] $BandwidthReservationMode,

        [ValidateSet("Present","Absent")]
        [String]$Ensure = "Present"
    )

    # Check if Hyper-V module is present for Hyper-V cmdlets
    if(!(Get-Module -ListAvailable -Name Hyper-V))
    {
        Throw $localizedData.NoHyperVModule
    }

    try
    {
        # Check if switch exists
        Write-Verbose $localizedData.CheckSwitchExists
        $switchTeam = Get-VMSwitchTeam -Name $Name -ErrorAction Stop

        # If SET exists
        if($switchTeam)
        {
            $Switch = Get-VMSwitch -Name $Name
            if($Ensure -eq 'Present')
            {
                Write-Verbose $localizedData.CheckSETMembers
                $SwitchAdapter = ((Get-NetAdapter).Where({$switchTeam.NetAdapterInterfaceDescription -contains $_.InterfaceDescription})).Name
                $SwitchTeamMembers = Compare-Object -ReferenceObject $NetAdapterName -DifferenceObject $SwitchAdapter
                if($SwitchTeamMembers -ne $null)
                {
                    Write-Verbose $localizedData.SETMembersDontMatch
                    return $false
                }
                 
                if($PSBoundParameters.ContainsKey("AllowManagementOS"))
                {
                    Write-Verbose $localizedData.CheckSETAllowManagementOS
                    if(($switch.AllowManagementOS -ne $AllowManagementOS))
                    {
                        Write-Verbose $localizedData.UpdateAllowManagementOS    
                        return $false
                    }
                }

                if ($EnableIov) {
                    Write-Verbose $localizedData.CheckSETIOV
                    if (-not $switch.IovEnabled) {
                        Write-Warning $localizedData.IOVcannotbeUpdated

                        #We cannot update this configuration once switch is created unless we destroy and re-create. Destroying is a good option. So, don't return false.
                        return $true    
                    }
                } else {
                    Write-Verbose $localizedData.CheckSETReservationMode
                    if ($BandwidthReservationMode -and ($BandwidthReservationMode -ne $switch.BandwidthReservationMode)) {
                        Write-Warning $localizedData.ReservationModeCannotBeUpdated
                        return $true
                    }
                }

                if ($EnablePacketDirect) {
                    Write-Verbose $localizedData.CheckSETEnablePacketDirect
                    if (-not $switch.EnablePacketDirect) {
                        Write-Warning $localizedData.PacketDirectCannotBeUpdated
                        #We cannot update this configuration once switch is created unless we destroy and re-create. Destroying is a good option. So, don't return false.
                        return $true
                    }                    
                }

                Write-Verbose $localizedData.CheckSETLoadBalacing
                if ($switchTeam.LoadBalancingAlgorithm -ne $LoadBalancingAlgorithm) {
                    return $false
                }
                
                Write-Verbose $localizedData.CheckSETTeamingMode
                if ($switchTeam.TeamingMode -ne $TeamingMode) {
                    return $false
                }

                Write-Verbose $localizedData.SwitchConfigPresentNoAction
                return $true
            }
            # If switch should be absent, but is there, return $false
            else
            {
                Write-Verbose $localizedData.SwitchPresentRemove
                return $false
            }
        } else {
            if ($Ensure -eq 'Present') {
                Write-Verbose $localizedData.SwitchNotPresentCreate
                return $false
            } else {
                Write-Verbose $localizedData.SwitchNotPresentNoAction
                return $true
            }
        }
    }

    catch [System.Management.Automation.ActionPreferenceStopException]
    {
        Write-Verbose $localizedData.SwitchNotPresent
        return $false
    }
}

Export-ModuleMember -Function *-TargetResource