json.go 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285
  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 json
  14. import (
  15. "encoding/json"
  16. "io"
  17. "strconv"
  18. "unsafe"
  19. "github.com/ghodss/yaml"
  20. jsoniter "github.com/json-iterator/go"
  21. "k8s.io/apimachinery/pkg/runtime"
  22. "k8s.io/apimachinery/pkg/runtime/schema"
  23. "k8s.io/apimachinery/pkg/runtime/serializer/recognizer"
  24. "k8s.io/apimachinery/pkg/util/framer"
  25. utilyaml "k8s.io/apimachinery/pkg/util/yaml"
  26. )
  27. // NewSerializer creates a JSON serializer that handles encoding versioned objects into the proper JSON form. If typer
  28. // is not nil, the object has the group, version, and kind fields set.
  29. func NewSerializer(meta MetaFactory, creater runtime.ObjectCreater, typer runtime.ObjectTyper, pretty bool) *Serializer {
  30. return &Serializer{
  31. meta: meta,
  32. creater: creater,
  33. typer: typer,
  34. yaml: false,
  35. pretty: pretty,
  36. }
  37. }
  38. // NewYAMLSerializer creates a YAML serializer that handles encoding versioned objects into the proper YAML form. If typer
  39. // is not nil, the object has the group, version, and kind fields set. This serializer supports only the subset of YAML that
  40. // matches JSON, and will error if constructs are used that do not serialize to JSON.
  41. func NewYAMLSerializer(meta MetaFactory, creater runtime.ObjectCreater, typer runtime.ObjectTyper) *Serializer {
  42. return &Serializer{
  43. meta: meta,
  44. creater: creater,
  45. typer: typer,
  46. yaml: true,
  47. }
  48. }
  49. type Serializer struct {
  50. meta MetaFactory
  51. creater runtime.ObjectCreater
  52. typer runtime.ObjectTyper
  53. yaml bool
  54. pretty bool
  55. }
  56. // Serializer implements Serializer
  57. var _ runtime.Serializer = &Serializer{}
  58. var _ recognizer.RecognizingDecoder = &Serializer{}
  59. func init() {
  60. // Force jsoniter to decode number to interface{} via ints, if possible.
  61. decodeNumberAsInt64IfPossible := func(ptr unsafe.Pointer, iter *jsoniter.Iterator) {
  62. switch iter.WhatIsNext() {
  63. case jsoniter.NumberValue:
  64. var number json.Number
  65. iter.ReadVal(&number)
  66. i64, err := strconv.ParseInt(string(number), 10, 64)
  67. if err == nil {
  68. *(*interface{})(ptr) = i64
  69. return
  70. }
  71. f64, err := strconv.ParseFloat(string(number), 64)
  72. if err == nil {
  73. *(*interface{})(ptr) = f64
  74. return
  75. }
  76. // Not much we can do here.
  77. default:
  78. *(*interface{})(ptr) = iter.Read()
  79. }
  80. }
  81. jsoniter.RegisterTypeDecoderFunc("interface {}", decodeNumberAsInt64IfPossible)
  82. }
  83. // CaseSensitiveJsonIterator returns a jsoniterator API that's configured to be
  84. // case-sensitive when unmarshalling, and otherwise compatible with
  85. // the encoding/json standard library.
  86. func CaseSensitiveJsonIterator() jsoniter.API {
  87. return jsoniter.Config{
  88. EscapeHTML: true,
  89. SortMapKeys: true,
  90. ValidateJsonRawMessage: true,
  91. CaseSensitive: true,
  92. }.Froze()
  93. }
  94. var caseSensitiveJsonIterator = CaseSensitiveJsonIterator()
  95. // gvkWithDefaults returns group kind and version defaulting from provided default
  96. func gvkWithDefaults(actual, defaultGVK schema.GroupVersionKind) schema.GroupVersionKind {
  97. if len(actual.Kind) == 0 {
  98. actual.Kind = defaultGVK.Kind
  99. }
  100. if len(actual.Version) == 0 && len(actual.Group) == 0 {
  101. actual.Group = defaultGVK.Group
  102. actual.Version = defaultGVK.Version
  103. }
  104. if len(actual.Version) == 0 && actual.Group == defaultGVK.Group {
  105. actual.Version = defaultGVK.Version
  106. }
  107. return actual
  108. }
  109. // Decode attempts to convert the provided data into YAML or JSON, extract the stored schema kind, apply the provided default gvk, and then
  110. // load that data into an object matching the desired schema kind or the provided into.
  111. // If into is *runtime.Unknown, the raw data will be extracted and no decoding will be performed.
  112. // If into is not registered with the typer, then the object will be straight decoded using normal JSON/YAML unmarshalling.
  113. // If into is provided and the original data is not fully qualified with kind/version/group, the type of the into will be used to alter the returned gvk.
  114. // If into is nil or data's gvk different from into's gvk, it will generate a new Object with ObjectCreater.New(gvk)
  115. // On success or most errors, the method will return the calculated schema kind.
  116. // The gvk calculate priority will be originalData > default gvk > into
  117. func (s *Serializer) Decode(originalData []byte, gvk *schema.GroupVersionKind, into runtime.Object) (runtime.Object, *schema.GroupVersionKind, error) {
  118. if versioned, ok := into.(*runtime.VersionedObjects); ok {
  119. into = versioned.Last()
  120. obj, actual, err := s.Decode(originalData, gvk, into)
  121. if err != nil {
  122. return nil, actual, err
  123. }
  124. versioned.Objects = []runtime.Object{obj}
  125. return versioned, actual, nil
  126. }
  127. data := originalData
  128. if s.yaml {
  129. altered, err := yaml.YAMLToJSON(data)
  130. if err != nil {
  131. return nil, nil, err
  132. }
  133. data = altered
  134. }
  135. actual, err := s.meta.Interpret(data)
  136. if err != nil {
  137. return nil, nil, err
  138. }
  139. if gvk != nil {
  140. *actual = gvkWithDefaults(*actual, *gvk)
  141. }
  142. if unk, ok := into.(*runtime.Unknown); ok && unk != nil {
  143. unk.Raw = originalData
  144. unk.ContentType = runtime.ContentTypeJSON
  145. unk.GetObjectKind().SetGroupVersionKind(*actual)
  146. return unk, actual, nil
  147. }
  148. if into != nil {
  149. _, isUnstructured := into.(runtime.Unstructured)
  150. types, _, err := s.typer.ObjectKinds(into)
  151. switch {
  152. case runtime.IsNotRegisteredError(err), isUnstructured:
  153. if err := caseSensitiveJsonIterator.Unmarshal(data, into); err != nil {
  154. return nil, actual, err
  155. }
  156. return into, actual, nil
  157. case err != nil:
  158. return nil, actual, err
  159. default:
  160. *actual = gvkWithDefaults(*actual, types[0])
  161. }
  162. }
  163. if len(actual.Kind) == 0 {
  164. return nil, actual, runtime.NewMissingKindErr(string(originalData))
  165. }
  166. if len(actual.Version) == 0 {
  167. return nil, actual, runtime.NewMissingVersionErr(string(originalData))
  168. }
  169. // use the target if necessary
  170. obj, err := runtime.UseOrCreateObject(s.typer, s.creater, *actual, into)
  171. if err != nil {
  172. return nil, actual, err
  173. }
  174. if err := caseSensitiveJsonIterator.Unmarshal(data, obj); err != nil {
  175. return nil, actual, err
  176. }
  177. return obj, actual, nil
  178. }
  179. // Encode serializes the provided object to the given writer.
  180. func (s *Serializer) Encode(obj runtime.Object, w io.Writer) error {
  181. if s.yaml {
  182. json, err := caseSensitiveJsonIterator.Marshal(obj)
  183. if err != nil {
  184. return err
  185. }
  186. data, err := yaml.JSONToYAML(json)
  187. if err != nil {
  188. return err
  189. }
  190. _, err = w.Write(data)
  191. return err
  192. }
  193. if s.pretty {
  194. data, err := caseSensitiveJsonIterator.MarshalIndent(obj, "", " ")
  195. if err != nil {
  196. return err
  197. }
  198. _, err = w.Write(data)
  199. return err
  200. }
  201. encoder := json.NewEncoder(w)
  202. return encoder.Encode(obj)
  203. }
  204. // RecognizesData implements the RecognizingDecoder interface.
  205. func (s *Serializer) RecognizesData(peek io.Reader) (ok, unknown bool, err error) {
  206. if s.yaml {
  207. // we could potentially look for '---'
  208. return false, true, nil
  209. }
  210. _, _, ok = utilyaml.GuessJSONStream(peek, 2048)
  211. return ok, false, nil
  212. }
  213. // Framer is the default JSON framing behavior, with newlines delimiting individual objects.
  214. var Framer = jsonFramer{}
  215. type jsonFramer struct{}
  216. // NewFrameWriter implements stream framing for this serializer
  217. func (jsonFramer) NewFrameWriter(w io.Writer) io.Writer {
  218. // we can write JSON objects directly to the writer, because they are self-framing
  219. return w
  220. }
  221. // NewFrameReader implements stream framing for this serializer
  222. func (jsonFramer) NewFrameReader(r io.ReadCloser) io.ReadCloser {
  223. // we need to extract the JSON chunks of data to pass to Decode()
  224. return framer.NewJSONFramedReader(r)
  225. }
  226. // Framer is the default JSON framing behavior, with newlines delimiting individual objects.
  227. var YAMLFramer = yamlFramer{}
  228. type yamlFramer struct{}
  229. // NewFrameWriter implements stream framing for this serializer
  230. func (yamlFramer) NewFrameWriter(w io.Writer) io.Writer {
  231. return yamlFrameWriter{w}
  232. }
  233. // NewFrameReader implements stream framing for this serializer
  234. func (yamlFramer) NewFrameReader(r io.ReadCloser) io.ReadCloser {
  235. // extract the YAML document chunks directly
  236. return utilyaml.NewDocumentDecoder(r)
  237. }
  238. type yamlFrameWriter struct {
  239. w io.Writer
  240. }
  241. // Write separates each document with the YAML document separator (`---` followed by line
  242. // break). Writers must write well formed YAML documents (include a final line break).
  243. func (w yamlFrameWriter) Write(data []byte) (n int, err error) {
  244. if _, err := w.w.Write([]byte("---\n")); err != nil {
  245. return 0, err
  246. }
  247. return w.w.Write(data)
  248. }