forked from kubernetes/kubernetes
-
Notifications
You must be signed in to change notification settings - Fork 0
/
codec.go
574 lines (506 loc) · 18.1 KB
/
codec.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
/*
Copyright 2015 The Kubernetes Authors 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
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 thirdpartyresourcedata
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/url"
"strings"
"k8s.io/kubernetes/pkg/api"
"k8s.io/kubernetes/pkg/api/meta"
"k8s.io/kubernetes/pkg/api/unversioned"
apiutil "k8s.io/kubernetes/pkg/api/util"
"k8s.io/kubernetes/pkg/api/v1"
"k8s.io/kubernetes/pkg/apimachinery/registered"
"k8s.io/kubernetes/pkg/apis/extensions"
"k8s.io/kubernetes/pkg/apis/extensions/v1beta1"
"k8s.io/kubernetes/pkg/runtime"
"k8s.io/kubernetes/pkg/util/sets"
"k8s.io/kubernetes/pkg/util/yaml"
"k8s.io/kubernetes/pkg/watch/versioned"
)
type thirdPartyObjectConverter struct {
converter runtime.ObjectConvertor
}
func (t *thirdPartyObjectConverter) ConvertToVersion(in runtime.Object, outVersion unversioned.GroupVersion) (out runtime.Object, err error) {
switch in.(type) {
// This seems weird, but in this case the ThirdPartyResourceData is really just a wrapper on the raw 3rd party data.
// The actual thing printed/sent to server is the actual raw third party resource data, which only has one version.
case *extensions.ThirdPartyResourceData:
return in, nil
default:
return t.converter.ConvertToVersion(in, outVersion)
}
}
func (t *thirdPartyObjectConverter) Convert(in, out interface{}) error {
return t.converter.Convert(in, out)
}
func (t *thirdPartyObjectConverter) ConvertFieldLabel(version, kind, label, value string) (string, string, error) {
return t.converter.ConvertFieldLabel(version, kind, label, value)
}
func NewThirdPartyObjectConverter(converter runtime.ObjectConvertor) runtime.ObjectConvertor {
return &thirdPartyObjectConverter{converter}
}
type thirdPartyResourceDataMapper struct {
mapper meta.RESTMapper
kind string
version string
group string
}
var _ meta.RESTMapper = &thirdPartyResourceDataMapper{}
func (t *thirdPartyResourceDataMapper) getResource() unversioned.GroupVersionResource {
plural, _ := meta.KindToResource(t.getKind())
return plural
}
func (t *thirdPartyResourceDataMapper) getKind() unversioned.GroupVersionKind {
return unversioned.GroupVersionKind{Group: t.group, Version: t.version, Kind: t.kind}
}
func (t *thirdPartyResourceDataMapper) isThirdPartyResource(partialResource unversioned.GroupVersionResource) bool {
actualResource := t.getResource()
if strings.ToLower(partialResource.Resource) != strings.ToLower(actualResource.Resource) {
return false
}
if len(partialResource.Group) != 0 && partialResource.Group != actualResource.Group {
return false
}
if len(partialResource.Version) != 0 && partialResource.Version != actualResource.Version {
return false
}
return true
}
func (t *thirdPartyResourceDataMapper) ResourcesFor(resource unversioned.GroupVersionResource) ([]unversioned.GroupVersionResource, error) {
if t.isThirdPartyResource(resource) {
return []unversioned.GroupVersionResource{t.getResource()}, nil
}
return t.mapper.ResourcesFor(resource)
}
func (t *thirdPartyResourceDataMapper) KindsFor(resource unversioned.GroupVersionResource) ([]unversioned.GroupVersionKind, error) {
if t.isThirdPartyResource(resource) {
return []unversioned.GroupVersionKind{t.getKind()}, nil
}
return t.mapper.KindsFor(resource)
}
func (t *thirdPartyResourceDataMapper) ResourceFor(resource unversioned.GroupVersionResource) (unversioned.GroupVersionResource, error) {
if t.isThirdPartyResource(resource) {
return t.getResource(), nil
}
return t.mapper.ResourceFor(resource)
}
func (t *thirdPartyResourceDataMapper) KindFor(resource unversioned.GroupVersionResource) (unversioned.GroupVersionKind, error) {
if t.isThirdPartyResource(resource) {
return t.getKind(), nil
}
return t.mapper.KindFor(resource)
}
func (t *thirdPartyResourceDataMapper) RESTMapping(gk unversioned.GroupKind, versions ...string) (*meta.RESTMapping, error) {
if len(versions) != 1 {
return nil, fmt.Errorf("unexpected set of versions: %v", versions)
}
if gk.Group != t.group {
return nil, fmt.Errorf("unknown group %q expected %s", gk.Group, t.group)
}
if gk.Kind != "ThirdPartyResourceData" {
return nil, fmt.Errorf("unknown kind %s expected %s", gk.Kind, t.kind)
}
if versions[0] != t.version {
return nil, fmt.Errorf("unknown version %q expected %q", versions[0], t.version)
}
// TODO figure out why we're doing this rewriting
extensionGK := unversioned.GroupKind{Group: extensions.GroupName, Kind: "ThirdPartyResourceData"}
mapping, err := t.mapper.RESTMapping(extensionGK, registered.GroupOrDie(extensions.GroupName).GroupVersion.Version)
if err != nil {
return nil, err
}
mapping.ObjectConvertor = &thirdPartyObjectConverter{mapping.ObjectConvertor}
return mapping, nil
}
func (t *thirdPartyResourceDataMapper) AliasesForResource(resource string) ([]string, bool) {
return t.mapper.AliasesForResource(resource)
}
func (t *thirdPartyResourceDataMapper) ResourceSingularizer(resource string) (singular string, err error) {
return t.mapper.ResourceSingularizer(resource)
}
func NewMapper(mapper meta.RESTMapper, kind, version, group string) meta.RESTMapper {
return &thirdPartyResourceDataMapper{
mapper: mapper,
kind: kind,
version: version,
group: group,
}
}
type thirdPartyResourceDataCodecFactory struct {
delegate runtime.NegotiatedSerializer
kind string
encodeGV unversioned.GroupVersion
decodeGV unversioned.GroupVersion
}
func NewNegotiatedSerializer(s runtime.NegotiatedSerializer, kind string, encodeGV, decodeGV unversioned.GroupVersion) runtime.NegotiatedSerializer {
return &thirdPartyResourceDataCodecFactory{
delegate: s,
kind: kind,
encodeGV: encodeGV,
decodeGV: decodeGV,
}
}
func (t *thirdPartyResourceDataCodecFactory) SupportedMediaTypes() []string {
supported := sets.NewString(t.delegate.SupportedMediaTypes()...)
return supported.Intersection(sets.NewString("application/json", "application/yaml")).List()
}
func (t *thirdPartyResourceDataCodecFactory) SerializerForMediaType(mediaType string, params map[string]string) (runtime.SerializerInfo, bool) {
switch mediaType {
case "application/json", "application/yaml":
return t.delegate.SerializerForMediaType(mediaType, params)
default:
return runtime.SerializerInfo{}, false
}
}
func (t *thirdPartyResourceDataCodecFactory) SupportedStreamingMediaTypes() []string {
supported := sets.NewString(t.delegate.SupportedStreamingMediaTypes()...)
return supported.Intersection(sets.NewString("application/json", "application/json;stream=watch")).List()
}
func (t *thirdPartyResourceDataCodecFactory) StreamingSerializerForMediaType(mediaType string, params map[string]string) (runtime.StreamSerializerInfo, bool) {
switch mediaType {
case "application/json", "application/json;stream=watch":
return t.delegate.StreamingSerializerForMediaType(mediaType, params)
default:
return runtime.StreamSerializerInfo{}, false
}
}
func (t *thirdPartyResourceDataCodecFactory) EncoderForVersion(s runtime.Encoder, gv unversioned.GroupVersion) runtime.Encoder {
return &thirdPartyResourceDataEncoder{delegate: t.delegate.EncoderForVersion(s, gv), gvk: gv.WithKind(t.kind)}
}
func (t *thirdPartyResourceDataCodecFactory) DecoderToVersion(s runtime.Decoder, gv unversioned.GroupVersion) runtime.Decoder {
return NewDecoder(t.delegate.DecoderToVersion(s, gv), t.kind)
}
func NewCodec(delegate runtime.Codec, gvk unversioned.GroupVersionKind) runtime.Codec {
return runtime.NewCodec(NewEncoder(delegate, gvk), NewDecoder(delegate, gvk.Kind))
}
type thirdPartyResourceDataDecoder struct {
delegate runtime.Decoder
kind string
}
func NewDecoder(delegate runtime.Decoder, kind string) runtime.Decoder {
return &thirdPartyResourceDataDecoder{delegate: delegate, kind: kind}
}
var _ runtime.Decoder = &thirdPartyResourceDataDecoder{}
func parseObject(data []byte) (map[string]interface{}, error) {
var obj interface{}
if err := json.Unmarshal(data, &obj); err != nil {
return nil, err
}
mapObj, ok := obj.(map[string]interface{})
if !ok {
return nil, fmt.Errorf("unexpected object: %#v", obj)
}
return mapObj, nil
}
func (t *thirdPartyResourceDataDecoder) populate(data []byte) (runtime.Object, error) {
mapObj, err := parseObject(data)
if err != nil {
return nil, err
}
return t.populateFromObject(mapObj, data)
}
func (t *thirdPartyResourceDataDecoder) populateFromObject(mapObj map[string]interface{}, data []byte) (runtime.Object, error) {
typeMeta := unversioned.TypeMeta{}
if err := json.Unmarshal(data, &typeMeta); err != nil {
return nil, err
}
isList := strings.HasSuffix(typeMeta.Kind, "List")
switch {
case !isList && (len(t.kind) == 0 || typeMeta.Kind == t.kind):
result := &extensions.ThirdPartyResourceData{}
if err := t.populateResource(result, mapObj, data); err != nil {
return nil, err
}
return result, nil
case isList && (len(t.kind) == 0 || typeMeta.Kind == t.kind+"List"):
list := &extensions.ThirdPartyResourceDataList{}
if err := t.populateListResource(list, mapObj); err != nil {
return nil, err
}
return list, nil
default:
return nil, fmt.Errorf("unexpected kind: %s, expected %s", typeMeta.Kind, t.kind)
}
}
func (t *thirdPartyResourceDataDecoder) populateResource(objIn *extensions.ThirdPartyResourceData, mapObj map[string]interface{}, data []byte) error {
metadata, ok := mapObj["metadata"].(map[string]interface{})
if !ok {
return fmt.Errorf("unexpected object for metadata: %#v", mapObj["metadata"])
}
metadataData, err := json.Marshal(metadata)
if err != nil {
return err
}
if err := json.Unmarshal(metadataData, &objIn.ObjectMeta); err != nil {
return err
}
// Override API Version with the ThirdPartyResourceData value
// TODO: fix this hard code
objIn.APIVersion = v1beta1.SchemeGroupVersion.String()
objIn.Data = data
return nil
}
func IsThirdPartyObject(rawData []byte, gvk *unversioned.GroupVersionKind) (isThirdParty bool, gvkOut *unversioned.GroupVersionKind, err error) {
var gv unversioned.GroupVersion
if gvk == nil {
data, err := yaml.ToJSON(rawData)
if err != nil {
return false, nil, err
}
metadata := unversioned.TypeMeta{}
if err = json.Unmarshal(data, &metadata); err != nil {
return false, nil, err
}
gv, err = unversioned.ParseGroupVersion(metadata.APIVersion)
if err != nil {
return false, nil, err
}
gvkOut = &unversioned.GroupVersionKind{
Group: gv.Group,
Version: gv.Version,
Kind: metadata.Kind,
}
} else {
gv = gvk.GroupVersion()
gvkOut = gvk
}
return registered.IsThirdPartyAPIGroupVersion(gv), gvkOut, nil
}
func (t *thirdPartyResourceDataDecoder) Decode(data []byte, gvk *unversioned.GroupVersionKind, into runtime.Object) (runtime.Object, *unversioned.GroupVersionKind, error) {
if into == nil {
if gvk == nil || gvk.Kind != t.kind {
if isThirdParty, _, err := IsThirdPartyObject(data, gvk); err != nil {
return nil, nil, err
} else if !isThirdParty {
return t.delegate.Decode(data, gvk, into)
}
}
obj, err := t.populate(data)
if err != nil {
return nil, nil, err
}
return obj, gvk, nil
}
switch o := into.(type) {
case *extensions.ThirdPartyResourceData:
break
case *runtime.VersionedObjects:
// We're not sure that it's third party, we need to test
if gvk == nil || gvk.Kind != t.kind {
if isThirdParty, _, err := IsThirdPartyObject(data, gvk); err != nil {
return nil, nil, err
} else if !isThirdParty {
return t.delegate.Decode(data, gvk, into)
}
}
obj, err := t.populate(data)
if err != nil {
return nil, nil, err
}
o.Objects = []runtime.Object{
obj,
}
return o, gvk, nil
default:
return t.delegate.Decode(data, gvk, into)
}
thirdParty := into.(*extensions.ThirdPartyResourceData)
var dataObj interface{}
if err := json.Unmarshal(data, &dataObj); err != nil {
return nil, nil, err
}
mapObj, ok := dataObj.(map[string]interface{})
if !ok {
return nil, nil, fmt.Errorf("unexpected object: %#v", dataObj)
}
/*if gvk.Kind != "ThirdPartyResourceData" {
return nil, nil, fmt.Errorf("unexpected kind: %s", gvk.Kind)
}*/
actual := &unversioned.GroupVersionKind{}
if kindObj, found := mapObj["kind"]; !found {
if gvk == nil {
return nil, nil, runtime.NewMissingKindErr(string(data))
}
mapObj["kind"] = gvk.Kind
actual.Kind = gvk.Kind
} else {
kindStr, ok := kindObj.(string)
if !ok {
return nil, nil, fmt.Errorf("unexpected object for 'kind': %v", kindObj)
}
if len(t.kind) > 0 && kindStr != t.kind {
return nil, nil, fmt.Errorf("kind doesn't match, expecting: %s, got %s", gvk.Kind, kindStr)
}
actual.Kind = kindStr
}
if versionObj, found := mapObj["apiVersion"]; !found {
if gvk == nil {
return nil, nil, runtime.NewMissingVersionErr(string(data))
}
mapObj["apiVersion"] = gvk.GroupVersion().String()
actual.Group, actual.Version = gvk.Group, gvk.Version
} else {
versionStr, ok := versionObj.(string)
if !ok {
return nil, nil, fmt.Errorf("unexpected object for 'apiVersion': %v", versionObj)
}
if gvk != nil && versionStr != gvk.GroupVersion().String() {
return nil, nil, fmt.Errorf("version doesn't match, expecting: %v, got %s", gvk.GroupVersion(), versionStr)
}
gv, err := unversioned.ParseGroupVersion(versionStr)
if err != nil {
return nil, nil, err
}
actual.Group, actual.Version = gv.Group, gv.Version
}
mapObj, err := parseObject(data)
if err != nil {
return nil, actual, err
}
if err := t.populateResource(thirdParty, mapObj, data); err != nil {
return nil, actual, err
}
return thirdParty, actual, nil
}
func (t *thirdPartyResourceDataDecoder) populateListResource(objIn *extensions.ThirdPartyResourceDataList, mapObj map[string]interface{}) error {
items, ok := mapObj["items"].([]interface{})
if !ok {
return fmt.Errorf("unexpected object for items: %#v", mapObj["items"])
}
objIn.Items = make([]extensions.ThirdPartyResourceData, len(items))
for ix := range items {
objData, err := json.Marshal(items[ix])
if err != nil {
return err
}
objMap, err := parseObject(objData)
if err != nil {
return err
}
if err := t.populateResource(&objIn.Items[ix], objMap, objData); err != nil {
return err
}
}
return nil
}
const template = `{
"kind": "%s",
"apiVersion": "%s",
"metadata": {},
"items": [ %s ]
}`
type thirdPartyResourceDataEncoder struct {
delegate runtime.Encoder
gvk unversioned.GroupVersionKind
}
func NewEncoder(delegate runtime.Encoder, gvk unversioned.GroupVersionKind) runtime.Encoder {
return &thirdPartyResourceDataEncoder{delegate: delegate, gvk: gvk}
}
var _ runtime.Encoder = &thirdPartyResourceDataEncoder{}
func encodeToJSON(obj *extensions.ThirdPartyResourceData, stream io.Writer) error {
var objOut interface{}
if err := json.Unmarshal(obj.Data, &objOut); err != nil {
return err
}
objMap, ok := objOut.(map[string]interface{})
if !ok {
return fmt.Errorf("unexpected type: %v", objOut)
}
objMap["metadata"] = obj.ObjectMeta
encoder := json.NewEncoder(stream)
return encoder.Encode(objMap)
}
func (t *thirdPartyResourceDataEncoder) Encode(obj runtime.Object, stream io.Writer) (err error) {
switch obj := obj.(type) {
case *extensions.ThirdPartyResourceData:
return encodeToJSON(obj, stream)
case *extensions.ThirdPartyResourceDataList:
// TODO: There must be a better way to do this...
dataStrings := make([]string, len(obj.Items))
for ix := range obj.Items {
buff := &bytes.Buffer{}
err := encodeToJSON(&obj.Items[ix], buff)
if err != nil {
return err
}
dataStrings[ix] = buff.String()
}
gv := t.gvk.GroupVersion()
fmt.Fprintf(stream, template, t.gvk.Kind+"List", gv.String(), strings.Join(dataStrings, ","))
return nil
case *versioned.InternalEvent:
event := &versioned.Event{}
err := versioned.Convert_versioned_InternalEvent_to_versioned_Event(obj, event, nil)
if err != nil {
return err
}
enc := json.NewEncoder(stream)
err = enc.Encode(event)
if err != nil {
return err
}
return nil
case *unversioned.Status, *unversioned.APIResourceList:
return t.delegate.Encode(obj, stream)
default:
return fmt.Errorf("unexpected object to encode: %#v", obj)
}
}
func NewObjectCreator(group, version string, delegate runtime.ObjectCreater) runtime.ObjectCreater {
return &thirdPartyResourceDataCreator{group, version, delegate}
}
type thirdPartyResourceDataCreator struct {
group string
version string
delegate runtime.ObjectCreater
}
func (t *thirdPartyResourceDataCreator) New(kind unversioned.GroupVersionKind) (out runtime.Object, err error) {
switch kind.Kind {
case "ThirdPartyResourceData":
if apiutil.GetGroupVersion(t.group, t.version) != kind.GroupVersion().String() {
return nil, fmt.Errorf("unknown kind %v", kind)
}
return &extensions.ThirdPartyResourceData{}, nil
case "ThirdPartyResourceDataList":
if apiutil.GetGroupVersion(t.group, t.version) != kind.GroupVersion().String() {
return nil, fmt.Errorf("unknown kind %v", kind)
}
return &extensions.ThirdPartyResourceDataList{}, nil
// TODO: this list needs to be formalized higher in the chain
case "ListOptions", "WatchEvent":
if apiutil.GetGroupVersion(t.group, t.version) == kind.GroupVersion().String() {
// Translate third party group to external group.
gvk := registered.EnabledVersionsForGroup(api.GroupName)[0].WithKind(kind.Kind)
return t.delegate.New(gvk)
}
return t.delegate.New(kind)
default:
return t.delegate.New(kind)
}
}
func NewThirdPartyParameterCodec(p runtime.ParameterCodec) runtime.ParameterCodec {
return &thirdPartyParameterCodec{p}
}
type thirdPartyParameterCodec struct {
delegate runtime.ParameterCodec
}
func (t *thirdPartyParameterCodec) DecodeParameters(parameters url.Values, from unversioned.GroupVersion, into runtime.Object) error {
return t.delegate.DecodeParameters(parameters, v1.SchemeGroupVersion, into)
}
func (t *thirdPartyParameterCodec) EncodeParameters(obj runtime.Object, to unversioned.GroupVersion) (url.Values, error) {
return t.delegate.EncodeParameters(obj, v1.SchemeGroupVersion)
}