json.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338
  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})
  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})
  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. }
  83. // Serializer handles encoding versioned objects into the proper JSON form
  84. type Serializer struct {
  85. meta MetaFactory
  86. options SerializerOptions
  87. creater runtime.ObjectCreater
  88. typer runtime.ObjectTyper
  89. identifier runtime.Identifier
  90. }
  91. // Serializer implements Serializer
  92. var _ runtime.Serializer = &Serializer{}
  93. var _ recognizer.RecognizingDecoder = &Serializer{}
  94. // gvkWithDefaults returns group kind and version defaulting from provided default
  95. func gvkWithDefaults(actual, defaultGVK schema.GroupVersionKind) schema.GroupVersionKind {
  96. if len(actual.Kind) == 0 {
  97. actual.Kind = defaultGVK.Kind
  98. }
  99. if len(actual.Version) == 0 && len(actual.Group) == 0 {
  100. actual.Group = defaultGVK.Group
  101. actual.Version = defaultGVK.Version
  102. }
  103. if len(actual.Version) == 0 && actual.Group == defaultGVK.Group {
  104. actual.Version = defaultGVK.Version
  105. }
  106. return actual
  107. }
  108. // Decode attempts to convert the provided data into YAML or JSON, extract the stored schema kind, apply the provided default gvk, and then
  109. // load that data into an object matching the desired schema kind or the provided into.
  110. // If into is *runtime.Unknown, the raw data will be extracted and no decoding will be performed.
  111. // If into is not registered with the typer, then the object will be straight decoded using normal JSON/YAML unmarshalling.
  112. // 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.
  113. // If into is nil or data's gvk different from into's gvk, it will generate a new Object with ObjectCreater.New(gvk)
  114. // On success or most errors, the method will return the calculated schema kind.
  115. // The gvk calculate priority will be originalData > default gvk > into
  116. func (s *Serializer) Decode(originalData []byte, gvk *schema.GroupVersionKind, into runtime.Object) (runtime.Object, *schema.GroupVersionKind, error) {
  117. data := originalData
  118. if s.options.Yaml {
  119. altered, err := yaml.YAMLToJSON(data)
  120. if err != nil {
  121. return nil, nil, err
  122. }
  123. data = altered
  124. }
  125. actual, err := s.meta.Interpret(data)
  126. if err != nil {
  127. return nil, nil, err
  128. }
  129. if gvk != nil {
  130. *actual = gvkWithDefaults(*actual, *gvk)
  131. }
  132. if unk, ok := into.(*runtime.Unknown); ok && unk != nil {
  133. unk.Raw = originalData
  134. unk.ContentType = runtime.ContentTypeJSON
  135. unk.GetObjectKind().SetGroupVersionKind(*actual)
  136. return unk, actual, nil
  137. }
  138. if into != nil {
  139. _, isUnstructured := into.(runtime.Unstructured)
  140. types, _, err := s.typer.ObjectKinds(into)
  141. switch {
  142. case runtime.IsNotRegisteredError(err), isUnstructured:
  143. strictErrs, err := s.unmarshal(into, data, originalData)
  144. if err != nil {
  145. return nil, actual, err
  146. } else if len(strictErrs) > 0 {
  147. return into, actual, runtime.NewStrictDecodingError(strictErrs)
  148. }
  149. return into, actual, nil
  150. case err != nil:
  151. return nil, actual, err
  152. default:
  153. *actual = gvkWithDefaults(*actual, types[0])
  154. }
  155. }
  156. if len(actual.Kind) == 0 {
  157. return nil, actual, runtime.NewMissingKindErr(string(originalData))
  158. }
  159. if len(actual.Version) == 0 {
  160. return nil, actual, runtime.NewMissingVersionErr(string(originalData))
  161. }
  162. // use the target if necessary
  163. obj, err := runtime.UseOrCreateObject(s.typer, s.creater, *actual, into)
  164. if err != nil {
  165. return nil, actual, err
  166. }
  167. strictErrs, err := s.unmarshal(obj, data, originalData)
  168. if err != nil {
  169. return nil, actual, err
  170. } else if len(strictErrs) > 0 {
  171. return obj, actual, runtime.NewStrictDecodingError(strictErrs)
  172. }
  173. return obj, actual, nil
  174. }
  175. // Encode serializes the provided object to the given writer.
  176. func (s *Serializer) Encode(obj runtime.Object, w io.Writer) error {
  177. if co, ok := obj.(runtime.CacheableObject); ok {
  178. return co.CacheEncode(s.Identifier(), s.doEncode, w)
  179. }
  180. return s.doEncode(obj, w)
  181. }
  182. func (s *Serializer) doEncode(obj runtime.Object, w io.Writer) error {
  183. if s.options.Yaml {
  184. json, err := json.Marshal(obj)
  185. if err != nil {
  186. return err
  187. }
  188. data, err := yaml.JSONToYAML(json)
  189. if err != nil {
  190. return err
  191. }
  192. _, err = w.Write(data)
  193. return err
  194. }
  195. if s.options.Pretty {
  196. data, err := json.MarshalIndent(obj, "", " ")
  197. if err != nil {
  198. return err
  199. }
  200. _, err = w.Write(data)
  201. return err
  202. }
  203. encoder := json.NewEncoder(w)
  204. return encoder.Encode(obj)
  205. }
  206. // IsStrict indicates whether the serializer
  207. // uses strict decoding or not
  208. func (s *Serializer) IsStrict() bool {
  209. return s.options.Strict
  210. }
  211. func (s *Serializer) unmarshal(into runtime.Object, data, originalData []byte) (strictErrs []error, err error) {
  212. // If the deserializer is non-strict, return here.
  213. if !s.options.Strict {
  214. if err := kjson.UnmarshalCaseSensitivePreserveInts(data, into); err != nil {
  215. return nil, err
  216. }
  217. return nil, nil
  218. }
  219. if s.options.Yaml {
  220. // In strict mode pass the original data through the YAMLToJSONStrict converter.
  221. // This is done to catch duplicate fields in YAML that would have been dropped in the original YAMLToJSON conversion.
  222. // TODO: rework YAMLToJSONStrict to return warnings about duplicate fields without terminating so we don't have to do this twice.
  223. _, err := yaml.YAMLToJSONStrict(originalData)
  224. if err != nil {
  225. strictErrs = append(strictErrs, err)
  226. }
  227. }
  228. var strictJSONErrs []error
  229. if u, isUnstructured := into.(runtime.Unstructured); isUnstructured {
  230. // Unstructured is a custom unmarshaler that gets delegated
  231. // to, so inorder to detect strict JSON errors we need
  232. // to unmarshal directly into the object.
  233. m := u.UnstructuredContent()
  234. strictJSONErrs, err = kjson.UnmarshalStrict(data, &m)
  235. u.SetUnstructuredContent(m)
  236. } else {
  237. strictJSONErrs, err = kjson.UnmarshalStrict(data, into)
  238. }
  239. if err != nil {
  240. // fatal decoding error, not due to strictness
  241. return nil, err
  242. }
  243. strictErrs = append(strictErrs, strictJSONErrs...)
  244. return strictErrs, nil
  245. }
  246. // Identifier implements runtime.Encoder interface.
  247. func (s *Serializer) Identifier() runtime.Identifier {
  248. return s.identifier
  249. }
  250. // RecognizesData implements the RecognizingDecoder interface.
  251. func (s *Serializer) RecognizesData(data []byte) (ok, unknown bool, err error) {
  252. if s.options.Yaml {
  253. // we could potentially look for '---'
  254. return false, true, nil
  255. }
  256. return utilyaml.IsJSONBuffer(data), false, nil
  257. }
  258. // Framer is the default JSON framing behavior, with newlines delimiting individual objects.
  259. var Framer = jsonFramer{}
  260. type jsonFramer struct{}
  261. // NewFrameWriter implements stream framing for this serializer
  262. func (jsonFramer) NewFrameWriter(w io.Writer) io.Writer {
  263. // we can write JSON objects directly to the writer, because they are self-framing
  264. return w
  265. }
  266. // NewFrameReader implements stream framing for this serializer
  267. func (jsonFramer) NewFrameReader(r io.ReadCloser) io.ReadCloser {
  268. // we need to extract the JSON chunks of data to pass to Decode()
  269. return framer.NewJSONFramedReader(r)
  270. }
  271. // YAMLFramer is the default JSON framing behavior, with newlines delimiting individual objects.
  272. var YAMLFramer = yamlFramer{}
  273. type yamlFramer struct{}
  274. // NewFrameWriter implements stream framing for this serializer
  275. func (yamlFramer) NewFrameWriter(w io.Writer) io.Writer {
  276. return yamlFrameWriter{w}
  277. }
  278. // NewFrameReader implements stream framing for this serializer
  279. func (yamlFramer) NewFrameReader(r io.ReadCloser) io.ReadCloser {
  280. // extract the YAML document chunks directly
  281. return utilyaml.NewDocumentDecoder(r)
  282. }
  283. type yamlFrameWriter struct {
  284. w io.Writer
  285. }
  286. // Write separates each document with the YAML document separator (`---` followed by line
  287. // break). Writers must write well formed YAML documents (include a final line break).
  288. func (w yamlFrameWriter) Write(data []byte) (n int, err error) {
  289. if _, err := w.w.Write([]byte("---\n")); err != nil {
  290. return 0, err
  291. }
  292. return w.w.Write(data)
  293. }