-
Notifications
You must be signed in to change notification settings - Fork 70
Expand file tree
/
Copy pathmain.go
More file actions
271 lines (241 loc) · 8.34 KB
/
main.go
File metadata and controls
271 lines (241 loc) · 8.34 KB
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
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
/*
Copyright 2022.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package main
import (
"context"
"flag"
"fmt"
"net/http"
"os"
"strings"
"github.com/openshift/cloud-ingress-operator/config"
"github.com/openshift/cloud-ingress-operator/pkg/cloudclient"
"github.com/openshift/cloud-ingress-operator/pkg/ingresscontroller"
"github.com/openshift/cloud-ingress-operator/pkg/localmetrics"
baseutils "github.com/openshift/cloud-ingress-operator/pkg/utils"
osdmetrics "github.com/openshift/operator-custom-metrics/pkg/metrics"
"github.com/operator-framework/operator-lib/leader"
"go.uber.org/zap/zapcore"
"k8s.io/apimachinery/pkg/runtime"
utilruntime "k8s.io/apimachinery/pkg/util/runtime"
clientgoscheme "k8s.io/client-go/kubernetes/scheme"
_ "k8s.io/client-go/plugin/pkg/client/auth"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/cache"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/healthz"
"sigs.k8s.io/controller-runtime/pkg/log/zap"
metricsserver "sigs.k8s.io/controller-runtime/pkg/metrics/server"
"sigs.k8s.io/controller-runtime/pkg/webhook"
configv1 "github.com/openshift/api/config/v1"
machinev1 "github.com/openshift/api/machine/v1"
machinev1beta1 "github.com/openshift/api/machine/v1beta1"
apiv1alpha1 "github.com/openshift/cloud-ingress-operator/api/v1alpha1"
apischemecontroller "github.com/openshift/cloud-ingress-operator/controllers/apischeme"
publishingstrategycontroller "github.com/openshift/cloud-ingress-operator/controllers/publishingstrategy"
routerservicecontroller "github.com/openshift/cloud-ingress-operator/controllers/routerservice"
appsv1 "k8s.io/api/apps/v1"
corev1 "k8s.io/api/core/v1"
//+kubebuilder:scaffold:imports
)
var (
scheme = runtime.NewScheme()
setupLog = ctrl.Log.WithName("setup")
)
var (
osdMetricsPort = "8181"
osdMetricsPath = "/metrics"
watchNamespaceEnvVar = "WATCH_NAMESPACE"
)
func init() {
utilruntime.Must(clientgoscheme.AddToScheme(scheme))
utilruntime.Must(apiv1alpha1.AddToScheme(scheme))
utilruntime.Must(configv1.Install(scheme))
utilruntime.Must(machinev1beta1.Install(scheme))
utilruntime.Must(ingresscontroller.AddToScheme(scheme))
utilruntime.Must(machinev1.AddToScheme(scheme))
scheme.AddKnownTypes(machinev1beta1.SchemeGroupVersion,
&machinev1beta1.AWSMachineProviderConfig{},
)
//+kubebuilder:scaffold:scheme
}
func main() {
var metricsAddr string
var enableLeaderElection bool
var probeAddr string
flag.StringVar(&metricsAddr, "metrics-bind-address", ":8080", "The address the metric endpoint binds to.")
flag.StringVar(&probeAddr, "health-probe-bind-address", ":8000", "The address the probe endpoint binds to.")
flag.BoolVar(&enableLeaderElection, "leader-elect", false,
"Enable leader election for controller manager. "+
"Enabling this will ensure there is only one active controller manager.")
opts := zap.Options{
Development: false,
TimeEncoder: zapcore.RFC3339TimeEncoder,
// Remove misleading controller-runtime stack traces https://github.com/kubernetes-sigs/kubebuilder/issues/1593
StacktraceLevel: zapcore.DPanicLevel,
}
opts.BindFlags(flag.CommandLine)
flag.Parse()
ctrl.SetLogger(zap.New(zap.UseFlagOptions(&opts)))
namespaces, err := getWatchNamespaces()
if err != nil {
setupLog.Error(err, "unable to get WatchNamespace,"+"the manager will watch and manage resources in all namespaces")
}
options := ctrl.Options{
Scheme: scheme,
Metrics: metricsserver.Options{
BindAddress: metricsAddr,
},
WebhookServer: webhook.NewServer(webhook.Options{
Port: 9443,
}),
HealthProbeBindAddress: probeAddr,
LeaderElection: enableLeaderElection,
Cache: cache.Options{
ByObject: map[client.Object]cache.ByObject{
&ingresscontroller.IngressController{}: {
Namespaces: namespaces,
},
&apiv1alpha1.PublishingStrategy{}: {
Namespaces: namespaces,
},
&apiv1alpha1.APIScheme{}: {
Namespaces: namespaces,
},
&corev1.Service{}: {
Namespaces: namespaces,
},
&corev1.Secret{}: {
Namespaces: namespaces,
},
&machinev1beta1.Machine{}: {
Namespaces: namespaces,
},
&machinev1beta1.MachineSet{}: {
Namespaces: namespaces,
},
&machinev1.ControlPlaneMachineSet{}: {
Namespaces: namespaces,
},
&appsv1.Deployment{}: {
Namespaces: namespaces,
},
},
},
}
ctx := context.TODO()
// Become the leader before proceeding
if options.LeaderElection {
err = leader.Become(ctx, "cloud-ingress-operator-lock")
if err != nil {
setupLog.Error(err, "failed to setup leader lock")
os.Exit(1)
}
}
mgr, err := ctrl.NewManager(ctrl.GetConfigOrDie(), options)
if err != nil {
setupLog.Error(err, "unable to start manager")
os.Exit(1)
}
// Setup Global Variables
cli := mgr.GetClient()
if err := baseutils.SetClusterVersion(cli); err != nil {
setupLog.Error(err, "")
os.Exit(1)
}
// setup apischemecontroller with mgr
if err = (&apischemecontroller.APISchemeReconciler{
Client: mgr.GetClient(),
Scheme: mgr.GetScheme(),
}).SetupWithManager(mgr); err != nil {
setupLog.Error(err, "unable to create controller", "controller", "APIScheme")
os.Exit(1)
}
// setup publishingstrategycontroller with mgr
if err = (&publishingstrategycontroller.PublishingStrategyReconciler{
Client: mgr.GetClient(),
Scheme: mgr.GetScheme(),
}).SetupWithManager(mgr); err != nil {
setupLog.Error(err, "unable to create controller", "controller", "PublishingStrategy")
os.Exit(1)
}
// setup routerservice with mgr
if err = (&routerservicecontroller.RouterServiceReconciler{
Client: mgr.GetClient(),
Scheme: mgr.GetScheme(),
}).SetupWithManager(mgr); err != nil {
setupLog.Error(err, "unable to create controller", "controller", "RouterService")
os.Exit(1)
}
addMetrics(ctx)
//+kubebuilder:scaffold:builder
if err = mgr.AddHealthzCheck("healthz", func(req *http.Request) error {
kubeCli := mgr.GetClient()
cloudPlatform, err := baseutils.GetPlatformType(kubeCli)
if err != nil {
return err
}
cloudClient := cloudclient.GetClientFor(kubeCli, *cloudPlatform)
if err := cloudClient.Healthcheck(context.TODO(), kubeCli); err != nil {
return err
}
return baseutils.SAhealthcheck(kubeCli)
}); err != nil {
setupLog.Error(err, "unable to set up health check")
os.Exit(1)
}
if err = mgr.AddReadyzCheck("readyz", healthz.Ping); err != nil {
setupLog.Error(err, "unable to set up ready check")
os.Exit(1)
}
setupLog.Info("starting manager")
if err = mgr.Start(ctrl.SetupSignalHandler()); err != nil {
setupLog.Error(err, "problem running manager")
os.Exit(1)
}
}
// addMetrics will create the Services and Service Monitors to allow the operator export the metrics by using
// the Prometheus operator
func addMetrics(ctx context.Context) {
metricsServer := osdmetrics.NewBuilder(config.OperatorNamespace, config.OperatorName).
WithPort(osdMetricsPort).
WithPath(osdMetricsPath).
WithCollectors(localmetrics.MetricsList).
WithServiceMonitor().
GetConfig()
if err := osdmetrics.ConfigureMetrics(ctx, *metricsServer); err != nil {
setupLog.Error(err, "Failed to configure OSD metrics")
}
}
func getWatchNamespaces() (map[string]cache.Config, error) {
// The env variable WATCH_NAMESPACE specifies the namespace(s) to watch.
// An empty value means the operator is running with cluster scope.
ns, found := os.LookupEnv(watchNamespaceEnvVar)
if !found {
return nil, fmt.Errorf("%s must be set", watchNamespaceEnvVar)
}
var namespaces = strings.TrimSpace(ns)
if namespaces == "" {
setupLog.Info("manager set up with cluster scope")
// Return nil map (cluster-wide scope) with no error
return nil, nil
}
nsCacheConfig := make(map[string]cache.Config)
for _, ns := range strings.Split(namespaces, ",") {
if v := strings.TrimSpace(ns); v != "" {
nsCacheConfig[v] = cache.Config{}
}
}
setupLog.Info("manager set up with multiple namespaces", "namespaces", namespaces)
return nsCacheConfig, nil
}