|
| 1 | +package client |
| 2 | + |
| 3 | +import ( |
| 4 | + "fmt" |
| 5 | + "strconv" |
| 6 | + "strings" |
| 7 | + "time" |
| 8 | + |
| 9 | + "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/costmanagement/armcostmanagement" |
| 10 | + "github.com/Azure/go-autorest/autorest/to" |
| 11 | + |
| 12 | + "github.com/grafana/cloudcost-exporter/pkg/azure/blob" |
| 13 | + "github.com/grafana/cloudcost-exporter/pkg/utils" |
| 14 | +) |
| 15 | + |
| 16 | +// buildBlobStorageCostQuery returns a Cost Management Usage query for Microsoft.Storage-style |
| 17 | +// capacity meters: ServiceName Storage, grouped by ResourceLocation and Meter, daily granularity |
| 18 | +// (aggregated client-side). Matches the S3 TimedStorage rate shape: (cost / HoursInMonth) / usage. |
| 19 | +func buildBlobStorageCostQuery(lookback time.Duration) armcostmanagement.QueryDefinition { |
| 20 | + if lookback < 24*time.Hour { |
| 21 | + lookback = 24 * time.Hour |
| 22 | + } |
| 23 | + end := time.Now().UTC().Truncate(24 * time.Hour) |
| 24 | + start := end.Add(-lookback) |
| 25 | + |
| 26 | + dimType := armcostmanagement.QueryColumnTypeDimension |
| 27 | + opIn := armcostmanagement.QueryOperatorTypeIn |
| 28 | + exportType := armcostmanagement.ExportTypeActualCost |
| 29 | + timeframe := armcostmanagement.TimeframeTypeCustom |
| 30 | + granularity := armcostmanagement.GranularityTypeDaily |
| 31 | + sumCostFn := armcostmanagement.FunctionTypeSum |
| 32 | + sumUsageFn := armcostmanagement.FunctionTypeSum |
| 33 | + |
| 34 | + return armcostmanagement.QueryDefinition{ |
| 35 | + Type: &exportType, |
| 36 | + Timeframe: &timeframe, |
| 37 | + TimePeriod: &armcostmanagement.QueryTimePeriod{ |
| 38 | + From: &start, |
| 39 | + To: &end, |
| 40 | + }, |
| 41 | + Dataset: &armcostmanagement.QueryDataset{ |
| 42 | + Granularity: &granularity, |
| 43 | + Aggregation: map[string]*armcostmanagement.QueryAggregation{ |
| 44 | + "cost": { |
| 45 | + Name: to.StringPtr("PreTaxCost"), |
| 46 | + Function: &sumCostFn, |
| 47 | + }, |
| 48 | + "usageQty": { |
| 49 | + Name: to.StringPtr("UsageQuantity"), |
| 50 | + Function: &sumUsageFn, |
| 51 | + }, |
| 52 | + }, |
| 53 | + Grouping: []*armcostmanagement.QueryGrouping{ |
| 54 | + {Type: &dimType, Name: to.StringPtr("ResourceLocation")}, |
| 55 | + {Type: &dimType, Name: to.StringPtr("Meter")}, |
| 56 | + }, |
| 57 | + Filter: &armcostmanagement.QueryFilter{ |
| 58 | + Dimensions: &armcostmanagement.QueryComparisonExpression{ |
| 59 | + Name: to.StringPtr("ServiceName"), |
| 60 | + Operator: &opIn, |
| 61 | + Values: []*string{to.StringPtr("Storage")}, |
| 62 | + }, |
| 63 | + }, |
| 64 | + }, |
| 65 | + } |
| 66 | +} |
| 67 | + |
| 68 | +func subscriptionQueryScope(subscriptionID string) string { |
| 69 | + return fmt.Sprintf("/subscriptions/%s/", strings.TrimSpace(subscriptionID)) |
| 70 | +} |
| 71 | + |
| 72 | +// blobStorageRowsFromProperties turns Cost Management Usage rows into blob.StorageCostRow rates. |
| 73 | +// Daily rows for the same (location, meter) are summed before rate calculation. |
| 74 | +func blobStorageRowsFromProperties(props *armcostmanagement.QueryProperties) ([]blob.StorageCostRow, error) { |
| 75 | + if props == nil || len(props.Columns) == 0 { |
| 76 | + return nil, nil |
| 77 | + } |
| 78 | + idx := columnNameIndex(props.Columns) |
| 79 | + locIdx := firstColumnIndex(idx, "resourcelocation") |
| 80 | + meterIdx := firstColumnIndex(idx, "meter") |
| 81 | + costIdx := firstColumnIndex(idx, "cost", "pretaxcost", "totalcost") |
| 82 | + usageIdx := firstColumnIndex(idx, "usageqty", "usagequantity") |
| 83 | + |
| 84 | + if locIdx < 0 || meterIdx < 0 || costIdx < 0 || usageIdx < 0 { |
| 85 | + return nil, fmt.Errorf("cost management query columns missing (need ResourceLocation, Meter, cost, usageQty); got %v", columnNames(props.Columns)) |
| 86 | + } |
| 87 | + |
| 88 | + type agg struct { |
| 89 | + cost float64 |
| 90 | + qty float64 |
| 91 | + } |
| 92 | + merged := make(map[string]agg) |
| 93 | + |
| 94 | + need := max(locIdx, meterIdx, costIdx, usageIdx) + 1 |
| 95 | + for _, row := range props.Rows { |
| 96 | + if len(row) < need { |
| 97 | + continue |
| 98 | + } |
| 99 | + loc := normalizeLocation(cellString(row[locIdx])) |
| 100 | + meter := strings.TrimSpace(cellString(row[meterIdx])) |
| 101 | + if meter == "" { |
| 102 | + continue |
| 103 | + } |
| 104 | + cost, okC := cellFloat(row[costIdx]) |
| 105 | + qty, okQ := cellFloat(row[usageIdx]) |
| 106 | + if !okC || !okQ { |
| 107 | + continue |
| 108 | + } |
| 109 | + key := loc + "\x00" + meter |
| 110 | + a := merged[key] |
| 111 | + a.cost += cost |
| 112 | + a.qty += qty |
| 113 | + merged[key] = a |
| 114 | + } |
| 115 | + |
| 116 | + out := make([]blob.StorageCostRow, 0, len(merged)) |
| 117 | + for key, a := range merged { |
| 118 | + if a.qty == 0 { |
| 119 | + continue |
| 120 | + } |
| 121 | + parts := strings.SplitN(key, "\x00", 2) |
| 122 | + loc := parts[0] |
| 123 | + meter := parts[1] |
| 124 | + // S3 TimedStorage-style: USD/(GiB*h) from billing cost and GB-mo style usage totals. |
| 125 | + rate := (a.cost / utils.HoursInMonth) / a.qty |
| 126 | + out = append(out, blob.StorageCostRow{ |
| 127 | + Region: loc, |
| 128 | + Class: meter, |
| 129 | + Rate: rate, |
| 130 | + }) |
| 131 | + } |
| 132 | + return out, nil |
| 133 | +} |
| 134 | + |
| 135 | +func columnNames(cols []*armcostmanagement.QueryColumn) []string { |
| 136 | + var names []string |
| 137 | + for _, c := range cols { |
| 138 | + if c != nil && c.Name != nil { |
| 139 | + names = append(names, *c.Name) |
| 140 | + } |
| 141 | + } |
| 142 | + return names |
| 143 | +} |
| 144 | + |
| 145 | +func columnNameIndex(cols []*armcostmanagement.QueryColumn) map[string]int { |
| 146 | + m := make(map[string]int) |
| 147 | + for i, c := range cols { |
| 148 | + if c == nil || c.Name == nil { |
| 149 | + continue |
| 150 | + } |
| 151 | + m[strings.ToLower(strings.TrimSpace(*c.Name))] = i |
| 152 | + } |
| 153 | + return m |
| 154 | +} |
| 155 | + |
| 156 | +func firstColumnIndex(idx map[string]int, names ...string) int { |
| 157 | + for _, n := range names { |
| 158 | + if i, ok := idx[strings.ToLower(n)]; ok { |
| 159 | + return i |
| 160 | + } |
| 161 | + } |
| 162 | + return -1 |
| 163 | +} |
| 164 | + |
| 165 | +func max(vals ...int) int { |
| 166 | + m := vals[0] |
| 167 | + for _, v := range vals[1:] { |
| 168 | + if v > m { |
| 169 | + m = v |
| 170 | + } |
| 171 | + } |
| 172 | + return m |
| 173 | +} |
| 174 | + |
| 175 | +func normalizeLocation(s string) string { |
| 176 | + s = strings.TrimSpace(s) |
| 177 | + if s == "" || strings.EqualFold(s, "unassigned") { |
| 178 | + return utils.RegionUnknown |
| 179 | + } |
| 180 | + return s |
| 181 | +} |
| 182 | + |
| 183 | +func cellString(v any) string { |
| 184 | + if v == nil { |
| 185 | + return "" |
| 186 | + } |
| 187 | + switch x := v.(type) { |
| 188 | + case string: |
| 189 | + return x |
| 190 | + default: |
| 191 | + return fmt.Sprint(x) |
| 192 | + } |
| 193 | +} |
| 194 | + |
| 195 | +func cellFloat(v any) (float64, bool) { |
| 196 | + switch x := v.(type) { |
| 197 | + case float64: |
| 198 | + return x, true |
| 199 | + case float32: |
| 200 | + return float64(x), true |
| 201 | + case int: |
| 202 | + return float64(x), true |
| 203 | + case int64: |
| 204 | + return float64(x), true |
| 205 | + case string: |
| 206 | + f, err := strconv.ParseFloat(strings.TrimSpace(x), 64) |
| 207 | + return f, err == nil |
| 208 | + default: |
| 209 | + return 0, false |
| 210 | + } |
| 211 | +} |
0 commit comments