This repository has been archived by the owner on Oct 9, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 60
/
redis_resourcemanager.go
233 lines (194 loc) · 8.28 KB
/
redis_resourcemanager.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
package resourcemanager
import (
"context"
"fmt"
"sync"
"time"
"github.com/go-redis/redis"
pluginCore "github.com/lyft/flyteplugins/go/tasks/pluginmachinery/core"
rmConfig "github.com/lyft/flytepropeller/pkg/controller/nodes/task/resourcemanager/config"
"github.com/lyft/flytestdlib/logger"
"github.com/lyft/flytestdlib/promutils"
"github.com/pkg/errors"
"github.com/prometheus/client_golang/prometheus"
"k8s.io/apimachinery/pkg/util/wait"
)
// This is the key that will point to the Redis Set.
// https://redis.io/commands#set
const RedisSetKeyPrefix = "resourcemanager"
type RedisResourceManagerBuilder struct {
client *redis.Client
MetricsScope promutils.Scope
redisSetKeyPrefix string
namespacedResourcesQuotaMap map[pluginCore.ResourceNamespace]int
}
func (r *RedisResourceManagerBuilder) ResourceRegistrar(namespacePrefix pluginCore.ResourceNamespace) pluginCore.ResourceRegistrar {
return ResourceRegistrarProxy{
ResourceRegistrar: r,
NamespacePrefix: namespacePrefix,
}
}
func (r *RedisResourceManagerBuilder) RegisterResourceQuota(ctx context.Context, namespace pluginCore.ResourceNamespace, quota int) error {
if r.client == nil {
err := errors.Errorf("Redis client does not exist.")
return err
}
config := rmConfig.GetConfig()
if quota <= 0 || quota > config.ResourceMaxQuota {
err := errors.Errorf("Invalid request for resource quota (<= 0 || > %v): [%v]", config.ResourceMaxQuota, quota)
return err
}
// Checking if the namespace already exists
// We use linear search here because this function is only called a few times
if _, ok := r.namespacedResourcesQuotaMap[namespace]; ok {
return errors.Errorf("Resource namespace already exists [%v]", namespace)
}
// Add this registration to the list
r.namespacedResourcesQuotaMap[namespace] = quota
logger.Infof(ctx, "Registering resource quota for Namespace [%v]. Quota [%v]", namespace, quota)
return nil
}
func (r *RedisResourceManagerBuilder) BuildResourceManager(ctx context.Context) (pluginCore.ResourceManager, error) {
if r.client == nil || r.redisSetKeyPrefix == "" || r.MetricsScope == nil || r.namespacedResourcesQuotaMap == nil {
return nil, errors.Errorf("Failed to build a redis resource manager. Missing key property(s)")
}
rm := &RedisResourceManager{
client: r.client,
redisSetKeyPrefix: r.redisSetKeyPrefix,
MetricsScope: r.MetricsScope,
namespacedResourcesMap: map[pluginCore.ResourceNamespace]*Resource{},
}
// building the resources and insert them into the resource manager
for namespace, quota := range r.namespacedResourcesQuotaMap {
prefixedNamespace := r.getNamespacedRedisSetKey(namespace)
metrics := NewRedisResourceManagerMetrics(r.MetricsScope.NewSubScope(prefixedNamespace))
rm.namespacedResourcesMap[namespace] = &Resource{
quota: quota,
metrics: metrics,
rejectedTokens: sync.Map{},
}
}
rm.startMetricsGathering(ctx)
return rm, nil
}
func (r *RedisResourceManagerBuilder) getNamespacedRedisSetKey(namespace pluginCore.ResourceNamespace) string {
return fmt.Sprintf("%s:%s", r.redisSetKeyPrefix, namespace)
}
func NewRedisResourceManagerBuilder(_ context.Context, client *redis.Client, scope promutils.Scope) (*RedisResourceManagerBuilder, error) {
rn := &RedisResourceManagerBuilder{
client: client,
MetricsScope: scope,
redisSetKeyPrefix: RedisSetKeyPrefix,
namespacedResourcesQuotaMap: map[pluginCore.ResourceNamespace]int{},
}
return rn, nil
}
type RedisResourceManager struct {
client *redis.Client
redisSetKeyPrefix string
MetricsScope promutils.Scope
namespacedResourcesMap map[pluginCore.ResourceNamespace]*Resource
}
func GetTaskResourceManager(r pluginCore.ResourceManager, namespacePrefix pluginCore.ResourceNamespace) pluginCore.ResourceManager {
return Proxy{
ResourceManager: r,
NamespacePrefix: namespacePrefix,
}
}
type RedisResourceManagerMetrics struct {
Scope promutils.Scope
RedisSizeCheckTime promutils.StopWatch
AllocatedTokensGauge prometheus.Gauge
ApproximateBackedUpLength prometheus.Gauge
}
func (rrmm RedisResourceManagerMetrics) GetScope() promutils.Scope {
return rrmm.Scope
}
func (r *RedisResourceManager) getResource(namespace pluginCore.ResourceNamespace) *Resource {
return r.namespacedResourcesMap[namespace]
}
func (r *RedisResourceManager) pollRedis(ctx context.Context, namespace pluginCore.ResourceNamespace) {
namespacedRedisSetKey := r.getNamespacedRedisSetKey(namespace)
resource := r.getResource(namespace)
stopWatch := resource.metrics.(*RedisResourceManagerMetrics).RedisSizeCheckTime.Start()
defer stopWatch.Stop()
size, err := r.client.SCard(namespacedRedisSetKey).Result()
if err != nil {
logger.Errorf(ctx, "Error getting size of Redis set in metrics poller %v", err)
return
}
metrics := resource.metrics.(*RedisResourceManagerMetrics)
metrics.AllocatedTokensGauge.Set(float64(size))
rejectedTokensCount := 0
resource.rejectedTokens.Range(func(key, value interface{}) bool {
rejectedTokensCount++
return true
})
metrics.ApproximateBackedUpLength.Set(float64(rejectedTokensCount))
}
func (r *RedisResourceManager) startMetricsGathering(ctx context.Context) {
go wait.Until(func() {
for namespace := range r.namespacedResourcesMap {
r.pollRedis(ctx, namespace)
}
}, 10*time.Second, ctx.Done())
}
func NewRedisResourceManagerMetrics(scope promutils.Scope) *RedisResourceManagerMetrics {
return &RedisResourceManagerMetrics{
Scope: scope,
RedisSizeCheckTime: scope.MustNewStopWatch("size_check_time_ms",
"The time it takes to measure the size of the Redis Set where all utilized resource are stored", time.Millisecond),
AllocatedTokensGauge: scope.MustNewGauge("size",
"The number of allocation resourceRegistryTokens currently in the Redis set"),
ApproximateBackedUpLength: scope.MustNewGauge("approx_backup",
"Approximation for how long the current not-fulfilled-tokens queue is."),
}
}
func (r *RedisResourceManager) getNamespacedRedisSetKey(namespace pluginCore.ResourceNamespace) string {
return fmt.Sprintf("%s:%s", r.redisSetKeyPrefix, namespace)
}
func (r *RedisResourceManager) AllocateResource(ctx context.Context, namespace pluginCore.ResourceNamespace, allocationToken string) (
pluginCore.AllocationStatus, error) {
namespacedRedisSetKey := r.getNamespacedRedisSetKey(namespace)
namespacedResource := r.getResource(namespace)
// Check to see if the allocation token is already in the set
found, err := r.client.SIsMember(namespacedRedisSetKey, allocationToken).Result()
if err != nil {
logger.Errorf(ctx, "Error getting size of Redis set %v", err)
return pluginCore.AllocationUndefined, err
}
if found {
logger.Infof(ctx, "Already allocated [%s:%s]", namespace, allocationToken)
return pluginCore.AllocationStatusGranted, nil
}
size, err := r.client.SCard(namespacedRedisSetKey).Result()
if err != nil {
logger.Errorf(ctx, "Error getting size of Redis set %v", err)
return pluginCore.AllocationUndefined, err
}
if size > int64(namespacedResource.quota) {
logger.Infof(ctx, "Too many allocations (total [%d]), rejecting [%s:%s]", size, namespace, allocationToken)
namespacedResource.rejectedTokens.Store(allocationToken, struct{}{})
return pluginCore.AllocationStatusExhausted, nil
}
countAdded, err := r.client.SAdd(namespacedRedisSetKey, allocationToken).Result()
if err != nil {
logger.Errorf(ctx, "Error adding token [%s:%s] %v", namespace, allocationToken, err)
return pluginCore.AllocationUndefined, err
}
logger.Infof(ctx, "Added %d to the Redis Qubole set", countAdded)
namespacedResource.rejectedTokens.Delete(allocationToken)
return pluginCore.AllocationStatusGranted, err
}
func (r *RedisResourceManager) ReleaseResource(ctx context.Context, namespace pluginCore.ResourceNamespace, allocationToken string) error {
namespacedRedisSetKey := r.getNamespacedRedisSetKey(namespace)
countRemoved, err := r.client.SRem(namespacedRedisSetKey, allocationToken).Result()
if err != nil {
logger.Errorf(ctx, "Error removing token [%v:%s] %v", namespace, allocationToken, err)
return err
}
namespacedResource := r.getResource(namespace)
namespacedResource.rejectedTokens.Delete(allocationToken)
logger.Infof(ctx, "Removed %d token: %s", countRemoved, allocationToken)
return nil
}