DSCResources/Grani_S3Content/Grani_S3Content.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
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
#region Initialize

function Initialize {
    # Enum for Item Type
    Add-Type -TypeDefinition @"
        public enum GraniDonwloadItemTypeEx
        {
            FileInfo,
            DirectoryInfo,
            Other,
            NotExists
        }
"@
 -ErrorAction SilentlyContinue

    # Enum for Ensure
    Add-Type -TypeDefinition @"
        public enum GraniDonwloadEnsuretype
        {
            Present,
            Absent
        }
"@
 -ErrorAction SilentlyContinue

    # Enum for CheckSum
    Add-Type -TypeDefinition @"
        public enum GraniDonwloadCheckSumtype
        {
            FileHash,
            FileName
        }
"@
 -ErrorAction SilentlyContinue
}

Initialize

#endregion

#region Message Definition

$debugMessage = DATA {
    ConvertFrom-StringData -StringData "
        ExecuteScriptBlock = Execute ScriptBlock without Credential. '{0}'
        ExecuteScriptBlockWithCredential = Execute ScriptBlock with Credential. '{0}'
        FileExists = File found from DestinationPath.
        IsCheckSumFileName = CheckSum was '{0}', File already exist in destination path. Complete file checking.
        IsDestinationPathExist = Checking Destination Path is existing and Valid as a FileInfo
        IsDestinationPathAlreadyUpToDate = CheckSum was '{0}', matching FileHash to verify file is already Up-To-Date.
        IsFileAlreadyUpToDate = CurrentFileHash : S3 FileHash -> {0} : {1}
        IsS3ObjectExist = Testing S3 Object is exist or not.
        ItemTypeWasFile = Destination Path found as File : '{0}'
        ItemTypeWasDirectory = Destination Path found but was Directory : '{0}'
        ItemTypeWasOther = Destination Path found but was neither File nor Directory: '{0}'
        ItemTypeWasNotExists = Destination Path not found : '{0}'
        OverrideRegion = Overriding Region : '{0}'
        ValidateS3Bucket = Checking S3 Bucket '{0}' is exist.
        ValidateS3Object = Checking S3 Object Key '{0}' is exist.
        ValidateFilePath = Check DestinationPath '{0}' is FileInfo and Parent Directory already exist.
    "

}

$verboseMessage = DATA {
    ConvertFrom-StringData -StringData "
        AlreadyUpToDate = Current DestinationPath FileHash and S3 FileHash matched. File already Up-To-Date.
        NotUpToDate = Current DestinationPath FileHash and S3 FileHash not matched. Need to download latest file.
        ResultS3Bucket = S3Bucket exist status : S3Bucket {0}, Status : {1}
        ResultS3Object = S3Object exist status : S3Object {0}, Status : {1}
        StartS3Download = Downloading S3 Object.
    "

}
$exceptionMessage = DATA {
    ConvertFrom-StringData -StringData "
        DestinationPathAlreadyExistAsNotFile = Destination Path '{0}' already exist but not a file. Found itemType is {1}. Windows not allowed exist same name item.
        S3BucketNotExistEXception = Desired S3 Bucket not found exception. S3Bucket : {0}
        S3ObjectNotExistEXception = Desired S3 Object not found in S3Bucket exception. S3Bucket : {0}, S3Object : {1}
        ScriptBlockException = Error thrown on ScriptBlock. ScriptBlock : {0}
    "

}

#endregion

