diff --git a/cmd/scheduler/metrics.go b/cmd/scheduler/metrics.go index 00e0764bed..642b7b9d12 100644 --- a/cmd/scheduler/metrics.go +++ b/cmd/scheduler/metrics.go @@ -404,6 +404,12 @@ func initMetrics(bindAddress string, metricsProvider schedulerMetricsProvider, l klog.Info("Initializing metrics for scheduler") reg := prometheus.NewRegistry() reg.MustRegister(versionmetrics.NewBuildInfoCollector()) + reg.MustRegister(schedulerpkg.BindDuration) + reg.MustRegister(schedulerpkg.BindTotal) + reg.MustRegister(schedulerpkg.FilterDuration) + reg.MustRegister(schedulerpkg.FilterTotal) + reg.MustRegister(schedulerpkg.ScoreDuration) + reg.MustRegister(schedulerpkg.ScoreTotal) NewClusterManager("vGPU", reg, metricsProvider, legacyMetrics) diff --git a/pkg/scheduler/metrics.go b/pkg/scheduler/metrics.go new file mode 100644 index 0000000000..8a7a2dbf1e --- /dev/null +++ b/pkg/scheduler/metrics.go @@ -0,0 +1,93 @@ +/* +Copyright 2024 The HAMi Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package scheduler + +import ( + "github.com/prometheus/client_golang/prometheus" +) + +var ( + BindDuration = prometheus.NewHistogramVec( + prometheus.HistogramOpts{ + Namespace: "hami", + Subsystem: "scheduler", + Name: "bind_duration_seconds", + Help: "Time spent in each phase of the Bind workflow.", + Buckets: []float64{0.001, 0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 10}, + }, + []string{"phase", "result"}, + ) + + BindTotal = prometheus.NewCounterVec( + prometheus.CounterOpts{ + Namespace: "hami", + Subsystem: "scheduler", + Name: "bind_total", + Help: "Total number of Bind requests processed.", + }, + []string{"result"}, + ) + + FilterDuration = prometheus.NewHistogramVec( + prometheus.HistogramOpts{ + Namespace: "hami", + Subsystem: "scheduler", + Name: "filter_duration_seconds", + Help: "Time spent processing Filter requests.", + Buckets: []float64{0.001, 0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 10}, + }, + []string{"result"}, + ) + + FilterTotal = prometheus.NewCounterVec( + prometheus.CounterOpts{ + Namespace: "hami", + Subsystem: "scheduler", + Name: "filter_total", + Help: "Total number of Filter requests processed.", + }, + []string{"result"}, + ) + + ScoreDuration = prometheus.NewHistogramVec( + prometheus.HistogramOpts{ + Namespace: "hami", + Subsystem: "scheduler", + Name: "score_duration_seconds", + Help: "Time spent calculating scores for nodes.", + Buckets: []float64{0.001, 0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 10}, + }, + []string{"result"}, + ) + + ScoreTotal = prometheus.NewCounterVec( + prometheus.CounterOpts{ + Namespace: "hami", + Subsystem: "scheduler", + Name: "score_total", + Help: "Total number of Score calculations processed.", + }, + []string{"result"}, + ) +) + +func ResultLabel(err error) string { + if err != nil { + return "error" + } + return "success" +} diff --git a/pkg/scheduler/metrics_test.go b/pkg/scheduler/metrics_test.go new file mode 100644 index 0000000000..5b16f38c03 --- /dev/null +++ b/pkg/scheduler/metrics_test.go @@ -0,0 +1,82 @@ +/* +Copyright 2024 The HAMi Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package scheduler + +import ( + "errors" + "testing" + + "github.com/prometheus/client_golang/prometheus" + "github.com/prometheus/client_golang/prometheus/testutil" +) + +func TestMetricsRegistrationAndObservation(t *testing.T) { + reg := prometheus.NewPedanticRegistry() + if err := reg.Register(BindDuration); err != nil { + t.Fatalf("Failed to register BindDuration: %v", err) + } + if err := reg.Register(BindTotal); err != nil { + t.Fatalf("Failed to register BindTotal: %v", err) + } + if err := reg.Register(FilterDuration); err != nil { + t.Fatalf("Failed to register FilterDuration: %v", err) + } + if err := reg.Register(FilterTotal); err != nil { + t.Fatalf("Failed to register FilterTotal: %v", err) + } + if err := reg.Register(ScoreDuration); err != nil { + t.Fatalf("Failed to register ScoreDuration: %v", err) + } + if err := reg.Register(ScoreTotal); err != nil { + t.Fatalf("Failed to register ScoreTotal: %v", err) + } + + BindDuration.WithLabelValues("pod_lookup", "success").Observe(0.005) + BindTotal.WithLabelValues("success").Inc() + FilterDuration.WithLabelValues("success").Observe(0.01) + FilterTotal.WithLabelValues("success").Inc() + ScoreDuration.WithLabelValues("success").Observe(0.02) + ScoreTotal.WithLabelValues("success").Inc() + + count, err := testutil.GatherAndCount(reg) + if err != nil { + t.Fatalf("Gather failed: %v", err) + } + if count < 6 { + t.Errorf("Expected at least 6 metric families gathered, got %d", count) + } +} + +func TestBindDurationLabelsAreBounded(t *testing.T) { + validPhases := []string{"total", "pod_lookup", "node_lookup", "node_lock", "patch_annotations", "apiserver_bind"} + validResults := []string{"success", "error"} + + for _, phase := range validPhases { + for _, result := range validResults { + BindDuration.WithLabelValues(phase, result).Observe(0.001) + } + } +} + +func TestResultLabel(t *testing.T) { + if got := ResultLabel(nil); got != "success" { + t.Errorf("ResultLabel(nil) = %q, want %q", got, "success") + } + if got := ResultLabel(errors.New("lookup failed")); got != "error" { + t.Errorf("ResultLabel(err) = %q, want %q", got, "error") + } +} diff --git a/pkg/scheduler/routes/route.go b/pkg/scheduler/routes/route.go index 8c5d29410e..4bb6dfbc5d 100644 --- a/pkg/scheduler/routes/route.go +++ b/pkg/scheduler/routes/route.go @@ -22,6 +22,7 @@ import ( "fmt" "io" "net/http" + "time" "github.com/julienschmidt/httprouter" "k8s.io/klog/v2" @@ -43,13 +44,20 @@ func checkBody(w http.ResponseWriter, r *http.Request) bool { func PredicateRoute(s *scheduler.Scheduler) httprouter.Handle { klog.Infoln("Initializing Predicate Route") return func(w http.ResponseWriter, r *http.Request, _ httprouter.Params) { + filterStart := time.Now() + filterResult := "success" + defer func() { + scheduler.FilterDuration.WithLabelValues(filterResult).Observe(time.Since(filterStart).Seconds()) + scheduler.FilterTotal.WithLabelValues(filterResult).Inc() + }() + klog.V(5).Infoln("Entering Predicate Route handler") if !checkBody(w, r) { + filterResult = "error" return } var buf bytes.Buffer - // Limit the body size to prevent deep nesting/resource exhaustion attacks limitedReader := io.LimitReader(r.Body, maxRequestSize) body := io.TeeReader(limitedReader, &buf) @@ -57,6 +65,7 @@ func PredicateRoute(s *scheduler.Scheduler) httprouter.Handle { var extenderFilterResult *extenderv1.ExtenderFilterResult if err := json.NewDecoder(body).Decode(&extenderArgs); err != nil { + filterResult = "error" klog.ErrorS(err, "Failed to decode extender arguments") extenderFilterResult = &extenderv1.ExtenderFilterResult{ Error: err.Error(), @@ -64,8 +73,8 @@ func PredicateRoute(s *scheduler.Scheduler) httprouter.Handle { } else { synced := s.WaitForCacheSync(r.Context()) if !synced { - // Poll may return false when context is cancelled err := fmt.Errorf("context cancelled") + filterResult = "error" klog.ErrorS(err, "Cache not synced, cannot proceed with filtering") extenderFilterResult = &extenderv1.ExtenderFilterResult{ Error: err.Error(), @@ -73,6 +82,7 @@ func PredicateRoute(s *scheduler.Scheduler) httprouter.Handle { } else { extenderFilterResult, err = s.Filter(extenderArgs) if err != nil { + filterResult = "error" klog.ErrorS(err, "Filter error for pod", "pod", extenderArgs.Pod.Name) extenderFilterResult = &extenderv1.ExtenderFilterResult{ Error: err.Error(), diff --git a/pkg/scheduler/routes/route_test.go b/pkg/scheduler/routes/route_test.go index 5cf3b45ec7..70c2b3c566 100644 --- a/pkg/scheduler/routes/route_test.go +++ b/pkg/scheduler/routes/route_test.go @@ -24,6 +24,7 @@ import ( "strings" "testing" + "github.com/prometheus/client_golang/prometheus/testutil" corev1 "k8s.io/api/core/v1" extenderv1 "k8s.io/kube-scheduler/extender/v1" @@ -258,3 +259,19 @@ func TestBind_DecodeError(t *testing.T) { t.Error("expected a decode error to be reported in the bind result") } } + +func TestPredicateRoute_MetricsObserved(t *testing.T) { + initialCount := testutil.ToFloat64(scheduler.FilterTotal.WithLabelValues("error")) + + req := httptest.NewRequest("POST", "/predicate", strings.NewReader("{invalid-json")) + w := httptest.NewRecorder() + + s := &scheduler.Scheduler{} + handler := PredicateRoute(s) + handler(w, req, nil) + + afterCount := testutil.ToFloat64(scheduler.FilterTotal.WithLabelValues("error")) + if afterCount <= initialCount { + t.Errorf("Expected FilterTotal with result=error to increment, before: %v, after: %v", initialCount, afterCount) + } +} diff --git a/pkg/scheduler/scheduler.go b/pkg/scheduler/scheduler.go index 3216b55843..9924540c85 100644 --- a/pkg/scheduler/scheduler.go +++ b/pkg/scheduler/scheduler.go @@ -946,6 +946,13 @@ func (s *Scheduler) acquireNodeLocks(node *corev1.Node, pod *corev1.Pod) error { } func (s *Scheduler) Bind(args extenderv1.ExtenderBindingArgs) (*extenderv1.ExtenderBindingResult, error) { + bindStart := time.Now() + bindResult := "success" + defer func() { + BindDuration.WithLabelValues("total", bindResult).Observe(time.Since(bindStart).Seconds()) + BindTotal.WithLabelValues(bindResult).Inc() + }() + klog.InfoS("Attempting to bind pod to node", "pod", args.PodName, "namespace", args.PodNamespace, "node", args.Node) var res *extenderv1.ExtenderBindingResult @@ -954,8 +961,11 @@ func (s *Scheduler) Bind(args extenderv1.ExtenderBindingArgs) (*extenderv1.Exten Target: corev1.ObjectReference{Kind: "Node", Name: args.Node}, } + phaseStart := time.Now() current, err := s.podLister.Pods(args.PodNamespace).Get(args.PodName) + BindDuration.WithLabelValues("pod_lookup", ResultLabel(err)).Observe(time.Since(phaseStart).Seconds()) if err != nil { + bindResult = "error" klog.ErrorS(err, "Failed to get pod from cache", "pod", args.PodName, "namespace", args.PodNamespace) s.cleanupStalePodAllocation(&corev1.Pod{ ObjectMeta: metav1.ObjectMeta{ @@ -969,8 +979,11 @@ func (s *Scheduler) Bind(args extenderv1.ExtenderBindingArgs) (*extenderv1.Exten klog.InfoS("Trying to get the target node for pod", "pod", args.PodName, "namespace", args.PodNamespace, "node", args.Node) + phaseStart = time.Now() node, err := s.nodeLister.Get(args.Node) + BindDuration.WithLabelValues("node_lookup", ResultLabel(err)).Observe(time.Since(phaseStart).Seconds()) if err != nil { + bindResult = "error" klog.ErrorS(err, "Failed to get node from cache", "node", args.Node) s.recordScheduleBindingResultEvent(current, EventReasonBindingFailed, []string{}, fmt.Errorf("failed to get node %s", args.Node)) s.cleanupStalePodAllocation(current) @@ -994,20 +1007,32 @@ func (s *Scheduler) Bind(args extenderv1.ExtenderBindingArgs) (*extenderv1.Exten return &extenderv1.ExtenderBindingResult{Error: errStr}, nil } + phaseStart = time.Now() if err = s.acquireNodeLocks(node, current); err != nil { + bindResult = "error" + BindDuration.WithLabelValues("node_lock", "error").Observe(time.Since(phaseStart).Seconds()) klog.ErrorS(err, "Failed to lock node", "node", args.Node, "pod", klog.KObj(current)) return fail(err) } + BindDuration.WithLabelValues("node_lock", "success").Observe(time.Since(phaseStart).Seconds()) + phaseStart = time.Now() if err = util.PatchPodAnnotations(current, tmppatch); err != nil { + bindResult = "error" + BindDuration.WithLabelValues("patch_annotations", "error").Observe(time.Since(phaseStart).Seconds()) klog.ErrorS(err, "Failed to patch pod annotations", "pod", klog.KObj(current)) return fail(err) } + BindDuration.WithLabelValues("patch_annotations", "success").Observe(time.Since(phaseStart).Seconds()) + phaseStart = time.Now() if err = s.kubeClient.CoreV1().Pods(args.PodNamespace).Bind(context.Background(), binding, metav1.CreateOptions{}); err != nil { + bindResult = "error" + BindDuration.WithLabelValues("apiserver_bind", "error").Observe(time.Since(phaseStart).Seconds()) klog.ErrorS(err, "Failed to bind pod", "pod", args.PodName, "namespace", args.PodNamespace, "node", args.Node) return fail(err) } + BindDuration.WithLabelValues("apiserver_bind", "success").Observe(time.Since(phaseStart).Seconds()) s.recordScheduleBindingResultEvent(current, EventReasonBindingSucceed, []string{args.Node}, nil) klog.InfoS("Successfully bound pod to node", "pod", args.PodName, "namespace", args.PodNamespace, "node", args.Node) diff --git a/pkg/scheduler/score.go b/pkg/scheduler/score.go index 4e0edbbbb2..b41eef688c 100644 --- a/pkg/scheduler/score.go +++ b/pkg/scheduler/score.go @@ -20,6 +20,7 @@ import ( "sort" "strings" "sync" + "time" corev1 "k8s.io/api/core/v1" utilerrors "k8s.io/apimachinery/pkg/util/errors" @@ -340,6 +341,13 @@ func (s *Scheduler) calcScore(nodes *map[string]*NodeUsage, resourceReqs device. } func (s *Scheduler) calcScoreWithOptions(nodes *map[string]*NodeUsage, resourceReqs device.PodDeviceRequests, task *corev1.Pod, failedNodes map[string]string, recordEvents bool, detailedFailureReason bool) (*policy.NodeScoreList, error) { + scoreStart := time.Now() + scoreResult := "success" + defer func() { + ScoreDuration.WithLabelValues(scoreResult).Observe(time.Since(scoreStart).Seconds()) + ScoreTotal.WithLabelValues(scoreResult).Inc() + }() + userNodePolicy := resolveNodeSchedulerPolicy(task) res := policy.NodeScoreList{ Policy: userNodePolicy,