generated from kubernetes/kubernetes-template-project
-
Notifications
You must be signed in to change notification settings - Fork 44
/
Copy pathdatastore.go
383 lines (334 loc) · 10.8 KB
/
datastore.go
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
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
/*
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 datastore
import (
"context"
"errors"
"fmt"
"math/rand"
"sync"
"github.com/go-logr/logr"
corev1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/labels"
"k8s.io/apimachinery/pkg/types"
"sigs.k8s.io/controller-runtime/pkg/client"
"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"
)
const (
ModelNameIndexKey = "spec.modelName"
)
var (
errPoolNotSynced = errors.New("InferencePool is not initialized in data store")
)
// The datastore is a local cache of relevant data for the given InferencePool (currently all pulled from k8s-api)
type Datastore interface {
// InferencePool operations
PoolSet(pool *v1alpha2.InferencePool)
PoolGet() (*v1alpha2.InferencePool, error)
PoolHasSynced() bool
PoolLabelsMatch(podLabels map[string]string) bool
// InferenceModel operations
ModelSetIfOlder(infModel *v1alpha2.InferenceModel) bool
ModelGet(modelName string) *v1alpha2.InferenceModel
ModelDelete(namespacedName types.NamespacedName) *v1alpha2.InferenceModel
ModelResync(ctx context.Context, ctrlClient client.Client, modelName string) (bool, error)
ModelGetAll() []*v1alpha2.InferenceModel
// PodMetrics operations
PodUpdateOrAddIfNotExist(pod *corev1.Pod) bool
PodUpdateMetricsIfExist(namespacedName types.NamespacedName, m *Metrics) bool
PodGet(namespacedName types.NamespacedName) *PodMetrics
PodDelete(namespacedName types.NamespacedName)
PodResyncAll(ctx context.Context, ctrlClient client.Client)
PodGetAll() []*PodMetrics
PodDeleteAll() // This is only for testing.
PodRange(f func(key, value any) bool)
// Clears the store state, happens when the pool gets deleted.
Clear()
}
func NewDatastore() Datastore {
store := &datastore{
poolAndModelsMu: sync.RWMutex{},
models: make(map[string]*v1alpha2.InferenceModel),
pods: &sync.Map{},
}
return store
}
// Used for test only
func NewFakeDatastore(pods []*PodMetrics, models []*v1alpha2.InferenceModel, pool *v1alpha2.InferencePool) Datastore {
store := NewDatastore()
for _, pod := range pods {
// Making a copy since in tests we may use the same global PodMetric across tests.
p := *pod
store.(*datastore).pods.Store(pod.NamespacedName, &p)
}
for _, m := range models {
store.ModelSetIfOlder(m)
}
if pool != nil {
store.(*datastore).pool = pool
}
return store
}
type datastore struct {
// poolAndModelsMu is used to synchronize access to pool and the models map.
poolAndModelsMu sync.RWMutex
pool *v1alpha2.InferencePool
// key: InferenceModel.Spec.ModelName, value: *InferenceModel
models map[string]*v1alpha2.InferenceModel
// key: types.NamespacedName, value: *PodMetrics
pods *sync.Map
}
func (ds *datastore) Clear() {
ds.poolAndModelsMu.Lock()
defer ds.poolAndModelsMu.Unlock()
ds.pool = nil
ds.models = make(map[string]*v1alpha2.InferenceModel)
ds.pods.Clear()
}
// /// InferencePool APIs ///
func (ds *datastore) PoolSet(pool *v1alpha2.InferencePool) {
ds.poolAndModelsMu.Lock()
defer ds.poolAndModelsMu.Unlock()
ds.pool = pool
}
func (ds *datastore) PoolGet() (*v1alpha2.InferencePool, error) {
ds.poolAndModelsMu.RLock()
defer ds.poolAndModelsMu.RUnlock()
if !ds.PoolHasSynced() {
return nil, errPoolNotSynced
}
return ds.pool, nil
}
func (ds *datastore) PoolHasSynced() bool {
ds.poolAndModelsMu.RLock()
defer ds.poolAndModelsMu.RUnlock()
return ds.pool != nil
}
func (ds *datastore) PoolLabelsMatch(podLabels map[string]string) bool {
ds.poolAndModelsMu.RLock()
defer ds.poolAndModelsMu.RUnlock()
poolSelector := selectorFromInferencePoolSelector(ds.pool.Spec.Selector)
podSet := labels.Set(podLabels)
return poolSelector.Matches(podSet)
}
func (ds *datastore) ModelSetIfOlder(infModel *v1alpha2.InferenceModel) bool {
ds.poolAndModelsMu.Lock()
defer ds.poolAndModelsMu.Unlock()
// Check first if the existing model is older.
// One exception is if the incoming model object is the same, in which case, we should not
// check for creation timestamp since that means the object was re-created, and so we should override.
existing, exists := ds.models[infModel.Spec.ModelName]
if exists {
diffObj := infModel.Name != existing.Name || infModel.Namespace != existing.Namespace
if diffObj && existing.ObjectMeta.CreationTimestamp.Before(&infModel.ObjectMeta.CreationTimestamp) {
return false
}
}
// Set the model.
ds.models[infModel.Spec.ModelName] = infModel
return true
}
func (ds *datastore) ModelResync(ctx context.Context, c client.Client, modelName string) (bool, error) {
ds.poolAndModelsMu.Lock()
defer ds.poolAndModelsMu.Unlock()
var models v1alpha2.InferenceModelList
if err := c.List(ctx, &models, client.MatchingFields{ModelNameIndexKey: modelName}, client.InNamespace(ds.pool.Namespace)); err != nil {
return false, fmt.Errorf("listing models that match the modelName %s: %w", modelName, err)
}
if len(models.Items) == 0 {
// No other instances of InferenceModels with this ModelName exists.
return false, nil
}
var oldest *v1alpha2.InferenceModel
for i := range models.Items {
m := &models.Items[i]
if m.Spec.ModelName != modelName || // The index should filter those out, but just in case!
m.Spec.PoolRef.Name != v1alpha2.ObjectName(ds.pool.Name) || // We don't care about other pools, we could setup an index on this too!
!m.DeletionTimestamp.IsZero() { // ignore objects marked for deletion
continue
}
if oldest == nil || m.ObjectMeta.CreationTimestamp.Before(&oldest.ObjectMeta.CreationTimestamp) {
oldest = m
}
}
if oldest == nil {
return false, nil
}
ds.models[modelName] = oldest
return true, nil
}
func (ds *datastore) ModelGet(modelName string) *v1alpha2.InferenceModel {
ds.poolAndModelsMu.RLock()
defer ds.poolAndModelsMu.RUnlock()
return ds.models[modelName]
}
func (ds *datastore) ModelDelete(namespacedName types.NamespacedName) *v1alpha2.InferenceModel {
ds.poolAndModelsMu.Lock()
defer ds.poolAndModelsMu.Unlock()
for _, m := range ds.models {
if m.Name == namespacedName.Name && m.Namespace == namespacedName.Namespace {
delete(ds.models, m.Spec.ModelName)
return m
}
}
return nil
}
func (ds *datastore) ModelGetAll() []*v1alpha2.InferenceModel {
ds.poolAndModelsMu.RLock()
defer ds.poolAndModelsMu.RUnlock()
res := []*v1alpha2.InferenceModel{}
for _, v := range ds.models {
res = append(res, v)
}
return res
}
// /// Pods/endpoints APIs ///
func (ds *datastore) PodUpdateMetricsIfExist(namespacedName types.NamespacedName, m *Metrics) bool {
if val, ok := ds.pods.Load(namespacedName); ok {
existing := val.(*PodMetrics)
existing.Metrics = *m
return true
}
return false
}
func (ds *datastore) PodGet(namespacedName types.NamespacedName) *PodMetrics {
val, ok := ds.pods.Load(namespacedName)
if ok {
return val.(*PodMetrics)
}
return nil
}
func (ds *datastore) PodGetAll() []*PodMetrics {
res := []*PodMetrics{}
fn := func(k, v any) bool {
res = append(res, v.(*PodMetrics))
return true
}
ds.pods.Range(fn)
return res
}
func (ds *datastore) PodRange(f func(key, value any) bool) {
ds.pods.Range(f)
}
func (ds *datastore) PodDelete(namespacedName types.NamespacedName) {
ds.pods.Delete(namespacedName)
}
func (ds *datastore) PodUpdateOrAddIfNotExist(pod *corev1.Pod) bool {
new := &PodMetrics{
Pod: Pod{
NamespacedName: types.NamespacedName{
Name: pod.Name,
Namespace: pod.Namespace,
},
Address: pod.Status.PodIP,
},
Metrics: Metrics{
ActiveModels: make(map[string]int),
},
}
existing, ok := ds.pods.Load(new.NamespacedName)
if !ok {
ds.pods.Store(new.NamespacedName, new)
return true
}
// Update pod properties if anything changed.
existing.(*PodMetrics).Pod = new.Pod
return false
}
func (ds *datastore) PodResyncAll(ctx context.Context, ctrlClient client.Client) {
// Pool must exist to invoke this function.
pool, _ := ds.PoolGet()
podList := &corev1.PodList{}
if err := ctrlClient.List(ctx, podList, &client.ListOptions{
LabelSelector: selectorFromInferencePoolSelector(pool.Spec.Selector),
Namespace: pool.Namespace,
}); err != nil {
log.FromContext(ctx).V(logutil.DEFAULT).Error(err, "Failed to list clients")
return
}
activePods := make(map[string]bool)
for _, pod := range podList.Items {
if podIsReady(&pod) {
activePods[pod.Name] = true
ds.PodUpdateOrAddIfNotExist(&pod)
}
}
// Remove pods that don't belong to the pool or not ready any more.
deleteFn := func(k, v any) bool {
pm := v.(*PodMetrics)
if exist := activePods[pm.NamespacedName.Name]; !exist {
ds.pods.Delete(pm.NamespacedName)
}
return true
}
ds.pods.Range(deleteFn)
}
func (ds *datastore) PodDeleteAll() {
ds.pods.Clear()
}
func selectorFromInferencePoolSelector(selector map[v1alpha2.LabelKey]v1alpha2.LabelValue) labels.Selector {
return labels.SelectorFromSet(stripLabelKeyAliasFromLabelMap(selector))
}
func stripLabelKeyAliasFromLabelMap(labels map[v1alpha2.LabelKey]v1alpha2.LabelValue) map[string]string {
outMap := make(map[string]string)
for k, v := range labels {
outMap[string(k)] = string(v)
}
return outMap
}
func RandomWeightedDraw(logger logr.Logger, model *v1alpha2.InferenceModel, seed int64) string {
source := rand.NewSource(rand.Int63())
if seed > 0 {
source = rand.NewSource(seed)
}
r := rand.New(source)
// all the weight values are nil, then we should return random model name
if model.Spec.TargetModels[0].Weight == nil {
index := r.Int31n(int32(len(model.Spec.TargetModels)))
return model.Spec.TargetModels[index].Name
}
var weights int32
for _, model := range model.Spec.TargetModels {
weights += *model.Weight
}
logger.V(logutil.TRACE).Info("Weights for model computed", "model", model.Name, "weights", weights)
randomVal := r.Int31n(weights)
// TODO: optimize this without using loop
for _, model := range model.Spec.TargetModels {
if randomVal < *model.Weight {
return model.Name
}
randomVal -= *model.Weight
}
return ""
}
func IsCritical(model *v1alpha2.InferenceModel) bool {
if model.Spec.Criticality != nil && *model.Spec.Criticality == v1alpha2.Critical {
return true
}
return false
}
// TODO: move out to share with pod_reconciler.go
func podIsReady(pod *corev1.Pod) bool {
for _, condition := range pod.Status.Conditions {
if condition.Type == corev1.PodReady {
if condition.Status == corev1.ConditionTrue {
return true
}
break
}
}
return false
}