Seed code for the Plugin
[ovn4nfv-k8s-plugin.git] / internal / pkg / ovn / ovn.go
1 package ovn
2
3 import (
4         "fmt"
5         kapi "k8s.io/api/core/v1"
6         "k8s.io/client-go/kubernetes"
7         "k8s.io/client-go/tools/cache"
8         "ovn4nfv-k8s-plugin/internal/pkg/factory"
9         "ovn4nfv-k8s-plugin/internal/pkg/kube"
10 )
11
12 // Controller structure is the object which holds the controls for starting
13 // and reacting upon the watched resources (e.g. pods, endpoints)
14 type Controller struct {
15         kube         kube.Interface
16         watchFactory *factory.WatchFactory
17
18         gatewayCache map[string]string
19         // A cache of all logical switches seen by the watcher
20         logicalSwitchCache map[string]bool
21         // A cache of all logical ports seen by the watcher and
22         // its corresponding logical switch
23         logicalPortCache map[string]string
24 }
25
26 // NewOvnController creates a new OVN controller for creating logical network
27 // infrastructure and policy
28 func NewOvnController(kubeClient kubernetes.Interface, wf *factory.WatchFactory) *Controller {
29         return &Controller{
30                 kube:               &kube.Kube{KClient: kubeClient},
31                 watchFactory:       wf,
32                 logicalSwitchCache: make(map[string]bool),
33                 logicalPortCache:   make(map[string]string),
34                 gatewayCache:       make(map[string]string),
35         }
36 }
37
38 // Run starts the actual watching. Also initializes any local structures needed.
39 func (oc *Controller) Run() error {
40         fmt.Println("ovn4nfvk8s watching Pods")
41         for _, f := range []func() error{oc.WatchPods} {
42                 if err := f(); err != nil {
43                         return err
44                 }
45         }
46         return nil
47 }
48
49 // WatchPods starts the watching of Pod resource and calls back the appropriate handler logic
50 func (oc *Controller) WatchPods() error {
51         _, err := oc.watchFactory.AddPodHandler(cache.ResourceEventHandlerFuncs{
52                 AddFunc: func(obj interface{}) {
53                         pod := obj.(*kapi.Pod)
54                         if pod.Spec.NodeName != "" {
55                                 oc.addLogicalPort(pod)
56                         }
57                 },
58                 UpdateFunc: func(old, newer interface{}) {
59                         podNew := newer.(*kapi.Pod)
60                         podOld := old.(*kapi.Pod)
61                         if podOld.Spec.NodeName == "" && podNew.Spec.NodeName != "" {
62                                 oc.addLogicalPort(podNew)
63                         }
64                 },
65                 DeleteFunc: func(obj interface{}) {
66                         pod := obj.(*kapi.Pod)
67                         oc.deleteLogicalPort(pod)
68                 },
69         }, oc.syncPods)
70         return err
71 }