-
Notifications
You must be signed in to change notification settings - Fork 3
/
StorageGRID-Webscale.psm1
16434 lines (14776 loc) · 719 KB
/
StorageGRID-Webscale.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
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
$SGW_PROFILE_PATH = "$HOME/.sgw/"
$SGW_CREDENTIALS_FILE = $SGW_PROFILE_PATH + "credentials"
# workarounds for PowerShell issues
if ($PSVersionTable.PSVersion.Major -lt 6) {
Add-Type @"
using System.Net;
using System.Security.Cryptography.X509Certificates;
public class TrustAllCertsPolicy : ICertificatePolicy {
public bool CheckValidationResult(
ServicePoint srvPoint, X509Certificate certificate,
WebRequest request, int certificateProblem) {
return true;
}
}
"@
# StorageGRID supports TLS 1.2 and PowerShell does not auto negotiate it, thus enforcing TLS 1.2
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
# Using .NET JSON Serializer as JSON serialization included in Invoke-RestMethod has a length restriction for JSON content
Add-Type -AssemblyName System.Web.Extensions
$global:javaScriptSerializer = New-Object System.Web.Script.Serialization.JavaScriptSerializer
$global:javaScriptSerializer.MaxJsonLength = [System.Int32]::MaxValue
$global:javaScriptSerializer.RecursionLimit = 99
# Functions necessary to parse JSON output from .NET serializer to PowerShell Objects
function ParseItem($jsonItem) {
#private
if ($jsonItem.PSObject.TypeNames -match "Array") {
return ParseJsonArray($jsonItem)
}
elseif ($jsonItem.PSObject.TypeNames -match "Dictionary") {
return ParseJsonObject([HashTable]$jsonItem)
}
else {
return $jsonItem
}
}
function ParseJsonObject($jsonObj) {
#private
$Response = New-Object -TypeName PSCustomObject
foreach ($key in $jsonObj.Keys) {
$item = $jsonObj[$key]
if ($item) {
$parsedItem = ParseItem $item
}
else {
$parsedItem = $null
}
$Response | Add-Member -MemberType NoteProperty -Name $key -Value $parsedItem
}
return $Response
}
function ParseJsonArray($jsonArray) {
#private
$Response = @()
$jsonArray | ForEach-Object {
$Response += ,(ParseItem $_)
}
return $Response
}
}
### Helper Functions ###
function ParseErrorForResponseBody($Error) {
#private
if ($PSVersionTable.PSVersion.Major -lt 6) {
if ($Error.Exception.Response) {
$Reader = New-Object System.IO.StreamReader($Error.Exception.Response.GetResponseStream())
$Reader.BaseStream.Position = 0
$Reader.DiscardBufferedData()
$ResponseBody = $Reader.ReadToEnd()
if ( $ResponseBody.StartsWith('{')) {
$ResponseBody = $ResponseBody | ConvertFrom-Json | ConvertTo-Json
}
return $ResponseBody
}
}
else {
return $Error.ErrorDetails.Message
}
}
# helper function to convert unix timestamp to datetime
function ConvertFrom-UnixTimestamp {
#private
[CmdletBinding()]
PARAM (
[parameter(Mandatory = $True,
Position = 0,
ValueFromPipeline = $True,
ValueFromPipelineByPropertyName = $True,
HelpMessage = "Timestamp to be converted.")][String]$Timestamp,
[parameter(Mandatory = $False,
Position = 0,
ValueFromPipeline = $True,
ValueFromPipelineByPropertyName = $True,
HelpMessage = "Unit of timestamp.")][ValidateSet("Seconds", "Milliseconds")][String]$Unit = "Milliseconds",
[parameter(Mandatory = $False,
Position = 1,
HelpMessage = "Optional timezone to be used as basis for timestamp. Default is system timezone.")][System.TimeZoneInfo]$Timezone = [System.TimeZoneInfo]::Local
)
PROCESS {
$Timestamp = @($Timestamp)
foreach ($Timestamp in $Timestamp) {
if ($Unit -eq "Seconds") {
$Date = [System.TimeZoneInfo]::ConvertTimeFromUtc(([datetime]'1/1/1970').AddSeconds($Timestamp), $Timezone)
}
else {
$Date = [System.TimeZoneInfo]::ConvertTimeFromUtc(([datetime]'1/1/1970').AddMilliseconds($Timestamp), $Timezone)
}
Write-Output $Date
}
}
}
function ConvertFrom-SgwConfigFile {
#private
[CmdletBinding()]
PARAM (
[parameter(
Mandatory=$True,
Position=0,
HelpMessage="StorageGRID config file")][String]$SgwConfigFile
)
Process {
# TODO: Verify that folder is only readable by current user
if (!(Test-Path $SgwConfigFile))
{
throw "Config file $SgwConfigFile does not exist!"
}
Write-Verbose "Reading StorageGRID configuration from config file $SgwConfigFile"
$Content = Get-Content -Path $SgwConfigFile -Raw
# convert to JSON structure
# replace all carriage returns
$Content = $Content -replace "\r",""
# remove empty lines
$Content = $Content -replace "(\n$)*", ""
# remove profile string from profile section
$Content = $Content -replace "profile ", ""
# remove keys with empty value
$Content = $Content -replace "\n\s*([^=\s`"]+)\s*=\s*\n","`n"
# replace key value pairs with quoted key value pairs and replace = with :
$Content = $Content -replace "\n\s*([^=\s`"]+)\s*=\s*([^\s\n]*)","`n`"`$1`":`"`$2`","
# make sure that Profile is a Key Value inside the JSON Object
$Content = $Content -replace "\[([^\]]+)\]([^\[]+)","{`"ProfileName`":`"`$1`",`$2},`n"
# remove additional , before a closing curly bracket
$Content = $Content -replace "\s*,\s*\n?}","}"
# ensure that the complete output is an array consisting of multiple JSON objects
$Content = $Content -replace "\A","["
$Content = $Content -replace "},?\s*\n?\s*\z","}]"
# TODO: Implement proper handling of special characters!
$Content = $Content -replace '\\','\\'
$Config = ConvertFrom-Json -InputObject $Content
Write-Output $Config
}
}
function ConvertTo-SgwConfigFile {
#private
[CmdletBinding()]
PARAM (
[parameter(
Mandatory=$False,
Position=0,
HelpMessage="Configs to store in config file")][PSCustomObject]$Configs,
[parameter(
Mandatory=$True,
Position=1,
HelpMessage="StorageGRID config file")][String]$SgwConfigFile
)
Process {
# TODO: Verify that folder is only readable by current user
if (!(Test-Path $SgwConfigFile)) {
New-Item -Path $SgwConfigFile -ItemType File -Force
}
$SgwConfigDirectory = ([System.IO.DirectoryInfo]$SgwConfigFile).Parent.FullName
# make sure that parent folder is only accessible by current user
Write-Host "Profile information will be stored in directory $SgwConfigDirectory . Ensuring that access is only possible for current user."
try {
if ([environment]::OSVersion.Platform -match "win") {
$Acl = Get-Acl -Path $SgwConfigDirectory
# remove inheritance
$Acl.SetAccessRuleProtection($true,$false)
$AcessRule = [System.Security.AccessControl.FileSystemAccessRule]::new(
$env:USERNAME,"FullControl",
([System.Security.AccessControl.InheritanceFlags]::ContainerInherit -bor [System.Security.AccessControl.InheritanceFlags]::ObjectInherit),
[System.Security.AccessControl.PropagationFlags]::None,
[System.Security.AccessControl.AccessControlType]::Allow)
$Acl.AddAccessRule($AcessRule)
$null = Set-Acl -Path $SgwConfigDirectory -AclRule -ErrorAction Stop
}
else {
Invoke-Expression "chmod 700 $SgwConfigDirectory"
Invoke-Expression "chmod 600 $SgwConfigFile"
}
}
catch {
Write-Verbose "Couldn't restrict access to directory $SgwConfigDirectory"
}
Write-Verbose "Writing StorageGRID configuration to $SgwConfigFile"
if ($SgwConfigFile -match "credentials$") {
foreach ($Config in $Configs) {
if ([environment]::OSVersion.Platform -match "win") {
if ($Config.secure_password) {
$secure_password = $Config.secure_password
}
elseif ($Config.password) {
$secure_password = ConvertTo-SecureString -String $Config.password -AsPlainText -Force | ConvertFrom-SecureString
}
else {
throw "Neither password nor secure_password provided"
}
$Output += "[$( $Config.ProfileName )]`n"
$Output += "username = $($Config.username)`n"
$Output += "secure_password = $($secure_password)`n"
}
else {
# ConvertTo-SecureString is only implemented on Windows, so we need to rely on the security of the .sgw folder
$Output += "[$( $Config.ProfileName )]`n"
$Output += "username = $($Config.username)`n"
$Output += "password = $($Config.password)`n"
}
}
}
else {
foreach ($Config in $Configs) {
if ($Config.ProfileName -eq "default") {
$Output += "[$( $Config.ProfileName )]`n"
}
else {
$Output += "[profile $( $Config.ProfileName )]`n"
}
$Properties = $Config.PSObject.Members | Where-Object { $_.MemberType -eq "NoteProperty" -and $_.Name -ne "ProfileName" -and $_.Value -isnot [PSCustomObject] }
$Sections = $Config.PSObject.Members | Where-Object { $_.MemberType -eq "NoteProperty" -and $_.Name -ne "ProfileName" -and $_.Value -is [PSCustomObject]}
foreach ($Property in $Properties) {
$Output += "$($Property.Name) = $($Property.Value)`n"
}
foreach ($Section in $Sections) {
$Output += "$($Section.Name) =`n"
$Properties = $Section.Value.PSObject.Members | Where-Object { $_.MemberType -eq "NoteProperty" }
foreach ($Property in $Properties) {
$Output += " $($Property.Name) = $($Property.Value)`n"
}
}
}
}
Write-Debug "Output:`n$Output"
if ([environment]::OSVersion.Platform -match "win") {
# replace LF with CRLF
$Output = $Output -replace "`n","`r`n"
}
$Output | Out-File -FilePath $SgwConfigFile
}
}
<#
.SYNOPSIS
Invoke request to StorageGRID server
.DESCRIPTION
Invoke request to StorageGRID server
.PARAMETER Uri
Uri
.PARAMETER WebSession
WebSession
.PARAMETER Method
HTTP Method
.PARAMETER Headers
HTTP Headers
.PARAMETER Body
Body
.PARAMETER ContentType
Content Type
.PARAMETER SessionVariable
Variable to store session details in
.PARAMETER TimeoutSec
Timeout in seconds
.PARAMETER SkipCertificateCheck
Skip certificate check
.PARAMETER OutFile
File to output result to
#>
function Invoke-SgwRequest {
[CmdletBinding()]
PARAM (
[parameter(Mandatory = $True,
Position = 0,
HelpMessage = "Uri")][Uri]$Uri,
[parameter(Mandatory = $False,
Position = 1,
HelpMessage = "WebSession")][Microsoft.PowerShell.Commands.WebRequestSession]$WebSession,
[parameter(Mandatory = $False,
Position = 2,
HelpMessage = "HTTP Method")][ValidateSet("Default", "Get", "Head", "Post", "Put", "Delete", "Trace", "Options", "Merge", "Patch")][String]$Method = "Get",
[parameter(Mandatory = $False,
Position = 3,
HelpMessage = "HTTP Headers")][Hashtable]$Headers,
[parameter(Mandatory = $False,
Position = 4,
HelpMessage = "Body")][Object]$Body,
[parameter(Mandatory = $False,
Position = 5,
HelpMessage = "Content Type")][String]$ContentType = "application/json",
[parameter(Mandatory = $False,
Position = 6,
HelpMessage = "Variable to store session details in")][String]$SessionVariable,
[parameter(Mandatory = $False,
Position = 7,
HelpMessage = "Timeout in seconds")][Int]$TimeoutSec = 60,
[parameter(Mandatory = $False,
Position = 8,
HelpMessage = "Skip certificate check")][Switch]$SkipCertificateCheck,
[parameter(
Mandatory=$False,
Position=9,
HelpMessage="File to output result to")][System.IO.DirectoryInfo]$OutFile
)
Process {
# if $OutFile is a directory, create a temporary file and save content to temporary file
# and later rename the file according to the Content-Disposition header or
$OutPath = $null
if ($OutFile -and (Test-Path -PathType Container -Path $OutFile)) {
$OutPath = $OutFile.PSObject.Copy()
$OutFile = (New-TemporaryFile).ToString()
}
Write-Verbose "Request Headers:`n$(ConvertTo-Json -InputObject $Headers)"
try {
if ($PSVersionTable.PSVersion.Major -lt 6) {
Write-Verbose "Using Invoke-WebRequest for PowerShell 5 and earlier"
if ($SkipCertificateCheck.isPresent) {
$CurrentCertificatePolicy = [System.Net.ServicePointManager]::CertificatePolicy
[System.Net.ServicePointManager]::CertificatePolicy = New-Object TrustAllCertsPolicy
}
if ($Body) {
Write-Verbose "Request Body:`n$Body"
if ($SessionVariable) {
if ($OutFile) {
Write-Verbose "Saving output in file:`n$OutFile"
$Response = Invoke-WebRequest -Method $Method -Uri $Uri -Headers $Headers -TimeoutSec $TimeoutSec -Body ([System.Text.Encoding]::UTF8.GetBytes($Body)) -ContentType $ContentType -SessionVariable $SessionVariable -OutFile $OutFile -PassThru
}
else {
$Response = Invoke-WebRequest -Method $Method -Uri $Uri -Headers $Headers -TimeoutSec $TimeoutSec -Body ([System.Text.Encoding]::UTF8.GetBytes($Body)) -ContentType $ContentType -SessionVariable $SessionVariable
}
$Response | Add-Member -MemberType NoteProperty -Name $SessionVariable -Value (Get-Variable -Name $SessionVariable -ValueOnly)
}
else {
if ($OutFile) {
Write-Verbose "Saving output in file:`n$OutFile"
$Response = Invoke-WebRequest -Method $Method -Uri $Uri -Headers $Headers -TimeoutSec $TimeoutSec -Body ([System.Text.Encoding]::UTF8.GetBytes($Body)) -ContentType $ContentType -WebSession $WebSession -OutFile $OutFile -PassThru
}
else {
$Response = Invoke-WebRequest -Method $Method -Uri $Uri -Headers $Headers -TimeoutSec $TimeoutSec -Body ([System.Text.Encoding]::UTF8.GetBytes($Body)) -ContentType $ContentType -WebSession $WebSession
}
}
}
else {
if ($SessionVariable) {
if ($OutFile) {
Write-Verbose "Saving output in file:`n$OutFile"
$Response = Invoke-WebRequest -Method $Method -Uri $Uri -Headers $Headers -TimeoutSec $TimeoutSec -SessionVariable $SessionVariable -OutFile $OutFile -PassThru
}
else {
$Response = Invoke-WebRequest -Method $Method -Uri $Uri -Headers $Headers -TimeoutSec $TimeoutSec -SessionVariable $SessionVariable
}
$Response | Add-Member -MemberType NoteProperty -Name $SessionVariable -Value (Get-Variable -Name $SessionVariable -ValueOnly) -PassThru
}
else {
if ($OutFile) {
Write-Verbose "Saving output in file:`n$OutFile"
$Response = Invoke-WebRequest -Method $Method -Uri $Uri -Headers $Headers -TimeoutSec $TimeoutSec -WebSession $WebSession -OutFile $OutFile -PassThru
}
else {
$Response = Invoke-WebRequest -Method $Method -Uri $Uri -Headers $Headers -TimeoutSec $TimeoutSec -WebSession $WebSession
}
}
}
if ($SkipCertificateCheck.isPresent) {
[System.Net.ServicePointManager]::CertificatePolicy = $CurrentCertificatePolicy
}
}
else {
Write-Verbose "Using Invoke-WebRequest for PowerShell 6 and later"
if ($Body) {
Write-Verbose "Request Body:`n$Body"
if ($SessionVariable) {
if ($OutFile) {
Write-Verbose "Saving output in file:`n$OutFile"
$Response = Invoke-WebRequest -Method $Method -Uri $Uri -Headers $Headers -SkipCertificateCheck:$SkipCertificateCheck -SkipHeaderValidation -TimeoutSec $TimeoutSec -Body ([System.Text.Encoding]::UTF8.GetBytes($Body)) -ContentType $ContentType -SessionVariable $SessionVariable -OutFile $OutFile -PassThru
}
else {
$Response = Invoke-WebRequest -Method $Method -Uri $Uri -Headers $Headers -SkipCertificateCheck:$SkipCertificateCheck -SkipHeaderValidation -TimeoutSec $TimeoutSec -Body ([System.Text.Encoding]::UTF8.GetBytes($Body)) -ContentType $ContentType -SessionVariable $SessionVariable
}
$Response | Add-Member -MemberType NoteProperty -Name $SessionVariable -Value (Get-Variable -Name $SessionVariable -ValueOnly) -PassThru
}
else {
if ($OutFile) {
Write-Verbose "Saving output in file:`n$OutFile"
$Response = Invoke-WebRequest -Method $Method -Uri $Uri -Headers $Headers -SkipCertificateCheck:$SkipCertificateCheck -SkipHeaderValidation -TimeoutSec $TimeoutSec -Body ([System.Text.Encoding]::UTF8.GetBytes($Body)) -ContentType $ContentType -WebSession $WebSession -OutFile $OutFile -PassThru
}
else {
$Response = Invoke-WebRequest -Method $Method -Uri $Uri -Headers $Headers -SkipCertificateCheck:$SkipCertificateCheck -SkipHeaderValidation -TimeoutSec $TimeoutSec -Body ([System.Text.Encoding]::UTF8.GetBytes($Body)) -ContentType $ContentType -WebSession $WebSession
}
}
}
else {
if ($SessionVariable) {
if ($OutFile) {
Write-Verbose "Saving output in file:`n$OutFile"
$Response = Invoke-WebRequest -Method $Method -Uri $Uri -Headers $Headers -SkipCertificateCheck:$SkipCertificateCheck -SkipHeaderValidation -TimeoutSec $TimeoutSec -SessionVariable $SessionVariable -OutFile $OutFile -PassThru
}
else {
$Response = Invoke-WebRequest -Method $Method -Uri $Uri -Headers $Headers -SkipCertificateCheck:$SkipCertificateCheck -SkipHeaderValidation -TimeoutSec $TimeoutSec -SessionVariable $SessionVariable
}
$Response | Add-Member -MemberType NoteProperty -Name $SessionVariable -Value (Get-Variable -Name $SessionVariable -ValueOnly)
}
else {
if ($OutFile) {
Write-Verbose "Saving output in file:`n$OutFile"
$Response = Invoke-WebRequest -Method $Method -Uri $Uri -Headers $Headers -SkipCertificateCheck:$SkipCertificateCheck -SkipHeaderValidation -TimeoutSec $TimeoutSec -WebSession $WebSession -OutFile $OutFile -PassThru
}
else {
$Response = Invoke-WebRequest -Method $Method -Uri $Uri -Headers $Headers -SkipCertificateCheck:$SkipCertificateCheck -SkipHeaderValidation -TimeoutSec $TimeoutSec -WebSession $WebSession
}
}
}
}
Write-Verbose "Response Headers:`n$(ConvertTo-Json -InputObject $Response.Headers)"
if ($Response.Headers.'Content-Type' -match "text|application/xml|application/json") {
Write-Verbose "Response Body:`n$($Response.Content)"
}
switch ($Response.Headers.'Content-Type') {
'application/json' {
$Response | Add-Member -MemberType NoteProperty -Name Json -Value (ConvertFrom-Json -InputObject $Response.Content)
}
}
if ($OutPath) {
if ($Response.Headers.'Content-Disposition' -match "filename") {
$FileName = ($Response.Headers.'Content-Disposition' | Select-Object -Last 1) -replace '.*filename="*(.*)"*','$1'
}
else {
# use last part of Request URI as filename
$FileName = $Response.BaseResponse.RequestMessage.RequestUri.Segments | Select-Object -Last 1
if ($FileName -eq "/") {
$FileName = "index.html"
}
}
$Destination = Join-Path -Path $OutPath -ChildPath $FileName
Move-Item -Path $OutFile -Destination $Destination -ErrorAction Stop
Write-Host "Output written to $Destination"
}
return $Response
}
catch {
# TODO: handle errors
Throw $_
}
finally {
if ($OutFile) {
Remove-Item -Path $OutFile -Force -ErrorAction SilentlyContinue
}
}
}
}
### Cmdlets ###
## install ##
# grid #
<#
.SYNOPSIS
Reset all user-provided information for installation and primary Admin Node recovery
.DESCRIPTION
Reset all user-provided information for installation and primary Admin Node recovery
.PARAMETER AdminNode
StorageGRID admin node (e.g. admin-node.example.com).
.PARAMETER ProfileName
StorageGRID profile to use for connection.
#>
function Global:Reset-SgwInstall {
[CmdletBinding(DefaultParameterSetName="AdminNode")]
PARAM (
[parameter(Mandatory = $False,
Position = 0,
HelpMessage = "StorageGRID admin node (e.g. admin-node.example.com).",
ParameterSetName="AdminNode")][String]$AdminNode,
[parameter(Mandatory = $False,
Position = 0,
HelpMessage = "StorageGRID profile to use for connection.",
ParameterSetName="ProfileName")][Alias("Profile")][String]$ProfileName
)
Begin {
if (!$ProfileName -and !$AdminNode) {
$ProfileName = "default"
}
if ($ProfileName) {
$Profile = Get-SgwProfile -ProfileName $ProfileName
if (!$Profile.Name) {
Throw "Profile $ProfileName not found. Create a profile using New-SgwProfile or connect to a StorageGRID server using Connect-SgwServer"
}
$AdminNode = $Profile.Name
}
if (!$AdminNode) {
Throw "No StorageGRID admin node management server found."
}
}
Process {
$Uri = "https://" + $AdminNode + "/api/v2/install"
$Method = "DELETE"
Try {
$Response = Invoke-SgwRequest -Method $Method -Uri $Uri -SkipCertificateCheck
}
Catch {
$ResponseBody = ParseErrorForResponseBody $_
Write-Host "$ResponseBody"
Write-Warning "Certificate of the server may not be trusted. Use -SkipCertificateCheck switch if you want to skip certificate verification."
Throw "$Method to $Uri failed with Exception $( $_.Exception.Message ) `n $responseBody"
}
Write-Output $Response.Json.Data
}
}
<#
.SYNOPSIS
Retrieve grid-wide details
.DESCRIPTION
Retrieve grid-wide details
.PARAMETER AdminNode
StorageGRID admin node (e.g. admin-node.example.com).
.PARAMETER ProfileName
StorageGRID profile to use for connection.
#>
function Global:Get-SgwInstallGridDetails {
[CmdletBinding(DefaultParameterSetName="AdminNode")]
PARAM (
[parameter(Mandatory = $False,
Position = 0,
HelpMessage = "StorageGRID admin node (e.g. admin-node.example.com).",
ParameterSetName="AdminNode")][String]$AdminNode,
[parameter(Mandatory = $False,
Position = 0,
HelpMessage = "StorageGRID profile to use for connection.",
ParameterSetName="ProfileName")][Alias("Profile")][String]$ProfileName
)
Begin {
if (!$ProfileName -and !$AdminNode) {
$ProfileName = "default"
}
if ($ProfileName) {
$Profile = Get-SgwProfile -ProfileName $ProfileName
if (!$Profile.Name) {
Throw "Profile $ProfileName not found. Create a profile using New-SgwProfile or connect to a StorageGRID server using Connect-SgwServer"
}
$AdminNode = $Profile.Name
}
if (!$AdminNode) {
Throw "No StorageGRID admin node management server found."
}
}
Process {
$Uri = "https://" + $AdminNode + "/api/v2/install/grid-details"
$Method = "GET"
Try {
$Response = Invoke-SgwRequest -Method $Method -Uri $Uri -SkipCertificateCheck
}
Catch {
$ResponseBody = ParseErrorForResponseBody $_
Write-Host "$ResponseBody"
Write-Warning "Certificate of the server may not be trusted. Use -SkipCertificateCheck switch if you want to skip certificate verification."
Throw "$Method to $Uri failed with Exception $( $_.Exception.Message ) `n $responseBody"
}
Write-Output $Response.Json.Data
}
}
Set-Alias -Name Set-SgwInstallGridDetails -Value Update-SgwInstallGridDetails
<#
.SYNOPSIS
Update grid-wide details
.DESCRIPTION
Update grid-wide details
.PARAMETER AdminNode
StorageGRID admin node (e.g. admin-node.example.com).
.PARAMETER ProfileName
StorageGRID profile to use for connection.
.PARAMETER Name
Name of the Grid.
.PARAMETER License
The grid license.
#>
function Global:Update-SgwInstallGridDetails {
[CmdletBinding(DefaultParameterSetName="AdminNode")]
PARAM (
[parameter(Mandatory = $False,
Position = 0,
HelpMessage = "StorageGRID admin node (e.g. admin-node.example.com).",
ParameterSetName="AdminNode")][String]$AdminNode,
[parameter(Mandatory = $False,
Position = 0,
HelpMessage = "StorageGRID profile to use for connection.",
ParameterSetName="ProfileName")][Alias("Profile")][String]$ProfileName,
[parameter(Mandatory = $False,
Position = 1,
HelpMessage = "Name of the Grid.")][String]$Name,
[parameter(Mandatory = $False,
Position = 2,
HelpMessage = "The grid license.")][String]$License
)
Begin {
if (!$ProfileName -and !$AdminNode) {
$ProfileName = "default"
}
if ($ProfileName) {
$Profile = Get-SgwProfile -ProfileName $ProfileName
if (!$Profile.Name) {
Throw "Profile $ProfileName not found. Create a profile using New-SgwProfile or connect to a StorageGRID server using Connect-SgwServer"
}
$AdminNode = $Profile.Name
}
if (!$AdminNode) {
Throw "No StorageGRID admin node management server found."
}
}
Process {
$Uri = "https://" + $AdminNode + "/api/v2/install/grid-details"
$Method = "PUT"
$GridDetails = Get-SgwInstallGridDetails -AdminNode $AdminNode
$GridDetails.name = $Name
if (!$License -and !$GridDetails.license) {
Write-Warning "No license provided, using default PoC license"
$GridDetails.license = 'eyJzdGF0dXNSZXNwIjp7InN0YXR1c0NvZGUiOiJTMDA3IiwibWVzc2FnZSI6IlN1Y2Nlc3MiLCJzblN0YXR1cyI6IkFjdGl2ZSIsIndhcnJhbnR5U3RhcnQiOiIyMDE2LTAxLTAxIiwid2FycmFudHlFbmQiOiIyMDE2LTAxLTAyIiwiY21hdElEIjoiNTAwMTY0MiIsImNvbXBhbnlCUElEIjoiMDAwMTAzMjc2NyIsInNpdGVCUElEIjoiMDAwMTM1MDQ5MSIsImNvbnRyYWN0U3RhcnQiOiIyMDE2LTAxLTAxIiwiY29udHJhY3RFbmQiOiIyMDE2LTAxLTAyIiwidmVyc2lvbiI6IjEiLCJzZXJpYWxOdW1iZXIiOiIwMDAwMDAiLCJsaWNlbnNlcyI6eyJ0eXBlIjoiY2FwYWNpdHkiLCJwYWNrYWdlIjoiU0ctV0VCU0NBTEUiLCJjYXBhY2l0eSI6IjAiLCJlbmREYXRlIjoiMjAxNi0wMS0wMSJ9fSwiU2lnbmF0dXJlIjoiUG5kdWQ0RGZWd2ppL0VBU3VWNXhQcU5MbWVwdndmRlQ1a0NMc2tzZEtOK0l3Z0tvdGE2VG0xemRNY1V6T01xTHFCZTFwS2QzR1JybzFVQjJpRlJWMlVwalp2V2JaOHhBWDU0NVBQb0VNNFNsNFQydks3ZGhBd2pCTTlXMS8yNmxWMjVHVU1wSjFabjc2VUtDWWRieFdJSjVrSXplTHFJRVVKOWZGRG1aRWxiV01DTXV0czBvcW9KRWlCbFFOUUpBQytVekZhOGZxalk2K3Rhakc2WkN1dE1kWTlYYnI4b3c4RTNrekFpK2oxcmR6c092ODY3ZjMyZDdCdFBFWVg4NGZiUlVETHMzdHZub1JIcGdFbnF3U2tlWmZZekNzRTRLZ0lodmFXV0MyakRQUkUvMytRMUNLV1B5dUhSd01jVmd4d2F5ME1ab0lFMWJpSW1PRDVXSmZRPT0iLCJ0cmFja2luZ0lkIjoiZDA1ZTU5MmQtZjM0MC00N2E1LWE5ZjYtNGJmNDVjZGMzYTEyIn0='
}
else {
# convert license to Base-64
$GridDetails.license = [System.Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes($License))
}
$Body = ConvertTo-Json -InputObject $GridDetails
Try {
$Response = Invoke-SgwRequest -Method $Method -Uri $Uri -SkipCertificateCheck -Body $Body
}
Catch {
$ResponseBody = ParseErrorForResponseBody $_
Write-Host "$ResponseBody"
Write-Warning "Certificate of the server may not be trusted. Use -SkipCertificateCheck switch if you want to skip certificate verification."
Throw "$Method to $Uri failed with Exception $( $_.Exception.Message ) `n $responseBody"
}
Write-Output $Response.Json.Data
}
}
<#
.SYNOPSIS
Retrieve the list of Grid Network subnets
.DESCRIPTION
Retrieve the list of Grid Network subnets
.PARAMETER AdminNode
StorageGRID admin node (e.g. admin-node.example.com).
.PARAMETER ProfileName
StorageGRID profile to use for connection.
#>
function Global:Get-SgwInstallGridNetworks {
[CmdletBinding(DefaultParameterSetName="AdminNode")]
PARAM (
[parameter(Mandatory = $False,
Position = 0,
HelpMessage = "StorageGRID admin node (e.g. admin-node.example.com).",
ParameterSetName="AdminNode")][String]$AdminNode,
[parameter(Mandatory = $False,
Position = 0,
HelpMessage = "StorageGRID profile to use for connection.",
ParameterSetName="ProfileName")][Alias("Profile")][String]$ProfileName
)
Begin {
if (!$ProfileName -and !$AdminNode) {
$ProfileName = "default"
}
if ($ProfileName) {
$Profile = Get-SgwProfile -ProfileName $ProfileName
if (!$Profile.Name) {
Throw "Profile $ProfileName not found. Create a profile using New-SgwProfile or connect to a StorageGRID server using Connect-SgwServer"
}
$AdminNode = $Profile.Name
}
if (!$AdminNode) {
Throw "No StorageGRID admin node management server found."
}
}
Process {
$Uri = "https://" + $AdminNode + "/api/v2/install/grid-networks"
$Method = "GET"
Try {
$Response = Invoke-SgwRequest -Method $Method -Uri $Uri -SkipCertificateCheck
}
Catch {
$ResponseBody = ParseErrorForResponseBody $_
Write-Host "$ResponseBody"
Write-Warning "Certificate of the server may not be trusted. Use -SkipCertificateCheck switch if you want to skip certificate verification."
Throw "$Method to $Uri failed with Exception $( $_.Exception.Message ) `n $responseBody"
}
Write-Output $Response.Json.Data
}
}
Set-Alias -Name Set-SgwInstallGridNetworks -Value Update-SgwInstallGridNetworks
<#
.SYNOPSIS
Update the list of Grid Network subnets
.DESCRIPTION
Update the list of Grid Network subnets
.PARAMETER AdminNode
StorageGRID admin node (e.g. admin-node.example.com).
.PARAMETER ProfileName
StorageGRID profile to use for connection.
.PARAMETER GridNetworks
The list of Grid Network subnets (in CIDR notation)
#>
function Global:Update-SgwInstallGridNetworks {
[CmdletBinding(DefaultParameterSetName="AdminNode")]
PARAM (
[parameter(Mandatory = $False,
Position = 0,
HelpMessage = "StorageGRID admin node (e.g. admin-node.example.com).",
ParameterSetName="AdminNode")][String]$AdminNode,
[parameter(Mandatory = $False,
Position = 0,
HelpMessage = "StorageGRID profile to use for connection.",
ParameterSetName="ProfileName")][Alias("Profile")][String]$ProfileName,
[parameter(Mandatory = $False,
Position = 1,
HelpMessage = "The list of Grid Network subnets (in CIDR notation).")][Alias("Networks")][String[]]$GridNetworks
)
Begin {
if (!$ProfileName -and !$AdminNode) {
$ProfileName = "default"
}
if ($ProfileName) {
$Profile = Get-SgwProfile -ProfileName $ProfileName
if (!$Profile.Name) {
Throw "Profile $ProfileName not found. Create a profile using New-SgwProfile or connect to a StorageGRID server using Connect-SgwServer"
}
$AdminNode = $Profile.Name
}
if (!$AdminNode) {
Throw "No StorageGRID admin node management server found."
}
}
Process {
$Uri = "https://" + $AdminNode + "/api/v2/install/grid-networks"
$Method = "PUT"
$Body = ConvertTo-Json -InputObject $GridNetworks
Try {
$Response = Invoke-SgwRequest -Method $Method -Uri $Uri -SkipCertificateCheck -Body $Body
}
Catch {
$ResponseBody = ParseErrorForResponseBody $_
Write-Host "$ResponseBody"
Write-Warning "Certificate of the server may not be trusted. Use -SkipCertificateCheck switch if you want to skip certificate verification."
Throw "$Method to $Uri failed with Exception $( $_.Exception.Message ) `n $responseBody"
}
Write-Output $Response.Json.Data
}
}
<#
.SYNOPSIS
Retrieve grid passwords
.DESCRIPTION
Retrieve grid passwords
.PARAMETER AdminNode
StorageGRID admin node (e.g. admin-node.example.com).
.PARAMETER ProfileName
StorageGRID profile to use for connection.
#>
function Global:Get-SgwInstallPasswords {
[CmdletBinding(DefaultParameterSetName="AdminNode")]
PARAM (
[parameter(Mandatory = $False,
Position = 0,
HelpMessage = "StorageGRID admin node (e.g. admin-node.example.com).",
ParameterSetName="AdminNode")][String]$AdminNode,
[parameter(Mandatory = $False,
Position = 0,
HelpMessage = "StorageGRID profile to use for connection.",
ParameterSetName="ProfileName")][Alias("Profile")][String]$ProfileName
)
Begin {
if (!$ProfileName -and !$AdminNode) {
$ProfileName = "default"
}
if ($ProfileName) {
$Profile = Get-SgwProfile -ProfileName $ProfileName
if (!$Profile.Name) {
Throw "Profile $ProfileName not found. Create a profile using New-SgwProfile or connect to a StorageGRID server using Connect-SgwServer"
}
$AdminNode = $Profile.Name
}
if (!$AdminNode) {
Throw "No StorageGRID admin node management server found."
}
}
Process {
$Uri = "https://" + $AdminNode + "/api/v2/install/passwords"
$Method = "GET"
Try {
$Response = Invoke-SgwRequest -Method $Method -Uri $Uri -SkipCertificateCheck
}
Catch {
$ResponseBody = ParseErrorForResponseBody $_
Write-Host "$ResponseBody"
Write-Warning "Certificate of the server may not be trusted. Use -SkipCertificateCheck switch if you want to skip certificate verification."
Throw "$Method to $Uri failed with Exception $( $_.Exception.Message ) `n $responseBody"
}
Write-Output $Response.Json.Data
}
}
Set-Alias -Name Set-SgwInstallPasswords -Value Update-SgwInstallPasswords
<#
.SYNOPSIS
Update grid passwords
.DESCRIPTION
Update grid passwords
.PARAMETER AdminNode
StorageGRID admin node (e.g. admin-node.example.com).
.PARAMETER ProfileName
StorageGRID profile to use for connection.
.PARAMETER Provision
The password used during maintenance procedures to make changes to the grid topology and to download the grid Recovery Package; optional once set
.PARAMETER Management
The password for the grid management root user, which can log into the grid management interface and has access to all features; optional once set
.PARAMETER UseRandom
Whether the grid will use random passwords for the command line root user, or the default passwords.
#>
function Global:Update-SgwInstallPasswords {
[CmdletBinding(DefaultParameterSetName="AdminNode")]
PARAM (
[parameter(Mandatory = $False,
Position = 0,
HelpMessage = "StorageGRID admin node (e.g. admin-node.example.com).",
ParameterSetName="AdminNode")][String]$AdminNode,
[parameter(Mandatory = $False,
Position = 0,
HelpMessage = "StorageGRID profile to use for connection.",
ParameterSetName="ProfileName")][Alias("Profile")][String]$ProfileName,
[parameter(Mandatory = $False,
Position = 1,
HelpMessage = "The password used during maintenance procedures to make changes to the grid topology and to download the grid Recovery Package; optional once set.")][Alias("ProvisionPassphrase","Passphrase")][String]$Provision,
[parameter(Mandatory = $False,
Position = 2,
HelpMessage = "The password for the grid management root user, which can log into the grid management interface and has access to all features; optional once set.")][String]$Management,
[parameter(Mandatory = $False,
Position = 3,
HelpMessage = "Whether the grid will use random passwords for the command line root user, or the default passwords.")][Boolean]$UseRandom
)
Begin {
if (!$ProfileName -and !$AdminNode) {
$ProfileName = "default"
}
if ($ProfileName) {
$Profile = Get-SgwProfile -ProfileName $ProfileName
if (!$Profile.Name) {
Throw "Profile $ProfileName not found. Create a profile using New-SgwProfile or connect to a StorageGRID server using Connect-SgwServer"
}
$AdminNode = $Profile.Name
}
if (!$AdminNode) {
Throw "No StorageGRID admin node management server found."
}
}
Process {
$Uri = "https://" + $AdminNode + "/api/v2/install/passwords"
$Method = "PUT"
$Passwords = Get-SgwInstallPasswords -AdminNode $AdminNode
if ($Provision) {
$Passwords.provision = $Provision
}
if ($Management) {
$Passwords.management = $Management
}
if ($UseRandom) {
$Passwords.useRandom = $UseRandom
}
$Body = ConvertTo-Json -InputObject $Passwords
Try {
$Response = Invoke-SgwRequest -Method $Method -Uri $Uri -SkipCertificateCheck -Body $Body
}
Catch {
$ResponseBody = ParseErrorForResponseBody $_
Write-Host "$ResponseBody"
Write-Warning "Certificate of the server may not be trusted. Use -SkipCertificateCheck switch if you want to skip certificate verification."
Throw "$Method to $Uri failed with Exception $( $_.Exception.Message ) `n $responseBody"
}
Write-Output $Response.Json.Data
}
}
<#
.SYNOPSIS
Retrieve the list of NTP server IP addresses
.DESCRIPTION
Retrieve the list of NTP server IP addresses
.PARAMETER AdminNode
StorageGRID admin node (e.g. admin-node.example.com).
.PARAMETER ProfileName
StorageGRID profile to use for connection.
#>
function Global:Get-SgwInstallNtpServers {
[CmdletBinding(DefaultParameterSetName="AdminNode")]
PARAM (
[parameter(Mandatory = $False,
Position = 0,
HelpMessage = "StorageGRID admin node (e.g. admin-node.example.com).",
ParameterSetName="AdminNode")][String]$AdminNode,
[parameter(Mandatory = $False,
Position = 0,