DSCResources/MSFT_xCluster/MSFT_xCluster.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
Import-Module -Name (Join-Path -Path (Split-Path -Path $PSScriptRoot -Parent) `
        -ChildPath 'CommonResourceHelper.psm1')

$script:localizedData = Get-LocalizedData -ResourceName 'MSFT_xCluster'

<#
    .SYNOPSIS
        Returns the current state of the failover cluster.
 
    .PARAMETER Name
        Name of the failover cluster.
 
    .PARAMETER StaticIPAddress
        Static IP Address of the failover cluster.
 
    .PARAMETER IgnoreNetwork
        One or more networks to ignore when creating the cluster. Only networks
        using Static IP can be ignored, networks that are assigned an IP address
        through DHCP cannot be ignored, and are added for cluster communication.
        To remove networks assigned an IP address through DHCP use the resource
        xClusterNetwork to change the role of the network.
        This parameter is only used during the creation of the cluster and is
        not monitored after.
 
    .PARAMETER DomainAdministratorCredential
        Credential used to create the failover cluster in Active Directory.
#>

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

        [Parameter()]
        [System.String]
        $StaticIPAddress,

        [Parameter()]
        [System.String[]]
        $IgnoreNetwork,

        [Parameter(Mandatory = $true)]
        [System.Management.Automation.PSCredential]
        $DomainAdministratorCredential
    )

    Write-Verbose -Message ($script:localizedData.GetClusterInformation -f $Name)

    $computerInformation = Get-CimInstance -ClassName Win32_ComputerSystem
    if (($null -eq $computerInformation) -or ($null -eq $computerInformation.Domain))
    {
        $errorMessage = $script:localizedData.TargetNodeDomainMissing
        New-InvalidOperationException -Message $errorMessage
    }

    try
    {
        ($oldToken, $context, $newToken) = Set-ImpersonateAs -Credential $DomainAdministratorCredential

        $cluster = Get-Cluster -Name $Name -Domain $computerInformation.Domain
        if ($null -eq $cluster)
        {
            $errorMessage = $script:localizedData.ClusterNameNotFound -f $Name
            New-ObjectNotFoundException -Message $errorMessage
        }

        # This will return the IP address regardless if using Static IP or DHCP.
        $address = Get-ClusterResource -Cluster $Name -Name 'Cluster IP Address' | Get-ClusterParameter -Name 'Address'
    }
    finally
    {
        if ($context)
        {
            $context.Undo()
            $context.Dispose()
            Close-UserToken -Token $newToken
        }
    }

    @{
        Name                          = $Name
        StaticIPAddress               = $address.Value
        IgnoreNetwork                 = $IgnoreNetwork
        DomainAdministratorCredential = $DomainAdministratorCredential
    }
}

<#
    .SYNOPSIS
        Creates the failover cluster and adds a node to the failover cluster.
 
    .PARAMETER Name
        Name of the failover cluster.
 
    .PARAMETER StaticIPAddress
        Static IP Address of the failover cluster.
 
    .PARAMETER IgnoreNetwork
        One or more networks to ignore when creating the cluster. Only networks
        using Static IP can be ignored, networks that are assigned an IP address
        through DHCP cannot be ignored, and are added for cluster communication.
        To remove networks assigned an IP address through DHCP use the resource
        xClusterNetwork to change the role of the network.
        This parameter is only used during the creation of the cluster and is
        not monitored after.
 
    .PARAMETER DomainAdministratorCredential
        Credential used to create the failover cluster in Active Directory.
 
    .NOTES
        If the cluster does not exist, it will be created in the domain and the
        static IP address will be assigned to the cluster.
        When the cluster exist (either it was created or already existed), it
        will add the target node ($env:COMPUTERNAME) to the cluster.
        If the target node already is a member of the failover cluster but has
        status down, it will be removed and then added again to the failover
        cluster.
#>

function Set-TargetResource
{
    param
    (
        [Parameter(Mandatory = $true)]
        [System.String]
        $Name,

        [Parameter()]
        [System.String]
        $StaticIPAddress,

        [Parameter()]
        [System.String[]]
        $IgnoreNetwork,

        [Parameter(Mandatory = $true)]
        [System.Management.Automation.PSCredential]
        $DomainAdministratorCredential
    )

    $bCreate = $true

    Write-Verbose -Message ($script:localizedData.CheckClusterPresent -f $Name)

    $computerInformation = Get-CimInstance -ClassName Win32_ComputerSystem
    if (($null -eq $computerInformation) -or ($null -eq $computerInformation.Domain))
    {
        $errorMessage = $script:localizedData.TargetNodeDomainMissing
        New-InvalidOperationException -Message $errorMessage
    }

    try
    {
        $cluster = Get-Cluster -Name $Name -Domain $computerInformation.Domain

        if ($cluster)
        {
            $bCreate = $false
        }
    }
    catch
    {
        $bCreate = $true
    }

    try
    {
        ($oldToken, $context, $newToken) = Set-ImpersonateAs -Credential $DomainAdministratorCredential

        if ($bCreate)
        {
            Write-Verbose -Message ($script:localizedData.ClusterAbsent -f $Name)

            $newClusterParameters = @{
              Name          = $Name
              Node          = $env:COMPUTERNAME
              NoStorage     = $true
              ErrorAction   = 'Stop'
            }

            if ((Get-Command New-Cluster).Parameters['Force'])
            {
                $newClusterParameters.Force = $true
            }

            if ($StaticIPAddress)
            {
                $newClusterParameters += @{
                    StaticAddress = $StaticIPAddress
                  }
            }

            if ($PSBoundParameters.ContainsKey('IgnoreNetwork'))
            {
                $newClusterParameters += @{
                    IgnoreNetwork = $IgnoreNetwork
                }
            }

            New-Cluster @newClusterParameters

            if (-not (Get-Cluster))
            {
                $errorMessage = $script:localizedData.FailedCreatingCluster
                New-InvalidOperationException -Message $errorMessage
            }

            Write-Verbose -Message ($script:localizedData.ClusterCreated -f $Name)
        }
        else
        {
            $targetNodeName = $env:COMPUTERNAME

            Write-Verbose -Message ($script:localizedData.AddNodeToCluster -f $targetNodeName, $Name)

            $list = Get-ClusterNode -Cluster $Name
            foreach ($node in $list)
            {
                if ($node.Name -eq $targetNodeName)
                {
                    if ($node.State -eq 'Down')
                    {
                        Write-Verbose -Message ($script:localizedData.RemoveOfflineNodeFromCluster -f $targetNodeName, $Name)

                        Remove-ClusterNode -Name $targetNodeName -Cluster $Name -Force
                    }
                }
            }

            Add-ClusterNode -Name $targetNodeName -Cluster $Name -NoStorage

            Write-Verbose -Message ($script:localizedData.AddNodeToClusterSuccessful -f $targetNodeName, $Name)
        }
    }
    finally
    {
        if ($context)
        {
            $context.Undo()
            $context.Dispose()
            Close-UserToken -Token $newToken
        }
    }
}

<#
    .SYNOPSIS
        Test the failover cluster exist and that the node is a member of the
        failover cluster.
 
    .PARAMETER Name
        Name of the failover cluster.
 
    .PARAMETER StaticIPAddress
        Static IP Address of the failover cluster.
        Not used in Test-TargetResource.
 
    .PARAMETER IgnoreNetwork
        One or more networks to ignore when creating the cluster. Only networks
        using Static IP can be ignored, networks that are assigned an IP address
        through DHCP cannot be ignored, and are added for cluster communication.
        To remove networks assigned an IP address through DHCP use the resource
        xClusterNetwork to change the role of the network.
        This parameter is only used during the creation of the cluster and is
        not monitored after.
 
        Not used in Test-TargetResource. Currently it is unknown how to determine
        which networks are ignored, to test so they ar ein desired state.
 
    .PARAMETER DomainAdministratorCredential
        Credential used to create the failover cluster in Active Directory.
 
    .NOTES
        The code will check the following in order:
 
          1. Is target node a member of the Active Directory domain?
          2. Does the failover cluster exist in the Active Directory domain?
          3. Is the target node a member of the failover cluster?
          4. Does the cluster node have the status UP?
 
        If the first return false an error will be thrown. If either of the
        other return $false, then the cluster will be created, if it does not
        exist and then the node will be added to the failover cluster.
#>

function Test-TargetResource
{
    [OutputType([Boolean])]
    param
    (
        [Parameter(Mandatory = $true)]
        [System.String]
        $Name,

        [Parameter()]
        [System.String]
        $StaticIPAddress,

        [Parameter()]
        [System.String[]]
        $IgnoreNetwork,

        [Parameter(Mandatory = $true)]
        [System.Management.Automation.PSCredential]
        $DomainAdministratorCredential
    )

    $returnValue = $false

    Write-Verbose -Message ($script:localizedData.CheckClusterPresent -f $Name)

    $ComputerInfo = Get-CimInstance -ClassName Win32_ComputerSystem
    if (($null -eq $ComputerInfo) -or ($null -eq $ComputerInfo.Domain))
    {
        $errorMessage = $script:localizedData.TargetNodeDomainMissing
        New-InvalidOperationException -Message $errorMessage
    }

    try
    {
        ($oldToken, $context, $newToken) = Set-ImpersonateAs -Credential $DomainAdministratorCredential

        $cluster = Get-Cluster -Name $Name -Domain $ComputerInfo.Domain

        Write-Verbose -Message ($script:localizedData.ClusterPresent -f $Name)

        if ($cluster)
        {
            $targetNodeName = $env:COMPUTERNAME

            Write-Verbose -Message ($script:localizedData.CheckClusterNodeIsUp -f $targetNodeName, $Name)

            $allNodes = Get-ClusterNode -Cluster $Name

            foreach ($node in $allNodes)
            {
                if ($node.Name -eq $targetNodeName)
                {
                    if ($node.State -eq 'Up')
                    {
                        $returnValue = $true
                    }
                    else
                    {
                        Write-Verbose -Message ($script:localizedData.ClusterNodeIsDown -f $targetNodeName, $Name)
                    }

                    break
                }
            }

            if ($returnValue)
            {
                Write-Verbose -Message ($script:localizedData.ClusterNodePresent -f $targetNodeName, $Name)
            }
            else
            {
                Write-Verbose -Message ($script:localizedData.ClusterNodeAbsent -f $targetNodeName, $Name)
            }
        }
    }
    catch
    {
        Write-Verbose -Message ($script:localizedData.ClusterAbsentWithError -f $Name, $_.Message)
    }
    finally
    {
        if ($context)
        {
            $context.Undo()
            $context.Dispose()

            Close-UserToken -Token $newToken
        }
    }

    $returnValue
}

<#
    .SYNOPSIS
        Loads and returns a reference to the impersonation library.
 
#>

function Get-ImpersonateLib
{
    if ($script:ImpersonateLib)
    {
        return $script:ImpersonateLib
    }

    $sig = @'
[DllImport("advapi32.dll", SetLastError = true)]
public static extern bool LogonUser(string lpszUsername, string lpszDomain, string lpszPassword, int dwLogonType, int dwLogonProvider, ref IntPtr phToken);
 
[DllImport("kernel32.dll")]
public static extern Boolean CloseHandle(IntPtr hObject);
'@

    $script:ImpersonateLib = Add-Type -PassThru -Namespace 'Lib.Impersonation' -Name ImpersonationLib -MemberDefinition $sig

    return $script:ImpersonateLib
}

<#
    .SYNOPSIS
        Starts to impersonate the credentials provided in parameter Credential on the current user context.
 
    .PARAMETER Credential
        The credentials that should be impersonated.
 
    .OUTPUTS
        Returns three values.
 
        First value: The current user token before impersonation.
        Second value: The impersonation context returned when impersonation is started.
        Third value: The impersonated user token.
 
    .NOTES
        LogonUser function
        https://msdn.microsoft.com/en-us/library/windows/desktop/aa378184(v=vs.85).aspx
 
        WindowsIdentity.Impersonate Method ()
        https://msdn.microsoft.com/en-us/library/w070t6ka(v=vs.110).aspx
#>

function Set-ImpersonateAs
{
    param
    (
        [Parameter(Mandatory = $true)]
        [System.Management.Automation.PSCredential]
        $Credential
    )

    [IntPtr] $userToken = [Security.Principal.WindowsIdentity]::GetCurrent().Token
    $userToken
    $ImpersonateLib = Get-ImpersonateLib

    $bLogin = $ImpersonateLib::LogonUser($Credential.GetNetworkCredential().UserName, $Credential.GetNetworkCredential().Domain, $Credential.GetNetworkCredential().Password,
        9, 0, [ref]$userToken)

    if ($bLogin)
    {
        $Identity = New-Object -TypeName Security.Principal.WindowsIdentity -ArgumentList $userToken
        $context = $Identity.Impersonate()
    }
    else
    {
        $errorMessage = $script:localizedData.UnableToImpersonateUser -f $Credential.GetNetworkCredential().UserName
        New-InvalidOperationException -Message $errorMessage
    }

    $context, $userToken
}

<#
    .SYNOPSIS
        Closes a (impersonation) user token.
 
    .PARAMETER Token
        The user token to close.
 
    .NOTES
        CloseHandle function
        https://msdn.microsoft.com/en-us/library/windows/desktop/ms724211(v=vs.85).aspx
#>

function Close-UserToken
{
    param
    (
        [Parameter(Mandatory = $true)]
        [System.IntPtr]
        $Token
    )

    $ImpersonateLib = Get-ImpersonateLib

    $bLogin = $ImpersonateLib::CloseHandle($Token)
    if (-not $bLogin)
    {
        $errorMessage = $script:localizedData.UnableToCloseToken -f $Token.ToString()
        New-InvalidOperationException -Message $errorMessage
    }
}