-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAnalyze-AzSqlDatabases.ps1
More file actions
1637 lines (1379 loc) · 66.7 KB
/
Copy pathAnalyze-AzSqlDatabases.ps1
File metadata and controls
1637 lines (1379 loc) · 66.7 KB
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
#Requires -Version 5.1
<#
.SYNOPSIS
Analyzes Azure SQL Database metrics and generates optimization recommendations.
.DESCRIPTION
Processes metric CSVs to calculate statistics, classify workload patterns,
and run through a comprehensive decision tree (Tier 1-5) to generate
specific recommendations for each database.
.PARAMETER MetricsPath
Path to directory containing metric CSV files
.PARAMETER OutputPath
Optional path to export results CSV
.EXAMPLE
$results = .\Analyze-AzSqlDatabases.ps1 -MetricsPath "C:\Metrics"
$results | Export-Csv "recommendations.csv" -NoTypeInformation
.EXAMPLE
$results = .\Analyze-AzSqlDatabases.ps1 -MetricsPath "C:\Metrics" |
Where-Object { $_.Status -eq 'OPTIMIZE' }
#>
[CmdletBinding()]
param(
[Parameter(Mandatory = $true)]
[string]$MetricsPath
)
#region Configuration
# DTU Tier Limits
$DTULimits = @{
'Basic' = @{ Sessions = 30; Workers = 30; DTU = 5 }
'S0' = @{ Sessions = 60; Workers = 200; DTU = 10 }
'S1' = @{ Sessions = 90; Workers = 200; DTU = 20 }
'S2' = @{ Sessions = 120; Workers = 400; DTU = 50 }
'S3' = @{ Sessions = 200; Workers = 400; DTU = 100 }
'S4' = @{ Sessions = 400; Workers = 1600; DTU = 200 }
'S6' = @{ Sessions = 800; Workers = 1600; DTU = 400 }
'S7' = @{ Sessions = 1600; Workers = 3200; DTU = 800 }
'S9' = @{ Sessions = 3200; Workers = 6400; DTU = 1600 }
'S12' = @{ Sessions = 6400; Workers = 12800; DTU = 3000 }
'P1' = @{ Sessions = 200; Workers = 400; DTU = 125 }
'P2' = @{ Sessions = 400; Workers = 800; DTU = 250 }
'P4' = @{ Sessions = 800; Workers = 1600; DTU = 500 }
'P6' = @{ Sessions = 1600; Workers = 3200; DTU = 1000 }
'P11' = @{ Sessions = 3200; Workers = 6400; DTU = 1750 }
'P15' = @{ Sessions = 6400; Workers = 12800; DTU = 4000 }
}
# vCore per-core limits
$vCoreSessionsPerCore = 30000
$vCoreWorkersPerCore = 512
# Azure Pricing (West Europe, EUR, monthly, Feb 2025 estimates)
$Pricing = @{
# DTU tiers
'Basic' = 4.45
'S0' = 13.39
'S1' = 26.77
'S2' = 66.93
'S3' = 133.86
'S4' = 267.72
'S6' = 535.44
'S7' = 1070.88
'S9' = 2141.76
'S12' = 4283.52
'P1' = 401.04
'P2' = 802.08
'P4' = 1604.16
'P6' = 2406.24
'P11' = 4011.12
'P15' = 6416.64
# vCore GP (per vCore per month)
'GP_Gen5_vCore' = 267.0
'GP_S_Gen5_vCore' = 66.75 # Serverless avg (50% discount when paused)
# vCore BC (per vCore per month)
'BC_Gen5_vCore' = 534.0
# Elastic Pool per eDTU
'Pool_Standard_eDTU' = 1.34
'Pool_Premium_eDTU' = 3.21
# Storage pricing (per GB per month)
'Storage_GB_Monthly' = 0.115 # Standard storage, West Europe
}
# Scheduled pause automation cost (EUR per month)
# Assumes single Azure Automation account managing multiple databases
$AutomationCostMonthly = 10
#endregion
#region Helper Functions
function Get-Percentile {
param([double[]]$Data, [int]$Percentile)
if ($Data.Count -eq 0) { return 0 }
$sorted = $Data | Sort-Object
$index = [Math]::Ceiling($Percentile / 100 * $sorted.Count) - 1
if ($index -lt 0) { $index = 0 }
return $sorted[$index]
}
function Get-CoefficientOfVariation {
param([double[]]$Data)
if ($Data.Count -eq 0) { return 0 }
$mean = ($Data | Measure-Object -Average).Average
if ($mean -eq 0) { return 0 }
$variance = ($Data | ForEach-Object { [Math]::Pow($_ - $mean, 2) } | Measure-Object -Average).Average
$stdDev = [Math]::Sqrt($variance)
return ($stdDev / $mean) * 100
}
function Get-LinearTrend {
param([object[]]$TimeSeries, [string]$ValueProperty)
if ($TimeSeries.Count -lt 2) { return 0 }
$n = $TimeSeries.Count
$x = 0..($n - 1)
$y = $TimeSeries | ForEach-Object { $_.$ValueProperty }
$sumX = ($x | Measure-Object -Sum).Sum
$sumY = ($y | Measure-Object -Sum).Sum
$sumXY = 0..($n - 1) | ForEach-Object { $x[$_] * $y[$_] } | Measure-Object -Sum | Select-Object -ExpandProperty Sum
$sumX2 = ($x | ForEach-Object { $_ * $_ } | Measure-Object -Sum).Sum
$slope = ($n * $sumXY - $sumX * $sumY) / ($n * $sumX2 - $sumX * $sumX)
$meanY = $sumY / $n
if ($meanY -eq 0) { return 0 }
# Return trend as % change per month (assuming 30 days of data)
return ($slope * 30 / $meanY) * 100
}
function Get-Autocorrelation {
param([double[]]$Data, [int]$Lag = 288) # 24 hours in 5-min intervals
if ($Data.Count -lt ($Lag * 2)) { return 0 }
$mean = ($Data | Measure-Object -Average).Average
$variance = ($Data | ForEach-Object { [Math]::Pow($_ - $mean, 2) } | Measure-Object -Average).Average
if ($variance -eq 0) { return 0 }
$autocovariance = 0
for ($i = 0; $i -lt ($Data.Count - $Lag); $i++) {
$autocovariance += ($Data[$i] - $mean) * ($Data[$i + $Lag] - $mean)
}
$autocovariance /= ($Data.Count - $Lag)
return $autocovariance / $variance
}
function Test-BimodalDistribution {
param([double[]]$Data)
if ($Data.Count -lt 20) { return $false }
# Simple bimodal test: check if there are two distinct clusters
$sorted = $Data | Sort-Object
$q1 = Get-Percentile -Data $sorted -Percentile 25
$q3 = Get-Percentile -Data $sorted -Percentile 75
$median = Get-Percentile -Data $sorted -Percentile 50
$iqr = $q3 - $q1
if ($iqr -eq 0) { return $false }
# Check for gap around median (Hartigan's dip test approximation)
$midRange = $Data | Where-Object { $_ -gt ($median - $iqr * 0.5) -and $_ -lt ($median + $iqr * 0.5) }
$midCount = $midRange.Count
$totalCount = $Data.Count
# If middle range is sparse (<20% of data), likely bimodal
return ($midCount / $totalCount) -lt 0.2
}
function Get-WeeklyVariance {
param([object[]]$TimeSeries, [string]$ValueProperty)
if ($TimeSeries.Count -lt 2016) { return 0 } # Need at least 1 week (7 days × 24 hours × 12 intervals)
$weekdays = $TimeSeries | Where-Object {
$dow = ([DateTime]$_.Timestamp).DayOfWeek
$dow -ne 'Saturday' -and $dow -ne 'Sunday'
} | ForEach-Object { $_.$ValueProperty }
$weekends = $TimeSeries | Where-Object {
$dow = ([DateTime]$_.Timestamp).DayOfWeek
$dow -eq 'Saturday' -or $dow -eq 'Sunday'
} | ForEach-Object { $_.$ValueProperty }
if ($weekdays.Count -eq 0 -or $weekends.Count -eq 0) { return 0 }
$weekdayAvg = ($weekdays | Measure-Object -Average).Average
$weekendAvg = ($weekends | Measure-Object -Average).Average
if ($weekdayAvg -eq 0 -and $weekendAvg -eq 0) { return 0 }
$maxAvg = [Math]::Max($weekdayAvg, $weekendAvg)
$minAvg = [Math]::Min($weekdayAvg, $weekendAvg)
return [Math]::Abs(($maxAvg - $minAvg) / $maxAvg * 100)
}
function Get-DatabaseCost {
param(
[string]$Edition,
[string]$SkuName,
[int]$Capacity
)
# First check if SkuName is already in the pricing table (e.g., "S3", "P2")
if ($Pricing.ContainsKey($SkuName)) {
return $Pricing[$SkuName]
}
# Map Edition + Capacity to SKU code for DTU tiers
$skuCode = $null
if ($Edition -eq 'Basic') {
$skuCode = 'Basic'
}
elseif ($Edition -eq 'Standard') {
# Map DTU capacity to Standard tier SKU
$skuCode = switch ($Capacity) {
10 { 'S0' }
20 { 'S1' }
50 { 'S2' }
100 { 'S3' }
200 { 'S4' }
400 { 'S6' }
800 { 'S7' }
1600 { 'S9' }
3000 { 'S12' }
default { $null }
}
}
elseif ($Edition -eq 'Premium') {
# Map DTU capacity to Premium tier SKU
$skuCode = switch ($Capacity) {
125 { 'P1' }
250 { 'P2' }
500 { 'P4' }
1000 { 'P6' }
1750 { 'P11' }
4000 { 'P15' }
default { $null }
}
}
# If we found a SKU code, return its price
if ($skuCode -and $Pricing.ContainsKey($skuCode)) {
return $Pricing[$skuCode]
}
# vCore pricing
if ($Edition -eq 'GeneralPurpose') {
if ($SkuName -match 'Serverless' -or $SkuName -match '_S_') {
return $Capacity * $Pricing['GP_S_Gen5_vCore']
}
return $Capacity * $Pricing['GP_Gen5_vCore']
}
if ($Edition -eq 'BusinessCritical') {
return $Capacity * $Pricing['BC_Gen5_vCore']
}
if ($Edition -eq 'Hyperscale') {
return $Capacity * $Pricing['GP_Gen5_vCore'] # Hyperscale pricing similar to GP
}
return 0
}
function Get-SkuCode {
param(
[string]$Edition,
[string]$SkuName,
[int]$Capacity
)
# If SkuName already looks like a SKU code (S3, P2, etc.), return it
if ($SkuName -match '^(S\d+|P\d+|Basic)$') {
return $SkuName
}
# Map Edition + Capacity to SKU code
if ($Edition -eq 'Basic') {
return 'Basic'
}
elseif ($Edition -eq 'Standard') {
return $(switch ($Capacity) {
10 { 'S0' }
20 { 'S1' }
50 { 'S2' }
100 { 'S3' }
200 { 'S4' }
400 { 'S6' }
800 { 'S7' }
1600 { 'S9' }
3000 { 'S12' }
default { $null }
})
}
elseif ($Edition -eq 'Premium') {
return $(switch ($Capacity) {
125 { 'P1' }
250 { 'P2' }
500 { 'P4' }
1000 { 'P6' }
1750 { 'P11' }
4000 { 'P15' }
default { $null }
})
}
return $null
}
function Get-EstimatedServerlessCost {
param(
[double]$VCores,
[object[]]$TimeSeries,
[string]$ValueProperty,
[double]$StorageGB
)
if ($TimeSeries.Count -eq 0) {
return [PSCustomObject]@{
ComputeCost = 0
StorageCost = 0
TotalCost = 0
ActiveHoursMonthly = 0
}
}
# Calculate active hours (slots with >5% usage)
$activeSlots = $TimeSeries | Where-Object { $_.$ValueProperty -gt 5 }
$activeHoursPerDay = ($activeSlots.Count / 288) # 288 five-minute intervals per day
$activeHoursPerMonth = $activeHoursPerDay * 30
# Serverless compute cost (billed per second when active)
# Price is per month, so divide by 730 hours to get hourly rate
$computeCostPerHour = ($VCores * $Pricing['GP_S_Gen5_vCore']) / 730
$computeCost = $activeHoursPerMonth * $computeCostPerHour
# Storage cost (always billed, even when paused)
$storageCost = $StorageGB * $Pricing['Storage_GB_Monthly']
return [PSCustomObject]@{
ComputeCost = [Math]::Round($computeCost, 2)
StorageCost = [Math]::Round($storageCost, 2)
TotalCost = [Math]::Round($computeCost + $storageCost, 2)
ActiveHoursMonthly = [Math]::Round($activeHoursPerMonth, 1)
}
}
function Get-WeeklyBusyWindows {
param(
[object[]]$TimeSeries,
[string]$ValueProperty,
[double]$BusyThreshold
)
if ($TimeSeries.Count -eq 0) { return @() }
# Group by day-of-week + time slot
$weeklySlots = $TimeSeries | Group-Object {
$dt = [DateTime]$_.Timestamp
"$($dt.DayOfWeek) $($dt.ToString('HH:mm'))"
}
# Calculate average for each weekly slot
$slotAverages = $weeklySlots | ForEach-Object {
$parts = $_.Name -split ' '
[PSCustomObject]@{
DayOfWeek = $parts[0]
Time = $parts[1]
Avg = ($_.Group.$ValueProperty | Measure-Object -Average).Average
}
} | Where-Object { $_.Avg -gt $BusyThreshold }
if ($slotAverages.Count -eq 0) { return @() }
# Sort by day order then time
$dayOrder = @{Monday=1; Tuesday=2; Wednesday=3; Thursday=4; Friday=5; Saturday=6; Sunday=7}
$slotAverages = $slotAverages | Sort-Object {
$dayOrder[$_.DayOfWeek] * 10000 + [int]$_.Time.Replace(':','')
}
# Group contiguous slots into windows
$windows = @()
$currentWindow = $null
foreach ($slot in $slotAverages) {
if (-not $currentWindow) {
# Start new window
$currentWindow = @{
Day = $slot.DayOfWeek
Start = $slot.Time
End = $slot.Time
AvgUsage = @($slot.Avg)
}
}
elseif ($currentWindow.Day -eq $slot.DayOfWeek) {
# Same day - check if contiguous (5 minutes apart)
$currentEndTime = [DateTime]::ParseExact($currentWindow.End, 'HH:mm', $null)
$slotTime = [DateTime]::ParseExact($slot.Time, 'HH:mm', $null)
$diffMinutes = ($slotTime - $currentEndTime).TotalMinutes
if ($diffMinutes -eq 5) {
# Extend current window
$currentWindow.End = $slot.Time
$currentWindow.AvgUsage += $slot.Avg
}
else {
# Gap detected - save current window and start new one
$startTime = [DateTime]::ParseExact($currentWindow.Start, 'HH:mm', $null)
$endTime = [DateTime]::ParseExact($currentWindow.End, 'HH:mm', $null)
$durationHours = ($endTime - $startTime).TotalHours + (5.0/60) # Add final 5-min slot
$windows += [PSCustomObject]@{
Period = "$($currentWindow.Day) $($currentWindow.Start)-$($currentWindow.End)"
AvgUsage = [Math]::Round(($currentWindow.AvgUsage | Measure-Object -Average).Average, 2)
DurationHours = [Math]::Round($durationHours, 2)
}
$currentWindow = @{
Day = $slot.DayOfWeek
Start = $slot.Time
End = $slot.Time
AvgUsage = @($slot.Avg)
}
}
}
else {
# Different day - save current window and start new one
$startTime = [DateTime]::ParseExact($currentWindow.Start, 'HH:mm', $null)
$endTime = [DateTime]::ParseExact($currentWindow.End, 'HH:mm', $null)
$durationHours = ($endTime - $startTime).TotalHours + (5.0/60)
$windows += [PSCustomObject]@{
Period = "$($currentWindow.Day) $($currentWindow.Start)-$($currentWindow.End)"
AvgUsage = [Math]::Round(($currentWindow.AvgUsage | Measure-Object -Average).Average, 2)
DurationHours = [Math]::Round($durationHours, 2)
}
$currentWindow = @{
Day = $slot.DayOfWeek
Start = $slot.Time
End = $slot.Time
AvgUsage = @($slot.Avg)
}
}
}
# Add last window
if ($currentWindow) {
$startTime = [DateTime]::ParseExact($currentWindow.Start, 'HH:mm', $null)
$endTime = [DateTime]::ParseExact($currentWindow.End, 'HH:mm', $null)
$durationHours = ($endTime - $startTime).TotalHours + (5.0/60)
$windows += [PSCustomObject]@{
Period = "$($currentWindow.Day) $($currentWindow.Start)-$($currentWindow.End)"
AvgUsage = [Math]::Round(($currentWindow.AvgUsage | Measure-Object -Average).Average, 2)
DurationHours = [Math]::Round($durationHours, 2)
}
}
return $windows
}
function Get-PredictabilityScore {
param(
[object[]]$TimeSeries,
[string]$ValueProperty,
[double]$BusyThreshold
)
if ($TimeSeries.Count -lt 288) { return 0 } # Need at least 1 day
# Calculate busy hours per day
$dailyBusyHours = $TimeSeries |
Group-Object { ([DateTime]$_.Timestamp).Date } |
ForEach-Object {
$busySlots = $_.Group | Where-Object { $_.$ValueProperty -gt $BusyThreshold }
$busySlots.Count / 12 # 12 five-minute intervals per hour
}
if ($dailyBusyHours.Count -eq 0) { return 0 }
# Calculate coefficient of variation
$stats = $dailyBusyHours | Measure-Object -Average -StandardDeviation
if ($stats.Average -eq 0) { return 0 }
$cv = ($stats.StandardDeviation / $stats.Average) * 100
# Score: 100 = perfectly predictable (CV=0), 0 = chaotic (CV>=100)
# CV < 20 = excellent (score 80-100)
# CV 20-50 = good (score 50-80)
# CV 50-100 = fair (score 0-50)
# CV > 100 = poor (score 0)
$score = [Math]::Max(0, [Math]::Min(100, 100 - $cv))
return [Math]::Round($score, 0)
}
function Get-ScheduledPauseCost {
param(
[double]$CurrentCost,
[object[]]$BusyWindows,
[double]$BufferHours = 0.5
)
if ($BusyWindows.Count -eq 0) {
return [PSCustomObject]@{
RuntimeCost = 0
AutomationCost = 0
TotalCost = 0
ActiveHoursWeekly = 0
ActiveFraction = 0
}
}
# Total busy hours per week
$busyHoursPerWeek = ($BusyWindows.DurationHours | Measure-Object -Sum).Sum
# Add buffer for startup/shutdown (30 min each side per window)
$totalActiveHoursPerWeek = $busyHoursPerWeek + ($BusyWindows.Count * $BufferHours * 2)
# Calculate runtime cost
$activeFraction = $totalActiveHoursPerWeek / 168 # 168 hours per week
$runtimeCost = $CurrentCost * $activeFraction
# Azure Automation cost
$automationCost = $AutomationCostMonthly
return [PSCustomObject]@{
RuntimeCost = [Math]::Round($runtimeCost, 2)
AutomationCost = $automationCost
TotalCost = [Math]::Round($runtimeCost + $automationCost, 2)
ActiveHoursWeekly = [Math]::Round($totalActiveHoursPerWeek, 1)
ActiveFraction = [Math]::Round($activeFraction * 100, 1)
}
}
#endregion
#region Data Import
Write-Verbose "Importing metric files from $MetricsPath"
# Import SKU data
$skuFile = Join-Path $MetricsPath "AzSQLDb_SKU.csv"
if (-not (Test-Path $skuFile)) {
throw "SKU file not found: $skuFile"
}
$databases = Import-Csv $skuFile -Delimiter "`t"
# Import metrics
$metricFiles = @{
DTU = "azsqldb_metric_dtu_consumption.csv"
CPU = "azsqldb_metric_cpu.csv"
Workers = "azsqldb_metric_workers.csv"
Sessions = "azsqldb_metric_sessions.csv"
Storage = "azsqldb_metric_storage.csv"
Connections = "azsqldb_metric_connection_successful.csv"
LogWrite = "azsqldb_metric_log_write.csv"
}
$metrics = @{}
foreach ($metricName in $metricFiles.Keys) {
$file = Join-Path $MetricsPath $metricFiles[$metricName]
if (Test-Path $file) {
Write-Verbose "Importing $metricName metrics"
$metrics[$metricName] = Import-Csv $file -Delimiter "`t"
} else {
Write-Warning "Metric file not found: $file"
$metrics[$metricName] = @()
}
}
#endregion
#region Main Analysis Loop
$results = foreach ($db in $databases) {
Write-Verbose "Analyzing $($db.ServerName)/$($db.DatabaseName)"
# Detect database type early
$isDTU = $db.Edition -in @('Basic', 'Standard', 'Premium')
$isInPool = -not [string]::IsNullOrEmpty($db.ElasticPoolName)
$isServerless = $db.SkuName -match '_S_' -or $db.Edition -match 'Serverless'
$isHyperscale = $db.Edition -eq 'Hyperscale'
# Get actual SKU code for DTU databases (e.g., "S3" from Edition="Standard", Capacity=100)
$skuCode = if ($isDTU) {
Get-SkuCode -Edition $db.Edition -SkuName $db.SkuName -Capacity $db.Capacity
} else {
$db.SkuName
}
# Initialize result object
$result = [PSCustomObject]@{
# Identity
ServerName = $db.ServerName
DatabaseName = $db.DatabaseName
# Current State
CurrentEdition = $db.Edition
CurrentSkuName = if ($isDTU) { $skuCode } else { $db.SkuName }
CurrentCapacity = $db.Capacity
CurrentModel = if ($isDTU) { 'DTU' } else { 'vCore' }
CurrentMaxSizeGB = if ($db.MaxSizeBytes) { [Math]::Round($db.MaxSizeBytes / 1GB, 2) } else { $db.MaxSizeGB }
ElasticPoolName = $db.ElasticPoolName
IsInPool = $isInPool
IsServerless = $isServerless
IsHyperscale = $isHyperscale
# Recommendation
Status = 'ANALYZING'
Classification = 'UNKNOWN'
Recommendation = 'Analyzing...'
RecommendedTier = ''
RecommendedCapacity = 0
Confidence = 'Medium'
Priority = 'Medium'
Impact = 'Medium'
NextAction = ''
Flags = ''
# Statistics - Usage
DTU_Avg = $null
DTU_P95 = $null
DTU_Max = $null
CPU_Avg = $null
CPU_P95 = $null
CPU_Max = $null
CV_DTU = $null
CV_CPU = $null
Idle_Percent = $null
# Statistics - Resources
Sessions_Peak_Actual = $null
Sessions_Peak_Percent = $null
Workers_Peak_Actual = $null
Workers_Peak_Percent = $null
Storage_Used_GB = $null
Storage_Percent = $null
LogWrite_P95 = $null
# Statistics - Patterns
Connections_Per_Hour_Avg = $null
Pattern_Autocorrelation = $null
Weekly_Variance_Percent = $null
Growth_DTU_Trend = $null
Growth_CPU_Trend = $null
Growth_Storage_MB_Per_Month = $null
Days_Of_Data = 0
# Busy Period Detection
Busy_Windows = $null
Busy_Hours_Per_Week = $null
Active_Hours_Per_Day_Avg = $null
Pattern_Predictability_Score = $null
Scheduled_Pause_Feasibility = $null
# Decisions
Serverless_Viable = $false
ElasticPool_Candidate = $false
# Costs
Current_Cost_EUR_Monthly = 0
Recommended_Cost_EUR_Monthly = 0
Savings_EUR_Monthly = 0
Savings_Percent = 0
Alternative_Recommendation = $null
Alternative_Cost_EUR_Monthly = $null
# Serverless Cost Breakdown
Serverless_Active_Hours_Monthly = $null
Serverless_Compute_Cost = $null
Serverless_Storage_Cost = $null
Serverless_Total_Cost = $null
# Scheduled Pause Cost Breakdown
Scheduled_Pause_Runtime_Cost = $null
Scheduled_Pause_Automation_Cost = $null
Scheduled_Pause_Active_Hours_Weekly = $null
Scheduled_Pause_Total_Cost = $null
}
# Get metrics for this database
$dbKey = "$($db.ServerName)|$($db.DatabaseName)"
# Special handling for databases in elastic pools
if ($isInPool) {
# Pooled databases don't have individual DTU limits
# They share the pool's eDTU and should be analyzed differently
# We can still get CPU, sessions, workers, storage metrics
$computeData = $metrics.CPU | Where-Object {
"$($_.ServerName)|$($_.DBName)" -eq $dbKey
}
$sessionsData = $metrics.Sessions | Where-Object {
"$($_.ServerName)|$($_.DBName)" -eq $dbKey
}
$workersData = $metrics.Workers | Where-Object {
"$($_.ServerName)|$($_.DBName)" -eq $dbKey
}
$storageData = $metrics.Storage | Where-Object {
"$($_.ServerName)|$($_.DBName)" -eq $dbKey
}
$connectionsData = $metrics.Connections | Where-Object {
"$($_.ServerName)|$($_.DBName)" -eq $dbKey
}
$logWriteData = $metrics.LogWrite | Where-Object {
"$($_.ServerName)|$($_.DBName)" -eq $dbKey
}
# Check data sufficiency
if ($computeData.Count -eq 0) {
# No data at all - likely permission issue
$result.Status = 'REVIEW'
$result.Classification = 'NO_DATA'
$result.Recommendation = "No metric data available (check permissions)"
$result.NextAction = 'Verify metric collection permissions'
$result.Confidence = 'Low'
$result.Priority = 'Low'
$result.Days_Of_Data = 0
$result.Flags = 'No metric data collected - permission issue or collection failure'
# Leave all metric values as 0 (default) - they're unknown, not actually zero
$result
continue
}
if ($computeData.Count -lt 2016) { # Less than 7 days (5-min intervals)
$result.Status = 'OK'
$result.Classification = 'IN_POOL'
$result.Recommendation = "OK (in elastic pool '$($db.ElasticPoolName)', insufficient data)"
$result.NextAction = 'Monitor pool performance'
$result.Confidence = 'Low'
$result.Priority = 'Low'
$result.Days_Of_Data = [Math]::Round($computeData.Count / 288, 1) # 288 intervals per day
$result.Flags = 'Part of elastic pool - individual optimization not applicable'
$result
continue
}
$result.Days_Of_Data = [Math]::Round($computeData.Count / 288, 1) # 288 intervals per day
# Calculate basic statistics for pooled database
$cpuValues = $computeData.Nominal_Value
$result.CPU_Avg = [Math]::Round(($cpuValues | Measure-Object -Average).Average, 2)
$result.CPU_P95 = [Math]::Round((Get-Percentile -Data $cpuValues -Percentile 95), 2)
$result.CPU_Max = [Math]::Round(($cpuValues | Measure-Object -Maximum).Maximum, 2)
if ($sessionsData.Count -gt 0) {
$result.Sessions_Peak_Percent = [Math]::Round(($sessionsData.Metric_Value | Measure-Object -Maximum).Maximum, 2)
$result.Sessions_Peak_Actual = [Math]::Round(($sessionsData.Nominal_Value | Measure-Object -Maximum).Maximum, 0)
}
if ($workersData.Count -gt 0) {
$result.Workers_Peak_Percent = [Math]::Round(($workersData.Metric_Value | Measure-Object -Maximum).Maximum, 2)
$result.Workers_Peak_Actual = [Math]::Round(($workersData.Nominal_Value | Measure-Object -Maximum).Maximum, 0)
}
if ($storageData.Count -gt 0) {
$result.Storage_Percent = [Math]::Round(($storageData.Metric_Value | Measure-Object -Average).Average, 2)
$result.Storage_Used_GB = [Math]::Round(($result.Storage_Percent / 100) * $result.CurrentMaxSizeGB, 2)
}
# Check if hitting pool-level constraints
if ($result.Sessions_Peak_Percent -gt 80 -or $result.Workers_Peak_Percent -gt 80) {
$result.Status = 'REVIEW'
$result.Classification = 'IN_POOL_CONSTRAINED'
$result.Recommendation = "Review pool capacity (database hitting pool limits)"
$result.Priority = 'High'
$result.NextAction = "Check elastic pool '$($db.ElasticPoolName)' sizing"
$result.Flags = if ($result.Sessions_Peak_Percent -gt 80) { 'Sessions constrained' } else { 'Workers constrained' }
} else {
$result.Status = 'OK'
$result.Classification = 'IN_POOL'
$result.Recommendation = "OK (in elastic pool '$($db.ElasticPoolName)')"
$result.NextAction = 'Monitor pool performance'
$result.Flags = 'Part of elastic pool - individual optimization not applicable'
}
$result
continue
}
# For non-pooled databases, determine if DTU or vCore
# Get time-series data
if ($isDTU) {
$computeData = $metrics.DTU | Where-Object {
"$($_.ServerName)|$($_.DBName)" -eq $dbKey
}
# Fallback to CPU if DTU metrics missing
if ($computeData.Count -eq 0) {
Write-Warning "DTU metrics missing for $dbKey, using CPU metrics as fallback"
$computeData = $metrics.CPU | Where-Object {
"$($_.ServerName)|$($_.DBName)" -eq $dbKey
}
$isDTU = $false # Treat as vCore for analysis
}
} else {
$computeData = $metrics.CPU | Where-Object {
"$($_.ServerName)|$($_.DBName)" -eq $dbKey
}
}
$sessionsData = $metrics.Sessions | Where-Object {
"$($_.ServerName)|$($_.DBName)" -eq $dbKey
}
$workersData = $metrics.Workers | Where-Object {
"$($_.ServerName)|$($_.DBName)" -eq $dbKey
}
$storageData = $metrics.Storage | Where-Object {
"$($_.ServerName)|$($_.DBName)" -eq $dbKey
}
$connectionsData = $metrics.Connections | Where-Object {
"$($_.ServerName)|$($_.DBName)" -eq $dbKey
}
$logWriteData = $metrics.LogWrite | Where-Object {
"$($_.ServerName)|$($_.DBName)" -eq $dbKey
}
# Check data sufficiency (Tier 2)
if ($computeData.Count -eq 0) {
# No data at all - likely permission issue
$result.Status = 'REVIEW'
$result.Classification = 'NO_DATA'
$result.Recommendation = 'No metric data available (check permissions)'
$result.NextAction = 'Verify metric collection permissions'
$result.Confidence = 'Low'
$result.Priority = 'Low'
$result.Days_Of_Data = 0
$result.Flags = 'No metric data collected - permission issue or collection failure'
$result.Current_Cost_EUR_Monthly = Get-DatabaseCost -Edition $db.Edition -SkuName $db.SkuName -Capacity $db.Capacity
# Leave all metrics as 0 - they're unknown, not actually zero
$result
continue
}
if ($computeData.Count -lt 2016) { # Less than 7 days (5-min intervals: 7×24×12)
$result.Status = 'REVIEW'
$result.Classification = 'INSUFFICIENT_DATA'
$result.Recommendation = 'OK (insufficient data for analysis)'
$result.NextAction = 'Re-analyze after day 30'
$result.Confidence = 'Low'
$result.Priority = 'Low'
$result.Days_Of_Data = [Math]::Round($computeData.Count / 288, 1) # 288 intervals per day
$result.Current_Cost_EUR_Monthly = Get-DatabaseCost -Edition $db.Edition -SkuName $db.SkuName -Capacity $db.Capacity
$result
continue
}
$result.Days_Of_Data = [Math]::Round($computeData.Count / 288, 1) # 288 intervals per day
# Calculate statistics
if ($isDTU) {
$dtuValues = $computeData.Nominal_Value
$result.DTU_Avg = [Math]::Round(($dtuValues | Measure-Object -Average).Average, 2)
$result.DTU_P95 = [Math]::Round((Get-Percentile -Data $dtuValues -Percentile 95), 2)
$result.DTU_Max = [Math]::Round(($dtuValues | Measure-Object -Maximum).Maximum, 2)
$result.CV_DTU = [Math]::Round((Get-CoefficientOfVariation -Data $dtuValues), 2)
$idleCount = ($computeData | Where-Object { $_.Metric_Value -lt 5 }).Count
$result.Idle_Percent = [Math]::Round(($idleCount / $computeData.Count * 100), 2)
$result.Growth_DTU_Trend = [Math]::Round((Get-LinearTrend -TimeSeries $computeData -ValueProperty 'Nominal_Value'), 2)
$result.Pattern_Autocorrelation = [Math]::Round((Get-Autocorrelation -Data $dtuValues -Lag 288), 2) # 24 hours in 5-min intervals
$result.Weekly_Variance_Percent = [Math]::Round((Get-WeeklyVariance -TimeSeries $computeData -ValueProperty 'Nominal_Value'), 2)
$computeMetricName = 'DTU'
$computeP95 = $result.DTU_P95
} else {
$cpuValues = $computeData.Nominal_Value
$result.CPU_Avg = [Math]::Round(($cpuValues | Measure-Object -Average).Average, 2)
$result.CPU_P95 = [Math]::Round((Get-Percentile -Data $cpuValues -Percentile 95), 2)
$result.CPU_Max = [Math]::Round(($cpuValues | Measure-Object -Maximum).Maximum, 2)
$result.CV_CPU = [Math]::Round((Get-CoefficientOfVariation -Data $cpuValues), 2)
$idleCount = ($computeData | Where-Object { $_.Metric_Value -lt 5 }).Count
$result.Idle_Percent = [Math]::Round(($idleCount / $computeData.Count * 100), 2)
$result.Growth_CPU_Trend = [Math]::Round((Get-LinearTrend -TimeSeries $computeData -ValueProperty 'Nominal_Value'), 2)
$result.Pattern_Autocorrelation = [Math]::Round((Get-Autocorrelation -Data $cpuValues -Lag 288), 2) # 24 hours in 5-min intervals
$result.Weekly_Variance_Percent = [Math]::Round((Get-WeeklyVariance -TimeSeries $computeData -ValueProperty 'Nominal_Value'), 2)
$computeMetricName = 'CPU'
$computeP95 = $result.CPU_P95
}
# Sessions/Workers statistics
if ($sessionsData.Count -gt 0) {
$result.Sessions_Peak_Percent = [Math]::Round(($sessionsData.Metric_Value | Measure-Object -Maximum).Maximum, 2)
$result.Sessions_Peak_Actual = [Math]::Round(($sessionsData.Nominal_Value | Measure-Object -Maximum).Maximum, 0)
}
if ($workersData.Count -gt 0) {
$result.Workers_Peak_Percent = [Math]::Round(($workersData.Metric_Value | Measure-Object -Maximum).Maximum, 2)
$result.Workers_Peak_Actual = [Math]::Round(($workersData.Nominal_Value | Measure-Object -Maximum).Maximum, 0)
}
# Storage statistics
if ($storageData.Count -gt 0) {
$result.Storage_Percent = [Math]::Round(($storageData.Metric_Value | Measure-Object -Average).Average, 2)
$result.Storage_Used_GB = [Math]::Round(($result.Storage_Percent / 100) * $result.CurrentMaxSizeGB, 2)
# Storage growth
$storageGrowth = Get-LinearTrend -TimeSeries $storageData -ValueProperty 'Metric_Value'
$result.Growth_Storage_MB_Per_Month = [Math]::Round(($storageGrowth / 100 * $result.CurrentMaxSizeGB * 1024), 0)
}
# Connections statistics
if ($connectionsData.Count -gt 0) {
$totalConnections = ($connectionsData.Metric_Value | Measure-Object -Sum).Sum
$totalHours = $connectionsData.Count
$result.Connections_Per_Hour_Avg = [Math]::Round(($totalConnections / $totalHours), 2)
}
# Log write statistics
if ($logWriteData.Count -gt 0) {
$result.LogWrite_P95 = [Math]::Round((Get-Percentile -Data $logWriteData.Metric_Value -Percentile 95), 2)
}
# Current cost
if ($isServerless) {
# For serverless, calculate estimated cost with active hours
$serverlessCostCalc = Get-EstimatedServerlessCost -VCores $db.Capacity -TimeSeries $computeData -ValueProperty 'Metric_Value' -StorageGB $result.Storage_Used_GB
$result.Current_Cost_EUR_Monthly = $serverlessCostCalc.TotalCost
} else {
$result.Current_Cost_EUR_Monthly = Get-DatabaseCost -Edition $db.Edition -SkuName $db.SkuName -Capacity $db.Capacity
}
# Detect busy windows and calculate predictability
$busyThreshold = $computeP95 * 0.10
$busyWindows = Get-WeeklyBusyWindows -TimeSeries $computeData -ValueProperty 'Nominal_Value' -BusyThreshold $busyThreshold
if ($busyWindows.Count -gt 0) {
# Format busy windows
$result.Busy_Windows = ($busyWindows.Period -join ', ')
$result.Busy_Hours_Per_Week = [Math]::Round(($busyWindows.DurationHours | Measure-Object -Sum).Sum, 1)
$result.Active_Hours_Per_Day_Avg = [Math]::Round($result.Busy_Hours_Per_Week / 7, 1)
# Calculate predictability score
$result.Pattern_Predictability_Score = Get-PredictabilityScore -TimeSeries $computeData -ValueProperty 'Nominal_Value' -BusyThreshold $busyThreshold
$result.Scheduled_Pause_Feasibility = $result.Pattern_Predictability_Score
}
#region Decision Tree
# TIER 1: Constraint Triage
$constraintViolation = $false
$constraintReason = ''
if ($result.Sessions_Peak_Percent -gt 80) {
$constraintViolation = $true
$constraintReason = 'Sessions constraint'
}
if ($result.Workers_Peak_Percent -gt 80) {
$constraintViolation = $true
$constraintReason = if ($constraintReason) { "$constraintReason + Workers constraint" } else { 'Workers constraint' }
}
if ($result.Storage_Percent -gt 90) {
$constraintViolation = $true
$constraintReason = if ($constraintReason) { "$constraintReason + Storage constraint" } else { 'Storage constraint' }
}
if ($constraintViolation) {
$result.Status = 'UPGRADE'
$result.Classification = 'CONSTRAINED'
$result.Recommendation = "Upgrade required: $constraintReason"
$result.Priority = 'High'
$result.Confidence = 'High'
$result.Flags = $constraintReason
# Suggest next tier