k8s.io/perf-tests/clusterloader2@v0.0.0-20240304094227-64bdb12da87e/pkg/config/codec.go (about) 1 /* 2 Copyright 2018 The Kubernetes Authors. 3 4 Licensed under the Apache License, Version 2.0 (the "License"); 5 you may not use this file except in compliance with the License. 6 You may obtain a copy of the License at 7 8 http://www.apache.org/licenses/LICENSE-2.0 9 10 Unless required by applicable law or agreed to in writing, software 11 distributed under the License is distributed on an "AS IS" BASIS, 12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 See the License for the specific language governing permissions and 14 limitations under the License. 15 */ 16 17 package config 18 19 import ( 20 "bytes" 21 "errors" 22 "fmt" 23 "strings" 24 25 "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" 26 "k8s.io/apimachinery/pkg/util/yaml" 27 "k8s.io/client-go/kubernetes/scheme" 28 ) 29 30 var ( 31 // ErrorEmptyFile indicates that manifest file was empty. 32 // Useful to distinguish where the manifast was empty or malformed. 33 ErrorEmptyFile = errors.New("emptyfile") 34 ) 35 36 // convertToObject converts array of bytes into unstructured object. 37 func convertToObject(raw []byte) (*unstructured.Unstructured, error) { 38 if isEmpty(raw) { 39 return nil, ErrorEmptyFile 40 } 41 obj := &unstructured.Unstructured{} 42 _, _, err := scheme.Codecs.UniversalDeserializer().Decode(raw, nil, obj) 43 if err != nil { 44 return nil, fmt.Errorf("unmarshaling error: %v", err) 45 } 46 return obj, nil 47 } 48 49 func decodeInto(raw []byte, v interface{}) error { 50 if err := yaml.NewYAMLOrJSONDecoder(bytes.NewBuffer(raw), 4096).Decode(v); err != nil { 51 return fmt.Errorf("decoding failed: %v", err) 52 } 53 return nil 54 } 55 56 func isEmpty(raw []byte) bool { 57 return strings.TrimSpace(string(raw[:])) == "" 58 }