-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathinfo.go
More file actions
219 lines (195 loc) · 8.12 KB
/
Copy pathinfo.go
File metadata and controls
219 lines (195 loc) · 8.12 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
// Copyright SAP SE
// SPDX-License-Identifier: Apache-2.0
package api
import (
"context"
"encoding/json"
"fmt"
"math"
"net/http"
"strconv"
"strings"
"time"
"github.com/cobaltcore-dev/cortex/internal/scheduling/reservations"
commitments "github.com/cobaltcore-dev/cortex/internal/scheduling/reservations/commitments"
"github.com/go-logr/logr"
"github.com/google/uuid"
liquid "github.com/sapcc/go-api-declarations/liquid"
)
// handles GET /commitments/v1/info requests from Limes:
// See: https://github.com/sapcc/go-api-declarations/blob/main/liquid/commitment.go
// See: https://pkg.go.dev/github.com/sapcc/go-api-declarations/liquid
func (api *HTTPAPI) HandleInfo(w http.ResponseWriter, r *http.Request) {
startTime := time.Now()
statusCode := http.StatusOK
// Extract or generate request ID for tracing
requestID := r.Header.Get("X-Request-ID")
if requestID == "" {
requestID = uuid.New().String()
}
// Set request ID in response header for client correlation
w.Header().Set("X-Request-ID", requestID)
ctx := reservations.WithGlobalRequestID(r.Context(), "committed-resource-"+requestID)
logger := commitments.LoggerFromContext(ctx).WithValues("component", "api", "endpoint", "/commitments/v1/info")
// Only accept GET method
if r.Method != http.MethodGet {
statusCode = http.StatusMethodNotAllowed
http.Error(w, "Method not allowed", statusCode)
api.recordInfoMetrics(statusCode, startTime)
return
}
logger.V(1).Info("processing info request")
// Build info response
info, err := api.buildServiceInfo(ctx, logger)
if err != nil {
logger.Info("service info not available yet", "error", err.Error())
statusCode = http.StatusServiceUnavailable
http.Error(w, "Service temporarily unavailable: "+err.Error(), statusCode)
api.recordInfoMetrics(statusCode, startTime)
return
}
// Return response
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(statusCode)
if err := json.NewEncoder(w).Encode(info); err != nil {
logger.Error(err, "failed to encode service info")
}
api.recordInfoMetrics(statusCode, startTime)
}
// recordInfoMetrics records Prometheus metrics for an info API request.
func (api *HTTPAPI) recordInfoMetrics(statusCode int, startTime time.Time) {
duration := time.Since(startTime).Seconds()
statusCodeStr := strconv.Itoa(statusCode)
api.infoMonitor.requestCounter.WithLabelValues(statusCodeStr).Inc()
api.infoMonitor.requestDuration.WithLabelValues(statusCodeStr).Observe(duration)
}
// resourceAttributes holds the custom attributes for a resource in the info API response.
// Ratio values are in GiB per vCPU.
type resourceAttributes struct {
RamCoreRatio *uint64 `json:"ramCoreRatio,omitempty"`
RamCoreRatioMin *uint64 `json:"ramCoreRatioMin,omitempty"`
RamCoreRatioMax *uint64 `json:"ramCoreRatioMax,omitempty"`
}
// mibToGiB converts a MiB pointer value to GiB, rounded to the nearest integer. Returns nil if v is nil.
func mibToGiB(v *uint64) *uint64 {
if v == nil {
return nil
}
gib := uint64(math.Round(float64(*v) / 1024))
return &gib
}
// buildServiceInfo constructs the ServiceInfo response with metadata for all flavor groups.
// For each flavor group, three resources are registered:
// - _ram: RAM resource (unit = multiples of smallest flavor RAM, HandlesCommitments=true only if fixed ratio)
// - _cores: CPU cores resource (unit = 1, HandlesCommitments=false)
// - _instances: Instance count resource (unit = 1, HandlesCommitments=false)
// All flavor groups report usage; only those with fixed RAM/core ratio accept commitments.
func (api *HTTPAPI) buildServiceInfo(ctx context.Context, logger logr.Logger) (liquid.ServiceInfo, error) {
// Get all flavor groups from Knowledge CRDs
knowledge := &reservations.FlavorGroupKnowledgeClient{Client: api.client}
flavorGroups, err := knowledge.GetAllFlavorGroups(ctx, nil)
if err != nil {
// Return -1 as version when knowledge is not ready
return liquid.ServiceInfo{
Version: -1,
Resources: make(map[liquid.ResourceName]liquid.ResourceInfo),
}, err
}
// Build resources map
resources := make(map[liquid.ResourceName]liquid.ResourceInfo)
for groupName, groupData := range flavorGroups {
resCfg := api.config.ResourceConfigForGroup(groupName)
flavorNames := make([]string, 0, len(groupData.Flavors))
for _, flavor := range groupData.Flavors {
flavorNames = append(flavorNames, flavor.Name)
}
flavorListStr := strings.Join(flavorNames, ", ")
// Build attributes JSON with ratio info (shared across all resource types).
// Ratios are stored in MiB/vCPU in the knowledge CRD; convert to GiB/vCPU here
// so the values match the GiB unit used by the RAM resource.
attrs := resourceAttributes{
RamCoreRatio: mibToGiB(groupData.RamCoreRatio),
RamCoreRatioMin: mibToGiB(groupData.RamCoreRatioMin),
RamCoreRatioMax: mibToGiB(groupData.RamCoreRatioMax),
}
attrsJSON, err := json.Marshal(attrs)
if err != nil {
logger.Error(err, "failed to marshal resource attributes", "flavorGroup", groupName)
attrsJSON = nil
}
// === 1. RAM Resource ===
ramResourceName := liquid.ResourceName(commitments.ResourceNameRAM(groupName))
// Fixed-ratio groups: unit = smallest flavor's RAM in MiB (e.g. "480 GiB" for hana);
// variable-ratio groups: unit = 1 GiB. RAMUnitMiB() encodes both cases.
ramUnit, err := liquid.UnitMebibytes.MultiplyBy(groupData.RAMUnitMiB())
if err != nil {
return liquid.ServiceInfo{}, fmt.Errorf("failed to create RAM unit for flavor group %q: %w", groupName, err)
}
var ramDisplayName string
if groupData.HasFixedRamCoreRatio() && groupData.SmallestFlavor.MemoryMB > 0 {
ramDisplayName = fmt.Sprintf("multiples of %d MiB (usable by: %s)", groupData.SmallestFlavor.MemoryMB, flavorListStr)
} else {
ramDisplayName = fmt.Sprintf("GiB of RAM (usable by: %s)", flavorListStr)
}
resources[ramResourceName] = liquid.ResourceInfo{
DisplayName: ramDisplayName,
Unit: ramUnit,
Topology: liquid.AZSeparatedTopology,
NeedsResourceDemand: false,
HasCapacity: resCfg.RAM.HasCapacity,
HasQuota: resCfg.RAM.HasQuota,
HandlesCommitments: resCfg.RAM.HandlesCommitments,
Attributes: attrsJSON,
}
// === 2. Cores Resource ===
coresResourceName := liquid.ResourceName(commitments.ResourceNameCores(groupName))
resources[coresResourceName] = liquid.ResourceInfo{
DisplayName: fmt.Sprintf(
"CPU cores (usable by: %s)",
flavorListStr,
),
Unit: liquid.UnitNone,
Topology: liquid.AZSeparatedTopology,
NeedsResourceDemand: false,
HasCapacity: resCfg.Cores.HasCapacity,
HasQuota: resCfg.Cores.HasQuota,
HandlesCommitments: resCfg.Cores.HandlesCommitments,
Attributes: attrsJSON,
}
// === 3. Instances Resource ===
instancesResourceName := liquid.ResourceName(commitments.ResourceNameInstances(groupName))
resources[instancesResourceName] = liquid.ResourceInfo{
DisplayName: fmt.Sprintf(
"instances (usable by: %s)",
flavorListStr,
),
Unit: liquid.UnitNone,
Topology: liquid.AZSeparatedTopology,
NeedsResourceDemand: false,
HasCapacity: resCfg.Instances.HasCapacity,
HasQuota: resCfg.Instances.HasQuota,
HandlesCommitments: resCfg.Instances.HandlesCommitments,
Attributes: attrsJSON,
}
logger.V(1).Info("registered flavor group resources",
"flavorGroup", groupName,
"ramResource", ramResourceName,
"coresResource", coresResourceName,
"instancesResource", instancesResourceName,
"ramCoreRatio", groupData.RamCoreRatio)
}
// Get last content changed from flavor group knowledge and treat it as version
var version int64 = -1
if knowledgeCRD, err := knowledge.Get(ctx); err == nil && knowledgeCRD != nil && !knowledgeCRD.Status.LastContentChange.IsZero() {
version = knowledgeCRD.Status.LastContentChange.Unix()
}
logger.Info("built service info",
"resourceCount", len(resources),
"version", version)
return liquid.ServiceInfo{
Version: version,
Resources: resources,
QuotaUpdateNeedsProjectMetadata: true,
CommitmentHandlingNeedsProjectMetadata: true,
}, nil
}