codec.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330
  1. /*
  2. Copyright 2014 The Kubernetes Authors.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package runtime
  14. import (
  15. "bytes"
  16. "encoding/base64"
  17. "fmt"
  18. "io"
  19. "net/url"
  20. "reflect"
  21. "k8s.io/apimachinery/pkg/conversion/queryparams"
  22. "k8s.io/apimachinery/pkg/runtime/schema"
  23. )
  24. // codec binds an encoder and decoder.
  25. type codec struct {
  26. Encoder
  27. Decoder
  28. }
  29. // NewCodec creates a Codec from an Encoder and Decoder.
  30. func NewCodec(e Encoder, d Decoder) Codec {
  31. return codec{e, d}
  32. }
  33. // Encode is a convenience wrapper for encoding to a []byte from an Encoder
  34. func Encode(e Encoder, obj Object) ([]byte, error) {
  35. // TODO: reuse buffer
  36. buf := &bytes.Buffer{}
  37. if err := e.Encode(obj, buf); err != nil {
  38. return nil, err
  39. }
  40. return buf.Bytes(), nil
  41. }
  42. // Decode is a convenience wrapper for decoding data into an Object.
  43. func Decode(d Decoder, data []byte) (Object, error) {
  44. obj, _, err := d.Decode(data, nil, nil)
  45. return obj, err
  46. }
  47. // DecodeInto performs a Decode into the provided object.
  48. func DecodeInto(d Decoder, data []byte, into Object) error {
  49. out, gvk, err := d.Decode(data, nil, into)
  50. if err != nil {
  51. return err
  52. }
  53. if out != into {
  54. return fmt.Errorf("unable to decode %s into %v", gvk, reflect.TypeOf(into))
  55. }
  56. return nil
  57. }
  58. // EncodeOrDie is a version of Encode which will panic instead of returning an error. For tests.
  59. func EncodeOrDie(e Encoder, obj Object) string {
  60. bytes, err := Encode(e, obj)
  61. if err != nil {
  62. panic(err)
  63. }
  64. return string(bytes)
  65. }
  66. // DefaultingSerializer invokes defaulting after decoding.
  67. type DefaultingSerializer struct {
  68. Defaulter ObjectDefaulter
  69. Decoder Decoder
  70. // Encoder is optional to allow this type to be used as both a Decoder and an Encoder
  71. Encoder
  72. }
  73. // Decode performs a decode and then allows the defaulter to act on the provided object.
  74. func (d DefaultingSerializer) Decode(data []byte, defaultGVK *schema.GroupVersionKind, into Object) (Object, *schema.GroupVersionKind, error) {
  75. obj, gvk, err := d.Decoder.Decode(data, defaultGVK, into)
  76. if err != nil {
  77. return obj, gvk, err
  78. }
  79. d.Defaulter.Default(obj)
  80. return obj, gvk, nil
  81. }
  82. // UseOrCreateObject returns obj if the canonical ObjectKind returned by the provided typer matches gvk, or
  83. // invokes the ObjectCreator to instantiate a new gvk. Returns an error if the typer cannot find the object.
  84. func UseOrCreateObject(t ObjectTyper, c ObjectCreater, gvk schema.GroupVersionKind, obj Object) (Object, error) {
  85. if obj != nil {
  86. kinds, _, err := t.ObjectKinds(obj)
  87. if err != nil {
  88. return nil, err
  89. }
  90. for _, kind := range kinds {
  91. if gvk == kind {
  92. return obj, nil
  93. }
  94. }
  95. }
  96. return c.New(gvk)
  97. }
  98. // NoopEncoder converts an Decoder to a Serializer or Codec for code that expects them but only uses decoding.
  99. type NoopEncoder struct {
  100. Decoder
  101. }
  102. var _ Serializer = NoopEncoder{}
  103. func (n NoopEncoder) Encode(obj Object, w io.Writer) error {
  104. return fmt.Errorf("encoding is not allowed for this codec: %v", reflect.TypeOf(n.Decoder))
  105. }
  106. // NoopDecoder converts an Encoder to a Serializer or Codec for code that expects them but only uses encoding.
  107. type NoopDecoder struct {
  108. Encoder
  109. }
  110. var _ Serializer = NoopDecoder{}
  111. func (n NoopDecoder) Decode(data []byte, gvk *schema.GroupVersionKind, into Object) (Object, *schema.GroupVersionKind, error) {
  112. return nil, nil, fmt.Errorf("decoding is not allowed for this codec: %v", reflect.TypeOf(n.Encoder))
  113. }
  114. // NewParameterCodec creates a ParameterCodec capable of transforming url values into versioned objects and back.
  115. func NewParameterCodec(scheme *Scheme) ParameterCodec {
  116. return &parameterCodec{
  117. typer: scheme,
  118. convertor: scheme,
  119. creator: scheme,
  120. defaulter: scheme,
  121. }
  122. }
  123. // parameterCodec implements conversion to and from query parameters and objects.
  124. type parameterCodec struct {
  125. typer ObjectTyper
  126. convertor ObjectConvertor
  127. creator ObjectCreater
  128. defaulter ObjectDefaulter
  129. }
  130. var _ ParameterCodec = &parameterCodec{}
  131. // DecodeParameters converts the provided url.Values into an object of type From with the kind of into, and then
  132. // converts that object to into (if necessary). Returns an error if the operation cannot be completed.
  133. func (c *parameterCodec) DecodeParameters(parameters url.Values, from schema.GroupVersion, into Object) error {
  134. if len(parameters) == 0 {
  135. return nil
  136. }
  137. targetGVKs, _, err := c.typer.ObjectKinds(into)
  138. if err != nil {
  139. return err
  140. }
  141. for i := range targetGVKs {
  142. if targetGVKs[i].GroupVersion() == from {
  143. if err := c.convertor.Convert(&parameters, into, nil); err != nil {
  144. return err
  145. }
  146. // in the case where we going into the same object we're receiving, default on the outbound object
  147. if c.defaulter != nil {
  148. c.defaulter.Default(into)
  149. }
  150. return nil
  151. }
  152. }
  153. input, err := c.creator.New(from.WithKind(targetGVKs[0].Kind))
  154. if err != nil {
  155. return err
  156. }
  157. if err := c.convertor.Convert(&parameters, input, nil); err != nil {
  158. return err
  159. }
  160. // if we have defaulter, default the input before converting to output
  161. if c.defaulter != nil {
  162. c.defaulter.Default(input)
  163. }
  164. return c.convertor.Convert(input, into, nil)
  165. }
  166. // EncodeParameters converts the provided object into the to version, then converts that object to url.Values.
  167. // Returns an error if conversion is not possible.
  168. func (c *parameterCodec) EncodeParameters(obj Object, to schema.GroupVersion) (url.Values, error) {
  169. gvks, _, err := c.typer.ObjectKinds(obj)
  170. if err != nil {
  171. return nil, err
  172. }
  173. gvk := gvks[0]
  174. if to != gvk.GroupVersion() {
  175. out, err := c.convertor.ConvertToVersion(obj, to)
  176. if err != nil {
  177. return nil, err
  178. }
  179. obj = out
  180. }
  181. return queryparams.Convert(obj)
  182. }
  183. type base64Serializer struct {
  184. Encoder
  185. Decoder
  186. }
  187. func NewBase64Serializer(e Encoder, d Decoder) Serializer {
  188. return &base64Serializer{e, d}
  189. }
  190. func (s base64Serializer) Encode(obj Object, stream io.Writer) error {
  191. e := base64.NewEncoder(base64.StdEncoding, stream)
  192. err := s.Encoder.Encode(obj, e)
  193. e.Close()
  194. return err
  195. }
  196. func (s base64Serializer) Decode(data []byte, defaults *schema.GroupVersionKind, into Object) (Object, *schema.GroupVersionKind, error) {
  197. out := make([]byte, base64.StdEncoding.DecodedLen(len(data)))
  198. n, err := base64.StdEncoding.Decode(out, data)
  199. if err != nil {
  200. return nil, nil, err
  201. }
  202. return s.Decoder.Decode(out[:n], defaults, into)
  203. }
  204. // SerializerInfoForMediaType returns the first info in types that has a matching media type (which cannot
  205. // include media-type parameters), or the first info with an empty media type, or false if no type matches.
  206. func SerializerInfoForMediaType(types []SerializerInfo, mediaType string) (SerializerInfo, bool) {
  207. for _, info := range types {
  208. if info.MediaType == mediaType {
  209. return info, true
  210. }
  211. }
  212. for _, info := range types {
  213. if len(info.MediaType) == 0 {
  214. return info, true
  215. }
  216. }
  217. return SerializerInfo{}, false
  218. }
  219. var (
  220. // InternalGroupVersioner will always prefer the internal version for a given group version kind.
  221. InternalGroupVersioner GroupVersioner = internalGroupVersioner{}
  222. // DisabledGroupVersioner will reject all kinds passed to it.
  223. DisabledGroupVersioner GroupVersioner = disabledGroupVersioner{}
  224. )
  225. type internalGroupVersioner struct{}
  226. // KindForGroupVersionKinds returns an internal Kind if one is found, or converts the first provided kind to the internal version.
  227. func (internalGroupVersioner) KindForGroupVersionKinds(kinds []schema.GroupVersionKind) (schema.GroupVersionKind, bool) {
  228. for _, kind := range kinds {
  229. if kind.Version == APIVersionInternal {
  230. return kind, true
  231. }
  232. }
  233. for _, kind := range kinds {
  234. return schema.GroupVersionKind{Group: kind.Group, Version: APIVersionInternal, Kind: kind.Kind}, true
  235. }
  236. return schema.GroupVersionKind{}, false
  237. }
  238. type disabledGroupVersioner struct{}
  239. // KindForGroupVersionKinds returns false for any input.
  240. func (disabledGroupVersioner) KindForGroupVersionKinds(kinds []schema.GroupVersionKind) (schema.GroupVersionKind, bool) {
  241. return schema.GroupVersionKind{}, false
  242. }
  243. // GroupVersioners implements GroupVersioner and resolves to the first exact match for any kind.
  244. type GroupVersioners []GroupVersioner
  245. // KindForGroupVersionKinds returns the first match of any of the group versioners, or false if no match occurred.
  246. func (gvs GroupVersioners) KindForGroupVersionKinds(kinds []schema.GroupVersionKind) (schema.GroupVersionKind, bool) {
  247. for _, gv := range gvs {
  248. target, ok := gv.KindForGroupVersionKinds(kinds)
  249. if !ok {
  250. continue
  251. }
  252. return target, true
  253. }
  254. return schema.GroupVersionKind{}, false
  255. }
  256. // Assert that schema.GroupVersion and GroupVersions implement GroupVersioner
  257. var _ GroupVersioner = schema.GroupVersion{}
  258. var _ GroupVersioner = schema.GroupVersions{}
  259. var _ GroupVersioner = multiGroupVersioner{}
  260. type multiGroupVersioner struct {
  261. target schema.GroupVersion
  262. acceptedGroupKinds []schema.GroupKind
  263. }
  264. // NewMultiGroupVersioner returns the provided group version for any kind that matches one of the provided group kinds.
  265. // Kind may be empty in the provided group kind, in which case any kind will match.
  266. func NewMultiGroupVersioner(gv schema.GroupVersion, groupKinds ...schema.GroupKind) GroupVersioner {
  267. if len(groupKinds) == 0 || (len(groupKinds) == 1 && groupKinds[0].Group == gv.Group) {
  268. return gv
  269. }
  270. return multiGroupVersioner{target: gv, acceptedGroupKinds: groupKinds}
  271. }
  272. // KindForGroupVersionKinds returns the target group version if any kind matches any of the original group kinds. It will
  273. // use the originating kind where possible.
  274. func (v multiGroupVersioner) KindForGroupVersionKinds(kinds []schema.GroupVersionKind) (schema.GroupVersionKind, bool) {
  275. for _, src := range kinds {
  276. for _, kind := range v.acceptedGroupKinds {
  277. if kind.Group != src.Group {
  278. continue
  279. }
  280. if len(kind.Kind) > 0 && kind.Kind != src.Kind {
  281. continue
  282. }
  283. return v.target.WithKind(src.Kind), true
  284. }
  285. }
  286. return schema.GroupVersionKind{}, false
  287. }