#region *-TargetResource

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

        [parameter(Mandatory = $false)]
        [System.String]$Key,

        [parameter(Mandatory = $true)]
        [System.String]$DestinationPath,

        [parameter(Mandatory = $false)]
        [System.String]$PreAction = [string]::Empty,

        [parameter(Mandatory = $false)]
        [System.String]$PostAction = [string]::Empty,

        [parameter(Mandatory = $false)]
        [System.Management.Automation.PSCredential]$Credential = [PSCredential]::Empty,

        [parameter(Mandatory = $false)]
        [ValidateSet("FileHash", "FileName")]
        [System.String]$CheckSum = [GraniDonwloadCheckSumtype]::FileHash.ToString(),

        [parameter(Mandatory = $false)]
        [System.String]$Region = [string]::Empty
    )

    # Initialize return values
    # Header and OAuth2Token will never return as TypeConversion problem
    $returnHash = @{
        S3BucketName    = $S3BucketName
        Key             = $Key
        DestinationPath = $DestinationPath
        Ensure          = [GraniDonwloadEnsuretype]::Absent.ToString()
        PreAction       = $PreAction
        PostAction      = $PostAction
        Credential      = New-CimInstance -ClassName MSFT_Credential -Property @{Username = [string]$Credential.UserName; Password = [string]$null} -Namespace root/microsoft/windows/desiredstateconfiguration -ClientOnly
        CheckSum        = $CheckSum
        Region          = $Region
    }

    try {
        # Fail fast S3Bucket and S3Object existance.
        $isBucketExist = TestS3Bucket -BucketName $S3BucketName -Region $Region
        if (-not $isBucketExist) {        
            Write-Verbose -Message ($verboseMessage.ResultS3Bucket -f $S3BucketName, $isBucketExist);
            return $returnHash
        }
        $isObjectExist = TestS3Object -BucketName $S3BucketName -Key $Key -Region $Region;
        if (-not $isObjectExist) {        
            Write-Verbose -Message ($verboseMessage.ResultS3Object -f $Key, $isObjectExist);
            return $returnHash
        }

        # Start checking destination Path check if S3Bucket and S3Object exists
        Write-Debug -Message $debugMessage.IsDestinationPathExist
        $itemType = GetPathItemType -Path $DestinationPath

        $fileExists = $false
        switch ($itemType.ToString()) {
            ([GraniDonwloadItemTypeEx]::FileInfo.ToString()) {
                Write-Debug -Message ($debugMessage.ItemTypeWasFile -f $DestinationPath)
                $fileExists = $true
            }
            ([GraniDonwloadItemTypeEx]::DirectoryInfo.ToString()) {
                Write-Debug -Message ($debugMessage.ItemTypeWasDirectory -f $DestinationPath)
            }
            ([GraniDonwloadItemTypeEx]::Other.ToString()) {
                Write-Debug -Message ($debugMessage.ItemTypeWasOther -f $DestinationPath)
                return $returnHash
            }
            ([GraniDonwloadItemTypeEx]::NotExists.ToString()) {
                Write-Debug -Message ($debugMessage.ItemTypeWasNotExists -f $DestinationPath)
                return $returnHash
            }
        }

        # Already Up-to-date Check
        if ($fileExists -eq $true) {
            Write-Debug -Message $debugMessage.FileExists
            switch ($CheckSum) {
                ([GraniDonwloadCheckSumtype]::FileHash.ToString()) {
                    Write-Debug -Message ($debugMessage.IsDestinationPathAlreadyUpToDate -f $CheckSum)
                    $currentFileHash = GetFileHash -Path $DestinationPath
                    $s3ObjectCache = GetS3ObjectHash -BucketName $S3BucketName -Key $Key -Region $Region

                    Write-Debug -Message ($debugMessage.IsFileAlreadyUpToDate -f $currentFileHash, $s3ObjectCache)
                    if ($currentFileHash -eq $s3ObjectCache) {
                        Write-Verbose -Message $verboseMessage.AlreadyUpToDate
                        $returnHash.Ensure = [GraniDonwloadEnsuretype]::Present.ToString()
                    }
                    else {
                        Write-Verbose -Message $verboseMessage.NotUpToDate
                    }
                }
                ([GraniDonwloadCheckSumtype]::FileName.ToString()) {
                    # FileName only check : Is destination file exists or not.
                    Write-Debug -Message ($debugMessage.IsCheckSumFileName -f $CheckSum)
                    $returnHash.Ensure = [GraniDonwloadEnsuretype]::Present.ToString()
                }
            }
        }
    }
    catch {
        Write-Error $_
    }
    
    return $returnHash
}


function Set-TargetResource {
    [OutputType([Void])]
    [CmdletBinding()]
    param (
        [parameter(Mandatory = $true)]
        [System.String]$S3BucketName,

        [parameter(Mandatory = $false)]
        [System.String]$Key,

        [parameter(Mandatory = $true)]
        [System.String]$DestinationPath,

        [parameter(Mandatory = $false)]
        [System.String]$PreAction = [string]::Empty,

        [parameter(Mandatory = $false)]
        [System.String]$PostAction = [string]::Empty,

        [parameter(Mandatory = $false)]
        [System.Management.Automation.PSCredential]$Credential = [PSCredential]::Empty,

        [parameter(Mandatory = $false)]
        [ValidateSet("FileHash", "FileName")]
        [System.String]$CheckSum = [GraniDonwloadCheckSumtype]::FileHash.ToString(),

        [parameter(Mandatory = $false)]
        [System.String]$Region = [string]::Empty
    )

    # validate S3 Bucket is exist
    ValidateS3Bucket -BucketName $S3BucketName -Region $Region
    ValidateS3Object -BucketName $S3BucketName -Key $Key -Region $Region

    # validate DestinationPath is valid
    ValidateFilePath -Path $DestinationPath

    # PreAction
    ExecuteScriptBlock -ScriptBlockString $PreAction -Credential $Credential

    # Start Download
    Write-Verbose $verboseMessage.StartS3Download
    ReadS3Object -BucketName $S3BucketName -Key $Key -File $DestinationPath -Region $Region

    # PostAction
    ExecuteScriptBlock -ScriptBlockString $PostAction -Credential $Credential
}


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

        [parameter(Mandatory = $false)]
        [System.String]$Key,

        [parameter(Mandatory = $true)]
        [System.String]$DestinationPath,

        [parameter(Mandatory = $false)]
        [System.String]$PreAction = [string]::Empty,

        [parameter(Mandatory = $false)]
        [System.String]$PostAction = [string]::Empty,

        [parameter(Mandatory = $false)]
        [System.Management.Automation.PSCredential]$Credential = [PSCredential]::Empty,

        [parameter(Mandatory = $false)]
        [ValidateSet("FileHash", "FileName")]
        [System.String]$CheckSum = [GraniDonwloadCheckSumtype]::FileHash.ToString(),

        [parameter(Mandatory = $false)]
        [System.String]$Region = [string]::Empty
    )

    $param = @{
        S3BucketName    = $S3BucketName
        Key             = $Key
        DestinationPath = $DestinationPath
        PreAction       = $PreAction
        PostAction      = $PostAction
        CheckSum        = $CheckSum
        Region          = $Region
    }
    return (Get-TargetResource @param).Ensure -eq [GraniDonwloadEnsuretype]::Present.ToString()
}

