-
Notifications
You must be signed in to change notification settings - Fork 1
/
storage_interface.go
636 lines (597 loc) · 17.6 KB
/
storage_interface.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
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
/*
Copyright 2017 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 tpr
import (
"bytes"
"errors"
"fmt"
"net/http"
"github.com/golang/glog"
"golang.org/x/net/context"
"k8s.io/apimachinery/pkg/api/meta"
"k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/conversion"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/watch"
"k8s.io/apiserver/pkg/storage"
"k8s.io/apiserver/pkg/storage/etcd"
"k8s.io/apiserver/pkg/storage/storagebackend/factory"
restclient "k8s.io/client-go/rest"
)
var (
errNotImplemented = errors.New("not implemented for third party resources")
)
type store struct {
hasNamespace bool
codec runtime.Codec
defaultNamespace string
cl restclient.Interface
singularKind Kind
singularShell func(string, string) runtime.Object
listKind Kind
listShell func() runtime.Object
checkObject func(runtime.Object) error
decodeKey func(string) (string, string, error)
versioner storage.Versioner
}
// NewStorage creates a new TPR-based storage.Interface implementation
func NewStorage(opts Options) (storage.Interface, factory.DestroyFunc) {
return &store{
hasNamespace: opts.HasNamespace,
codec: opts.RESTOptions.StorageConfig.Codec,
defaultNamespace: opts.DefaultNamespace,
cl: opts.RESTClient,
singularKind: opts.SingularKind,
singularShell: opts.NewSingularFunc,
listKind: opts.ListKind,
listShell: opts.NewListFunc,
checkObject: opts.CheckObjectFunc,
decodeKey: opts.Keyer.NamespaceAndNameFromKey,
versioner: etcd.APIObjectVersioner{},
}, opts.DestroyFunc
}
// Versioned returns the versioned associated with this interface
func (t *store) Versioner() storage.Versioner {
return t.versioner
}
// Create adds a new object at a key unless it already exists. 'ttl' is time-to-live
// in seconds (0 means forever). If no error is returned and out is not nil, out will be
// set to the read value from database.
func (t *store) Create(
ctx context.Context,
key string,
obj,
out runtime.Object,
ttl uint64,
) error {
ns, name, err := t.decodeKey(key)
if err != nil {
glog.Errorf("decoding key %s (%s)", key, err)
return err
}
data, err := runtime.Encode(t.codec, obj)
if err != nil {
return err
}
req := t.cl.Post().AbsPath(
"apis",
groupName,
tprVersion,
"namespaces",
ns,
t.singularKind.URLName(),
).Body(data)
res := req.Do()
if res.Error() != nil {
glog.Errorf("executing POST for %s/%s (%s)", ns, name, res.Error())
}
var statusCode int
res.StatusCode(&statusCode)
if statusCode == http.StatusConflict {
return storage.NewKeyExistsError(key, 0)
}
if statusCode != http.StatusCreated {
return fmt.Errorf(
"executing POST for %s/%s, received response code %d",
ns,
name,
statusCode,
)
}
var unknown runtime.Unknown
if err := res.Into(&unknown); err != nil {
glog.Errorf("decoding response (%s)", err)
return err
}
if err := decode(t.codec, unknown.Raw, out); err != nil {
return err
}
return nil
}
// Delete removes the specified key and returns the value that existed at that spot.
// If key didn't exist, it will return NotFound storage error.
//
// In this implementation, Delete will not write the deleted object back to out
func (t *store) Delete(
ctx context.Context,
key string,
out runtime.Object,
preconditions *storage.Preconditions,
) error {
ns, name, err := t.decodeKey(key)
if err != nil {
glog.Errorf("decoding key %s (%s)", key, err)
return err
}
req := t.cl.Delete().AbsPath(
"apis",
groupName,
tprVersion,
"namespaces",
ns,
t.singularKind.URLName(),
name,
)
res := req.Do()
if res.Error() != nil {
glog.Errorf("executing DELETE for %s/%s (%s)", ns, name, res.Error())
}
var statusCode int
res.StatusCode(&statusCode)
if statusCode == http.StatusNotFound {
return storage.NewKeyNotFoundError(key, 0)
}
if statusCode != http.StatusAccepted {
return fmt.Errorf(
"executing DELETE for %s/%s, received response code %d",
ns,
name,
statusCode,
)
}
return nil
}
// Watch begins watching the specified key. Events are decoded into API objects,
// and any items selected by 'p' are sent down to returned watch.Interface.
// resourceVersion may be used to specify what version to begin watching,
// which should be the current resourceVersion, and no longer rv+1
// (e.g. reconnecting without missing any updates).
// If resource version is "0", this interface will get current object at given key
// and send it in an "ADDED" event, before watch starts.
func (t *store) Watch(
ctx context.Context,
key string,
resourceVersion string,
p storage.SelectionPredicate,
) (watch.Interface, error) {
ns, name, err := t.decodeKey(key)
if err != nil {
return nil, err
}
req := t.cl.Get().AbsPath(
"apis",
groupName,
tprVersion,
"watch",
"namespaces",
ns,
t.singularKind.URLName(),
name,
).Param("resourceVersion", resourceVersion)
watchIface, err := req.Watch()
if err != nil {
glog.Errorf("initiating the raw watch (%s)", err)
return nil, err
}
filteredIFace := watch.Filter(watchIface, watchFilterer(t, ns, false))
return filteredIFace, nil
}
// watchFilterer returns a function that can be used as an argument to watch.Filter
func watchFilterer(t *store, ns string, list bool) func(watch.Event) (watch.Event, bool) {
return func(in watch.Event) (watch.Event, bool) {
encodedBytes, err := runtime.Encode(t.codec, in.Object)
if err != nil {
glog.Errorf("couldn't encode watch event object (%s)", err)
return watch.Event{}, false
}
if list {
// if we're watching a list, extract to a list object
finalObj := t.listShell()
if err := decode(t.codec, encodedBytes, finalObj); err != nil {
glog.Errorf("couldn't decode watch event bytes (%s)", err)
return watch.Event{}, false
}
if !t.hasNamespace {
// if we're watching a list and not supposed to have a namespace, strip namespaces
objs, err := meta.ExtractList(finalObj)
if err != nil {
glog.Errorf("couldn't extract a list from %#v (%s)", finalObj, err)
return watch.Event{}, false
}
objList := make([]runtime.Object, len(objs))
for i, obj := range objs {
if err := removeNamespace(obj); err != nil {
glog.Errorf("couldn't remove namespace from %#v (%s)", obj, err)
return watch.Event{}, false
}
objList[i] = obj
}
if err := meta.SetList(finalObj, objList); err != nil {
glog.Errorf("setting list items (%s)", err)
return watch.Event{}, false
}
return watch.Event{
Type: in.Type,
Object: finalObj,
}, true
}
return watch.Event{
Type: in.Type,
Object: finalObj,
}, true
}
finalObj := t.singularShell("", "")
if err := decode(t.codec, encodedBytes, finalObj); err != nil {
glog.Errorf("couldn't decode watch event bytes (%s)", err)
return watch.Event{}, false
}
if !t.hasNamespace {
if err := removeNamespace(finalObj); err != nil {
glog.Errorf("couldn't remove namespace from %#v (%s)", finalObj, err)
return watch.Event{}, false
}
}
return watch.Event{
Type: in.Type,
Object: finalObj,
}, true
}
}
// WatchList begins watching the specified key's items. Items are decoded into API
// objects and any item selected by 'p' are sent down to returned watch.Interface.
// resourceVersion may be used to specify what version to begin watching,
// which should be the current resourceVersion, and no longer rv+1
// (e.g. reconnecting without missing any updates).
// If resource version is "0", this interface will list current objects directory defined by key
// and send them in "ADDED" events, before watch starts.
func (t *store) WatchList(
ctx context.Context,
key string,
resourceVersion string,
p storage.SelectionPredicate,
) (watch.Interface, error) {
ns, _, err := t.decodeKey(key)
if err != nil {
return nil, err
}
req := t.cl.Get().AbsPath(
"apis",
groupName,
tprVersion,
"watch",
"namespaces",
ns,
t.singularKind.URLName(),
).Param("resourceVersion", resourceVersion)
watchIface, err := req.Watch()
if err != nil {
glog.Errorf("initiating the raw watch (%s)", err)
return nil, err
}
return watch.Filter(watchIface, watchFilterer(t, ns, true)), nil
}
// Get unmarshals json found at key into objPtr. On a not found error, will either
// return a zero object of the requested type, or an error, depending on ignoreNotFound.
// Treats empty responses and nil response nodes exactly like a not found error.
// The returned contents may be delayed, but it is guaranteed that they will
// be have at least 'resourceVersion'.
func (t *store) Get(
ctx context.Context,
key string,
resourceVersion string,
objPtr runtime.Object,
ignoreNotFound bool,
) error {
ns, name, err := t.decodeKey(key)
if err != nil {
glog.Errorf("decoding key %s (%s)", key, err)
return err
}
req := t.cl.Get().AbsPath(
"apis",
groupName,
tprVersion,
"namespaces",
ns,
t.singularKind.URLName(),
name,
)
res := req.Do()
if res.Error() != nil {
glog.Errorf("executing GET for %s/%s (%s)", ns, name, res.Error())
}
var statusCode int
res.StatusCode(&statusCode)
if statusCode == http.StatusNotFound {
if ignoreNotFound {
return runtime.SetZeroValue(objPtr)
}
glog.Errorf("executing GET for %s/%s: not found", ns, name)
return storage.NewKeyNotFoundError(key, 0)
}
if statusCode != http.StatusOK {
return fmt.Errorf(
"executing GET for %s/%s, received response code %d",
ns,
name,
statusCode,
)
}
var unknown runtime.Unknown
if res.Into(&unknown); err != nil {
glog.Errorf("decoding response (%s)", err)
return err
}
if err := decode(t.codec, unknown.Raw, objPtr); err != nil {
return nil
}
if !t.hasNamespace {
if err := removeNamespace(objPtr); err != nil {
glog.Errorf("removing namespace from %#v (%s)", objPtr, err)
return err
}
}
return nil
}
// GetToList unmarshals json found at key and opaque it into *List api object
// (an object that satisfies the runtime.IsList definition).
// The returned contents may be delayed, but it is guaranteed that they will
// be have at least 'resourceVersion'.
func (t *store) GetToList(
ctx context.Context,
key string,
resourceVersion string,
p storage.SelectionPredicate,
listObj runtime.Object,
) error {
return t.List(ctx, key, resourceVersion, p, listObj)
}
// List unmarshalls jsons found at directory defined by key and opaque them
// into *List api object (an object that satisfies runtime.IsList definition).
// The returned contents may be delayed, but it is guaranteed that they will
// be have at least 'resourceVersion'.
func (t *store) List(
ctx context.Context,
key string,
resourceVersion string,
p storage.SelectionPredicate,
listObj runtime.Object,
) error {
ns, _, err := t.decodeKey(key)
if err != nil {
glog.Errorf("decoding %s (%s)", key, err)
return err
}
if t.hasNamespace && ns == t.defaultNamespace {
// if the resource is supposed to have a namespace, and the given one is the default,
// then assume that '--all-namespaces' was given on the kubectl command line.
// this assumption means that a kubectl command that specifies a namespace equal to
// the default namespace (i.e. '-n default-ns'), we will still list all resources.
//
// to list all resources, we get all namespaces, list all resources in each namespace,
// and then collect all resources into the single listObj
allNamespaces, err := getAllNamespaces(t.cl)
if err != nil {
glog.Errorf("listing all namespaces (%s)", err)
return err
}
var objList []runtime.Object
for _, ns := range allNamespaces.Items {
allObjs, err := listResource(t.cl, ns.Name, t.singularKind, listObj, t.codec)
if err != nil {
glog.Errorf("error listing resources (%s)", err)
return err
}
objList = append(objList, allObjs...)
}
if err := meta.SetList(listObj, objList); err != nil {
glog.Errorf("setting list items (%s)", err)
return err
}
return nil
}
// otherwise, list all the resources in the given namespace. if the resource is not supposed
// to be namespaced, then ns will be the default namespace
objs, err := listResource(t.cl, ns, t.singularKind, listObj, t.codec)
if err != nil {
glog.Errorf("listing resources (%s)", err)
return err
}
if !t.hasNamespace {
for i, obj := range objs {
if err := removeNamespace(obj); err != nil {
glog.Errorf("removing namespace from obj %d (%s)", i, err)
return err
}
}
}
if err := meta.SetList(listObj, objs); err != nil {
glog.Errorf("setting list items (%s)", err)
return err
}
return nil
}
// GuaranteedUpdate implements storage.Interface.GuaranteedUpdate.
func (t *store) GuaranteedUpdate(
ctx context.Context,
key string,
out runtime.Object,
ignoreNotFound bool,
precondtions *storage.Preconditions,
userUpdate storage.UpdateFunc,
suggestion ...runtime.Object,
) error {
// If a suggestion was passed, use that as the initial object, otherwise
// use Get() to retrieve it
var initObj runtime.Object
if len(suggestion) == 1 && suggestion[0] != nil {
initObj = suggestion[0]
} else {
initObj = t.singularShell("", "")
if err := t.Get(ctx, key, "", initObj, ignoreNotFound); err != nil {
glog.Errorf("getting initial object (%s)", err)
return err
}
}
// In either case, extract current state from the initial object
curState, err := t.getStateFromObject(initObj)
if err != nil {
glog.Errorf("getting state from initial object (%s)", err)
return err
}
// Loop until update succeeds or we get an error
for {
if err := checkPreconditions(key, precondtions, curState.obj); err != nil {
glog.Errorf("checking preconditions (%s)", err)
return err
}
// Create a candidate for the new object by applying the userUpdate func
candidate, _, err := userUpdate(curState.obj, *curState.meta)
if err != nil {
glog.Errorf("applying user update: (%s)", err)
return err
}
// Get bytes from the candidate
candidateData, err := runtime.Encode(t.codec, candidate)
if err != nil {
glog.Errorf("encoding candidate obj (%s)", err)
return err
}
// If the candidate matches what we already have, then all we need to do is
// decode into the out object
if bytes.Equal(candidateData, curState.data) {
err := decode(t.codec, candidateData, out)
if err != nil {
glog.Errorf("decoding to output object (%s)", err)
}
return err
}
// Otherwise, get an up-to-date copy of the resource we're trying to update
// (because it may have changed if we're looping and in a race)
newCurObj := t.singularShell("", "")
if err := t.Get(ctx, key, "", newCurObj, ignoreNotFound); err != nil {
glog.Errorf("getting new current object (%s)", err)
return err
}
newCurState, err := t.getStateFromObject(newCurObj)
if err != nil {
glog.Errorf("getting state from new current object (%s)", err)
return err
}
// If the new current version of the object is the same as the old current
// then proceed with trying to PUT the candidate to the core apiserver
if newCurState.rev == curState.rev {
ns, name, err := t.decodeKey(key)
if err != nil {
glog.Errorf("decoding key %s (%s)", key, err)
return err
}
putReq := t.cl.Put().AbsPath(
"apis",
groupName,
tprVersion,
"namespaces",
ns,
t.singularKind.URLName(),
name,
).Body(candidateData)
putRes := putReq.Do()
if putRes.Error() != nil {
glog.Errorf("executing PUT to %s/%s (%s)", ns, name, putRes.Error())
return err
}
var statusCode int
putRes.StatusCode(&statusCode)
if statusCode != http.StatusOK {
return fmt.Errorf(
"executing PUT for %s/%s, received response code %d",
ns,
name,
statusCode,
)
}
var putUnknown runtime.Unknown
if err := putRes.Into(&putUnknown); err != nil {
glog.Errorf("reading response (%s)", err)
return err
}
if err := decode(t.codec, putUnknown.Raw, out); err != nil {
glog.Errorf("decoding response (%s)", err)
return err
}
} else {
glog.V(4).Infof(
"GuaranteedUpdate of %s failed because of a conflict, going to retry",
key,
)
curState = newCurState
continue
}
return nil
}
}
func decode(
codec runtime.Codec,
value []byte,
objPtr runtime.Object,
) error {
if _, err := conversion.EnforcePtr(objPtr); err != nil {
panic("unable to convert output object to pointer")
}
_, _, err := codec.Decode(value, nil, objPtr)
if err != nil {
return err
}
return nil
}
func removeNamespace(obj runtime.Object) error {
if err := accessor.SetNamespace(obj, ""); err != nil {
glog.Errorf("removing namespace from %#v (%s)", obj, err)
return err
}
return nil
}
func checkPreconditions(
key string,
preconditions *storage.Preconditions,
out runtime.Object,
) error {
if preconditions == nil {
return nil
}
objMeta, err := v1.ObjectMetaFor(out)
if err != nil {
return storage.NewInternalErrorf(
"can't enforce preconditions %v on un-introspectable object %v, got error: %v",
*preconditions, out, err,
)
}
if preconditions.UID != nil && *preconditions.UID != objMeta.UID {
errMsg := fmt.Sprintf(
"Precondition failed: UID in precondition: %v, UID in object meta: %v",
*preconditions.UID, objMeta.UID,
)
return storage.NewInvalidObjError(key, errMsg)
}
return nil
}