forked from rancher/rancher
-
Notifications
You must be signed in to change notification settings - Fork 0
/
resource_quota_validate.go
306 lines (272 loc) · 8.09 KB
/
resource_quota_validate.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
package resourcequota
import (
"fmt"
"sort"
"strings"
"sync"
"time"
"github.com/rancher/norman/types/convert"
namespaceutil "github.com/rancher/rancher/pkg/controllers/user/namespace"
"github.com/rancher/types/apis/core/v1"
"github.com/rancher/types/apis/management.cattle.io/v3"
corev1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/api/resource"
"k8s.io/apimachinery/pkg/labels"
"k8s.io/apimachinery/pkg/util/cache"
clientcache "k8s.io/client-go/tools/cache"
api "k8s.io/kubernetes/pkg/apis/core"
"k8s.io/kubernetes/pkg/quota"
)
const (
resourceQuotaTemplateIDAnnotation = "field.cattle.io/resourceQuotaTemplateId"
resourceQuotaAppliedTemplateIDAnnotation = "field.cattle.io/resourceQuotaAppliedTemplateId"
resourceQuotaValidatedCondition = "ResourceQuotaValidated"
)
var (
projectLockCache = cache.NewLRUExpireCache(1000)
)
/*
validationController listens on namespace creation, and if the namespace has resourceQuotaTemplate set,
the quota will be validated against the project's quota
*/
type validationController struct {
namespaces v1.NamespaceInterface
nsIndexer clientcache.Indexer
resourceQuotaLister v1.ResourceQuotaLister
projectLister v3.ProjectLister
resourceQuotaTemplateLister v3.ResourceQuotaTemplateLister
clusterName string
}
/*
reconcile controller listens on project updates, and enqueues the namespaces of the project
so they get a chance to reconcile the resource quotas
*/
type reconcileController struct {
namespaces v1.NamespaceInterface
nsIndexer clientcache.Indexer
}
func (r *reconcileController) reconcileNamespaces(key string, p *v3.Project) error {
if p == nil || p.DeletionTimestamp != nil {
return nil
}
projectID := fmt.Sprintf("%s:%s", p.Namespace, p.Name)
namespaces, err := r.nsIndexer.ByIndex(nsByProjectIndex, projectID)
if err != nil {
return err
}
for _, n := range namespaces {
ns := n.(*corev1.Namespace)
r.namespaces.Controller().Enqueue("", ns.Name)
}
return nil
}
func (c *validationController) validateTemplate(key string, ns *corev1.Namespace) error {
if ns == nil || ns.DeletionTimestamp != nil {
return nil
}
// get project limit
projectLimit, projectID, err := getProjectLimit(ns, c.projectLister)
if err != nil {
return err
}
if projectLimit == nil {
return c.setAppliedTemplateID(ns, err)
}
// validate resource quota
isFit, msg, err := c.validateResourceQuotaTemplate(ns, projectID, projectLimit)
if err != nil {
return err
}
if isFit {
return nil
}
set, err := namespaceutil.IsNamespaceConditionSet(ns, resourceQuotaValidatedCondition, false)
if set || err != nil {
return err
}
toUpdate := ns.DeepCopy()
err = namespaceutil.SetNamespaceCondition(toUpdate, time.Second*1, resourceQuotaValidatedCondition, false, msg)
if err != nil {
return err
}
_, err = c.namespaces.Update(toUpdate)
return err
}
func getProjectLock(projectID string) *sync.Mutex {
val, ok := projectLockCache.Get(projectID)
if !ok {
projectLockCache.Add(projectID, &sync.Mutex{}, time.Hour)
val, _ = projectLockCache.Get(projectID)
}
mu := val.(*sync.Mutex)
return mu
}
func (c *validationController) validateResourceQuotaTemplate(ns *corev1.Namespace, projectID string,
projectLimit *v3.ProjectResourceLimit) (bool, string, error) {
mu := getProjectLock(projectID)
mu.Lock()
defer mu.Unlock()
templateIDToUpdate, err := c.getTemplateIDToUpdate(ns)
if err != nil {
return false, "", err
}
finalNs := *ns
if templateIDToUpdate != "" {
toUpdate := ns.DeepCopy()
if toUpdate.Annotations == nil {
toUpdate.Annotations = map[string]string{}
}
toUpdate.Annotations[resourceQuotaTemplateIDAnnotation] = templateIDToUpdate
toUpdate, err = c.namespaces.Update(toUpdate)
if err != nil {
return false, "", err
}
finalNs = *toUpdate
}
isFit, msg, err := c.isQuotaFit(&finalNs, projectID, projectLimit)
if err != nil {
return false, "", err
}
if isFit {
return true, "", c.setAppliedTemplateID(&finalNs, err)
}
return false, msg, nil
}
func (c *validationController) setAppliedTemplateID(ns *corev1.Namespace, err error) error {
templateID := getTemplateID(ns)
validatedTemplateID := getAppliedTemplateID(ns)
if templateID == validatedTemplateID {
return nil
}
toUpdate := ns.DeepCopy()
toUpdate.Annotations[resourceQuotaAppliedTemplateIDAnnotation] = templateID
_, err = c.namespaces.Update(toUpdate)
return err
}
func (c *validationController) getTemplateIDToUpdate(ns *corev1.Namespace) (string, error) {
templateID := getTemplateID(ns)
if templateID != "" {
return "", nil
}
templates, err := c.resourceQuotaTemplateLister.List(c.clusterName, labels.NewSelector())
if err != nil {
return "", err
}
for _, t := range templates {
if t.IsDefault {
return formatTemplateID(t), nil
}
}
return "", nil
}
func (c *validationController) isQuotaFit(ns *corev1.Namespace, projectID string, projectLimit *v3.ProjectResourceLimit) (bool, string, error) {
templates, err := c.resourceQuotaTemplateLister.List(c.clusterName, labels.NewSelector())
if err != nil {
return false, "", err
}
templatesMap := map[string]*v3.ResourceQuotaTemplate{}
for _, template := range templates {
templatesMap[formatTemplateID(template)] = template
}
nssResourceList := api.ResourceList{}
nsLimit, err := getNamespaceLimit(ns, templatesMap, false)
if err != nil {
return false, "", err
}
// add itself on create
nsResourceList, err := convertLimitToResourceList(nsLimit)
if err != nil {
return false, "", err
}
nssResourceList = quota.Add(nssResourceList, nsResourceList)
// get other Namespaces
namespaces, err := c.nsIndexer.ByIndex(nsByProjectIndex, projectID)
if err != nil {
return false, "", err
}
for _, n := range namespaces {
other := n.(*corev1.Namespace)
if other.Name == ns.Name {
continue
}
nsLimit, err := getNamespaceLimit(other, templatesMap, true)
if err != nil {
return false, "", err
}
nsResourceList, err := convertLimitToResourceList(nsLimit)
if err != nil {
return false, "", err
}
nssResourceList = quota.Add(nssResourceList, nsResourceList)
}
projectResourceList, err := convertLimitToResourceList(projectLimit)
if err != nil {
return false, "", err
}
allowed, exceeded := quota.LessThanOrEqual(nssResourceList, projectResourceList)
if allowed {
return true, "", nil
}
failedHard := quota.Mask(nssResourceList, exceeded)
return false, fmt.Sprintf("Resource quota [%v] exceeds project limit ", prettyPrint(failedHard)), nil
}
func prettyPrint(item api.ResourceList) string {
parts := []string{}
keys := []string{}
for key := range item {
keys = append(keys, string(key))
}
sort.Strings(keys)
for _, key := range keys {
value := item[api.ResourceName(key)]
constraint := key + "=" + value.String()
parts = append(parts, constraint)
}
return strings.Join(parts, ",")
}
func formatTemplateID(template *v3.ResourceQuotaTemplate) string {
return fmt.Sprintf("%s:%s", template.Namespace, template.Name)
}
func getNamespaceLimit(ns *corev1.Namespace, templates map[string]*v3.ResourceQuotaTemplate, applied bool) (*v3.ProjectResourceLimit, error) {
templateID := ""
if applied {
templateID = getAppliedTemplateID(ns)
} else {
templateID = getTemplateID(ns)
}
if templateID == "" {
return nil, nil
}
template := templates[templateID]
if template == nil {
return nil, fmt.Errorf("failed to find the template by id [%s]", templateID)
}
return &template.Limit, nil
}
func convertLimitToResourceList(limit *v3.ProjectResourceLimit) (api.ResourceList, error) {
toReturn := api.ResourceList{}
converted, err := convert.EncodeToMap(limit)
if err != nil {
return nil, err
}
for key, value := range converted {
q, err := resource.ParseQuantity(convert.ToString(value))
if err != nil {
return nil, err
}
toReturn[api.ResourceName(key)] = q
}
return toReturn, nil
}
func getAppliedTemplateID(ns *corev1.Namespace) string {
if ns.Annotations != nil {
return ns.Annotations[resourceQuotaAppliedTemplateIDAnnotation]
}
return ""
}
func getTemplateID(ns *corev1.Namespace) string {
if ns.Annotations != nil {
return ns.Annotations[resourceQuotaTemplateIDAnnotation]
}
return ""
}