json.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351
  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. }
  147. // when decoding directly into a provided unstructured object,
  148. // extract the actual gvk decoded from the provided data,
  149. // and ensure it is non-empty.
  150. if isUnstructured {
  151. *actual = into.GetObjectKind().GroupVersionKind()
  152. if len(actual.Kind) == 0 {
  153. return nil, actual, runtime.NewMissingKindErr(string(originalData))
  154. }
  155. // TODO(109023): require apiVersion here as well once unstructuredJSONScheme#Decode does
  156. }
  157. if len(strictErrs) > 0 {
  158. return into, actual, runtime.NewStrictDecodingError(strictErrs)
  159. }
  160. return into, actual, nil
  161. case err != nil:
  162. return nil, actual, err
  163. default:
  164. *actual = gvkWithDefaults(*actual, types[0])
  165. }
  166. }
  167. if len(actual.Kind) == 0 {
  168. return nil, actual, runtime.NewMissingKindErr(string(originalData))
  169. }
  170. if len(actual.Version) == 0 {
  171. return nil, actual, runtime.NewMissingVersionErr(string(originalData))
  172. }
  173. // use the target if necessary
  174. obj, err := runtime.UseOrCreateObject(s.typer, s.creater, *actual, into)
  175. if err != nil {
  176. return nil, actual, err
  177. }
  178. strictErrs, err := s.unmarshal(obj, data, originalData)
  179. if err != nil {
  180. return nil, actual, err
  181. } else if len(strictErrs) > 0 {
  182. return obj, actual, runtime.NewStrictDecodingError(strictErrs)
  183. }
  184. return obj, actual, nil
  185. }
  186. // Encode serializes the provided object to the given writer.
  187. func (s *Serializer) Encode(obj runtime.Object, w io.Writer) error {
  188. if co, ok := obj.(runtime.CacheableObject); ok {
  189. return co.CacheEncode(s.Identifier(), s.doEncode, w)
  190. }
  191. return s.doEncode(obj, w)
  192. }
  193. func (s *Serializer) doEncode(obj runtime.Object, w io.Writer) error {
  194. if s.options.Yaml {
  195. json, err := json.Marshal(obj)
  196. if err != nil {
  197. return err
  198. }
  199. data, err := yaml.JSONToYAML(json)
  200. if err != nil {
  201. return err
  202. }
  203. _, err = w.Write(data)
  204. return err
  205. }
  206. if s.options.Pretty {
  207. data, err := json.MarshalIndent(obj, "", " ")
  208. if err != nil {
  209. return err
  210. }
  211. _, err = w.Write(data)
  212. return err
  213. }
  214. encoder := json.NewEncoder(w)
  215. return encoder.Encode(obj)
  216. }
  217. // IsStrict indicates whether the serializer
  218. // uses strict decoding or not
  219. func (s *Serializer) IsStrict() bool {
  220. return s.options.Strict
  221. }
  222. func (s *Serializer) unmarshal(into runtime.Object, data, originalData []byte) (strictErrs []error, err error) {
  223. // If the deserializer is non-strict, return here.
  224. if !s.options.Strict {
  225. if err := kjson.UnmarshalCaseSensitivePreserveInts(data, into); err != nil {
  226. return nil, err
  227. }
  228. return nil, nil
  229. }
  230. if s.options.Yaml {
  231. // In strict mode pass the original data through the YAMLToJSONStrict converter.
  232. // This is done to catch duplicate fields in YAML that would have been dropped in the original YAMLToJSON conversion.
  233. // TODO: rework YAMLToJSONStrict to return warnings about duplicate fields without terminating so we don't have to do this twice.
  234. _, err := yaml.YAMLToJSONStrict(originalData)
  235. if err != nil {
  236. strictErrs = append(strictErrs, err)
  237. }
  238. }
  239. var strictJSONErrs []error
  240. if u, isUnstructured := into.(runtime.Unstructured); isUnstructured {
  241. // Unstructured is a custom unmarshaler that gets delegated
  242. // to, so in order to detect strict JSON errors we need
  243. // to unmarshal directly into the object.
  244. m := map[string]interface{}{}
  245. strictJSONErrs, err = kjson.UnmarshalStrict(data, &m)
  246. u.SetUnstructuredContent(m)
  247. } else {
  248. strictJSONErrs, err = kjson.UnmarshalStrict(data, into)
  249. }
  250. if err != nil {
  251. // fatal decoding error, not due to strictness
  252. return nil, err
  253. }
  254. strictErrs = append(strictErrs, strictJSONErrs...)
  255. return strictErrs, nil
  256. }
  257. // Identifier implements runtime.Encoder interface.
  258. func (s *Serializer) Identifier() runtime.Identifier {
  259. return s.identifier
  260. }
  261. // RecognizesData implements the RecognizingDecoder interface.
  262. func (s *Serializer) RecognizesData(data []byte) (ok, unknown bool, err error) {
  263. if s.options.Yaml {
  264. // we could potentially look for '---'
  265. return false, true, nil
  266. }
  267. return utilyaml.IsJSONBuffer(data), false, nil
  268. }
  269. // Framer is the default JSON framing behavior, with newlines delimiting individual objects.
  270. var Framer = jsonFramer{}
  271. type jsonFramer struct{}
  272. // NewFrameWriter implements stream framing for this serializer
  273. func (jsonFramer) NewFrameWriter(w io.Writer) io.Writer {
  274. // we can write JSON objects directly to the writer, because they are self-framing
  275. return w
  276. }
  277. // NewFrameReader implements stream framing for this serializer
  278. func (jsonFramer) NewFrameReader(r io.ReadCloser) io.ReadCloser {
  279. // we need to extract the JSON chunks of data to pass to Decode()
  280. return framer.NewJSONFramedReader(r)
  281. }
  282. // YAMLFramer is the default JSON framing behavior, with newlines delimiting individual objects.
  283. var YAMLFramer = yamlFramer{}
  284. type yamlFramer struct{}
  285. // NewFrameWriter implements stream framing for this serializer
  286. func (yamlFramer) NewFrameWriter(w io.Writer) io.Writer {
  287. return yamlFrameWriter{w}
  288. }
  289. // NewFrameReader implements stream framing for this serializer
  290. func (yamlFramer) NewFrameReader(r io.ReadCloser) io.ReadCloser {
  291. // extract the YAML document chunks directly
  292. return utilyaml.NewDocumentDecoder(r)
  293. }
  294. type yamlFrameWriter struct {
  295. w io.Writer
  296. }
  297. // Write separates each document with the YAML document separator (`---` followed by line
  298. // break). Writers must write well formed YAML documents (include a final line break).
  299. func (w yamlFrameWriter) Write(data []byte) (n int, err error) {
  300. if _, err := w.w.Write([]byte("---\n")); err != nil {
  301. return 0, err
  302. }
  303. return w.w.Write(data)
  304. }