forked from atkinsroy/HPESimpliVity
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathHPESimpliVity.psm1
5337 lines (4656 loc) · 190 KB
/
HPESimpliVity.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
###############################################################################################################
# HPESimpliVity.psm1
#
# Description:
# This module provides management cmdlets for HPE SimpliVity via the
# REST API. This module has tested with both VMware and Hyper-V.
#
# Website:
# https://github.com/atkinsroy/HPESimpliVity
#
# VERSION 1.1.5
#
# AUTHOR
# Roy Atkins HPE Pointnext Services
#
##############################################################################################################
<#
(C) Copyright 2019 Hewlett Packard Enterprise Development LP
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
#>
#region Utility
# Helper function for Invoke-RestMethod to handle REST errors in one place. The calling function then re-throws the error,
# generated here. This cmdlet either outputs a custom task object if the REST API response is a task object, or otherwise the raw JSON.
function Invoke-SVTrestMethod {
[CmdletBinding()]
param (
[Parameter(Mandatory = $true, Position = 0)]
[System.Object]$Uri,
[Parameter(Mandatory = $true, Position = 1)]
[System.Collections.IDictionary]$Header,
[Parameter(Mandatory = $true, Position = 2)]
[ValidateSet('get', 'post', 'delete', 'put')]
[System.String]$Method,
[Parameter(Mandatory = $false, Position = 3)]
[System.Object]$Body
)
[int]$Retrycount = 0
[bool]$Stoploop = $false
do {
try {
if ($Body) {
$Response = Invoke-RestMethod -Uri $Uri -Headers $Header -Body $Body -Method $Method -ErrorAction Stop
}
else {
$Response = Invoke-RestMethod -Uri $Uri -Headers $Header -Method $Method -ErrorAction Stop
}
$Stoploop = $true
}
catch [System.Management.Automation.RuntimeException] {
if ($_.Exception.Message -match "Unauthorized") {
if ($Retrycount -ge 3) {
# Exit after 3 retries
throw "Runtime error: Session expired and could not reconnect"
}
else {
$Retrycount += 1
Write-Verbose "Session expired, reconnecting..."
$OVC = $SVTconnection.OVC -replace 'https://',''
$Retry = Connect-SVT -OVC $OVC -Credential $SVTconnection.Credential
# Update the json header with the new token for the retry
$Header = @{'Authorization' = "Bearer $($Retry.Token)"
'Accept' = 'application/json'
}
}
}
elseif ($_.Exception.Message -match "The hostname could not be parsed") {
throw "Runtime error: You must first log in using Connect-SVT"
}
else {
throw "Runtime error: $($_.Exception.Message)"
}
}
catch {
# Catch any other error - API might provide a message
throw "An unexpected error occured: $($_.Exception.Message)"
}
}
until ($Stoploop -eq $true)
# If the JSON output is a task, convert it to a custom object of type 'HPE.SimpliVity.Task' and pass this back to the
# calling cmdlet. A lot of cmdlets produce task object types, so this cuts out repetition in the module.
# Note: $Response.task is incorrectly true with /api/omnistack_clusters/throughput, so added a check for this.
if ($Response.task -and $URI -notmatch '/api/omnistack_clusters/throughput') {
$culture = (Get-Culture).DateTimeFormat
$LocalDate = "$($culture.ShortDatePattern)" -creplace '^d/','dd/' -creplace '^M/','MM/' -creplace '/d/','/dd/'
$LocalTime = "$($culture.LongTimePattern)" -creplace '^h:mm', 'hh:mm' -creplace '^H:mm','HH:mm'
$LocalFormat = "$LocalDate $LocalTime"
$Response.task | ForEach-Object {
if ($_.start_time -as [datetime]) {
$StartTime = Get-Date -Date $_.start_time -Format $LocalFormat
}
else {
$StartTime = $null
}
if ($_.end_time -as [datetime]) {
$EndTime = Get-Date -Date $_.end_time -Format $LocalFormat
}
else {
$EndTime = $null
}
[PSCustomObject]@{
PStypeName = 'HPE.SimpliVity.Task'
TaskId = $_.id
State = $_.state
AffectedObjects = $_.affected_objects
ErrorCode = $_.error_code
StartTime = $StartTime
EndTime = $EndTime
Message = $_.message
}
}
}
else {
# For all other object types, return the raw JSON output for the calling cmdlet to deal with
$Response
}
}
<#
.SYNOPSIS
Show information about tasks that are currently executing or have finished executing in HPE SimpliVity
.DESCRIPTION
Performing most Post/Delete calls to the SimpliVity REST API will generate task objects as output.
Whilst these task objects are immediately returned, the task themselves will change state over time. For example,
when a Clone VM task completes, its state changes from IN_PROGRESS to COMPLETED.
All cmdlets that return a JSON 'task' object, e.g. New-SVTbackup, New-SVTclone will output custom task objects of
type HPE.SimpliVity.Task and can then be used as input here to find out if the task completed successfully. You can
either specify the Task ID from the cmdlet output or, more usefully, use $SVTtask. This is a global variable that all
'task producing' HPE SimpliVity cmdlets create. $SVTtask is overwritten each time one of these cmdlets is executed.
.PARAMETER Task
The task object(s). Use the global variable $SVTtask which is generated from a 'task producing' HPE SimpliVity cmdlet, like
New-SVTbackup, New-SVTclone and Move-SVTvm.
.INPUTS
System.String
HPE.SimpliVity.Task
.OUTPUTS
HPE.SimpliVity.Task
.EXAMPLE
PS C:\> Get-SVTtask
Provides an update of the task(s) from the last HPESimpliVity cmdlet that creates, deletes or updates a SimpliVity resource
.EXAMPLE
PS C:\> New-SVTbackup -VMname MyVM
PS C:\> Get-SVTtask
Shows the state of the task executed from the New-SVTbackup cmdlet.
.EXAMPLE
PS C:\> Get-SVTvm | Where-Object VMname -match '^A' | New-SVTclone
PS C:\> Get-SVTtask
The first command enumerates all virtual machines with names beginning with the letter A and clones them.
The second command monitors the progress of the clone tasks.
.NOTES
#>
function Get-SVTtask {
[CmdletBinding()]
param(
# by default, use the global variable. i.e. the output from the last task producing cmdlet in this session
[Parameter(Mandatory = $false, ValueFromPipeLine = $true)]
[PSobject]$Task = $SVTtask
)
begin {
$Header = @{'Authorization' = "Bearer $($global:SVTconnection.Token)"
'Accept' = 'application/json'
}
}
process {
foreach ($ThisTask in $Task) {
$Uri = $global:SVTconnection.OVC + '/api/tasks/' + $ThisTask.TaskId
try {
Invoke-SVTrestMethod -Uri $Uri -Header $Header -Method Get
}
catch {
throw $_.Exception.Message
}
}
}
}
<#
.SYNOPSIS
Obtain an authentication token from a HPE SimpliVity OmniStack Virtual Controller (OVC).
.DESCRIPTION
To access the SimpliVity REST API, you need to request an authentication token by issuing a request
using the OAuth authentication method. Once obtained, you can pass the resulting access token via the
HTTP header using an Authorisation Bearer token.
The access token is stored in a global variable accessible to all HPESimpliVity cmdlets in the PowerShell session.
Note that the access token times out after 10 minutes of inactivty. If this happens, simply run this
cmdlet again.
.PARAMETER OVC
The Fully Qualified Domain Name (FQDN) or IP address of any OmniStack Virtual Controller. This is the management
IP address of the OVC.
.PARAMETER Credential
User generated credential as System.Management.Automation.PSCredential. Use the Get-Credential PowerShell cmdlet
to create the credential. This can optionally be imported from a file in cases where you are invoking non-interactively.
E.g. shutting down the OVC's from a script invoked by UPS software.
.PARAMETER SignedCert
Requires a trusted cert. By default the cmdlet allows untrusted self-signed SSL certificates with HTTPS
connections and enable TLS 1.2.
NOTE: You don't need this with PowerShell 6.0; it supports TLS1.2 natively and allows certificate bypass
using Invoke-Method -SkipCertificateCheck. This is not implemented here yet.
.INPUTS
System.String
.OUTPUTS
System.Management.Automation.PSCustomObject
.EXAMPLE
PS C:\>Connect-SVT -OVC <FQDN or IP Address of OVC>
This will securely prompt you for credentials
.EXAMPLE
PS C:\>$Cred = Get-Credential -Message 'Enter Credentials'
PS C:\>Connect-SVT -OVC <FQDN or IP Address of OVC> -Credential $Cred
Create the credential first, then pass it as a parameter.
.EXAMPLE
PS C:\>$CredFile = "$((Get-Location).Path)\OVCcred.XML"
PS C:\>Get-Credential -Credential '<username@domain>'| Export-CLIXML $CredFile
Another way is to store the credential in a file (as above), then connect to the OVC using:
PS C:\> Connect-SVT -OVC <FQDN or IP Address of OVC> -Credential $(Import-CLIXML $CredFile)
or:
PS C:\>$Cred = Import-CLIXML $CredFile
PS C:\>Connect-SVT -OVC <FQDN or IP Address of OVC> -Credential $Cred
This method is useful in non-iteractive sessions. Once the file is created, run the Connect-SVT
command to connect and reconnect to the OVC, as required.
.NOTES
#>
function Connect-SVT {
[CmdletBinding()]
param(
[Parameter(Mandatory = $true, Position = 0)]
[System.String]$OVC,
[Parameter(Mandatory = $false, Position = 1)]
[System.Management.Automation.PSCredential]$Credential,
[switch]$SignedCert
)
if ($SignedCert) {
$SignedCertificates = $true
}
else {
if ( -not ("TrustAllCertsPolicy" -as [type])) {
$Source = @"
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;
}
}
"@
Add-Type -TypeDefinition $Source
}
[System.Net.ServicePointManager]::CertificatePolicy = New-Object TrustAllCertsPolicy
[System.Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
$SignedCertificates = $false
}
# 2 ways to securely authenticate - via an existing credential object or prompt for a credential
if ($Credential) {
$OVCcred = $Credential
}
else {
$OVCcred = Get-Credential -Message 'Enter credentials with authorisation to login to your OmniStack Virtual Controller (e.g. administrator@vsphere.local)'
}
$Uri = 'https://' + $OVC + '/api/oauth/token'
# Case is important here with property names
$Header = @{'Authorization' = 'Basic ' + [System.Convert]::ToBase64String([System.Text.UTF8Encoding]::UTF8.GetBytes('simplivity:'))
'Accept' = 'application/json'
}
$Body = @{'username' = $OVCcred.Username
'password' = $OVCcred.GetNetworkCredential().Password
'grant_type' = 'password'
}
try {
$Response = Invoke-SVTrestMethod -Uri $Uri -Header $Header -Body $Body -Method Post -ErrorAction Stop
}
catch {
throw $_.Exception.Message
}
$global:SVTconnection = [pscustomobject]@{
OVC = "https://$OVC"
Credential = $OVCcred
Token = $Response.access_token
UpdateTime = $Response.updated_at
Expiration = $Response.expires_in
SignedCertificates = $SignedCertificates
}
# Return connection object to the pipeline. Used by all other HPESimpliVity cmdlets.
$global:SVTconnection
}
<#
.SYNOPSIS
Get the REST API version and SVTFS version of the HPE SimpliVity installation
.DESCRIPTION
Get the REST API version and SVTFS version of the HPE SimpliVity installation
.INPUTS
None
.OUTPUTS
System.Management.Automation.PSCustomObject
.EXAMPLE
PS C:\> Get-SVTversion
Shows version information for the REST API and SVTFS.
.NOTES
#>
Function Get-SVTversion {
$Header = @{'Authorization' = "Bearer $($global:SVTconnection.Token)"
'Accept' = 'application/json'
}
$Uri = $global:SVTconnection.OVC + '/api/version'
try {
$Response = Invoke-SVTrestMethod -Uri $Uri -Header $Header -Method Get -ErrorAction Stop
}
catch {
throw $_.Exception.Message
}
$Response | ForEach-Object {
[PSCustomObject]@{
'RESTAPIversion' = $_.REST_API_Version
'SVTFSversion' = $_.SVTFS_Version
}
}
}
<#
.SYNOPSIS
Display the performance information about the specified HPE SimpliVity resource(s)
.DESCRIPTION
Displays the performance metrics for one of the following specified HPE SimpliVity resources:
- Cluster
- Host
- VM
In addition, output from the Get-SVTcluster, Get-Host and Get-SVTvm commands is accepted as input.
.PARAMETER SVTobject
Used to accept input from the pipeline. Accepts HPESimpliVity objects with a specific type
.PARAMETER ClusterName
Show performance metrics for the specified SimpliVity cluster(s)
.PARAMETER Hostname
Show performance metrics for the specified SimpliVity node(s)
.PARAMETER VMName
Show performance metrics for the specified virtual machine(s) hosted on SimpliVity storage
.PARAMETER OffsetHour
Show performance metrics starting from the specified offset (hours from now, default is now)
.PARAMETER Hour
Show performance metrics for the specifed number of hours (starting from OffsetHour)
.PARAMETER Resolution
The resolution in seconds, minutes, hours or days
.PARAMETER Chart
Create a chart instead of showing performance metrics. The chart file is saved to the current folder. One chart is
created for each object (e.g. cluster, host or VM)
.EXAMPLE
PS C:\>Get-SVTmetric -ClusterName Production
Shows performance metrics about the specified cluster, using the default hour setting (24 hours) and resolution (every hour)
.EXAMPLE
PS C:\>Get-SVThost | Get-SVTmetric -Hour 1 -Resolution SECOND
Shows performance metrics for all hosts in the federation, for every second of the last hour
.EXAMPLE
PS C:\>Get-SVTvm | Where VMname -match "SQL" | Get-SVTmetric
Show performance metrics for every VM that has "SQL" in its name
.EXAMPLE
PS C:\>Get-SVTcluster -ClusterName DR | Get-SVTmetric -Hour 1440 -Resolution DAY
Show daily performance metrics for the last two months for the specified cluster
.EXAMPLE
PS C:\>Get-SVThost | Get-Metric -Chart -Verbose
Create chart(s) instead of showing the metric data. Chart files are created in the current folder.
Use filtering when creating charts for virtual machines to avoid creating a lot of charts.
.EXAMPLE
PS C:\>Get-SVThost -HostName MyHost | Get-Metric -Chart | Foreach-Object {Invoke-Item $_}
Create a metrics chart for the specified host and display it. Note that Invoke-Item only works with
image files when the Desktop Experience Feature is installed (may not be installed on some servers)
.INPUTS
System.String
HPE.SimpliVity.Cluster
HPE.SimpliVity.Host
HPE.SimpliVity.VirtualMachine
.OUTPUTS
HPE.SimpliVity.Metric
.NOTES
#>
function Get-SVTmetric {
[CmdletBinding(DefaultParameterSetName = 'Host')]
param
(
[parameter(Mandatory = $true, Position = 0, ParameterSetName = 'Cluster')]
[string[]]$ClusterName,
[parameter(Mandatory = $true, Position = 0, ParameterSetName = 'Host')]
[string[]]$HostName,
[parameter(Mandatory = $true, Position = 0, ParameterSetName = 'VirtualMachine')]
[string[]]$VMName,
[Parameter(Mandatory = $true, Position = 0, ValueFromPipeline = $true, ParameterSetName = 'SVTobject')]
[psobject]$SVTobject,
[Parameter(Mandatory = $false, Position = 1)]
[int]$OffsetHour = 0,
[Parameter(Mandatory = $false, Position = 2)]
[int]$Hour = 24,
[Parameter(Mandatory = $false, Position = 3)]
[ValidateSet('SECOND', 'MINUTE', 'HOUR', 'DAY')]
[System.String]$Resolution = 'HOUR',
[Parameter(Mandatory = $false)]
[Switch]$Chart
)
begin {
$VerbosePreference = 'Continue'
$Header = @{'Authorization' = "Bearer $($global:SVTconnection.Token)"
'Accept' = 'application/json'
}
$Range = $Hour * 3600
$Offset = $OffsetHour * 3600
if ($Resolution -eq 'SECOND' -and $Range -gt 43200 ) {
throw "Maximum range value for resolution $resolution is 12 hours"
}
elseif ($Resolution -eq 'MINUTE' -and $Range -gt 604800 ) {
throw "Maximum range value for resolution $resolution is 168 hours (1 week)"
}
elseif ($Resolution -eq 'HOUR' -and $Range -gt 5184000 ) {
throw "Maximum range value for resolution $resolution is 1,440 hours (2 months)"
}
elseif ($Resolution -eq 'DAY' -and $Range -gt 94608000 ) {
throw "Maximum range value for resolution $resolution is 26,280 hours (3 years)"
}
if ($Resolution -eq 'SECOND' -and $range -gt 7200 ) {
Write-Warning 'Using the resolution of SECOND beyond a range of 2 hours can take a long time to complete'
}
if ($Resolution -eq 'MINUTE' -and $range -gt 86400 ) {
Write-Warning 'Using the resolution of MINUTE beyond a range of 24 hours can take a long time to complete'
}
$culture = (Get-Culture).DateTimeFormat
$LocalDate = "$($culture.ShortDatePattern)" -creplace '^d/','dd/' -creplace '^M/','MM/' -creplace '/d/','/dd/'
$LocalTime = "$($culture.LongTimePattern)" -creplace '^h:mm', 'hh:mm' -creplace '^H:mm','HH:mm'
$LocalFormat = "$LocalDate $LocalTime"
}
process {
if ($SVTobject) {
$InputObject = $SVTObject
}
elseif ($ClusterName) {
$InputObject = $ClusterName
}
elseif ($HostName) {
$InputObject = $HostName
}
else {
$InputObject = $VMName
}
foreach ($Item in $InputObject) {
$TypeName = $Item | Get-Member | Select-Object -ExpandProperty TypeName -Unique
if ($TypeName -eq 'HPE.SimpliVity.Cluster') {
$Uri = $global:SVTconnection.OVC + '/api/omnistack_clusters/' + $Item.ClusterId + '/metrics'
$ObjectName = $Item.ClusterName
}
elseif ($TypeName -eq 'HPE.SimpliVity.Host') {
$Uri = $global:SVTconnection.OVC + '/api/hosts/' + $Item.HostId + '/metrics'
$ObjectName = $Item.HostName
}
elseif ($TypeName -eq 'HPE.SimpliVity.VirtualMachine') {
$Uri = $global:SVTconnection.OVC + '/api/virtual_machines/' + $Item.VmId + '/metrics'
$ObjectName = $Item.VMname
}
elseif ($ClusterName) {
try {
$ClusterId = Get-SVTcluster -ClusterName $Item -ErrorAction Stop | Select-Object -ExpandProperty ClusterId
$Uri = $global:SVTconnection.OVC + '/api/omnistack_clusters/' + $ClusterId + '/metrics'
$ObjectName = $Item
}
catch {
throw $_.Exception.Message
}
}
elseif ($HostName) {
try {
$HostId = Get-SVThost -HostName $Item -ErrorAction Stop | Select-Object -ExpandProperty HostId
$Uri = $global:SVTconnection.OVC + '/api/hosts/' + $HostId + '/metrics'
$ObjectName = $Item
}
catch {
throw $_.Exception.Message
}
}
else {
try {
$VmId = Get-SVTvm -VMname $Item -ErrorAction Stop | Select-Object -ExpandProperty VmId
$Uri = $global:SVTconnection.OVC + '/api/virtual_machines/' + $VmId + '/metrics'
$ObjectName = $Item
}
catch {
throw $_.Exception.Message
}
}
Write-verbose "Object name is $ObjectName ($TypeName)"
$Uri = $Uri + "?time_offset=$Offset&range=$Range&resolution=$Resolution"
try {
$Response = Invoke-SVTrestMethod -Uri $Uri -Header $Header -Method Get -ErrorAction Stop
}
catch {
throw $_.Exception.Message
}
# Unpack the Json into a Custom object. This outputs each Metric with a date and some values
$CustomObject = $Response.metrics | foreach-object {
$MetricName = (Get-Culture).TextInfo.ToTitleCase($_.name)
$_.data_points | ForEach-Object {
if ($_.date -as [DateTime]) {
$Date = Get-Date -Date $_.date -Format $LocalFormat
}
else {
$Date = $null
}
[pscustomobject] @{
Name = $MetricName
Date = $Date
Read = $_.reads
Write = $_.writes
}
}
}
#Transpose the custom object to return each date with read and write for each metric
$MetricObject = $CustomObject | Sort-Object -Property Date,Name | Group-Object -Property Date | ForEach-Object {
$Property = [ordered]@{
PStypeName = 'HPE.SimpliVity.Metric'
Date = $_.Name
}
[string]$prevname=''
$_.Group | Foreach-object {
# We expect to see just 3 records per date. However, sometimes there are 6.
# So check for duplicates before creating the key.
If ($_.name -ne $prevname) {
$Property += [ordered]@{
"$($_.Name)Read" = $_.Read
"$($_.Name)Write" = $_.Write
}
}
$prevname = $_.Name
}
$Property += [ordered]@{
ObjectType = $TypeName
ObjectName = $ObjectName
}
New-Object -TypeName PSObject -Property $Property
}
if ($chart) {
[array]$ChartObject += $MetricObject
}
else {
$MetricObject
}
} #end for
} #end process
end {
if ($Chart) {
Get-SVTmetricChart -Metric $ChartObject -TypeName $TypeName
}
}
}
# Helper function for Get-SVTmetric
function Get-SVTmetricChart {
[CmdletBinding()]
param (
[Parameter(Mandatory = $true, Position = 0)]
[psobject]$Metric,
[Parameter(Mandatory = $true, Position = 1)]
[System.String]$TypeName
)
if ($PSVersionTable.PSVersion.Major -gt 5) {
throw "Microsoft Chart Controls are not currently supported with PowerShell Core, use Windows PowerShell"
}
$ObjectList = $Metric.ObjectName | Select-Object -Unique
#$ObjectTotal = $ObjectList | Measure-Object | Select-Object -ExpandProperty Count
$Path = Get-Location
$Culture = Get-Culture
$StartDate = $Metric | Select-Object -First 1 -ExpandProperty Date
$EndDate = $Metric | Select-Object -Last 1 -ExpandProperty Date
$ChartLabelFont = 'Arial, 8pt'
$ChartTitleFont = 'Arial, 12pt'
$DateStamp = Get-Date -Format "yyMMddhhmmss"
# define an object to determine the best inverval on the Y axis, given a maximum value
$Ylimit = (0,10000,20000,40000,80000,160000,320000,640000,1280000,2560000,5120000,10240000,20480000)
$Yinterval = (200,500,1000,5000,10000,15000,20000,50000,75000,100000,250000,400000,1000000)
$Yaxis = 0..11 | foreach-object {
[PSCustomObject]@{
Limit = $Ylimit[$_]
Interval = $YInterval[$_]
}
}
Add-Type -AssemblyName System.Windows.Forms.DataVisualization
foreach ($Instance in $ObjectList) {
$DataSource = $Metric | Where-Object ObjectName -eq $Instance
$DataPoint = $DataSource | Measure-Object | Select-Object -ExpandProperty Count
# chart object
$Chart1 = New-object System.Windows.Forms.DataVisualization.Charting.Chart
$Chart1.Width = 1200
$Chart1.Height = 600
$Chart1.BackColor = [System.Drawing.Color]::LightGray
# title
try {
$ShortName = ([ipaddress]$Instance).IPAddressToString
}
catch {
$ShortName = $Instance -split '\.' | Select-Object -First 1
}
[void]$Chart1.Titles.Add("$($TypeName): $ShortName - Metrics from $StartDate to $EndDate")
$Chart1.Titles[0].Font = "Arial,16pt"
$Chart1.Titles[0].Alignment = "topLeft"
# chart area
$AxisEnabled = New-Object System.Windows.Forms.DataVisualization.Charting.AxisEnabled
$AxisType = New-Object System.Windows.Forms.DataVisualization.Charting.AxisType
$Area1 = New-Object System.Windows.Forms.DataVisualization.Charting.ChartArea
$Area1.Name = "ChartArea1"
$Area1.AxisX.Title = "Date"
$Area1.AxisX.TitleFont = $ChartTitleFont
$Area1.AxisX.LabelStyle.Font = $ChartLabelFont
# to determine an appropriate X axis interval, find the number of data points in the data
$Interval = [math]::Round($DataPoint / 24) #show 24 dates on X axis only
if ($Interval -lt 1) {
$Area1.AxisX.Interval = 1
}
else {
$Area1.AxisX.Interval = $Interval
}
$Area1.AxisY.Title = "IOPS and Latency (milliseconds)"
$Area1.AxisY.TitleFont = $ChartTitleFont
$Area1.AxisY.LabelStyle.Font = $ChartLabelFont
if($Interval -gt 12) {
$BorderWidth = 1 #reduce line weight for charts with long time ranges
}
else {
$BorderWidth = 2
}
# To determine an appropriate interval on Y axis, find the maximum value in the data.
$MaxArray = @(
$DataSource | Measure-Object -Property LatencyRead -Maximum | Select-Object -ExpandProperty Maximum
$DataSource | Measure-Object -Property LatencyWrite -Maximum | Select-Object -ExpandProperty Maximum
$DataSource | Measure-Object -Property IopsRead -Maximum | Select-Object -ExpandProperty Maximum
$DataSource | Measure-Object -Property IopsWrite -Maximum | Select-Object -ExpandProperty Maximum
)
$Max = 0 #ensure Y axis has appropriate interval
$MaxArray | Foreach-Object {
if($_ -gt $Max) {
$Max = $_
}
}
# determine an appropriate Yaxis Inverval.
$Yaxis | ForEach-Object {
if ($Max -gt $_.Limit) {
$Yint = $_.Interval
}
}
$Area1.AxisY.Interval = $Yint
# title for second Y axis
$Area1.AxisY2.Title = "Throughput (Mbps)"
$Area1.AxisY2.TitleFont = $ChartTitleFont
$Area1.AxisY2.LabelStyle.Font = $ChartLabelFont
$Area1.AxisY2.LineColor = [System.Drawing.Color]::Transparent
$Area1.AxisY2.MajorGrid.Enabled = $false
$Area1.AxisY2.Enabled = $AxisEnabled::true
# Add Area to chart
$Chart1.ChartAreas.Add($Area1)
$Chart1.ChartAreas["ChartArea1"].AxisY.LabelStyle.Angle = 0
$Chart1.ChartAreas["ChartArea1"].AxisX.LabelStyle.Angle = -45
# legend to chart
$Legend = New-Object system.Windows.Forms.DataVisualization.Charting.Legend
$Legend.name = "Legend1"
$Chart1.Legends.Add($Legend)
# data series
[void]$Chart1.Series.Add("IopsRead")
$Chart1.Series["IopsRead"].YAxisType = $AxisType::Primary
$Chart1.Series["IopsRead"].ChartType = "Line"
$Chart1.Series["IopsRead"].BorderWidth = $BorderWidth
$Chart1.Series["IopsRead"].IsVisibleInLegend = $true
$Chart1.Series["IopsRead"].ChartArea = "ChartArea1"
$Chart1.Series["IopsRead"].Legend = "Legend1"
$Chart1.Series["IopsRead"].Color = [System.Drawing.Color]::RoyalBlue
$DataSource | ForEach-Object {
$Date = ([datetime]::parse($_.Date, $Culture)).ToString('hh:mm:ss tt')
[void]$Chart1.Series["IopsRead"].Points.addxy($Date, $_.IopsRead)
}
# data series
[void]$Chart1.Series.Add("IopsWrite")
$Chart1.Series["IopsWrite"].YAxisType = $AxisType::Primary
$Chart1.Series["IopsWrite"].ChartType = "Line"
$Chart1.Series["IopsWrite"].BorderWidth = $BorderWidth
$Chart1.Series["IopsWrite"].IsVisibleInLegend = $true
$Chart1.Series["IopsWrite"].ChartArea = "ChartArea1"
$Chart1.Series["IopsWrite"].Legend = "Legend1"
$Chart1.Series["IopsWrite"].Color = [System.Drawing.Color]::DarkTurquoise
$DataSource | ForEach-Object {
$Date = ([datetime]::parse($_.Date, $Culture)).ToString('hh:mm:ss tt')
[void]$Chart1.Series["IopsWrite"].Points.addxy($Date, $_.IopsWrite)
}
# data series
[void]$Chart1.Series.Add("LatencyRead")
$Chart1.Series["LatencyRead"].YAxisType = $AxisType::Primary
$Chart1.Series["LatencyRead"].ChartType = "Line"
$Chart1.Series["LatencyRead"].BorderWidth = $BorderWidth
$Chart1.Series["LatencyRead"].IsVisibleInLegend = $true
$Chart1.Series["LatencyRead"].ChartArea = "ChartArea1"
$Chart1.Series["LatencyRead"].Legend = "Legend1"
$Chart1.Series["LatencyRead"].Color = [System.Drawing.Color]::Green
$DataSource | ForEach-Object {
$Date = ([datetime]::parse($_.Date, $Culture)).ToString('hh:mm:ss tt')
[void]$Chart1.Series["LatencyRead"].Points.addxy($Date, $_.LatencyRead)
}
# data series
[void]$Chart1.Series.Add("LatencyWrite")
$Chart1.Series["LatencyWrite"].YAxisType = $AxisType::Primary
$Chart1.Series["LatencyWrite"].ChartType = "Line"
$Chart1.Series["LatencyWrite"].BorderWidth = $BorderWidth
$Chart1.Series["LatencyWrite"].IsVisibleInLegend = $true
$Chart1.Series["LatencyWrite"].ChartArea = "ChartArea1"
$Chart1.Series["LatencyWrite"].Legend = "Legend1"
$Chart1.Series["LatencyWrite"].Color = [System.Drawing.Color]::SpringGreen
$DataSource | ForEach-Object {
$Date = ([datetime]::parse($_.Date, $Culture)).ToString('hh:mm:ss tt')
[void]$Chart1.Series["LatencyWrite"].Points.addxy($Date, $_.LatencyWrite)
}
# data series
[void]$Chart1.Series.Add("ThroughputRead")
$Chart1.Series["ThroughputRead"].YAxisType = $AxisType::Secondary
$Chart1.Series["ThroughputRead"].ChartType = "Line"
$Chart1.Series["ThroughputRead"].BorderWidth = $BorderWidth
$Chart1.Series["ThroughputRead"].IsVisibleInLegend = $true
$Chart1.Series["ThroughputRead"].ChartArea = "ChartArea1"
$Chart1.Series["ThroughputRead"].Legend = "Legend1"
$Chart1.Series["ThroughputRead"].Color = [System.Drawing.Color]::Firebrick
$DataSource | ForEach-Object {
$Date = ([datetime]::parse($_.Date, $Culture)).ToString('hh:mm:ss tt')
[void]$Chart1.Series["ThroughputRead"].Points.addxy($Date, ($_.ThroughputRead / 1024 / 1024))
}
# data series
[void]$Chart1.Series.Add("ThroughputWrite")
$Chart1.Series["ThroughputWrite"].YAxisType = $AxisType::Secondary
$Chart1.Series["ThroughputWrite"].ChartType = "Line"
$Chart1.Series["ThroughputWrite"].BorderWidth = $BorderWidth
$Chart1.Series["ThroughputWrite"].IsVisibleInLegend = $true
$Chart1.Series["ThroughputWrite"].ChartArea = "ChartArea1"
$Chart1.Series["ThroughputWrite"].Legend = "Legend1"
$Chart1.Series["ThroughputWrite"].Color = [System.Drawing.Color]::OrangeRed
$DataSource | ForEach-Object {
$Date = ([datetime]::parse($_.Date, $Culture)).ToString('hh:mm:ss tt')
[void]$Chart1.Series["ThroughputWrite"].Points.addxy($Date, ($_.ThroughputWrite / 1024 / 1024))
}
# save chart and send filename to the pipeline
try {
$Chart1.SaveImage("$Path\SVTmetric-$ShortName-$DateStamp.png", "png")
Get-ChildItem "$Path\SVTmetric-$ShortName-$DateStamp.png"
}
catch {
throw "Could not create $Path\SVTmetric-$ShortName-$DateStamp.png"
}
}
}
# Helper function for Get-SVTcapacity
function Get-SVTcapacityChart {
[CmdletBinding()]
param (
[Parameter(Mandatory = $true, Position = 0)]
[psobject]$Capacity
)
if ($PSVersionTable.PSVersion.Major -gt 5) {
throw "Microsoft Chart Controls are not currently supported with PowerShell Core, use Windows PowerShell"
}
Add-Type -AssemblyName System.Windows.Forms.DataVisualization
$Path = Get-Location
$ChartLabelFont = 'Arial, 10pt'
$ChartTitleFont = 'Arial, 13pt'
$DateStamp = Get-Date -Format "yyMMddhhmmss"
$objectlist = $Capacity.HostName | Select-Object -Unique
foreach ($Instance in $ObjectList) {
$Cap = $Capacity | Where-Object Hostname -eq $Instance | Select-Object -Last 1
$DataSource = [ordered]@{
'Allocated Capacity' = $Cap.AllocatedCapacity / 1GB
'Used Capacity' = $Cap.UsedCapacity / 1GB
'Used Logical Capacity' = $Cap.UsedLogicalCapacity / 1GB
'Free Space' = $Cap.FreeSpace / 1GB
'Capacity Savings' = $Cap.CapacitySavings / 1GB
'Local Backup Capacity' = $Cap.LocalBackupCapacity / 1GB
'Remote Backup Capacity' = $Cap.RemoteBackupCapacity / 1GB
'Stored Compressed Data' = $Cap.StoredCompressedData / 1GB
'Stored Uncompressed Data' = $Cap.StoredUncompressedData / 1GB
'Stored Virtual Machine Data' = $Cap.StoredVirtualMachineData / 1GB
}
# chart object
$Chart1 = New-object System.Windows.Forms.DataVisualization.Charting.Chart
$Chart1.Width = 1200
$Chart1.Height = 600
# title
try {
$ShortName = ([ipaddress]$Instance).IPAddressToString
}
catch {
$ShortName = $Instance -split '\.' | Select-Object -First 1
}
[void]$Chart1.Titles.Add("HPE.SimpliVity.Host: $ShortName - Capacity from $($Cap.Date)")
$Chart1.Titles[0].Font = "Arial,16pt"
$Chart1.Titles[0].Alignment = "topLeft"
# chart area
$Area1 = New-Object System.Windows.Forms.DataVisualization.Charting.ChartArea
$Area3Dstyle = New-Object System.Windows.Forms.DataVisualization.Charting.ChartArea3DStyle
$Area3Dstyle.Enable3D = $true
$Area3Dstyle.LightStyle = 1
$Area3Dstyle.Inclination = 20
$Area3Dstyle.Perspective = 0
$Area1 = $Chart1.ChartAreas.Add('ChartArea1')
$Area1.Area3DStyle = $Area3Dstyle
$Area1.AxisY.Title = "Size (GB)"
$Area1.AxisY.TitleFont = $ChartTitleFont
$Area1.AxisY.LabelStyle.Font = $ChartLabelFont
$Area1.AxisX.MajorGrid.Enabled = $false
$Area1.AxisX.MajorTickMark.Enabled = $true
$Area1.AxisX.LabelStyle.Enabled = $true
$Max = $DataSource.Values | Measure-Object -Maximum | Select-Object -ExpandProperty Maximum
if ($Max -lt 10000) {
$Area1.AxisY.Interval = 500
}
Elseif ($Max -lt 20000) {
$Area1.AxisY.Interval = 1000
}
Else {
$Area1.AxisY.Interval = 5000
}
$Area1.AxisX.Interval = 1
$Chart1.ChartAreas["ChartArea1"].AxisY.LabelStyle.Angle = 0
$Chart1.ChartAreas["ChartArea1"].AxisX.LabelStyle.Angle = -45
# add series
[void]$Chart1.Series.Add("Data")
$Chart1.Series["Data"].Points.DataBindXY($DataSource.Keys, $DataSource.Values)
# save chart
try {
$Chart1.SaveImage("$Path\SVTcapacity-$ShortName-$DateStamp.png", "png")
Get-ChildItem "$Path\SVTcapacity-$ShortName-$DateStamp.png"
}
catch {
throw "Could not create $Path\SVTcapacity-$ShortName-$DateStamp.png"
}
}
}
# Helper function for Get-SVTdisk
# Notes: This method works quite well when all the disks are the same capacity. The 380 H introduces a bit
# of a problem. As long as the disks are sorted by slot number (i.e. the first disk will always be an SSD),
# then the 380H disk capacity will be 1.92TB - the first disk is used to confirm. This method may break if
# additional models continue to be added.
function Get-SVTmodel {
$ModelNumer = ('325','325','2600','380','380','380','380','380','380 Gen10 H','380','380')
$DiskCount = (4,6,6,5,5,9,12,12,12,4,6)
$DiskCapacity = (2,2,2,1,2,2,2,4,2,2,2)
$Kit = ('4-8TB - SVT325 Extra Small',
'7-15TB - SVT325 Small',
'7-15TB - SVT2600',
'3-6TB - SVT380Gen10 Extra Small',
'6-12TB - SVT380Gen10 Small',
'12-25TB - SVT380Gen10 Medium',
'20-40TB - SVT380Gen10 Large',
'40-80TB - SVT380Gen10 Extra Large',
'20-50TB - SVT380Gen10H', #4X1.92 SSD + 8X4TB HDD
'8-16TB - SVT380Gen10G 4X1.92TB',
'7-15TB - SVT380Gen10G 6X.192TB'
)
0..7 | foreach-object {
[PSCustomObject]@{
ModelNumber = $ModelNumer[$_]
DiskCount = $DiskCount[$_]
DiskCapacity = $DiskCapacity[$_]
StorageKit = $Kit[$_]
}
}
}
#endregion Utility
#region Backup
<#
.SYNOPSIS
Display information about HPE SimpliVity backups.
.DESCRIPTION
Show backup information from the HPE SimpliVity Federation. By default SimpliVity backups from the last 24 hours are
shown, but this can be overridden by specifying the -Hour parameter. Alternatively, specify VM name, Cluster name,
or Datacenter name (with or without -Hour) to filter backups appropriately.