-
Notifications
You must be signed in to change notification settings - Fork 6
Add committed resource metrics and alerts #611
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from 6 commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -21,12 +21,9 @@ import ( | |
| "k8s.io/apimachinery/pkg/api/meta" | ||
| metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" | ||
| "k8s.io/apimachinery/pkg/types" | ||
| ctrl "sigs.k8s.io/controller-runtime" | ||
| "sigs.k8s.io/controller-runtime/pkg/client" | ||
| ) | ||
|
|
||
| var apiLog = ctrl.Log.WithName("commitment-reservation-api") | ||
|
|
||
| // sortedKeys returns map keys sorted alphabetically for deterministic iteration. | ||
| func sortedKeys[K ~string, V any](m map[K]V) []K { | ||
| keys := make([]K, 0, len(m)) | ||
|
|
@@ -46,9 +43,17 @@ func sortedKeys[K ~string, V any](m map[K]V) []K { | |
| // This endpoint handles commitment changes by creating/updating/deleting Reservation CRDs based on the commitment lifecycle. | ||
| // A request may contain multiple commitment changes which are processed in a single transaction. If any change fails, all changes are rolled back. | ||
| func (api *HTTPAPI) HandleChangeCommitments(w http.ResponseWriter, r *http.Request) { | ||
| startTime := time.Now() | ||
| // Initialize | ||
| resp := liquid.CommitmentChangeResponse{} | ||
| req := liquid.CommitmentChangeRequest{} | ||
| statusCode := http.StatusOK | ||
|
|
||
| // Check if API is enabled | ||
| if !api.config.EnableChangeCommitmentsAPI { | ||
| http.Error(w, "change-commitments API is disabled", http.StatusServiceUnavailable) | ||
| statusCode = http.StatusServiceUnavailable | ||
| http.Error(w, "change-commitments API is disabled", statusCode) | ||
| api.recordMetrics(req, resp, statusCode, startTime) | ||
| return | ||
| } | ||
|
|
||
|
|
@@ -61,31 +66,32 @@ func (api *HTTPAPI) HandleChangeCommitments(w http.ResponseWriter, r *http.Reque | |
| if requestID == "" { | ||
| requestID = uuid.New().String() | ||
| } | ||
| ctx := reservations.WithGlobalRequestID(context.Background(), requestID) | ||
| logger := APILoggerFromContext(ctx).WithValues("endpoint", "/v1/change-commitments") | ||
| ctx := reservations.WithGlobalRequestID(context.Background(), "committed-resource-"+requestID) | ||
| logger := LoggerFromContext(ctx).WithValues("component", "api", "endpoint", "/v1/change-commitments") | ||
|
|
||
| // Only accept POST method | ||
| if r.Method != http.MethodPost { | ||
| http.Error(w, "Method not allowed", http.StatusMethodNotAllowed) | ||
| statusCode = http.StatusMethodNotAllowed | ||
| http.Error(w, "Method not allowed", statusCode) | ||
| api.recordMetrics(req, resp, statusCode, startTime) | ||
| return | ||
| } | ||
|
|
||
| // Parse request body | ||
| var req liquid.CommitmentChangeRequest | ||
| if err := json.NewDecoder(r.Body).Decode(&req); err != nil { | ||
| logger.Error(err, "invalid request body") | ||
| http.Error(w, "Invalid request body: "+err.Error(), http.StatusBadRequest) | ||
| statusCode = http.StatusBadRequest | ||
| http.Error(w, "Invalid request body: "+err.Error(), statusCode) | ||
| api.recordMetrics(req, resp, statusCode, startTime) | ||
| return | ||
| } | ||
|
|
||
| logger.Info("received change commitments request", "affectedProjects", len(req.ByProject), "dryRun", req.DryRun, "availabilityZone", req.AZ) | ||
|
|
||
| // Initialize response | ||
| resp := liquid.CommitmentChangeResponse{} | ||
|
|
||
| // Check for dry run -> early reject, not supported yet | ||
| if req.DryRun { | ||
| resp.RejectionReason = "Dry run not supported yet" | ||
| api.recordMetrics(req, resp, statusCode, startTime) | ||
| logger.Info("rejecting dry run request") | ||
| w.Header().Set("Content-Type", "application/json") | ||
| w.WriteHeader(http.StatusOK) | ||
|
|
@@ -97,14 +103,26 @@ func (api *HTTPAPI) HandleChangeCommitments(w http.ResponseWriter, r *http.Reque | |
|
|
||
| // Process commitment changes | ||
| // For now, we'll implement a simplified path that checks capacity for immediate start CRs | ||
|
|
||
| if err := api.processCommitmentChanges(ctx, w, logger, req, &resp); err != nil { | ||
| // Error already written to response by processCommitmentChanges | ||
| // Determine status code from error context (409 or 503) | ||
| if strings.Contains(err.Error(), "version mismatch") { | ||
| statusCode = http.StatusConflict | ||
| } else if strings.Contains(err.Error(), "caches not ready") { | ||
| statusCode = http.StatusServiceUnavailable | ||
| } | ||
|
Comment on lines
+109
to
+114
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Fragile status code derivation via error string matching. Determining HTTP status codes by inspecting error message substrings is brittle—if the error messages change, this logic silently breaks. Consider using typed errors or sentinel errors to convey the status code. 💡 Suggested approach using sentinel errors+var (
+ errVersionMismatch = errors.New("version mismatch")
+ errCachesNotReady = errors.New("caches not ready")
+)
// In processCommitmentChanges, return the sentinel error:
-return errors.New("version mismatch")
+return errVersionMismatch
// In HandleChangeCommitments:
-if strings.Contains(err.Error(), "version mismatch") {
- statusCode = http.StatusConflict
-} else if strings.Contains(err.Error(), "caches not ready") {
- statusCode = http.StatusServiceUnavailable
-}
+if errors.Is(err, errVersionMismatch) {
+ statusCode = http.StatusConflict
+} else if errors.Is(err, errCachesNotReady) {
+ statusCode = http.StatusServiceUnavailable
+}🤖 Prompt for AI Agents |
||
| // Record metrics for error cases | ||
| api.recordMetrics(req, resp, statusCode, startTime) | ||
| return | ||
| } | ||
|
|
||
| // Record metrics | ||
| api.recordMetrics(req, resp, statusCode, startTime) | ||
|
|
||
| // Return response | ||
| w.Header().Set("Content-Type", "application/json") | ||
| w.WriteHeader(http.StatusOK) | ||
| w.WriteHeader(statusCode) | ||
| if err := json.NewEncoder(w).Encode(resp); err != nil { | ||
| return | ||
| } | ||
|
|
@@ -254,6 +272,7 @@ ProcessLoop: | |
| } | ||
| if len(failedReservations) == 0 { | ||
| resp.RejectionReason += "timeout reached while processing commitment changes" | ||
| api.monitor.timeouts.Inc() | ||
| } | ||
| requireRollback = true | ||
| } | ||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,44 @@ | ||
| // Copyright SAP SE | ||
| // SPDX-License-Identifier: Apache-2.0 | ||
|
|
||
| package commitments | ||
|
|
||
| import ( | ||
| "strconv" | ||
| "time" | ||
|
|
||
| "github.com/sapcc/go-api-declarations/liquid" | ||
| ) | ||
|
|
||
| // recordMetrics records Prometheus metrics for a change commitments request. | ||
| func (api *HTTPAPI) recordMetrics(req liquid.CommitmentChangeRequest, resp liquid.CommitmentChangeResponse, statusCode int, startTime time.Time) { | ||
| duration := time.Since(startTime).Seconds() | ||
| statusCodeStr := strconv.Itoa(statusCode) | ||
|
|
||
| // Record request counter and duration | ||
| api.monitor.requestCounter.WithLabelValues(statusCodeStr).Inc() | ||
| api.monitor.requestDuration.WithLabelValues(statusCodeStr).Observe(duration) | ||
|
|
||
| // Count total commitment changes in the request | ||
| commitmentCount := countCommitments(req) | ||
|
|
||
| // Determine result based on response | ||
| result := "success" | ||
| if resp.RejectionReason != "" { | ||
| result = "rejected" | ||
| } | ||
|
|
||
| // Record commitment changes counter | ||
| api.monitor.commitmentChanges.WithLabelValues(result).Add(float64(commitmentCount)) | ||
| } | ||
|
|
||
| // countCommitments counts the total number of commitments in a request. | ||
| func countCommitments(req liquid.CommitmentChangeRequest) int { | ||
| count := 0 | ||
| for _, projectChanges := range req.ByProject { | ||
| for _, resourceChanges := range projectChanges.ByResource { | ||
| count += len(resourceChanges.Commitments) | ||
| } | ||
| } | ||
| return count | ||
| } |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,54 @@ | ||
| // Copyright SAP SE | ||
| // SPDX-License-Identifier: Apache-2.0 | ||
|
|
||
| package commitments | ||
|
|
||
| import ( | ||
| "github.com/prometheus/client_golang/prometheus" | ||
| ) | ||
|
|
||
| // ChangeCommitmentsAPIMonitor provides metrics for the CR change API. | ||
| type ChangeCommitmentsAPIMonitor struct { | ||
| requestCounter *prometheus.CounterVec | ||
| requestDuration *prometheus.HistogramVec | ||
| commitmentChanges *prometheus.CounterVec | ||
| timeouts prometheus.Counter | ||
| } | ||
|
|
||
| // NewChangeCommitmentsAPIMonitor creates a new monitor with Prometheus metrics. | ||
| func NewChangeCommitmentsAPIMonitor() ChangeCommitmentsAPIMonitor { | ||
| return ChangeCommitmentsAPIMonitor{ | ||
| requestCounter: prometheus.NewCounterVec(prometheus.CounterOpts{ | ||
| Name: "cortex_committed_resource_change_api_requests_total", | ||
| Help: "Total number of committed resource change API requests by HTTP status code", | ||
| }, []string{"status_code"}), | ||
| requestDuration: prometheus.NewHistogramVec(prometheus.HistogramOpts{ | ||
| Name: "cortex_committed_resource_change_api_request_duration_seconds", | ||
| Help: "Duration of committed resource change API requests in seconds by HTTP status code", | ||
| }, []string{"status_code"}), | ||
| commitmentChanges: prometheus.NewCounterVec(prometheus.CounterOpts{ | ||
| Name: "cortex_committed_resource_change_api_commitment_changes_total", | ||
| Help: "Total number of commitment changes processed by result", | ||
| }, []string{"result"}), | ||
| timeouts: prometheus.NewCounter(prometheus.CounterOpts{ | ||
| Name: "cortex_committed_resource_change_api_timeouts_total", | ||
| Help: "Total number of commitment change requests that timed out while waiting for reservations to become ready", | ||
| }), | ||
| } | ||
| } | ||
|
|
||
| // Describe implements prometheus.Collector. | ||
| func (m *ChangeCommitmentsAPIMonitor) Describe(ch chan<- *prometheus.Desc) { | ||
| m.requestCounter.Describe(ch) | ||
| m.requestDuration.Describe(ch) | ||
| m.commitmentChanges.Describe(ch) | ||
| m.timeouts.Describe(ch) | ||
| } | ||
|
|
||
| // Collect implements prometheus.Collector. | ||
| func (m *ChangeCommitmentsAPIMonitor) Collect(ch chan<- prometheus.Metric) { | ||
| m.requestCounter.Collect(ch) | ||
| m.requestDuration.Collect(ch) | ||
| m.commitmentChanges.Collect(ch) | ||
| m.timeouts.Collect(ch) | ||
| } |
Uh oh!
There was an error while loading. Please reload this page.