json.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363
  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. kjson "sigs.k8s.io/json"
  19. "sigs.k8s.io/yaml"
  20. "k8s.io/apimachinery/pkg/runtime"
  21. "k8s.io/apimachinery/pkg/runtime/schema"
  22. "k8s.io/apimachinery/pkg/runtime/serializer/recognizer"
  23. "k8s.io/apimachinery/pkg/util/framer"
  24. utilyaml "k8s.io/apimachinery/pkg/util/yaml"
  25. "k8s.io/klog/v2"
  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. // Deprecated: use NewSerializerWithOptions instead.
  30. func NewSerializer(meta MetaFactory, creater runtime.ObjectCreater, typer runtime.ObjectTyper, pretty bool) *Serializer {
  31. return NewSerializerWithOptions(meta, creater, typer, SerializerOptions{false, pretty, false, false})
  32. }
  33. // NewYAMLSerializer creates a YAML serializer that handles encoding versioned objects into the proper YAML form. If typer
  34. // is not nil, the object has the group, version, and kind fields set. This serializer supports only the subset of YAML that
  35. // matches JSON, and will error if constructs are used that do not serialize to JSON.
  36. // Deprecated: use NewSerializerWithOptions instead.
  37. func NewYAMLSerializer(meta MetaFactory, creater runtime.ObjectCreater, typer runtime.ObjectTyper) *Serializer {
  38. return NewSerializerWithOptions(meta, creater, typer, SerializerOptions{true, false, false, false})
  39. }
  40. // NewSerializerWithOptions creates a JSON/YAML serializer that handles encoding versioned objects into the proper JSON/YAML
  41. // form. If typer is not nil, the object has the group, version, and kind fields set. Options are copied into the Serializer
  42. // and are immutable.
  43. func NewSerializerWithOptions(meta MetaFactory, creater runtime.ObjectCreater, typer runtime.ObjectTyper, options SerializerOptions) *Serializer {
  44. return &Serializer{
  45. meta: meta,
  46. creater: creater,
  47. typer: typer,
  48. options: options,
  49. identifier: identifier(options),
  50. }
  51. }
  52. // identifier computes Identifier of Encoder based on the given options.
  53. func identifier(options SerializerOptions) runtime.Identifier {
  54. result := map[string]string{
  55. "name": "json",
  56. "yaml": strconv.FormatBool(options.Yaml),
  57. "pretty": strconv.FormatBool(options.Pretty),
  58. "strict": strconv.FormatBool(options.Strict),
  59. }
  60. identifier, err := json.Marshal(result)
  61. if err != nil {
  62. klog.Fatalf("Failed marshaling identifier for json Serializer: %v", err)
  63. }
  64. return runtime.Identifier(identifier)
  65. }
  66. // SerializerOptions holds the options which are used to configure a JSON/YAML serializer.
  67. // example:
  68. // (1) To configure a JSON serializer, set `Yaml` to `false`.
  69. // (2) To configure a YAML serializer, set `Yaml` to `true`.
  70. // (3) To configure a strict serializer that can return strictDecodingError, set `Strict` to `true`.
  71. type SerializerOptions struct {
  72. // Yaml: configures the Serializer to work with JSON(false) or YAML(true).
  73. // When `Yaml` is enabled, this serializer only supports the subset of YAML that
  74. // matches JSON, and will error if constructs are used that do not serialize to JSON.
  75. Yaml bool
  76. // Pretty: configures a JSON enabled Serializer(`Yaml: false`) to produce human-readable output.
  77. // This option is silently ignored when `Yaml` is `true`.
  78. Pretty bool
  79. // Strict: configures the Serializer to return strictDecodingError's when duplicate fields are present decoding JSON or YAML.
  80. // Note that enabling this option is not as performant as the non-strict variant, and should not be used in fast paths.
  81. Strict bool
  82. // StreamingCollectionsEncoding enables encoding collection, one item at the time, drastically reducing memory needed.
  83. StreamingCollectionsEncoding bool
  84. }
  85. // Serializer handles encoding versioned objects into the proper JSON form
  86. type Serializer struct {
  87. meta MetaFactory
  88. options SerializerOptions
  89. creater runtime.ObjectCreater
  90. typer runtime.ObjectTyper
  91. identifier runtime.Identifier
  92. }
  93. // Serializer implements Serializer
  94. var _ runtime.Serializer = &Serializer{}
  95. var _ recognizer.RecognizingDecoder = &Serializer{}
  96. // gvkWithDefaults returns group kind and version defaulting from provided default
  97. func gvkWithDefaults(actual, defaultGVK schema.GroupVersionKind) schema.GroupVersionKind {
  98. if len(actual.Kind) == 0 {
  99. actual.Kind = defaultGVK.Kind
  100. }
  101. if len(actual.Version) == 0 && len(actual.Group) == 0 {
  102. actual.Group = defaultGVK.Group
  103. actual.Version = defaultGVK.Version
  104. }
  105. if len(actual.Version) == 0 && actual.Group == defaultGVK.Group {
  106. actual.Version = defaultGVK.Version
  107. }
  108. return actual
  109. }
  110. // Decode attempts to convert the provided data into YAML or JSON, extract the stored schema kind, apply the provided default gvk, and then
  111. // load that data into an object matching the desired schema kind or the provided into.
  112. // If into is *runtime.Unknown, the raw data will be extracted and no decoding will be performed.
  113. // If into is not registered with the typer, then the object will be straight decoded using normal JSON/YAML unmarshalling.
  114. // 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.
  115. // If into is nil or data's gvk different from into's gvk, it will generate a new Object with ObjectCreater.New(gvk)
  116. // On success or most errors, the method will return the calculated schema kind.
  117. // The gvk calculate priority will be originalData > default gvk > into
  118. func (s *Serializer) Decode(originalData []byte, gvk *schema.GroupVersionKind, into runtime.Object) (runtime.Object, *schema.GroupVersionKind, error) {
  119. data := originalData
  120. if s.options.Yaml {
  121. altered, err := yaml.YAMLToJSON(data)
  122. if err != nil {
  123. return nil, nil, err
  124. }
  125. data = altered
  126. }
  127. actual, err := s.meta.Interpret(data)
  128. if err != nil {
  129. return nil, nil, err
  130. }
  131. if gvk != nil {
  132. *actual = gvkWithDefaults(*actual, *gvk)
  133. }
  134. if unk, ok := into.(*runtime.Unknown); ok && unk != nil {
  135. unk.Raw = originalData
  136. unk.ContentType = runtime.ContentTypeJSON
  137. unk.GetObjectKind().SetGroupVersionKind(*actual)
  138. return unk, actual, nil
  139. }
  140. if into != nil {
  141. _, isUnstructured := into.(runtime.Unstructured)
  142. types, _, err := s.typer.ObjectKinds(into)
  143. switch {
  144. case runtime.IsNotRegisteredError(err), isUnstructured:
  145. strictErrs, err := s.unmarshal(into, data, originalData)
  146. if err != nil {
  147. return nil, actual, err
  148. }
  149. // when decoding directly into a provided unstructured object,
  150. // extract the actual gvk decoded from the provided data,
  151. // and ensure it is non-empty.
  152. if isUnstructured {
  153. *actual = into.GetObjectKind().GroupVersionKind()
  154. if len(actual.Kind) == 0 {
  155. return nil, actual, runtime.NewMissingKindErr(string(originalData))
  156. }
  157. // TODO(109023): require apiVersion here as well once unstructuredJSONScheme#Decode does
  158. }
  159. if len(strictErrs) > 0 {
  160. return into, actual, runtime.NewStrictDecodingError(strictErrs)
  161. }
  162. return into, actual, nil
  163. case err != nil:
  164. return nil, actual, err
  165. default:
  166. *actual = gvkWithDefaults(*actual, types[0])
  167. }
  168. }
  169. if len(actual.Kind) == 0 {
  170. return nil, actual, runtime.NewMissingKindErr(string(originalData))
  171. }
  172. if len(actual.Version) == 0 {
  173. return nil, actual, runtime.NewMissingVersionErr(string(originalData))
  174. }
  175. // use the target if necessary
  176. obj, err := runtime.UseOrCreateObject(s.typer, s.creater, *actual, into)
  177. if err != nil {
  178. return nil, actual, err
  179. }
  180. strictErrs, err := s.unmarshal(obj, data, originalData)
  181. if err != nil {
  182. return nil, actual, err
  183. } else if len(strictErrs) > 0 {
  184. return obj, actual, runtime.NewStrictDecodingError(strictErrs)
  185. }
  186. return obj, actual, nil
  187. }
  188. // Encode serializes the provided object to the given writer.
  189. func (s *Serializer) Encode(obj runtime.Object, w io.Writer) error {
  190. if co, ok := obj.(runtime.CacheableObject); ok {
  191. return co.CacheEncode(s.Identifier(), s.doEncode, w)
  192. }
  193. return s.doEncode(obj, w)
  194. }
  195. func (s *Serializer) doEncode(obj runtime.Object, w io.Writer) error {
  196. if s.options.Yaml {
  197. json, err := json.Marshal(obj)
  198. if err != nil {
  199. return err
  200. }
  201. data, err := yaml.JSONToYAML(json)
  202. if err != nil {
  203. return err
  204. }
  205. _, err = w.Write(data)
  206. return err
  207. }
  208. if s.options.Pretty {
  209. data, err := json.MarshalIndent(obj, "", " ")
  210. if err != nil {
  211. return err
  212. }
  213. _, err = w.Write(data)
  214. return err
  215. }
  216. if s.options.StreamingCollectionsEncoding {
  217. ok, err := streamEncodeCollections(obj, w)
  218. if err != nil {
  219. return err
  220. }
  221. if ok {
  222. return nil
  223. }
  224. }
  225. encoder := json.NewEncoder(w)
  226. return encoder.Encode(obj)
  227. }
  228. // IsStrict indicates whether the serializer
  229. // uses strict decoding or not
  230. func (s *Serializer) IsStrict() bool {
  231. return s.options.Strict
  232. }
  233. func (s *Serializer) unmarshal(into runtime.Object, data, originalData []byte) (strictErrs []error, err error) {
  234. // If the deserializer is non-strict, return here.
  235. if !s.options.Strict {
  236. if err := kjson.UnmarshalCaseSensitivePreserveInts(data, into); err != nil {
  237. return nil, err
  238. }
  239. return nil, nil
  240. }
  241. if s.options.Yaml {
  242. // In strict mode pass the original data through the YAMLToJSONStrict converter.
  243. // This is done to catch duplicate fields in YAML that would have been dropped in the original YAMLToJSON conversion.
  244. // TODO: rework YAMLToJSONStrict to return warnings about duplicate fields without terminating so we don't have to do this twice.
  245. _, err := yaml.YAMLToJSONStrict(originalData)
  246. if err != nil {
  247. strictErrs = append(strictErrs, err)
  248. }
  249. }
  250. var strictJSONErrs []error
  251. if u, isUnstructured := into.(runtime.Unstructured); isUnstructured {
  252. // Unstructured is a custom unmarshaler that gets delegated
  253. // to, so in order to detect strict JSON errors we need
  254. // to unmarshal directly into the object.
  255. m := map[string]interface{}{}
  256. strictJSONErrs, err = kjson.UnmarshalStrict(data, &m)
  257. u.SetUnstructuredContent(m)
  258. } else {
  259. strictJSONErrs, err = kjson.UnmarshalStrict(data, into)
  260. }
  261. if err != nil {
  262. // fatal decoding error, not due to strictness
  263. return nil, err
  264. }
  265. strictErrs = append(strictErrs, strictJSONErrs...)
  266. return strictErrs, nil
  267. }
  268. // Identifier implements runtime.Encoder interface.
  269. func (s *Serializer) Identifier() runtime.Identifier {
  270. return s.identifier
  271. }
  272. // RecognizesData implements the RecognizingDecoder interface.
  273. func (s *Serializer) RecognizesData(data []byte) (ok, unknown bool, err error) {
  274. if s.options.Yaml {
  275. // we could potentially look for '---'
  276. return false, true, nil
  277. }
  278. return utilyaml.IsJSONBuffer(data), false, nil
  279. }
  280. // Framer is the default JSON framing behavior, with newlines delimiting individual objects.
  281. var Framer = jsonFramer{}
  282. type jsonFramer struct{}
  283. // NewFrameWriter implements stream framing for this serializer
  284. func (jsonFramer) NewFrameWriter(w io.Writer) io.Writer {
  285. // we can write JSON objects directly to the writer, because they are self-framing
  286. return w
  287. }
  288. // NewFrameReader implements stream framing for this serializer
  289. func (jsonFramer) NewFrameReader(r io.ReadCloser) io.ReadCloser {
  290. // we need to extract the JSON chunks of data to pass to Decode()
  291. return framer.NewJSONFramedReader(r)
  292. }
  293. // YAMLFramer is the default JSON framing behavior, with newlines delimiting individual objects.
  294. var YAMLFramer = yamlFramer{}
  295. type yamlFramer struct{}
  296. // NewFrameWriter implements stream framing for this serializer
  297. func (yamlFramer) NewFrameWriter(w io.Writer) io.Writer {
  298. return yamlFrameWriter{w}
  299. }
  300. // NewFrameReader implements stream framing for this serializer
  301. func (yamlFramer) NewFrameReader(r io.ReadCloser) io.ReadCloser {
  302. // extract the YAML document chunks directly
  303. return utilyaml.NewDocumentDecoder(r)
  304. }
  305. type yamlFrameWriter struct {
  306. w io.Writer
  307. }
  308. // Write separates each document with the YAML document separator (`---` followed by line
  309. // break). Writers must write well formed YAML documents (include a final line break).
  310. func (w yamlFrameWriter) Write(data []byte) (n int, err error) {
  311. if _, err := w.w.Write([]byte("---\n")); err != nil {
  312. return 0, err
  313. }
  314. return w.w.Write(data)
  315. }