#endregion

#region S3 Helper

# Test
function TestS3Bucket {
    [OutputType([Boolean])]
    [CmdletBinding()]
    param (
        [parameter(Mandatory = $true)]
        [string]$BucketName,

        [parameter(Mandatory = $false)]
        [string]$Region
    )

    if ([string]::IsNullOrWhiteSpace($Region)) {
        return Test-S3Bucket -BucketName $BucketName
    }
    else {
        Write-Debug -Message ($debugMessage.OverrideRegion -f $Region)
        return Test-S3Bucket -BucketName $BucketName -Region $Region
    }
}
function TestS3Object {
    [OutputType([Boolean])]
    [CmdletBinding()]
    param (
        [parameter(Mandatory = $true)]
        [string]$BucketName,

        [parameter(Mandatory = $true)]
        [string]$Key,

        [parameter(Mandatory = $false)]
        [string]$Region
    )
    
    Write-Debug -Message ($debugMessage.IsS3ObjectExist)
    if ([string]::IsNullOrWhiteSpace($Region)) {
        $objects = Get-S3Object -BucketName $BucketName
    }
    else {
        Write-Debug -Message ($debugMessage.OverrideRegion -f $Region)
        $objects = Get-S3Object -BucketName $BucketName -Region $Region
    }

    $result = $null
    $dic = New-Object "System.Collections.Generic.Dictionary[[string], [string]]"
    $objects | Foreach-Object { $dic.Add($_.Key, $_.Etag) }
    return $dic.TryGetValue($Key, [ref]$result)
}

# Validation
function ValidateS3Bucket {
    [OutputType([Void])]
    [CmdletBinding()]
    param (
        [parameter(Mandatory = $true)]
        [string]$BucketName,

        [parameter(Mandatory = $false)]
        [string]$Region
    )

    Write-Debug -Message ($debugMessage.ValidateS3Bucket -f $BucketName)
    if (-not (TestS3Bucket -BucketName $BucketName -Region $Region)) {
        throw New-Object System.NullReferenceException ($exceptionMessage.S3BucketNotExistEXception -f $BucketName)
    }
}

function ValidateS3Object {
    [OutputType([Void])]
    [CmdletBinding()]
    param (
        [parameter(Mandatory = $true)]
        [string]$BucketName,

        [parameter(Mandatory = $true)]
        [string]$Key,

        [parameter(Mandatory = $false)]
        [string]$Region
    )

    Write-Debug -Message ($debugMessage.ValidateS3Object -f $Key)
    if (-not (TestS3Object -BucketName $BucketName -Key $Key -Region $Region)) {
        throw New-Object System.NullReferenceException ($exceptionMessage.S3ObjectNotExistEXception -f $BucketName, $Key)
    }
}

function ValidateFilePath {
    [OutputType([Void])]
    [CmdletBinding()]
    param (
        [parameter(Mandatory = $true)]
        [string]$Path
    )
    
    Write-Debug -Message ($debugMessage.ValidateFilePath -f $Path)
    $itemType = GetPathItemType -Path $Path
    switch ($itemType.ToString()) {
        ([GraniDonwloadItemTypeEx]::FileInfo.ToString()) {
            return;
        }
        ([GraniDonwloadItemTypeEx]::NotExists.ToString()) {
            # Create Parent Directory check
            $parentPath = Split-Path $Path -Parent
            if (-not (Test-Path -Path $parentPath)) {
                [System.IO.Directory]::CreateDirectory($parentPath) > $null
            }
        }
        Default {
            $errorId = "FileValidationFailure"
            $errorMessage = $exceptionMessage.DestinationPathAlreadyExistAsNotFile -f $Path, $itemType.ToString()
            ThrowInvalidDataException -ErrorId $errorId -ErrorMessage $errorMessage
        }
    }
}

