blob: 81a13d64a00d22d9856cd0d310dbd35d3f090836 [file] [log] [blame]
Matthias Andreas Benkard832a54e2019-01-29 09:27:38 +01001/*
2Copyright 2017 The Kubernetes Authors.
3
4Licensed under the Apache License, Version 2.0 (the "License");
5you may not use this file except in compliance with the License.
6You may obtain a copy of the License at
7
8 http://www.apache.org/licenses/LICENSE-2.0
9
10Unless required by applicable law or agreed to in writing, software
11distributed under the License is distributed on an "AS IS" BASIS,
12WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13See the License for the specific language governing permissions and
14limitations under the License.
15*/
16
17package discovery
18
19import (
20 "bytes"
21 "fmt"
22 "io"
23
24 "k8s.io/apimachinery/pkg/runtime"
25)
26
27const APIGroupPrefix = "/apis"
28
29func keepUnversioned(group string) bool {
30 return group == "" || group == "extensions"
31}
32
33// stripVersionEncoder strips APIVersion field from the encoding output. It's
34// used to keep the responses at the discovery endpoints backward compatible
35// with release-1.1, when the responses have empty APIVersion.
36type stripVersionEncoder struct {
37 encoder runtime.Encoder
38 serializer runtime.Serializer
39}
40
41func (c stripVersionEncoder) Encode(obj runtime.Object, w io.Writer) error {
42 buf := bytes.NewBuffer([]byte{})
43 err := c.encoder.Encode(obj, buf)
44 if err != nil {
45 return err
46 }
47 roundTrippedObj, gvk, err := c.serializer.Decode(buf.Bytes(), nil, nil)
48 if err != nil {
49 return err
50 }
51 gvk.Group = ""
52 gvk.Version = ""
53 roundTrippedObj.GetObjectKind().SetGroupVersionKind(*gvk)
54 return c.serializer.Encode(roundTrippedObj, w)
55}
56
57// stripVersionNegotiatedSerializer will return stripVersionEncoder when
58// EncoderForVersion is called. See comments for stripVersionEncoder.
59type stripVersionNegotiatedSerializer struct {
60 runtime.NegotiatedSerializer
61}
62
63func (n stripVersionNegotiatedSerializer) EncoderForVersion(encoder runtime.Encoder, gv runtime.GroupVersioner) runtime.Encoder {
64 serializer, ok := encoder.(runtime.Serializer)
65 if !ok {
66 // The stripVersionEncoder needs both an encoder and decoder, but is called from a context that doesn't have access to the
67 // decoder. We do a best effort cast here (since this code path is only for backwards compatibility) to get access to the caller's
68 // decoder.
69 panic(fmt.Sprintf("Unable to extract serializer from %#v", encoder))
70 }
71 versioned := n.NegotiatedSerializer.EncoderForVersion(encoder, gv)
72 return stripVersionEncoder{versioned, serializer}
73}