istio.io/istio@v0.0.0-20240520182934-d79c90f27776/operator/pkg/apis/istio/common.go (about) 1 // Copyright Istio Authors 2 // 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 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 package istio 16 17 import ( 18 "fmt" 19 20 "sigs.k8s.io/yaml" 21 22 "istio.io/api/operator/v1alpha1" 23 operator_v1alpha1 "istio.io/istio/operator/pkg/apis/istio/v1alpha1" 24 "istio.io/istio/operator/pkg/util" 25 "istio.io/istio/operator/pkg/validate" 26 ) 27 28 // UnmarshalAndValidateIOPS unmarshals a string containing IstioOperator YAML, validates it, and returns a struct 29 // representation if successful. In case of validation errors, it returns both the IstioOperatorSpec struct and 30 // an error, so the caller can decide how to handle it. 31 func UnmarshalAndValidateIOPS(iopsYAML string) (*v1alpha1.IstioOperatorSpec, error) { 32 iops := &v1alpha1.IstioOperatorSpec{} 33 if err := util.UnmarshalWithJSONPB(iopsYAML, iops, false); err != nil { 34 return nil, fmt.Errorf("could not unmarshal the merged YAML: %s\n\nYAML:\n%s", err, iopsYAML) 35 } 36 if errs := validate.CheckIstioOperatorSpec(iops, true); len(errs) != 0 { 37 return iops, fmt.Errorf(errs.Error()) 38 } 39 return iops, nil 40 } 41 42 // UnmarshalIstioOperator unmarshals a string containing IstioOperator YAML. 43 func UnmarshalIstioOperator(iopYAML string, allowUnknownField bool) (*operator_v1alpha1.IstioOperator, error) { 44 iop := &operator_v1alpha1.IstioOperator{} 45 if allowUnknownField { 46 if err := yaml.Unmarshal([]byte(iopYAML), iop); err != nil { 47 return nil, fmt.Errorf("could not unmarshal: %v", err) 48 } 49 } else { 50 if err := yaml.UnmarshalStrict([]byte(iopYAML), iop); err != nil { 51 return nil, fmt.Errorf("could not unmarshal: %v", err) 52 } 53 } 54 return iop, nil 55 }