Merge "Code cleanup"
[ovn4nfv-k8s-plugin.git] / cmd / ovn4nfvk8s-cni / ovn4nfvk8s-cni.go
1 // +build linux
2
3 package main
4
5 import (
6         "encoding/json"
7         "fmt"
8         "net"
9         "os"
10         "strconv"
11         "strings"
12         "time"
13
14         "github.com/sirupsen/logrus"
15         "github.com/urfave/cli"
16
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"
22
23         "ovn4nfv-k8s-plugin/internal/pkg/kube"
24
25         "ovn4nfv-k8s-plugin/cmd/ovn4nfvk8s-cni/app"
26         "ovn4nfv-k8s-plugin/internal/pkg/config"
27 )
28
29 func argString2Map(args string) (map[string]string, error) {
30         argsMap := make(map[string]string)
31
32         pairs := strings.Split(args, ";")
33         for _, pair := range pairs {
34                 kv := strings.Split(pair, "=")
35                 if len(kv) != 2 {
36                         return nil, fmt.Errorf("ARGS: invalid pair %q", pair)
37                 }
38                 keyString := kv[0]
39                 valueString := kv[1]
40                 argsMap[keyString] = valueString
41         }
42
43         return argsMap, nil
44 }
45
46 func parseOvnNetworkObject(ovnnetwork string) ([]map[string]string, error) {
47         var ovnNet []map[string]string
48
49         if ovnnetwork == "" {
50                 return nil, fmt.Errorf("parseOvnNetworkObject:error")
51         }
52
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)
55         }
56
57         return ovnNet, nil
58 }
59
60 func mergeWithResult(srcObj, dstObj types.Result) (types.Result, error) {
61
62         if dstObj == nil {
63                 return srcObj, nil
64         }
65         src, err := current.NewResultFromResult(srcObj)
66         if err != nil {
67                 return nil, fmt.Errorf("Couldn't convert old result to current version: %v", err)
68         }
69         dst, err := current.NewResultFromResult(dstObj)
70         if err != nil {
71                 return nil, fmt.Errorf("Couldn't convert old result to current version: %v", err)
72         }
73
74         ifacesLength := len(dst.Interfaces)
75
76         for _, iface := range src.Interfaces {
77                 dst.Interfaces = append(dst.Interfaces, iface)
78         }
79         for _, ip := range src.IPs {
80                 if ip.Interface != nil && *(ip.Interface) != -1 {
81                         ip.Interface = current.Int(*(ip.Interface) + ifacesLength)
82                 }
83                 dst.IPs = append(dst.IPs, ip)
84         }
85         for _, route := range src.Routes {
86                 dst.Routes = append(dst.Routes, route)
87         }
88
89         for _, ns := range src.DNS.Nameservers {
90                 dst.DNS.Nameservers = append(dst.DNS.Nameservers, ns)
91         }
92         for _, s := range src.DNS.Search {
93                 dst.DNS.Search = append(dst.DNS.Search, s)
94         }
95         for _, opt := range src.DNS.Options {
96                 dst.DNS.Options = append(dst.DNS.Options, opt)
97         }
98         // TODO: what about DNS.domain?
99         return dst, nil
100 }
101
102 func prettyPrint(i interface{}) string {
103         s, _ := json.MarshalIndent(i, "", "\t")
104         return string(s)
105 }
106
107 func addMultipleInterfaces(args *skel.CmdArgs, ovnAnnotation, namespace, podName string) types.Result {
108         logrus.Infof("ovn4nfvk8s-cni: addMultipleInterfaces ")
109
110         var ovnAnnotatedMap []map[string]string
111         ovnAnnotatedMap, err := parseOvnNetworkObject(ovnAnnotation)
112         if err != nil {
113                 logrus.Errorf("addLogicalPort : Error Parsing Ovn Network List %v", ovnAnnotatedMap)
114                 return nil
115         }
116         if namespace == "" || podName == "" {
117                 logrus.Errorf("required CNI variable missing")
118                 return nil
119         }
120         var interfacesArray []*current.Interface
121         var index int
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"]
129
130                 if ipAddress == "" || macAddress == "" {
131                         logrus.Errorf("failed in pod annotation key extract")
132                         return nil
133                 }
134
135                 index++
136                 interfaceName := ovnNet["interface"]
137                 if interfaceName == "" {
138                         logrus.Errorf("addMultipleInterfaces: interface can't be null")
139                         return nil
140                 }
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)
143                 if err != nil {
144                         logrus.Errorf("Failed to configure interface in pod: %v", err)
145                         return nil
146                 }
147                 addr, addrNet, err := net.ParseCIDR(ipAddress)
148                 if err != nil {
149                         logrus.Errorf("failed to parse IP address %q: %v", ipAddress, err)
150                         return nil
151                 }
152                 ipVersion := "6"
153                 if addr.To4() != nil {
154                         ipVersion = "4"
155                 }
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)}
160
161                         result = &current.Result{
162                                 Interfaces: interfacesArray,
163                                 IPs: []*current.IPConfig{
164                                         {
165                                                 Version:   ipVersion,
166                                                 Interface: current.Int(1),
167                                                 Address:   net.IPNet{IP: addr, Mask: addrNet.Mask},
168                                                 Gateway:   net.ParseIP(gatewayIP),
169                                         },
170                                 },
171                                 Routes: []*types.Route{&routes},
172                         }
173                 } else {
174                         result = &current.Result{
175                                 Interfaces: interfacesArray,
176                                 IPs: []*current.IPConfig{
177                                         {
178                                                 Version:   ipVersion,
179                                                 Interface: current.Int(1),
180                                                 Address:   net.IPNet{IP: addr, Mask: addrNet.Mask},
181                                                 Gateway:   net.ParseIP(gatewayIP),
182                                         },
183                                 },
184                         }
185
186                 }
187                 // Build the result structure to pass back to the runtime
188                 dstResult, err = mergeWithResult(types.Result(result), dstResult)
189                 if err != nil {
190                         logrus.Errorf("Failed to merge results: %v", err)
191                         return nil
192                 }
193         }
194         logrus.Infof("addMultipleInterfaces:  %s", prettyPrint(dstResult))
195         return dstResult
196 }
197
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)
203         }
204
205         argsMap, err := argString2Map(args.Args)
206         if err != nil {
207                 return err
208         }
209
210         namespace := argsMap["K8S_POD_NAMESPACE"]
211         podName := argsMap["K8S_POD_NAME"]
212         if namespace == "" || podName == "" {
213                 return fmt.Errorf("required CNI variable missing")
214         }
215
216         clientset, err := config.NewClientset(&config.Kubernetes)
217         if err != nil {
218                 return fmt.Errorf("Could not create clientset for kubernetes: %v", err)
219         }
220         kubecli := &kube.Kube{KClient: clientset}
221
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)
227                 if err != nil {
228                         // TODO: check if err is non recoverable
229                         logrus.Warningf("Error while obtaining pod annotations - %v", err)
230                         return false, nil
231                 }
232                 if _, ok := annotation["ovnIfaceList"]; ok {
233                         return true, nil
234                 }
235                 return false, nil
236         }); err != nil {
237                 return fmt.Errorf("failed to get pod annotation - %v", err)
238         }
239         logrus.Infof("ovn4nfvk8s-cni: Annotation Found ")
240         ovnAnnotation, ok := annotation["ovnIfaceList"]
241         if !ok {
242                 return fmt.Errorf("Error while obtaining pod annotations")
243         }
244         result := addMultipleInterfaces(args, ovnAnnotation, namespace, podName)
245         return result.Print()
246 }
247
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)
253                 if err != nil {
254                         logrus.Errorf("Teardown error: %v", err)
255                 }
256                 if done {
257                         break
258                 }
259         }
260         return nil
261 }
262
263 func main() {
264         logrus.Infof("ovn4nfvk8s-cni CNI Invoked by Multus")
265         c := cli.NewApp()
266         c.Name = "ovn4nfvk8s-cni"
267         c.Usage = "a CNI plugin to set up or tear down a additional interfaces with OVN"
268         c.Version = "0.0.2"
269         c.Flags = config.Flags
270
271         c.Action = func(ctx *cli.Context) error {
272                 if _, err := config.InitConfig(ctx); err != nil {
273                         return err
274                 }
275
276                 skel.PluginMain(cmdAdd, cmdDel, version.All)
277                 return nil
278         }
279
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)
283                 if !ok {
284                         e = &types.Error{Code: 100, Msg: err.Error()}
285                 }
286                 e.Print()
287         }
288 }