codec.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332
  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. // UseOrCreateObject returns obj if the canonical ObjectKind returned by the provided typer matches gvk, or
  67. // invokes the ObjectCreator to instantiate a new gvk. Returns an error if the typer cannot find the object.
  68. func UseOrCreateObject(t ObjectTyper, c ObjectCreater, gvk schema.GroupVersionKind, obj Object) (Object, error) {
  69. if obj != nil {
  70. kinds, _, err := t.ObjectKinds(obj)
  71. if err != nil {
  72. return nil, err
  73. }
  74. for _, kind := range kinds {
  75. if gvk == kind {
  76. return obj, nil
  77. }
  78. }
  79. }
  80. return c.New(gvk)
  81. }
  82. // NoopEncoder converts an Decoder to a Serializer or Codec for code that expects them but only uses decoding.
  83. type NoopEncoder struct {
  84. Decoder
  85. }
  86. var _ Serializer = NoopEncoder{}
  87. func (n NoopEncoder) Encode(obj Object, w io.Writer) error {
  88. return fmt.Errorf("encoding is not allowed for this codec: %v", reflect.TypeOf(n.Decoder))
  89. }
  90. // NoopDecoder converts an Encoder to a Serializer or Codec for code that expects them but only uses encoding.
  91. type NoopDecoder struct {
  92. Encoder
  93. }
  94. var _ Serializer = NoopDecoder{}
  95. func (n NoopDecoder) Decode(data []byte, gvk *schema.GroupVersionKind, into Object) (Object, *schema.GroupVersionKind, error) {
  96. return nil, nil, fmt.Errorf("decoding is not allowed for this codec: %v", reflect.TypeOf(n.Encoder))
  97. }
  98. // NewParameterCodec creates a ParameterCodec capable of transforming url values into versioned objects and back.
  99. func NewParameterCodec(scheme *Scheme) ParameterCodec {
  100. return &parameterCodec{
  101. typer: scheme,
  102. convertor: scheme,
  103. creator: scheme,
  104. defaulter: scheme,
  105. }
  106. }
  107. // parameterCodec implements conversion to and from query parameters and objects.
  108. type parameterCodec struct {
  109. typer ObjectTyper
  110. convertor ObjectConvertor
  111. creator ObjectCreater
  112. defaulter ObjectDefaulter
  113. }
  114. var _ ParameterCodec = &parameterCodec{}
  115. // DecodeParameters converts the provided url.Values into an object of type From with the kind of into, and then
  116. // converts that object to into (if necessary). Returns an error if the operation cannot be completed.
  117. func (c *parameterCodec) DecodeParameters(parameters url.Values, from schema.GroupVersion, into Object) error {
  118. if len(parameters) == 0 {
  119. return nil
  120. }
  121. targetGVKs, _, err := c.typer.ObjectKinds(into)
  122. if err != nil {
  123. return err
  124. }
  125. for i := range targetGVKs {
  126. if targetGVKs[i].GroupVersion() == from {
  127. if err := c.convertor.Convert(&parameters, into, nil); err != nil {
  128. return err
  129. }
  130. // in the case where we going into the same object we're receiving, default on the outbound object
  131. if c.defaulter != nil {
  132. c.defaulter.Default(into)
  133. }
  134. return nil
  135. }
  136. }
  137. input, err := c.creator.New(from.WithKind(targetGVKs[0].Kind))
  138. if err != nil {
  139. return err
  140. }
  141. if err := c.convertor.Convert(&parameters, input, nil); err != nil {
  142. return err
  143. }
  144. // if we have defaulter, default the input before converting to output
  145. if c.defaulter != nil {
  146. c.defaulter.Default(input)
  147. }
  148. return c.convertor.Convert(input, into, nil)
  149. }
  150. // EncodeParameters converts the provided object into the to version, then converts that object to url.Values.
  151. // Returns an error if conversion is not possible.
  152. func (c *parameterCodec) EncodeParameters(obj Object, to schema.GroupVersion) (url.Values, error) {
  153. gvks, _, err := c.typer.ObjectKinds(obj)
  154. if err != nil {
  155. return nil, err
  156. }
  157. gvk := gvks[0]
  158. if to != gvk.GroupVersion() {
  159. out, err := c.convertor.ConvertToVersion(obj, to)
  160. if err != nil {
  161. return nil, err
  162. }
  163. obj = out
  164. }
  165. return queryparams.Convert(obj)
  166. }
  167. type base64Serializer struct {
  168. Encoder
  169. Decoder
  170. }
  171. func NewBase64Serializer(e Encoder, d Decoder) Serializer {
  172. return &base64Serializer{e, d}
  173. }
  174. func (s base64Serializer) Encode(obj Object, stream io.Writer) error {
  175. e := base64.NewEncoder(base64.StdEncoding, stream)
  176. err := s.Encoder.Encode(obj, e)
  177. e.Close()
  178. return err
  179. }
  180. func (s base64Serializer) Decode(data []byte, defaults *schema.GroupVersionKind, into Object) (Object, *schema.GroupVersionKind, error) {
  181. out := make([]byte, base64.StdEncoding.DecodedLen(len(data)))
  182. n, err := base64.StdEncoding.Decode(out, data)
  183. if err != nil {
  184. return nil, nil, err
  185. }
  186. return s.Decoder.Decode(out[:n], defaults, into)
  187. }
  188. // SerializerInfoForMediaType returns the first info in types that has a matching media type (which cannot
  189. // include media-type parameters), or the first info with an empty media type, or false if no type matches.
  190. func SerializerInfoForMediaType(types []SerializerInfo, mediaType string) (SerializerInfo, bool) {
  191. for _, info := range types {
  192. if info.MediaType == mediaType {
  193. return info, true
  194. }
  195. }
  196. for _, info := range types {
  197. if len(info.MediaType) == 0 {
  198. return info, true
  199. }
  200. }
  201. return SerializerInfo{}, false
  202. }
  203. var (
  204. // InternalGroupVersioner will always prefer the internal version for a given group version kind.
  205. InternalGroupVersioner GroupVersioner = internalGroupVersioner{}
  206. // DisabledGroupVersioner will reject all kinds passed to it.
  207. DisabledGroupVersioner GroupVersioner = disabledGroupVersioner{}
  208. )
  209. type internalGroupVersioner struct{}
  210. // KindForGroupVersionKinds returns an internal Kind if one is found, or converts the first provided kind to the internal version.
  211. func (internalGroupVersioner) KindForGroupVersionKinds(kinds []schema.GroupVersionKind) (schema.GroupVersionKind, bool) {
  212. for _, kind := range kinds {
  213. if kind.Version == APIVersionInternal {
  214. return kind, true
  215. }
  216. }
  217. for _, kind := range kinds {
  218. return schema.GroupVersionKind{Group: kind.Group, Version: APIVersionInternal, Kind: kind.Kind}, true
  219. }
  220. return schema.GroupVersionKind{}, false
  221. }
  222. type disabledGroupVersioner struct{}
  223. // KindForGroupVersionKinds returns false for any input.
  224. func (disabledGroupVersioner) KindForGroupVersionKinds(kinds []schema.GroupVersionKind) (schema.GroupVersionKind, bool) {
  225. return schema.GroupVersionKind{}, false
  226. }
  227. // GroupVersioners implements GroupVersioner and resolves to the first exact match for any kind.
  228. type GroupVersioners []GroupVersioner
  229. // KindForGroupVersionKinds returns the first match of any of the group versioners, or false if no match occurred.
  230. func (gvs GroupVersioners) KindForGroupVersionKinds(kinds []schema.GroupVersionKind) (schema.GroupVersionKind, bool) {
  231. for _, gv := range gvs {
  232. target, ok := gv.KindForGroupVersionKinds(kinds)
  233. if !ok {
  234. continue
  235. }
  236. return target, true
  237. }
  238. return schema.GroupVersionKind{}, false
  239. }
  240. // Assert that schema.GroupVersion and GroupVersions implement GroupVersioner
  241. var _ GroupVersioner = schema.GroupVersion{}
  242. var _ GroupVersioner = schema.GroupVersions{}
  243. var _ GroupVersioner = multiGroupVersioner{}
  244. type multiGroupVersioner struct {
  245. target schema.GroupVersion
  246. acceptedGroupKinds []schema.GroupKind
  247. coerce bool
  248. }
  249. // NewMultiGroupVersioner returns the provided group version for any kind that matches one of the provided group kinds.
  250. // Kind may be empty in the provided group kind, in which case any kind will match.
  251. func NewMultiGroupVersioner(gv schema.GroupVersion, groupKinds ...schema.GroupKind) GroupVersioner {
  252. if len(groupKinds) == 0 || (len(groupKinds) == 1 && groupKinds[0].Group == gv.Group) {
  253. return gv
  254. }
  255. return multiGroupVersioner{target: gv, acceptedGroupKinds: groupKinds}
  256. }
  257. // NewCoercingMultiGroupVersioner returns the provided group version for any incoming kind.
  258. // Incoming kinds that match the provided groupKinds are preferred.
  259. // Kind may be empty in the provided group kind, in which case any kind will match.
  260. // Examples:
  261. // gv=mygroup/__internal, groupKinds=mygroup/Foo, anothergroup/Bar
  262. // KindForGroupVersionKinds(yetanother/v1/Baz, anothergroup/v1/Bar) -> mygroup/__internal/Bar (matched preferred group/kind)
  263. //
  264. // gv=mygroup/__internal, groupKinds=mygroup, anothergroup
  265. // KindForGroupVersionKinds(yetanother/v1/Baz, anothergroup/v1/Bar) -> mygroup/__internal/Bar (matched preferred group)
  266. //
  267. // gv=mygroup/__internal, groupKinds=mygroup, anothergroup
  268. // KindForGroupVersionKinds(yetanother/v1/Baz, yetanother/v1/Bar) -> mygroup/__internal/Baz (no preferred group/kind match, uses first kind in list)
  269. func NewCoercingMultiGroupVersioner(gv schema.GroupVersion, groupKinds ...schema.GroupKind) GroupVersioner {
  270. return multiGroupVersioner{target: gv, acceptedGroupKinds: groupKinds, coerce: true}
  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. if v.coerce && len(kinds) > 0 {
  287. return v.target.WithKind(kinds[0].Kind), true
  288. }
  289. return schema.GroupVersionKind{}, false
  290. }