blob: e081d7ff19324f62ef6c5129ccd0b99f53bfb1ee [file] [log] [blame]
Matteo Scandoloa4285862020-12-01 18:10:10 -08001/*
2Copyright 2014 The Kubernetes Authors.
3
4Licensed under the Apache License, Version 2.0 (the "License");
5you may not use this file except in compliance with the License.
6You may obtain a copy of the License at
7
8 http://www.apache.org/licenses/LICENSE-2.0
9
10Unless required by applicable law or agreed to in writing, software
11distributed under the License is distributed on an "AS IS" BASIS,
12WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13See the License for the specific language governing permissions and
14limitations under the License.
15*/
16
17package json
18
19import (
20 "encoding/json"
21 "io"
22 "strconv"
23 "unsafe"
24
25 jsoniter "github.com/json-iterator/go"
26 "github.com/modern-go/reflect2"
27 "sigs.k8s.io/yaml"
28
29 "k8s.io/apimachinery/pkg/runtime"
30 "k8s.io/apimachinery/pkg/runtime/schema"
31 "k8s.io/apimachinery/pkg/runtime/serializer/recognizer"
32 "k8s.io/apimachinery/pkg/util/framer"
33 utilyaml "k8s.io/apimachinery/pkg/util/yaml"
34 "k8s.io/klog/v2"
35)
36
37// NewSerializer creates a JSON serializer that handles encoding versioned objects into the proper JSON form. If typer
38// is not nil, the object has the group, version, and kind fields set.
39// Deprecated: use NewSerializerWithOptions instead.
40func NewSerializer(meta MetaFactory, creater runtime.ObjectCreater, typer runtime.ObjectTyper, pretty bool) *Serializer {
41 return NewSerializerWithOptions(meta, creater, typer, SerializerOptions{false, pretty, false})
42}
43
44// NewYAMLSerializer creates a YAML serializer that handles encoding versioned objects into the proper YAML form. If typer
45// is not nil, the object has the group, version, and kind fields set. This serializer supports only the subset of YAML that
46// matches JSON, and will error if constructs are used that do not serialize to JSON.
47// Deprecated: use NewSerializerWithOptions instead.
48func NewYAMLSerializer(meta MetaFactory, creater runtime.ObjectCreater, typer runtime.ObjectTyper) *Serializer {
49 return NewSerializerWithOptions(meta, creater, typer, SerializerOptions{true, false, false})
50}
51
52// NewSerializerWithOptions creates a JSON/YAML serializer that handles encoding versioned objects into the proper JSON/YAML
53// form. If typer is not nil, the object has the group, version, and kind fields set. Options are copied into the Serializer
54// and are immutable.
55func NewSerializerWithOptions(meta MetaFactory, creater runtime.ObjectCreater, typer runtime.ObjectTyper, options SerializerOptions) *Serializer {
56 return &Serializer{
57 meta: meta,
58 creater: creater,
59 typer: typer,
60 options: options,
61 identifier: identifier(options),
62 }
63}
64
65// identifier computes Identifier of Encoder based on the given options.
66func identifier(options SerializerOptions) runtime.Identifier {
67 result := map[string]string{
68 "name": "json",
69 "yaml": strconv.FormatBool(options.Yaml),
70 "pretty": strconv.FormatBool(options.Pretty),
71 }
72 identifier, err := json.Marshal(result)
73 if err != nil {
74 klog.Fatalf("Failed marshaling identifier for json Serializer: %v", err)
75 }
76 return runtime.Identifier(identifier)
77}
78
79// SerializerOptions holds the options which are used to configure a JSON/YAML serializer.
80// example:
81// (1) To configure a JSON serializer, set `Yaml` to `false`.
82// (2) To configure a YAML serializer, set `Yaml` to `true`.
83// (3) To configure a strict serializer that can return strictDecodingError, set `Strict` to `true`.
84type SerializerOptions struct {
85 // Yaml: configures the Serializer to work with JSON(false) or YAML(true).
86 // When `Yaml` is enabled, this serializer only supports the subset of YAML that
87 // matches JSON, and will error if constructs are used that do not serialize to JSON.
88 Yaml bool
89
90 // Pretty: configures a JSON enabled Serializer(`Yaml: false`) to produce human-readable output.
91 // This option is silently ignored when `Yaml` is `true`.
92 Pretty bool
93
94 // Strict: configures the Serializer to return strictDecodingError's when duplicate fields are present decoding JSON or YAML.
95 // Note that enabling this option is not as performant as the non-strict variant, and should not be used in fast paths.
96 Strict bool
97}
98
99type Serializer struct {
100 meta MetaFactory
101 options SerializerOptions
102 creater runtime.ObjectCreater
103 typer runtime.ObjectTyper
104
105 identifier runtime.Identifier
106}
107
108// Serializer implements Serializer
109var _ runtime.Serializer = &Serializer{}
110var _ recognizer.RecognizingDecoder = &Serializer{}
111
112type customNumberExtension struct {
113 jsoniter.DummyExtension
114}
115
116func (cne *customNumberExtension) CreateDecoder(typ reflect2.Type) jsoniter.ValDecoder {
117 if typ.String() == "interface {}" {
118 return customNumberDecoder{}
119 }
120 return nil
121}
122
123type customNumberDecoder struct {
124}
125
126func (customNumberDecoder) Decode(ptr unsafe.Pointer, iter *jsoniter.Iterator) {
127 switch iter.WhatIsNext() {
128 case jsoniter.NumberValue:
129 var number jsoniter.Number
130 iter.ReadVal(&number)
131 i64, err := strconv.ParseInt(string(number), 10, 64)
132 if err == nil {
133 *(*interface{})(ptr) = i64
134 return
135 }
136 f64, err := strconv.ParseFloat(string(number), 64)
137 if err == nil {
138 *(*interface{})(ptr) = f64
139 return
140 }
141 iter.ReportError("DecodeNumber", err.Error())
142 default:
143 *(*interface{})(ptr) = iter.Read()
144 }
145}
146
147// CaseSensitiveJsonIterator returns a jsoniterator API that's configured to be
148// case-sensitive when unmarshalling, and otherwise compatible with
149// the encoding/json standard library.
150func CaseSensitiveJsonIterator() jsoniter.API {
151 config := jsoniter.Config{
152 EscapeHTML: true,
153 SortMapKeys: true,
154 ValidateJsonRawMessage: true,
155 CaseSensitive: true,
156 }.Froze()
157 // Force jsoniter to decode number to interface{} via int64/float64, if possible.
158 config.RegisterExtension(&customNumberExtension{})
159 return config
160}
161
162// StrictCaseSensitiveJsonIterator returns a jsoniterator API that's configured to be
163// case-sensitive, but also disallows unknown fields when unmarshalling. It is compatible with
164// the encoding/json standard library.
165func StrictCaseSensitiveJsonIterator() jsoniter.API {
166 config := jsoniter.Config{
167 EscapeHTML: true,
168 SortMapKeys: true,
169 ValidateJsonRawMessage: true,
170 CaseSensitive: true,
171 DisallowUnknownFields: true,
172 }.Froze()
173 // Force jsoniter to decode number to interface{} via int64/float64, if possible.
174 config.RegisterExtension(&customNumberExtension{})
175 return config
176}
177
178// Private copies of jsoniter to try to shield against possible mutations
179// from outside. Still does not protect from package level jsoniter.Register*() functions - someone calling them
180// in some other library will mess with every usage of the jsoniter library in the whole program.
181// See https://github.com/json-iterator/go/issues/265
182var caseSensitiveJsonIterator = CaseSensitiveJsonIterator()
183var strictCaseSensitiveJsonIterator = StrictCaseSensitiveJsonIterator()
184
185// gvkWithDefaults returns group kind and version defaulting from provided default
186func gvkWithDefaults(actual, defaultGVK schema.GroupVersionKind) schema.GroupVersionKind {
187 if len(actual.Kind) == 0 {
188 actual.Kind = defaultGVK.Kind
189 }
190 if len(actual.Version) == 0 && len(actual.Group) == 0 {
191 actual.Group = defaultGVK.Group
192 actual.Version = defaultGVK.Version
193 }
194 if len(actual.Version) == 0 && actual.Group == defaultGVK.Group {
195 actual.Version = defaultGVK.Version
196 }
197 return actual
198}
199
200// Decode attempts to convert the provided data into YAML or JSON, extract the stored schema kind, apply the provided default gvk, and then
201// load that data into an object matching the desired schema kind or the provided into.
202// If into is *runtime.Unknown, the raw data will be extracted and no decoding will be performed.
203// If into is not registered with the typer, then the object will be straight decoded using normal JSON/YAML unmarshalling.
204// 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.
205// If into is nil or data's gvk different from into's gvk, it will generate a new Object with ObjectCreater.New(gvk)
206// On success or most errors, the method will return the calculated schema kind.
207// The gvk calculate priority will be originalData > default gvk > into
208func (s *Serializer) Decode(originalData []byte, gvk *schema.GroupVersionKind, into runtime.Object) (runtime.Object, *schema.GroupVersionKind, error) {
209 data := originalData
210 if s.options.Yaml {
211 altered, err := yaml.YAMLToJSON(data)
212 if err != nil {
213 return nil, nil, err
214 }
215 data = altered
216 }
217
218 actual, err := s.meta.Interpret(data)
219 if err != nil {
220 return nil, nil, err
221 }
222
223 if gvk != nil {
224 *actual = gvkWithDefaults(*actual, *gvk)
225 }
226
227 if unk, ok := into.(*runtime.Unknown); ok && unk != nil {
228 unk.Raw = originalData
229 unk.ContentType = runtime.ContentTypeJSON
230 unk.GetObjectKind().SetGroupVersionKind(*actual)
231 return unk, actual, nil
232 }
233
234 if into != nil {
235 _, isUnstructured := into.(runtime.Unstructured)
236 types, _, err := s.typer.ObjectKinds(into)
237 switch {
238 case runtime.IsNotRegisteredError(err), isUnstructured:
239 if err := caseSensitiveJsonIterator.Unmarshal(data, into); err != nil {
240 return nil, actual, err
241 }
242 return into, actual, nil
243 case err != nil:
244 return nil, actual, err
245 default:
246 *actual = gvkWithDefaults(*actual, types[0])
247 }
248 }
249
250 if len(actual.Kind) == 0 {
251 return nil, actual, runtime.NewMissingKindErr(string(originalData))
252 }
253 if len(actual.Version) == 0 {
254 return nil, actual, runtime.NewMissingVersionErr(string(originalData))
255 }
256
257 // use the target if necessary
258 obj, err := runtime.UseOrCreateObject(s.typer, s.creater, *actual, into)
259 if err != nil {
260 return nil, actual, err
261 }
262
263 if err := caseSensitiveJsonIterator.Unmarshal(data, obj); err != nil {
264 return nil, actual, err
265 }
266
267 // If the deserializer is non-strict, return successfully here.
268 if !s.options.Strict {
269 return obj, actual, nil
270 }
271
272 // In strict mode pass the data trough the YAMLToJSONStrict converter.
273 // This is done to catch duplicate fields regardless of encoding (JSON or YAML). For JSON data,
274 // the output would equal the input, unless there is a parsing error such as duplicate fields.
275 // As we know this was successful in the non-strict case, the only error that may be returned here
276 // is because of the newly-added strictness. hence we know we can return the typed strictDecoderError
277 // the actual error is that the object contains duplicate fields.
278 altered, err := yaml.YAMLToJSONStrict(originalData)
279 if err != nil {
280 return nil, actual, runtime.NewStrictDecodingError(err.Error(), string(originalData))
281 }
282 // As performance is not an issue for now for the strict deserializer (one has regardless to do
283 // the unmarshal twice), we take the sanitized, altered data that is guaranteed to have no duplicated
284 // fields, and unmarshal this into a copy of the already-populated obj. Any error that occurs here is
285 // due to that a matching field doesn't exist in the object. hence we can return a typed strictDecoderError,
286 // the actual error is that the object contains unknown field.
287 strictObj := obj.DeepCopyObject()
288 if err := strictCaseSensitiveJsonIterator.Unmarshal(altered, strictObj); err != nil {
289 return nil, actual, runtime.NewStrictDecodingError(err.Error(), string(originalData))
290 }
291 // Always return the same object as the non-strict serializer to avoid any deviations.
292 return obj, actual, nil
293}
294
295// Encode serializes the provided object to the given writer.
296func (s *Serializer) Encode(obj runtime.Object, w io.Writer) error {
297 if co, ok := obj.(runtime.CacheableObject); ok {
298 return co.CacheEncode(s.Identifier(), s.doEncode, w)
299 }
300 return s.doEncode(obj, w)
301}
302
303func (s *Serializer) doEncode(obj runtime.Object, w io.Writer) error {
304 if s.options.Yaml {
305 json, err := caseSensitiveJsonIterator.Marshal(obj)
306 if err != nil {
307 return err
308 }
309 data, err := yaml.JSONToYAML(json)
310 if err != nil {
311 return err
312 }
313 _, err = w.Write(data)
314 return err
315 }
316
317 if s.options.Pretty {
318 data, err := caseSensitiveJsonIterator.MarshalIndent(obj, "", " ")
319 if err != nil {
320 return err
321 }
322 _, err = w.Write(data)
323 return err
324 }
325 encoder := json.NewEncoder(w)
326 return encoder.Encode(obj)
327}
328
329// Identifier implements runtime.Encoder interface.
330func (s *Serializer) Identifier() runtime.Identifier {
331 return s.identifier
332}
333
334// RecognizesData implements the RecognizingDecoder interface.
335func (s *Serializer) RecognizesData(peek io.Reader) (ok, unknown bool, err error) {
336 if s.options.Yaml {
337 // we could potentially look for '---'
338 return false, true, nil
339 }
340 _, _, ok = utilyaml.GuessJSONStream(peek, 2048)
341 return ok, false, nil
342}
343
344// Framer is the default JSON framing behavior, with newlines delimiting individual objects.
345var Framer = jsonFramer{}
346
347type jsonFramer struct{}
348
349// NewFrameWriter implements stream framing for this serializer
350func (jsonFramer) NewFrameWriter(w io.Writer) io.Writer {
351 // we can write JSON objects directly to the writer, because they are self-framing
352 return w
353}
354
355// NewFrameReader implements stream framing for this serializer
356func (jsonFramer) NewFrameReader(r io.ReadCloser) io.ReadCloser {
357 // we need to extract the JSON chunks of data to pass to Decode()
358 return framer.NewJSONFramedReader(r)
359}
360
361// YAMLFramer is the default JSON framing behavior, with newlines delimiting individual objects.
362var YAMLFramer = yamlFramer{}
363
364type yamlFramer struct{}
365
366// NewFrameWriter implements stream framing for this serializer
367func (yamlFramer) NewFrameWriter(w io.Writer) io.Writer {
368 return yamlFrameWriter{w}
369}
370
371// NewFrameReader implements stream framing for this serializer
372func (yamlFramer) NewFrameReader(r io.ReadCloser) io.ReadCloser {
373 // extract the YAML document chunks directly
374 return utilyaml.NewDocumentDecoder(r)
375}
376
377type yamlFrameWriter struct {
378 w io.Writer
379}
380
381// Write separates each document with the YAML document separator (`---` followed by line
382// break). Writers must write well formed YAML documents (include a final line break).
383func (w yamlFrameWriter) Write(data []byte) (n int, err error) {
384 if _, err := w.w.Write([]byte("---\n")); err != nil {
385 return 0, err
386 }
387 return w.w.Write(data)
388}