14 "github.com/sirupsen/logrus"
15 "github.com/urfave/cli"
17 "github.com/containernetworking/cni/pkg/skel"
18 "github.com/containernetworking/cni/pkg/types"
19 "github.com/containernetworking/cni/pkg/types/current"
20 "github.com/containernetworking/cni/pkg/version"
21 "k8s.io/apimachinery/pkg/util/wait"
23 "ovn4nfv-k8s-plugin/internal/pkg/kube"
25 "ovn4nfv-k8s-plugin/cmd/ovn4nfvk8s-cni/app"
26 "ovn4nfv-k8s-plugin/internal/pkg/config"
29 func argString2Map(args string) (map[string]string, error) {
30 argsMap := make(map[string]string)
32 pairs := strings.Split(args, ";")
33 for _, pair := range pairs {
34 kv := strings.Split(pair, "=")
36 return nil, fmt.Errorf("ARGS: invalid pair %q", pair)
40 argsMap[keyString] = valueString
46 func parseOvnNetworkObject(ovnnetwork string) ([]map[string]string, error) {
47 var ovnNet []map[string]string
50 return nil, fmt.Errorf("parseOvnNetworkObject:error")
53 if err := json.Unmarshal([]byte(ovnnetwork), &ovnNet); err != nil {
54 return nil, fmt.Errorf("parseOvnNetworkObject: failed to load ovn network err: %v | ovn network: %v", err, ovnnetwork)
60 func mergeWithResult(srcObj, dstObj types.Result) (types.Result, error) {
65 src, err := current.NewResultFromResult(srcObj)
67 return nil, fmt.Errorf("Couldn't convert old result to current version: %v", err)
69 dst, err := current.NewResultFromResult(dstObj)
71 return nil, fmt.Errorf("Couldn't convert old result to current version: %v", err)
74 ifacesLength := len(dst.Interfaces)
76 for _, iface := range src.Interfaces {
77 dst.Interfaces = append(dst.Interfaces, iface)
79 for _, ip := range src.IPs {
80 if ip.Interface != nil && *(ip.Interface) != -1 {
81 ip.Interface = current.Int(*(ip.Interface) + ifacesLength)
83 dst.IPs = append(dst.IPs, ip)
85 for _, route := range src.Routes {
86 dst.Routes = append(dst.Routes, route)
89 for _, ns := range src.DNS.Nameservers {
90 dst.DNS.Nameservers = append(dst.DNS.Nameservers, ns)
92 for _, s := range src.DNS.Search {
93 dst.DNS.Search = append(dst.DNS.Search, s)
95 for _, opt := range src.DNS.Options {
96 dst.DNS.Options = append(dst.DNS.Options, opt)
98 // TODO: what about DNS.domain?
102 func prettyPrint(i interface{}) string {
103 s, _ := json.MarshalIndent(i, "", "\t")
107 func addMultipleInterfaces(args *skel.CmdArgs, ovnAnnotation, namespace, podName string) types.Result {
108 logrus.Infof("ovn4nfvk8s-cni: addMultipleInterfaces ")
110 var ovnAnnotatedMap []map[string]string
111 ovnAnnotatedMap, err := parseOvnNetworkObject(ovnAnnotation)
113 logrus.Errorf("addLogicalPort : Error Parsing Ovn Network List %v", ovnAnnotatedMap)
116 if namespace == "" || podName == "" {
117 logrus.Errorf("required CNI variable missing")
120 var interfacesArray []*current.Interface
122 var result *current.Result
123 var dstResult types.Result
124 for _, ovnNet := range ovnAnnotatedMap {
125 ipAddress := ovnNet["ip_address"]
126 macAddress := ovnNet["mac_address"]
127 gatewayIP := ovnNet["gateway_ip"]
128 defaultGateway := ovnNet["defaultGateway"]
130 if ipAddress == "" || macAddress == "" || gatewayIP == "" {
131 logrus.Errorf("failed in pod annotation key extract")
136 interfaceName := ovnNet["interface"]
137 if interfaceName == "" {
138 logrus.Errorf("addMultipleInterfaces: interface can't be null")
141 logrus.Debugf("addMultipleInterfaces: ipAddress %v %v", ipAddress, interfaceName)
142 interfacesArray, err = app.ConfigureInterface(args, namespace, podName, macAddress, ipAddress, gatewayIP, interfaceName, defaultGateway, config.Default.MTU)
144 logrus.Errorf("Failed to configure interface in pod: %v", err)
147 addr, addrNet, err := net.ParseCIDR(ipAddress)
149 logrus.Errorf("failed to parse IP address %q: %v", ipAddress, err)
153 if addr.To4() != nil {
156 var routes types.Route
157 if defaultGateway == "true" {
158 defaultAddr, defaultAddrNet, _ := net.ParseCIDR("0.0.0.0/0")
159 routes = types.Route{Dst: net.IPNet{IP: defaultAddr, Mask: defaultAddrNet.Mask}, GW: net.ParseIP(gatewayIP)}
161 result = ¤t.Result{
162 Interfaces: interfacesArray,
163 IPs: []*current.IPConfig{
166 Interface: current.Int(1),
167 Address: net.IPNet{IP: addr, Mask: addrNet.Mask},
168 Gateway: net.ParseIP(gatewayIP),
171 Routes: []*types.Route{&routes},
174 result = ¤t.Result{
175 Interfaces: interfacesArray,
176 IPs: []*current.IPConfig{
179 Interface: current.Int(1),
180 Address: net.IPNet{IP: addr, Mask: addrNet.Mask},
181 Gateway: net.ParseIP(gatewayIP),
187 // Build the result structure to pass back to the runtime
188 dstResult, err = mergeWithResult(types.Result(result), dstResult)
190 logrus.Errorf("Failed to merge results: %v", err)
194 logrus.Infof("addMultipleInterfaces: %s", prettyPrint(dstResult))
198 func cmdAdd(args *skel.CmdArgs) error {
199 logrus.Infof("ovn4nfvk8s-cni: cmdAdd ")
200 conf := &types.NetConf{}
201 if err := json.Unmarshal(args.StdinData, conf); err != nil {
202 return fmt.Errorf("failed to load netconf: %v", err)
205 argsMap, err := argString2Map(args.Args)
210 namespace := argsMap["K8S_POD_NAMESPACE"]
211 podName := argsMap["K8S_POD_NAME"]
212 if namespace == "" || podName == "" {
213 return fmt.Errorf("required CNI variable missing")
216 clientset, err := config.NewClientset(&config.Kubernetes)
218 return fmt.Errorf("Could not create clientset for kubernetes: %v", err)
220 kubecli := &kube.Kube{KClient: clientset}
222 // Get the IP address and MAC address from the API server.
223 var annotationBackoff = wait.Backoff{Duration: 1 * time.Second, Steps: 14, Factor: 1.5, Jitter: 0.1}
224 var annotation map[string]string
225 if err := wait.ExponentialBackoff(annotationBackoff, func() (bool, error) {
226 annotation, err = kubecli.GetAnnotationsOnPod(namespace, podName)
228 // TODO: check if err is non recoverable
229 logrus.Warningf("Error while obtaining pod annotations - %v", err)
232 if _, ok := annotation["ovnIfaceList"]; ok {
237 return fmt.Errorf("failed to get pod annotation - %v", err)
239 logrus.Infof("ovn4nfvk8s-cni: Annotation Found ")
240 ovnAnnotation, ok := annotation["ovnIfaceList"]
242 return fmt.Errorf("Error while obtaining pod annotations")
244 result := addMultipleInterfaces(args, ovnAnnotation, namespace, podName)
245 return result.Print()
248 func cmdDel(args *skel.CmdArgs) error {
249 logrus.Infof("ovn4nfvk8s-cni: cmdDel ")
250 for i := 0; i < 10; i++ {
251 ifaceName := args.ContainerID[:14] + strconv.Itoa(i)
252 done, err := app.PlatformSpecificCleanup(ifaceName)
254 logrus.Errorf("Teardown error: %v", err)
264 logrus.Infof("ovn4nfvk8s-cni CNI Invoked by Multus")
266 c.Name = "ovn4nfvk8s-cni"
267 c.Usage = "a CNI plugin to set up or tear down a additional interfaces with OVN"
269 c.Flags = config.Flags
271 c.Action = func(ctx *cli.Context) error {
272 if _, err := config.InitConfig(ctx); err != nil {
276 skel.PluginMain(cmdAdd, cmdDel, version.All)
280 if err := c.Run(os.Args); err != nil {
281 // Print the error to stdout in conformance with the CNI spec
282 e, ok := err.(*types.Error)
284 e = &types.Error{Code: 100, Msg: err.Error()}