generated from kubernetes/kubernetes-template-project
-
Notifications
You must be signed in to change notification settings - Fork 105
Each pod has independent loops to refresh metrics #460
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
Merged
Merged
Changes from 4 commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
cb38e61
Each pod has independent loops to refresh metrics
liu-cong 0241829
Major refactoring, move metrics logic from datastore to backend/metri…
liu-cong 98b9371
Address comments
liu-cong 27d60cb
Fix test and fmt
liu-cong 1ef6a91
The podMetrics updates the targetPort by reading the pool from the da…
liu-cong File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file was deleted.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,90 @@ | ||
/* | ||
Copyright 2025 The Kubernetes 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 metrics | ||
|
||
import ( | ||
"context" | ||
"fmt" | ||
"sync" | ||
|
||
corev1 "k8s.io/api/core/v1" | ||
"k8s.io/apimachinery/pkg/types" | ||
"sigs.k8s.io/controller-runtime/pkg/log" | ||
"sigs.k8s.io/gateway-api-inference-extension/api/v1alpha2" | ||
logutil "sigs.k8s.io/gateway-api-inference-extension/pkg/epp/util/logging" | ||
) | ||
|
||
// FakePodMetrics is an implementation of PodMetrics that doesn't run the async refresh loop. | ||
type FakePodMetrics struct { | ||
Pod *Pod | ||
Metrics *Metrics | ||
} | ||
|
||
func (fpm *FakePodMetrics) GetPod() *Pod { | ||
return fpm.Pod | ||
} | ||
func (fpm *FakePodMetrics) GetMetrics() *Metrics { | ||
return fpm.Metrics | ||
} | ||
func (fpm *FakePodMetrics) UpdatePod(pod *corev1.Pod) { | ||
fpm.Pod = toInternalPod(pod) | ||
} | ||
func (fpm *FakePodMetrics) StopRefreshLoop() {} // noop | ||
|
||
type FakePodMetricsClient struct { | ||
errMu sync.RWMutex | ||
Err map[types.NamespacedName]error | ||
resMu sync.RWMutex | ||
Res map[types.NamespacedName]*Metrics | ||
} | ||
|
||
func (f *FakePodMetricsClient) FetchMetrics(ctx context.Context, pod *Pod, existing *Metrics, port int32) (*Metrics, error) { | ||
f.errMu.RLock() | ||
err, ok := f.Err[pod.NamespacedName] | ||
f.errMu.RUnlock() | ||
if ok { | ||
return nil, err | ||
} | ||
f.resMu.RLock() | ||
res, ok := f.Res[pod.NamespacedName] | ||
f.resMu.RUnlock() | ||
if !ok { | ||
return nil, fmt.Errorf("no pod found: %v", pod.NamespacedName) | ||
} | ||
log.FromContext(ctx).V(logutil.VERBOSE).Info("Fetching metrics for pod", "existing", existing, "new", res) | ||
return res.Clone(), nil | ||
} | ||
|
||
func (f *FakePodMetricsClient) SetRes(new map[types.NamespacedName]*Metrics) { | ||
f.resMu.Lock() | ||
defer f.resMu.Unlock() | ||
f.Res = new | ||
} | ||
|
||
func (f *FakePodMetricsClient) SetErr(new map[types.NamespacedName]error) { | ||
f.errMu.Lock() | ||
defer f.errMu.Unlock() | ||
f.Err = new | ||
} | ||
|
||
type FakeDataStore struct { | ||
Res map[string]*v1alpha2.InferenceModel | ||
} | ||
|
||
func (fds *FakeDataStore) FetchModelData(modelName string) (returnModel *v1alpha2.InferenceModel) { | ||
return fds.Res[modelName] | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,109 @@ | ||
/* | ||
Copyright 2025 The Kubernetes 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 metrics | ||
|
||
import ( | ||
"context" | ||
"time" | ||
|
||
"github.com/go-logr/logr" | ||
"sigs.k8s.io/controller-runtime/pkg/log" | ||
"sigs.k8s.io/gateway-api-inference-extension/api/v1alpha2" | ||
"sigs.k8s.io/gateway-api-inference-extension/pkg/epp/metrics" | ||
logutil "sigs.k8s.io/gateway-api-inference-extension/pkg/epp/util/logging" | ||
) | ||
|
||
const ( | ||
// Note currently the EPP treats stale metrics same as fresh. | ||
// TODO: https://github.com/kubernetes-sigs/gateway-api-inference-extension/issues/336 | ||
metricsValidityPeriod = 5 * time.Second | ||
) | ||
|
||
type Datastore interface { | ||
PoolGet() (*v1alpha2.InferencePool, error) | ||
// PodMetrics operations | ||
// PodGetAll returns all pods and metrics, including fresh and stale. | ||
PodGetAll() []PodMetrics | ||
PodList(func(PodMetrics) bool) []PodMetrics | ||
} | ||
|
||
func LogMetricsPeriodically(ctx context.Context, datastore Datastore, refreshPrometheusMetricsInterval time.Duration) { | ||
logger := log.FromContext(ctx) | ||
|
||
// Periodically flush prometheus metrics for inference pool | ||
go func() { | ||
for { | ||
select { | ||
case <-ctx.Done(): | ||
logger.V(logutil.DEFAULT).Info("Shutting down prometheus metrics thread") | ||
return | ||
default: | ||
time.Sleep(refreshPrometheusMetricsInterval) | ||
flushPrometheusMetricsOnce(logger, datastore) | ||
} | ||
} | ||
}() | ||
|
||
// Periodically print out the pods and metrics for DEBUGGING. | ||
if logger := logger.V(logutil.DEBUG); logger.Enabled() { | ||
go func() { | ||
for { | ||
select { | ||
case <-ctx.Done(): | ||
logger.V(logutil.DEFAULT).Info("Shutting down metrics logger thread") | ||
return | ||
default: | ||
time.Sleep(5 * time.Second) | ||
podsWithFreshMetrics := datastore.PodList(func(pm PodMetrics) bool { | ||
return time.Since(pm.GetMetrics().UpdateTime) <= metricsValidityPeriod | ||
}) | ||
podsWithStaleMetrics := datastore.PodList(func(pm PodMetrics) bool { | ||
return time.Since(pm.GetMetrics().UpdateTime) > metricsValidityPeriod | ||
}) | ||
logger.Info("Current Pods and metrics gathered", "fresh metrics", podsWithFreshMetrics, "stale metrics", podsWithStaleMetrics) | ||
} | ||
} | ||
}() | ||
} | ||
} | ||
|
||
func flushPrometheusMetricsOnce(logger logr.Logger, datastore Datastore) { | ||
pool, err := datastore.PoolGet() | ||
if err != nil { | ||
// No inference pool or not initialize. | ||
logger.V(logutil.VERBOSE).Info("pool is not initialized, skipping flushing metrics") | ||
return | ||
} | ||
|
||
var kvCacheTotal float64 | ||
var queueTotal int | ||
|
||
podMetrics := datastore.PodGetAll() | ||
logger.V(logutil.VERBOSE).Info("Flushing Prometheus Metrics", "ReadyPods", len(podMetrics)) | ||
if len(podMetrics) == 0 { | ||
return | ||
} | ||
|
||
for _, pod := range podMetrics { | ||
kvCacheTotal += pod.GetMetrics().KVCacheUsagePercent | ||
queueTotal += pod.GetMetrics().WaitingQueueSize | ||
} | ||
|
||
podTotalCount := len(podMetrics) | ||
metrics.RecordInferencePoolAvgKVCache(pool.Name, kvCacheTotal/float64(podTotalCount)) | ||
metrics.RecordInferencePoolAvgQueueSize(pool.Name, float64(queueTotal/podTotalCount)) | ||
} |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.