...
1 package controller
2
3 import (
4 "fmt"
5 "net/http"
6 "time"
7
8 "k8s.io/client-go/rest"
9 ctrl "sigs.k8s.io/controller-runtime"
10 metricsserver "sigs.k8s.io/controller-runtime/pkg/metrics/server"
11 "sigs.k8s.io/controller-runtime/pkg/webhook"
12 )
13
14 var (
15 defaultMetricsBindAddress = ":8080"
16 defaultLeaderElection = false
17 )
18
19
20
21 type options struct {
22 config *rest.Config
23 ctrlOptions ctrl.Options
24 webHookOptions webhook.Options
25 }
26
27
28 type Option func(*options)
29
30
31
32 func WithCfg(c *rest.Config) Option {
33 return func(o *options) {
34 o.config = c
35 }
36 }
37
38
39
40 func WithLeaderElection() Option {
41 return func(o *options) {
42 o.ctrlOptions.LeaderElection = true
43 }
44 }
45
46
47
48 func WithMetricsAddress(a string) Option {
49 return func(o *options) {
50 o.ctrlOptions.Metrics.BindAddress = a
51 }
52 }
53
54
55 func WithCertDir(certDir string) Option {
56 return func(o *options) {
57 o.webHookOptions.CertDir = certDir
58 }
59 }
60
61
62 func WithPort(port int) Option {
63 return func(o *options) {
64 o.webHookOptions.Port = port
65 }
66 }
67
68 func WithPProf(route string, h http.Handler) Option {
69 return func(o *options) {
70 o.ctrlOptions.Metrics.ExtraHandlers[route] = h
71 }
72 }
73
74 func WithGracefulTimeout(timeout time.Duration) Option {
75 return func(o *options) {
76 o.ctrlOptions.GracefulShutdownTimeout = &timeout
77 }
78 }
79
80
81
82
83 func ProcessOptions(opts ...Option) (*rest.Config, ctrl.Options) {
84 o := &options{
85 ctrlOptions: ctrl.Options{
86 Metrics: metricsserver.Options{BindAddress: defaultMetricsBindAddress},
87 LeaderElection: defaultLeaderElection},
88 }
89 for _, opt := range opts {
90 opt(o)
91 }
92
93 if o.config == nil {
94
95
96
97
98 var err error
99 o.config, err = ctrl.GetConfig()
100 if err != nil {
101 panic(fmt.Sprintf("failed to get Kube client config: %s", err.Error()))
102 }
103 }
104
105 o.ctrlOptions.WebhookServer = webhook.NewServer(o.webHookOptions)
106
107 return o.config, o.ctrlOptions
108 }
109
View as plain text