/
store.go
297 lines (267 loc) · 9.52 KB
/
store.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
/*
* Tencent is pleased to support the open source community by making TKEStack
* available.
*
* Copyright (C) 2012-2019 Tencent. All Rights Reserved.
*
* 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
*
* https://opensource.org/licenses/Apache-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 OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package util
import (
"context"
"reflect"
"strings"
"k8s.io/apimachinery/pkg/api/errors"
metainternalversion "k8s.io/apimachinery/pkg/apis/meta/internalversion"
v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/types"
"k8s.io/apimachinery/pkg/watch"
"k8s.io/apiserver/pkg/registry/rest"
clientrest "k8s.io/client-go/rest"
platforminternalclient "tkestack.io/tke/api/client/clientset/internalversion/typed/platform/internalversion"
"tkestack.io/tke/pkg/platform/apiserver/filter"
)
// Store implements pkg/api/rest.StandardStorage.
type Store struct {
// NewFunc returns a new instance of the type this registry returns for a
// GET of a single object
NewFunc func() runtime.Object
// NewListFunc returns a new list of the type this registry
NewListFunc func() runtime.Object
Namespaced bool
PlatformClient platforminternalclient.PlatformInterface
}
// var _ rest.Exporter = &Store{}
// var _ rest.TableConvertor = &Store{}
// New implements RESTStorage.New.
func (s *Store) New() runtime.Object {
return s.NewFunc()
}
// NewList implements rest.Lister.
func (s *Store) NewList() runtime.Object {
return s.NewListFunc()
}
// NamespaceScoped indicates whether the resource is namespaced.
func (s *Store) NamespaceScoped() bool {
return s.Namespaced
}
// List returns a list of items matching labels and field according to the
// backend kubernetes api server.
func (s *Store) List(ctx context.Context, options *metainternalversion.ListOptions) (runtime.Object, error) {
client, requestInfo, err := RESTClient(ctx, s.PlatformClient)
if err != nil {
return nil, err
}
fuzzyResourceName := filter.FuzzyResourceFrom(ctx)
if options != nil && options.FieldSelector != nil {
if name, ok := options.FieldSelector.RequiresExactMatch("metadata.name"); ok {
options.FieldSelector, _ = options.FieldSelector.Transform(func(k, v string) (string, string, error) {
if k == "metadata.name" {
return "", "", nil
}
return k, v, nil
})
fuzzyResourceName = name
}
}
result := s.NewListFunc()
if err := client.
Get().
Context(ctx).
NamespaceIfScoped(requestInfo.Namespace, requestInfo.Namespace != "" && requestInfo.Resource != "namespaces").
Resource(requestInfo.Resource).
SubResource(requestInfo.Subresource).
// SpecificallyVersionedParams(options, metainternalversion.ParameterCodec, v1.SchemeGroupVersion).
Do().
Into(result); err != nil {
return nil, err
}
if fuzzyResourceName != "" {
if _, ok := result.(v1.ListInterface); ok {
v := reflect.ValueOf(result).Elem()
if items := v.FieldByName("Items"); items != (reflect.Value{}) {
if items.Kind() == reflect.Slice || items.Kind() == reflect.Array {
newResult := make([]reflect.Value, 0)
for i := 0; i < items.Len(); i++ {
item := items.Index(i)
for j := 0; j < item.Type().NumField(); j++ {
itemChild := item.Field(j)
if metadata, ok := itemChild.Interface().(v1.ObjectMeta); ok {
if strings.Contains(strings.ToLower(metadata.Name), strings.ToLower(fuzzyResourceName)) {
newResult = append(newResult, item)
}
break
}
}
}
slice := reflect.MakeSlice(items.Type(), 0, 0)
newResultValue := reflect.Append(slice, newResult...)
v.FieldByName("Items").Set(newResultValue)
}
}
}
}
return result, nil
}
// Get retrieves the item from storage.
func (s *Store) Get(ctx context.Context, name string, options *v1.GetOptions) (runtime.Object, error) {
client, requestInfo, err := RESTClient(ctx, s.PlatformClient)
if err != nil {
return nil, err
}
result := s.New()
if err := client.
Get().
Context(ctx).
NamespaceIfScoped(requestInfo.Namespace, requestInfo.Namespace != "" && requestInfo.Resource != "namespaces").
Resource(requestInfo.Resource).
SubResource(requestInfo.Subresource).
Name(name).
VersionedParams(options, v1.ParameterCodec).
Do().
Into(result); err != nil {
return nil, err
}
return result, nil
}
// Watch makes a matcher for the given label and field, and calls
// WatchPredicate. If possible, you should customize PredicateFunc to produce
// a matcher that matches by key. SelectionPredicate does this for you
// automatically.
func (s *Store) Watch(ctx context.Context, options *metainternalversion.ListOptions) (watch.Interface, error) {
client, requestInfo, err := RESTClient(ctx, s.PlatformClient)
if err != nil {
return nil, err
}
options.Watch = true
return client.Get().
Context(ctx).
NamespaceIfScoped(requestInfo.Namespace, requestInfo.Namespace != "" && requestInfo.Resource != "namespaces").
Resource(requestInfo.Resource).
SubResource(requestInfo.Subresource).
// SpecificallyVersionedParams(options, v1.ParameterCodec, metainternalversion.SchemeGroupVersion).
Watch()
}
// Create inserts a new item according to the unique key from the object.
func (s *Store) Create(ctx context.Context, obj runtime.Object, createValidation rest.ValidateObjectFunc, _ *v1.CreateOptions) (runtime.Object, error) {
client, requestInfo, err := RESTClient(ctx, s.PlatformClient)
if err != nil {
return nil, err
}
requestBody, ok := filter.RequestBodyFrom(ctx)
if !ok {
return nil, errors.NewBadRequest("request body is required")
}
result := s.New()
if err := client.
Post().
Context(ctx).
SetHeader("Content-Type", requestBody.ContentType).
NamespaceIfScoped(requestInfo.Namespace, requestInfo.Namespace != "" && requestInfo.Resource != "namespaces").
Resource(requestInfo.Resource).
SubResource(requestInfo.Subresource).
Body(requestBody.Data).
Do().
Into(result); err != nil {
return nil, err
}
return result, nil
}
// Update finds a resource in the storage and updates it. Some implementations
// may allow updates creates the object - they should set the created boolean
// to true.
func (s *Store) Update(ctx context.Context, name string, objInfo rest.UpdatedObjectInfo, createValidation rest.ValidateObjectFunc, updateValidation rest.ValidateObjectUpdateFunc, forceAllowCreate bool, options *v1.UpdateOptions) (runtime.Object, bool, error) {
client, requestInfo, err := RESTClient(ctx, s.PlatformClient)
if err != nil {
return nil, false, err
}
requestBody, ok := filter.RequestBodyFrom(ctx)
if !ok {
return nil, false, errors.NewBadRequest("request body is required")
}
result := s.New()
var req *clientrest.Request
if requestInfo.Verb == "patch" {
req = client.Patch(types.PatchType(requestBody.ContentType))
} else if requestInfo.Verb == "update" || requestInfo.Verb == "put" {
req = client.Put()
} else {
return nil, false, errors.NewBadRequest("unsupported request method")
}
if err := req.
Context(ctx).
SetHeader("Content-Type", requestBody.ContentType).
NamespaceIfScoped(requestInfo.Namespace, requestInfo.Namespace != "" && requestInfo.Resource != "namespaces").
Resource(requestInfo.Resource).
SubResource(requestInfo.Subresource).
Name(name).
Body(requestBody.Data).
Do().
Into(result); err != nil {
return nil, false, err
}
return result, true, nil
}
// Delete finds a resource in the storage and deletes it.
func (s *Store) Delete(ctx context.Context, name string, deleteValidation rest.ValidateObjectFunc, options *v1.DeleteOptions) (runtime.Object, bool, error) {
client, requestInfo, err := RESTClient(ctx, s.PlatformClient)
if err != nil {
return nil, false, err
}
result := client.
Delete().
Context(ctx).
NamespaceIfScoped(requestInfo.Namespace, requestInfo.Namespace != "" && requestInfo.Resource != "namespaces").
Resource(requestInfo.Resource).
SubResource(requestInfo.Subresource).
Name(name).
Body(options).
Do()
resultErr := result.Error()
if resultErr != nil {
return nil, false, resultErr
}
returnedObj, err := result.Get()
if err != nil {
return nil, false, err
}
return returnedObj, true, nil
}
// DeleteCollection selects all resources in the storage matching given 'listOptions'
// and deletes them. If 'options' are provided, the resource will attempt to honor
// them or return an invalid request error.
// DeleteCollection may not be atomic - i.e. it may delete some objects and still
// return an error after it. On success, returns a list of deleted objects.
func (s *Store) DeleteCollection(ctx context.Context, options *v1.DeleteOptions, listOptions *metainternalversion.ListOptions) (runtime.Object, error) {
client, requestInfo, err := RESTClient(ctx, s.PlatformClient)
if err != nil {
return nil, err
}
result := client.
Delete().
Context(ctx).
NamespaceIfScoped(requestInfo.Namespace, requestInfo.Namespace != "" && requestInfo.Resource != "namespaces").
Resource(requestInfo.Resource).
// SpecificallyVersionedParams(listOptions, v1.ParameterCodec, metainternalversion.SchemeGroupVersion).
Body(options).
Do()
resultErr := result.Error()
if resultErr != nil {
return nil, resultErr
}
returnedObj, err := result.Get()
if err != nil {
return nil, err
}
return returnedObj, nil
}