/
main.go
81 lines (68 loc) · 2.41 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
package main
import (
"context"
"flag"
"fmt"
"os"
"time"
utilruntime "k8s.io/apimachinery/pkg/util/runtime"
kubeinformers "k8s.io/client-go/informers"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/tools/cache"
"k8s.io/klog/v2"
"github.com/dixudx/yacht"
"github.com/dixudx/yacht/utils"
)
func main() {
klog.InitFlags(flag.CommandLine)
defer klog.Flush()
var kubeconfig string
flag.StringVar(&kubeconfig, "kubeconfig", "", "Path to a kubeconfig. Only required if out-of-cluster.")
flag.Parse()
ctx := context.TODO()
// 0. load kubeconfig and create clientset/informers/listers
config, err := utils.LoadsKubeConfig(kubeconfig) // TODO: we need to use an explicit configfile when running locally
if err != nil {
fmt.Println(err)
os.Exit(1)
}
kubeClient := kubernetes.NewForConfigOrDie(config)
kubeInformerFactory := kubeinformers.NewSharedInformerFactory(kubeClient, time.Hour*12)
nsLister := kubeInformerFactory.Core().V1().Namespaces().Lister()
// 1. create a controller for namespaces and use lease for leader election
namespaceController := yacht.NewController("namespaces").
WithWorkers(2).
WithLeaderElection(utils.NewLeaseLock(
"yacht-lease-demo",
"default",
"my-uuid", // TODO: we can generate a random uuid
kubeClient.CoordinationV1(),
),
15*time.Second,
10*time.Second,
2*time.Second,
).
WithHandlerFunc(func(key interface{}) (requeueAfter *time.Duration, err error) {
// We can use "WithEnqueueFunc" to set our own enqueueFunc, otherwise default namespacedKey will be used
// Convert the namespace/name string into a distinct namespace and name
_, name, err := cache.SplitMetaNamespaceKey(key.(string))
if err != nil {
utilruntime.HandleError(fmt.Errorf("invalid resource key: %s", key))
return nil, err
}
// TODO: we can add our real logics here
ns, err := nsLister.Get(name)
if err != nil {
return nil, err
}
klog.Infof("[mock] successfully processing namespace %s", ns.Name)
return nil, nil
})
// 2. add event handler for namespaces on the addition/update/deletion
kubeInformerFactory.Core().V1().Namespaces().Informer().AddEventHandler(namespaceController.DefaultResourceEventHandlerFuncs())
// 3. start the informer factory
kubeInformerFactory.Start(ctx.Done())
// 4. add a handlerFunc and run the controller
namespaceController.WithCacheSynced(kubeInformerFactory.Core().V1().Namespaces().Informer().HasSynced).
Run(ctx)
}