This repository has been archived by the owner on Oct 27, 2022. It is now read-only.
/
main.go
179 lines (147 loc) · 5.35 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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
// Copyright (c) 2020 Red Hat, Inc.
// Copyright Contributors to the Open Cluster Management project
package main
import (
"flag"
"fmt"
"os"
"runtime"
"strings"
"github.com/go-logr/zapr"
"github.com/spf13/pflag"
"github.com/stolostron/go-log-utils/zaputil"
k8sruntime "k8s.io/apimachinery/pkg/runtime"
utilruntime "k8s.io/apimachinery/pkg/util/runtime"
"k8s.io/klog/v2"
policiesv1 "open-cluster-management.io/governance-policy-propagator/api/v1"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/cache"
"sigs.k8s.io/controller-runtime/pkg/client/config"
"sigs.k8s.io/controller-runtime/pkg/healthz"
"sigs.k8s.io/controller-runtime/pkg/manager"
"sigs.k8s.io/controller-runtime/pkg/manager/signals"
synccontrollers "open-cluster-management.io/governance-policy-template-sync/controllers"
"open-cluster-management.io/governance-policy-template-sync/version"
)
var (
log = ctrl.Log.WithName("setup")
scheme = k8sruntime.NewScheme()
)
func printVersion() {
log.Info(
"Using",
"OperatorVersion", version.Version,
"GoVersion", runtime.Version(),
"GOOS", runtime.GOOS,
"GOARCH", runtime.GOARCH,
)
}
func init() {
utilruntime.Must(policiesv1.AddToScheme(scheme))
}
func main() {
zflags := zaputil.FlagConfig{
LevelName: "log-level",
EncoderName: "log-encoder",
}
zflags.Bind(flag.CommandLine)
klog.InitFlags(flag.CommandLine)
pflag.CommandLine.AddGoFlagSet(flag.CommandLine)
var enableLeaderElection, legacyLeaderElect bool
var probeAddr string
pflag.BoolVar(&enableLeaderElection, "leader-elect", true,
"Enable leader election for controller manager. "+
"Enabling this will ensure there is only one active controller manager.")
pflag.BoolVar(&legacyLeaderElect, "legacy-leader-elect", false,
"Use a legacy leader election method for controller manager instead of the lease API.")
pflag.StringVar(&probeAddr, "health-probe-bind-address", ":8083", "The address the probe endpoint binds to.")
pflag.Parse()
ctrlZap, err := zflags.BuildForCtrl()
if err != nil {
panic(fmt.Sprintf("Failed to build zap logger for controller: %v", err))
}
ctrl.SetLogger(zapr.NewLogger(ctrlZap))
klogZap, err := zaputil.BuildForKlog(zflags.GetConfig(), flag.CommandLine)
if err != nil {
log.Error(err, "Failed to build zap logger for klog, those logs will not go through zap")
} else {
klog.SetLogger(zapr.NewLogger(klogZap).WithName("klog"))
}
printVersion()
namespace, err := getWatchNamespace()
if err != nil {
log.Error(err, "Failed to get watch namespace")
os.Exit(1)
}
// Get a config to talk to the apiserver
managedCfg, err := config.GetConfig()
if err != nil {
log.Error(err, "Failed to get the Kubernetes configuration")
os.Exit(1)
}
// Set default manager options
options := manager.Options{
Scheme: scheme,
Namespace: namespace,
MetricsBindAddress: "0",
HealthProbeBindAddress: probeAddr,
LeaderElection: enableLeaderElection,
LeaderElectionID: "governance-policy-template-sync.open-cluster-management.io",
}
// Add support for MultiNamespace set in WATCH_NAMESPACE (e.g ns1,ns2)
// Note that this is not intended to be used for excluding namespaces, this is better done via a Predicate
// Also note that you may face performance issues when using this with a high number of namespaces.
// More Info: https://godoc.org/github.com/kubernetes-sigs/controller-runtime/pkg/cache#MultiNamespacedCacheBuilder
if strings.Contains(namespace, ",") {
options.Namespace = ""
options.NewCache = cache.MultiNamespacedCacheBuilder(strings.Split(namespace, ","))
}
if legacyLeaderElect {
// If legacyLeaderElection is enabled, then that means the lease API is not available.
// In this case, use the legacy leader election method of a ConfigMap.
options.LeaderElectionResourceLock = "configmaps"
}
// Create a new manager to provide shared dependencies and start components
mgr, err := manager.New(managedCfg, options)
if err != nil {
log.Error(err, "Unable to start the manager")
os.Exit(1)
}
log.Info("Registering components")
// Setup all Controllers
if err := (&synccontrollers.PolicyReconciler{
Client: mgr.GetClient(),
Scheme: mgr.GetScheme(),
Config: mgr.GetConfig(),
Recorder: mgr.GetEventRecorderFor(synccontrollers.ControllerName),
}).SetupWithManager(mgr); err != nil {
log.Error(err, "Unable to create the controller", "controller", synccontrollers.ControllerName)
os.Exit(1)
}
if err := mgr.AddHealthzCheck("healthz", healthz.Ping); err != nil {
log.Error(err, "Unable to set up health check")
os.Exit(1)
}
if err := mgr.AddReadyzCheck("readyz", healthz.Ping); err != nil {
log.Error(err, "Unable to set up ready check")
os.Exit(1)
}
log.Info("Starting the manager")
// Start the Cmd
if err := mgr.Start(signals.SetupSignalHandler()); err != nil {
log.Error(err, "Errored while running the manager")
os.Exit(1)
}
}
// WatchNamespaceEnvVar is the constant for env variable WATCH_NAMESPACE
// which specifies the Namespace to watch.
// An empty value means the operator is running with cluster scope.
const watchNamespaceEnvVar = "WATCH_NAMESPACE"
// GetWatchNamespace returns the Namespace the operator should be watching for changes
func getWatchNamespace() (string, error) {
ns, found := os.LookupEnv(watchNamespaceEnvVar)
if !found {
return "", fmt.Errorf("%s must be set", watchNamespaceEnvVar)
}
return ns, nil
}