# Hash
function GetFileHash {
    [OutputType([string])]
    [CmdletBinding()]
    param (
        [parameter(Mandatory = $true)]
        [string]$Path
    )

    return (Get-FileHash -Path $Path -Algorithm MD5).Hash
}

function GetS3ObjectHash {
    [OutputType([string])]
    [CmdletBinding()]
    param (
        [parameter(Mandatory = $true)]
        [string]$BucketName,

        [parameter(Mandatory = $true)]
        [string]$Key,

        [parameter(Mandatory = $false)]
        [string]$Region
    )

    if ([string]::IsNullOrWhiteSpace($Region)) {
        return (Get-S3Object -BucketName $BucketName -Key $Key | Where-Object Key -eq $Key).ETag.Replace('"', "")
    }
    else {
        Write-Debug -Message ($debugMessage.OverrideRegion -f $Region)
        return (Get-S3Object -BucketName $BucketName -Key $Key -Region $Region | Where-Object Key -eq $Key).ETag.Replace('"', "")
    }
}

# Reader
function ReadS3Object {
    [OutputType([void])]
    [CmdletBinding()]
    param (
        [parameter(Mandatory = $true)]
        [string]$BucketName,

        [parameter(Mandatory = $true)]
        [string]$Key,

        [parameter(Mandatory = $true)]
        [string]$File,

        [parameter(Mandatory = $false)]
        [string]$Region
    )

    if ([string]::IsNullOrWhiteSpace($Region)) {
        Read-S3Object -BucketName $BucketName -Key $Key -File $File
    }
    else {
        Write-Debug -Message ($debugMessage.OverrideRegion -f $Region)
        Read-S3Object -BucketName $BucketName -Key $Key -File $File -Region $Region
    }
}

#endregion

# ItemType Helper
function GetPathItemType {
    [OutputType([GraniDonwloadItemTypeEx])]
    [CmdletBinding()]
    param (
        [parameter(Mandatory = $true, ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true)]
        [Alias("FullName", "LiteralPath", "PSPath")]
        [System.String]$Path = [string]::Empty
    )

    $type = [string]::Empty

    # Check type of the Path Item
    if (-not (Test-Path -Path $Path)) {
        return [GraniDonwloadItemTypeEx]::NotExists
    }
    
    $pathItem = Get-Item -Path $path
    $pathItemType = $pathItem.GetType().FullName
    $type = switch ($pathItemType) {
        "System.IO.FileInfo" {
            [GraniDonwloadItemTypeEx]::FileInfo
        }
        "System.IO.DirectoryInfo" {
            [GraniDonwloadItemTypeEx]::DirectoryInfo
        }
        Default {
            [GraniDonwloadItemTypeEx]::Other
        }
    }

    return $type
}

# ScriptBlock Execute Helper
function ExecuteScriptBlock {
    [OutputType([Void])]
    [CmdletBinding()]
    param (
        [parameter(Mandatory = $false)]
        [System.String]$ScriptBlockString = [string]::Empty,

        [parameter(Mandatory = $false)]
        [System.Management.Automation.PSCredential]$Credential = [PSCredential]::Empty
    )

    if ($ScriptBlockString -eq [string]::Empty) { return; }

    try {
        $scriptBlock = [ScriptBlock]::Create($ScriptBlockString).GetNewClosure()
        if ($Credential -eq [PSCredential]::Empty) {
            Write-Debug ($debugMessage.ExecuteScriptBlock -f $ScriptBlockString)
            $scriptBlock.Invoke() | Out-String -Stream | Write-Debug
        }
        else {
            Write-Debug ($debugMessage.ExecuteScriptBlockWithCredential -f $ScriptBlockString)
            Invoke-Command -ScriptBlock $scriptBlock -Credential $Credential -ComputerName . | Out-String -Stream | Write-Debug
        }
    }
    catch {
        Write-Debug ($exceptionMessage.ScriptBlockException -f $ScriptBlockString)
        throw $_
    }
}

# Exception Helper
function ThrowInvalidDataException {
    [OutputType([Void])]
    [CmdletBinding()]
    param (
        [parameter(Mandatory = $true)]
        [System.String]$ErrorId,

        [parameter(Mandatory = $true)]
        [System.String]$ErrorMessage
    )
    
    $errorCategory = [System.Management.Automation.ErrorCategory]::InvalidData
    $exception = New-Object System.InvalidOperationException $ErrorMessage 
    $errorRecord = New-Object System.Management.Automation.ErrorRecord $exception, $ErrorId, $errorCategory, $null
    throw $errorRecord
}

Export-ModuleMember -Function *-TargetResource