github.com/openshift/dpu-operator@v0.0.0-20240502153209-3af840d137c2/dpu-cni/pkgs/cnihelper/cnihelper.go (about)

     1  package cnihelper
     2  
     3  import (
     4  	"encoding/json"
     5  	"os"
     6  	"strings"
     7  
     8  	"github.com/containernetworking/cni/pkg/skel"
     9  	"github.com/containernetworking/cni/pkg/version"
    10  	"github.com/openshift/dpu-operator/dpu-cni/pkgs/cnitypes"
    11  )
    12  
    13  // newCNIRequest creates and fills a Request with this CNI Plugin's environment and
    14  // stdin which contains the CNI variables and configuration.
    15  func NewCNIRequest(args *skel.CmdArgs) *cnitypes.Request {
    16  	envMap := make(map[string]string)
    17  	for _, item := range os.Environ() {
    18  		idx := strings.Index(item, "=")
    19  		if idx > 0 {
    20  			envMap[strings.TrimSpace(item[:idx])] = item[idx+1:]
    21  		}
    22  	}
    23  	return &cnitypes.Request{
    24  		Env:    envMap,
    25  		Config: args.StdinData,
    26  	}
    27  }
    28  
    29  // parseNetconf parses the cni config to a NetConf data structure.
    30  func parseNetConf(bytes []byte) (*cnitypes.NetConf, error) {
    31  	netconf := &cnitypes.NetConf{}
    32  	err := json.Unmarshal(bytes, &netconf)
    33  	if err != nil {
    34  		return nil, err
    35  	}
    36  
    37  	return netconf, nil
    38  }
    39  
    40  // ReadCNIConfig unmarshals a CNI JSON config into an NetConf structure.
    41  func ReadCNIConfig(bytes []byte) (*cnitypes.NetConf, error) {
    42  	conf, err := parseNetConf(bytes)
    43  	if err != nil {
    44  		return nil, err
    45  	}
    46  	if conf.RawPrevResult != nil {
    47  		if err := version.ParsePrevResult(&conf.NetConf); err != nil {
    48  			return nil, err
    49  		}
    50  	}
    51  	return conf, nil
    52  }