codec.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396
  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. "encoding/json"
  18. "fmt"
  19. "io"
  20. "net/url"
  21. "reflect"
  22. "strconv"
  23. "strings"
  24. "k8s.io/apimachinery/pkg/conversion/queryparams"
  25. "k8s.io/apimachinery/pkg/runtime/schema"
  26. "k8s.io/klog/v2"
  27. )
  28. // codec binds an encoder and decoder.
  29. type codec struct {
  30. Encoder
  31. Decoder
  32. }
  33. // NewCodec creates a Codec from an Encoder and Decoder.
  34. func NewCodec(e Encoder, d Decoder) Codec {
  35. return codec{e, d}
  36. }
  37. // Encode is a convenience wrapper for encoding to a []byte from an Encoder
  38. func Encode(e Encoder, obj Object) ([]byte, error) {
  39. buf := &bytes.Buffer{}
  40. if err := e.Encode(obj, buf); err != nil {
  41. return nil, err
  42. }
  43. return buf.Bytes(), nil
  44. }
  45. // Decode is a convenience wrapper for decoding data into an Object.
  46. func Decode(d Decoder, data []byte) (Object, error) {
  47. obj, _, err := d.Decode(data, nil, nil)
  48. return obj, err
  49. }
  50. // DecodeInto performs a Decode into the provided object.
  51. func DecodeInto(d Decoder, data []byte, into Object) error {
  52. out, gvk, err := d.Decode(data, nil, into)
  53. if err != nil {
  54. return err
  55. }
  56. if out != into {
  57. return fmt.Errorf("unable to decode %s into %v", gvk, reflect.TypeOf(into))
  58. }
  59. return nil
  60. }
  61. // EncodeOrDie is a version of Encode which will panic instead of returning an error. For tests.
  62. func EncodeOrDie(e Encoder, obj Object) string {
  63. bytes, err := Encode(e, obj)
  64. if err != nil {
  65. panic(err)
  66. }
  67. return string(bytes)
  68. }
  69. // UseOrCreateObject returns obj if the canonical ObjectKind returned by the provided typer matches gvk, or
  70. // invokes the ObjectCreator to instantiate a new gvk. Returns an error if the typer cannot find the object.
  71. func UseOrCreateObject(t ObjectTyper, c ObjectCreater, gvk schema.GroupVersionKind, obj Object) (Object, error) {
  72. if obj != nil {
  73. kinds, _, err := t.ObjectKinds(obj)
  74. if err != nil {
  75. return nil, err
  76. }
  77. for _, kind := range kinds {
  78. if gvk == kind {
  79. return obj, nil
  80. }
  81. }
  82. }
  83. return c.New(gvk)
  84. }
  85. // NoopEncoder converts an Decoder to a Serializer or Codec for code that expects them but only uses decoding.
  86. type NoopEncoder struct {
  87. Decoder
  88. }
  89. var _ Serializer = NoopEncoder{}
  90. const noopEncoderIdentifier Identifier = "noop"
  91. func (n NoopEncoder) Encode(obj Object, w io.Writer) error {
  92. // There is no need to handle runtime.CacheableObject, as we don't
  93. // process the obj at all.
  94. return fmt.Errorf("encoding is not allowed for this codec: %v", reflect.TypeOf(n.Decoder))
  95. }
  96. // Identifier implements runtime.Encoder interface.
  97. func (n NoopEncoder) Identifier() Identifier {
  98. return noopEncoderIdentifier
  99. }
  100. // NoopDecoder converts an Encoder to a Serializer or Codec for code that expects them but only uses encoding.
  101. type NoopDecoder struct {
  102. Encoder
  103. }
  104. var _ Serializer = NoopDecoder{}
  105. func (n NoopDecoder) Decode(data []byte, gvk *schema.GroupVersionKind, into Object) (Object, *schema.GroupVersionKind, error) {
  106. return nil, nil, fmt.Errorf("decoding is not allowed for this codec: %v", reflect.TypeOf(n.Encoder))
  107. }
  108. // NewParameterCodec creates a ParameterCodec capable of transforming url values into versioned objects and back.
  109. func NewParameterCodec(scheme *Scheme) ParameterCodec {
  110. return &parameterCodec{
  111. typer: scheme,
  112. convertor: scheme,
  113. creator: scheme,
  114. defaulter: scheme,
  115. }
  116. }
  117. // parameterCodec implements conversion to and from query parameters and objects.
  118. type parameterCodec struct {
  119. typer ObjectTyper
  120. convertor ObjectConvertor
  121. creator ObjectCreater
  122. defaulter ObjectDefaulter
  123. }
  124. var _ ParameterCodec = &parameterCodec{}
  125. // DecodeParameters converts the provided url.Values into an object of type From with the kind of into, and then
  126. // converts that object to into (if necessary). Returns an error if the operation cannot be completed.
  127. func (c *parameterCodec) DecodeParameters(parameters url.Values, from schema.GroupVersion, into Object) error {
  128. if len(parameters) == 0 {
  129. return nil
  130. }
  131. targetGVKs, _, err := c.typer.ObjectKinds(into)
  132. if err != nil {
  133. return err
  134. }
  135. for i := range targetGVKs {
  136. if targetGVKs[i].GroupVersion() == from {
  137. if err := c.convertor.Convert(&parameters, into, nil); err != nil {
  138. return err
  139. }
  140. // in the case where we going into the same object we're receiving, default on the outbound object
  141. if c.defaulter != nil {
  142. c.defaulter.Default(into)
  143. }
  144. return nil
  145. }
  146. }
  147. input, err := c.creator.New(from.WithKind(targetGVKs[0].Kind))
  148. if err != nil {
  149. return err
  150. }
  151. if err := c.convertor.Convert(&parameters, input, nil); err != nil {
  152. return err
  153. }
  154. // if we have defaulter, default the input before converting to output
  155. if c.defaulter != nil {
  156. c.defaulter.Default(input)
  157. }
  158. return c.convertor.Convert(input, into, nil)
  159. }
  160. // EncodeParameters converts the provided object into the to version, then converts that object to url.Values.
  161. // Returns an error if conversion is not possible.
  162. func (c *parameterCodec) EncodeParameters(obj Object, to schema.GroupVersion) (url.Values, error) {
  163. gvks, _, err := c.typer.ObjectKinds(obj)
  164. if err != nil {
  165. return nil, err
  166. }
  167. gvk := gvks[0]
  168. if to != gvk.GroupVersion() {
  169. out, err := c.convertor.ConvertToVersion(obj, to)
  170. if err != nil {
  171. return nil, err
  172. }
  173. obj = out
  174. }
  175. return queryparams.Convert(obj)
  176. }
  177. type base64Serializer struct {
  178. Encoder
  179. Decoder
  180. identifier Identifier
  181. }
  182. func NewBase64Serializer(e Encoder, d Decoder) Serializer {
  183. return &base64Serializer{
  184. Encoder: e,
  185. Decoder: d,
  186. identifier: identifier(e),
  187. }
  188. }
  189. func identifier(e Encoder) Identifier {
  190. result := map[string]string{
  191. "name": "base64",
  192. }
  193. if e != nil {
  194. result["encoder"] = string(e.Identifier())
  195. }
  196. identifier, err := json.Marshal(result)
  197. if err != nil {
  198. klog.Fatalf("Failed marshaling identifier for base64Serializer: %v", err)
  199. }
  200. return Identifier(identifier)
  201. }
  202. func (s base64Serializer) Encode(obj Object, stream io.Writer) error {
  203. if co, ok := obj.(CacheableObject); ok {
  204. return co.CacheEncode(s.Identifier(), s.doEncode, stream)
  205. }
  206. return s.doEncode(obj, stream)
  207. }
  208. func (s base64Serializer) doEncode(obj Object, stream io.Writer) error {
  209. e := base64.NewEncoder(base64.StdEncoding, stream)
  210. err := s.Encoder.Encode(obj, e)
  211. e.Close()
  212. return err
  213. }
  214. // Identifier implements runtime.Encoder interface.
  215. func (s base64Serializer) Identifier() Identifier {
  216. return s.identifier
  217. }
  218. func (s base64Serializer) Decode(data []byte, defaults *schema.GroupVersionKind, into Object) (Object, *schema.GroupVersionKind, error) {
  219. out := make([]byte, base64.StdEncoding.DecodedLen(len(data)))
  220. n, err := base64.StdEncoding.Decode(out, data)
  221. if err != nil {
  222. return nil, nil, err
  223. }
  224. return s.Decoder.Decode(out[:n], defaults, into)
  225. }
  226. // SerializerInfoForMediaType returns the first info in types that has a matching media type (which cannot
  227. // include media-type parameters), or the first info with an empty media type, or false if no type matches.
  228. func SerializerInfoForMediaType(types []SerializerInfo, mediaType string) (SerializerInfo, bool) {
  229. for _, info := range types {
  230. if info.MediaType == mediaType {
  231. return info, true
  232. }
  233. }
  234. for _, info := range types {
  235. if len(info.MediaType) == 0 {
  236. return info, true
  237. }
  238. }
  239. return SerializerInfo{}, false
  240. }
  241. var (
  242. // InternalGroupVersioner will always prefer the internal version for a given group version kind.
  243. InternalGroupVersioner GroupVersioner = internalGroupVersioner{}
  244. // DisabledGroupVersioner will reject all kinds passed to it.
  245. DisabledGroupVersioner GroupVersioner = disabledGroupVersioner{}
  246. )
  247. const (
  248. internalGroupVersionerIdentifier = "internal"
  249. disabledGroupVersionerIdentifier = "disabled"
  250. )
  251. type internalGroupVersioner struct{}
  252. // KindForGroupVersionKinds returns an internal Kind if one is found, or converts the first provided kind to the internal version.
  253. func (internalGroupVersioner) KindForGroupVersionKinds(kinds []schema.GroupVersionKind) (schema.GroupVersionKind, bool) {
  254. for _, kind := range kinds {
  255. if kind.Version == APIVersionInternal {
  256. return kind, true
  257. }
  258. }
  259. for _, kind := range kinds {
  260. return schema.GroupVersionKind{Group: kind.Group, Version: APIVersionInternal, Kind: kind.Kind}, true
  261. }
  262. return schema.GroupVersionKind{}, false
  263. }
  264. // Identifier implements GroupVersioner interface.
  265. func (internalGroupVersioner) Identifier() string {
  266. return internalGroupVersionerIdentifier
  267. }
  268. type disabledGroupVersioner struct{}
  269. // KindForGroupVersionKinds returns false for any input.
  270. func (disabledGroupVersioner) KindForGroupVersionKinds(kinds []schema.GroupVersionKind) (schema.GroupVersionKind, bool) {
  271. return schema.GroupVersionKind{}, false
  272. }
  273. // Identifier implements GroupVersioner interface.
  274. func (disabledGroupVersioner) Identifier() string {
  275. return disabledGroupVersionerIdentifier
  276. }
  277. // Assert that schema.GroupVersion and GroupVersions implement GroupVersioner
  278. var _ GroupVersioner = schema.GroupVersion{}
  279. var _ GroupVersioner = schema.GroupVersions{}
  280. var _ GroupVersioner = multiGroupVersioner{}
  281. type multiGroupVersioner struct {
  282. target schema.GroupVersion
  283. acceptedGroupKinds []schema.GroupKind
  284. coerce bool
  285. }
  286. // NewMultiGroupVersioner returns the provided group version for any kind that matches one of the provided group kinds.
  287. // Kind may be empty in the provided group kind, in which case any kind will match.
  288. func NewMultiGroupVersioner(gv schema.GroupVersion, groupKinds ...schema.GroupKind) GroupVersioner {
  289. if len(groupKinds) == 0 || (len(groupKinds) == 1 && groupKinds[0].Group == gv.Group) {
  290. return gv
  291. }
  292. return multiGroupVersioner{target: gv, acceptedGroupKinds: groupKinds}
  293. }
  294. // NewCoercingMultiGroupVersioner returns the provided group version for any incoming kind.
  295. // Incoming kinds that match the provided groupKinds are preferred.
  296. // Kind may be empty in the provided group kind, in which case any kind will match.
  297. // Examples:
  298. //
  299. // gv=mygroup/__internal, groupKinds=mygroup/Foo, anothergroup/Bar
  300. // KindForGroupVersionKinds(yetanother/v1/Baz, anothergroup/v1/Bar) -> mygroup/__internal/Bar (matched preferred group/kind)
  301. //
  302. // gv=mygroup/__internal, groupKinds=mygroup, anothergroup
  303. // KindForGroupVersionKinds(yetanother/v1/Baz, anothergroup/v1/Bar) -> mygroup/__internal/Bar (matched preferred group)
  304. //
  305. // gv=mygroup/__internal, groupKinds=mygroup, anothergroup
  306. // KindForGroupVersionKinds(yetanother/v1/Baz, yetanother/v1/Bar) -> mygroup/__internal/Baz (no preferred group/kind match, uses first kind in list)
  307. func NewCoercingMultiGroupVersioner(gv schema.GroupVersion, groupKinds ...schema.GroupKind) GroupVersioner {
  308. return multiGroupVersioner{target: gv, acceptedGroupKinds: groupKinds, coerce: true}
  309. }
  310. // KindForGroupVersionKinds returns the target group version if any kind matches any of the original group kinds. It will
  311. // use the originating kind where possible.
  312. func (v multiGroupVersioner) KindForGroupVersionKinds(kinds []schema.GroupVersionKind) (schema.GroupVersionKind, bool) {
  313. for _, src := range kinds {
  314. for _, kind := range v.acceptedGroupKinds {
  315. if kind.Group != src.Group {
  316. continue
  317. }
  318. if len(kind.Kind) > 0 && kind.Kind != src.Kind {
  319. continue
  320. }
  321. return v.target.WithKind(src.Kind), true
  322. }
  323. }
  324. if v.coerce && len(kinds) > 0 {
  325. return v.target.WithKind(kinds[0].Kind), true
  326. }
  327. return schema.GroupVersionKind{}, false
  328. }
  329. // Identifier implements GroupVersioner interface.
  330. func (v multiGroupVersioner) Identifier() string {
  331. groupKinds := make([]string, 0, len(v.acceptedGroupKinds))
  332. for _, gk := range v.acceptedGroupKinds {
  333. groupKinds = append(groupKinds, gk.String())
  334. }
  335. result := map[string]string{
  336. "name": "multi",
  337. "target": v.target.String(),
  338. "accepted": strings.Join(groupKinds, ","),
  339. "coerce": strconv.FormatBool(v.coerce),
  340. }
  341. identifier, err := json.Marshal(result)
  342. if err != nil {
  343. klog.Fatalf("Failed marshaling Identifier for %#v: %v", v, err)
  344. }
  345. return string(identifier)
  346. }