...

Source file src/edge-infra.dev/pkg/k8s/decoder/decoder.go

Documentation: edge-infra.dev/pkg/k8s/decoder

     1  // Package decoder provides common functionality for parsing raw data containing
     2  // K8s resources into structs that can then be applied via the K8s API.
     3  //
     4  // A common use case is reading embedded manifest bundles or manifest files from
     5  // disk (represented as byte[]) and applying them, similar to `kubectl apply`
     6  package decoder
     7  
     8  import (
     9  	"bytes"
    10  
    11  	"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
    12  	"k8s.io/apimachinery/pkg/runtime"
    13  	yamlutil "k8s.io/apimachinery/pkg/util/yaml"
    14  )
    15  
    16  // DecodeYAML decodes data containing a multi-doc YAML file into an array
    17  // of K8s resources, which can be applied to the K8s API via client-go
    18  func DecodeYAML(d []byte) ([]*unstructured.Unstructured, error) {
    19  	var manifests []*unstructured.Unstructured
    20  	// setup decoder for our multidoc YAML file, so we can output individual
    21  	decoder := yamlutil.NewYAMLToJSONDecoder(bytes.NewReader(d))
    22  
    23  	for {
    24  		// read a document from our multidoc yaml file
    25  		var rawObj runtime.RawExtension
    26  		if err := decoder.Decode(&rawObj); err != nil {
    27  			break
    28  		}
    29  
    30  		// decode using unstructured JSON scheme
    31  		obj := &unstructured.Unstructured{}
    32  		if rawObj.Size() == 0 {
    33  			continue
    34  		}
    35  		if err := obj.UnmarshalJSON(rawObj.Raw); err != nil {
    36  			return nil, err
    37  		}
    38  
    39  		// add usable unstructured.Unstructured object to our array of
    40  		// manifests
    41  		manifests = append(manifests, obj)
    42  	}
    43  
    44  	return manifests, nil
    45  }
    46  

View as plain text