Repository navigation
Expand file tree
/
Copy pathmain.go
More file actions
365 lines (323 loc) · 13.5 KB
/
Copy pathmain.go
File metadata and controls
365 lines (323 loc) · 13.5 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
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
/*
Copyright 2022 The Flux authors
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 (
"crypto/tls"
"fmt"
"os"
"time"
"github.com/sethvargo/go-limiter/memorystore"
prommetrics "github.com/slok/go-http-metrics/metrics/prometheus"
"github.com/slok/go-http-metrics/middleware"
flag "github.com/spf13/pflag"
"github.com/spiffe/go-spiffe/v2/workloadapi"
corev1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/runtime"
clientgoscheme "k8s.io/client-go/kubernetes/scheme"
_ "k8s.io/client-go/plugin/pkg/client/auth/gcp"
ctrl "sigs.k8s.io/controller-runtime"
ctrlcache "sigs.k8s.io/controller-runtime/pkg/cache"
ctrlclient "sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/config"
ctrlmetrics "sigs.k8s.io/controller-runtime/pkg/metrics"
metricsserver "sigs.k8s.io/controller-runtime/pkg/metrics/server"
"github.com/fluxcd/pkg/apis/meta"
"github.com/fluxcd/pkg/auth"
pkgcache "github.com/fluxcd/pkg/cache"
"github.com/fluxcd/pkg/runtime/acl"
"github.com/fluxcd/pkg/runtime/client"
runtimeCtrl "github.com/fluxcd/pkg/runtime/controller"
"github.com/fluxcd/pkg/runtime/events"
feathelper "github.com/fluxcd/pkg/runtime/features"
"github.com/fluxcd/pkg/runtime/leaderelection"
"github.com/fluxcd/pkg/runtime/logger"
"github.com/fluxcd/pkg/runtime/metrics"
"github.com/fluxcd/pkg/runtime/pprof"
"github.com/fluxcd/pkg/runtime/probes"
fluxspiffe "github.com/fluxcd/pkg/spiffe"
fluxbroker "github.com/fluxcd/pkg/spiffe/brokerapi"
apiv1 "github.com/fluxcd/notification-controller/api/v1"
"github.com/fluxcd/notification-controller/internal/controller"
"github.com/fluxcd/notification-controller/internal/features"
"github.com/fluxcd/notification-controller/internal/server"
// +kubebuilder:scaffold:imports
)
const controllerName = "notification-controller"
var (
scheme = runtime.NewScheme()
setupLog = ctrl.Log.WithName("setup")
)
func init() {
_ = clientgoscheme.AddToScheme(scheme)
_ = apiv1.AddToScheme(scheme)
// +kubebuilder:scaffold:scheme
}
func main() {
const (
tokenCacheDefaultMaxSize = 100
)
var (
eventsAddr string
receiverAddr string
healthAddr string
metricsAddr string
concurrent int
rateLimitInterval time.Duration
clientOptions client.Options
logOptions logger.Options
leaderElectionOptions leaderelection.Options
aclOptions acl.Options
rateLimiterOptions runtimeCtrl.RateLimiterOptions
featureGates feathelper.FeatureGates
exportHTTPPathMetrics bool
tokenCacheOptions pkgcache.TokenFlags
watchOptions runtimeCtrl.WatchOptions
defaultServiceAccount string
authorizedNotifiers []string
authorizedReceivers []string
spiffeBrokerEndpoint string
spiffeBrokerIDs []string
)
flag.StringVar(&metricsAddr, "metrics-addr", ":8080", "The address the metric endpoint binds to.")
flag.StringVar(&eventsAddr, "events-addr", ":9090", "The address the event endpoint binds to.")
flag.StringVar(&healthAddr, "health-addr", ":9440", "The address the health endpoint binds to.")
flag.StringVar(&receiverAddr, "receiverAddr", ":9292", "The address the webhook receiver endpoint binds to.")
flag.IntVar(&concurrent, "concurrent", 4, "The number of concurrent notification reconciles.")
flag.DurationVar(&rateLimitInterval, "rate-limit-interval", 5*time.Minute, "Interval in which rate limit has effect.")
flag.BoolVar(&exportHTTPPathMetrics, "export-http-path-metrics", false, "When enabled, the requests full path is included in the HTTP server metrics (risk as high cardinality")
// After implementing --watch-label-selector the following two bindings can be replaced by watchOptions.BindFlags().
flag.BoolVar(&watchOptions.AllNamespaces, "watch-all-namespaces", true,
"Watch for custom resources in all namespaces, if set to false it will only watch the runtime namespace.")
flag.CommandLine.StringVar(&watchOptions.ConfigsLabelSelector, "watch-configs-label-selector", meta.LabelKeyWatch+"="+meta.LabelValueWatchEnabled,
"Watch for ConfigMaps and Secrets with matching labels.")
clientOptions.BindFlags(flag.CommandLine)
logOptions.BindFlags(flag.CommandLine)
leaderElectionOptions.BindFlags(flag.CommandLine)
aclOptions.BindFlags(flag.CommandLine)
rateLimiterOptions.BindFlags(flag.CommandLine)
featureGates.BindFlags(flag.CommandLine)
tokenCacheOptions.BindFlags(flag.CommandLine, tokenCacheDefaultMaxSize)
flag.StringVar(&defaultServiceAccount, auth.ControllerFlagDefaultServiceAccount,
"", "Default service account to use for workload identity when not specified in resources.")
flag.StringArrayVar(&authorizedNotifiers, fluxspiffe.ControllerFlagAuthorizedNotifierSPIFFEID, nil,
"SPIFFE ID of a notifier authorized to send events. Can be repeated.")
flag.StringArrayVar(&authorizedReceivers, fluxspiffe.ControllerFlagAuthorizedReceiverSPIFFEID, nil,
"SPIFFE ID of a receiver authorized to send requests. Can be repeated.")
flag.StringVar(&spiffeBrokerEndpoint, fluxspiffe.ControllerFlagSPIFFEBrokerEndpoint, "",
"The gRPC URL of the SPIFFE Broker endpoint.")
flag.StringArrayVar(&spiffeBrokerIDs, fluxspiffe.ControllerFlagSPIFFEBrokerID, nil,
"SPIFFE ID of the SPIFFE Broker endpoint. Can be repeated.")
flag.Parse()
logger.SetLogger(logger.NewLogger(logOptions))
if err := featureGates.WithLogger(setupLog).SupportedFeatures(features.FeatureGates()); err != nil {
setupLog.Error(err, "unable to load feature gates")
os.Exit(1)
}
watchNamespace := ""
if !watchOptions.AllNamespaces {
watchNamespace = os.Getenv("RUNTIME_NAMESPACE")
}
var disableCacheFor []ctrlclient.Object
shouldCache, err := features.Enabled(features.CacheSecretsAndConfigMaps)
if err != nil {
setupLog.Error(err, "unable to check feature gate "+features.CacheSecretsAndConfigMaps)
os.Exit(1)
}
if !shouldCache {
disableCacheFor = append(disableCacheFor, &corev1.Secret{}, &corev1.ConfigMap{})
}
restConfig := client.GetConfigOrDie(clientOptions)
mgrConfig := ctrl.Options{
Scheme: scheme,
HealthProbeBindAddress: healthAddr,
LeaderElection: leaderElectionOptions.Enable,
LeaderElectionReleaseOnCancel: leaderElectionOptions.ReleaseOnCancel,
LeaseDuration: &leaderElectionOptions.LeaseDuration,
RenewDeadline: &leaderElectionOptions.RenewDeadline,
RetryPeriod: &leaderElectionOptions.RetryPeriod,
LeaderElectionID: fmt.Sprintf("%s-leader-election", controllerName),
Logger: ctrl.Log,
Controller: config.Controller{
RecoverPanic: new(true),
MaxConcurrentReconciles: concurrent,
},
Client: ctrlclient.Options{
Cache: &ctrlclient.CacheOptions{
DisableFor: disableCacheFor,
},
},
Metrics: metricsserver.Options{
BindAddress: metricsAddr,
ExtraHandlers: pprof.GetHandlers(),
},
}
if watchNamespace != "" {
mgrConfig.Cache = ctrlcache.Options{
DefaultNamespaces: map[string]ctrlcache.Config{
watchNamespace: {},
},
}
}
mgr, err := ctrl.NewManager(restConfig, mgrConfig)
if err != nil {
setupLog.Error(err, "unable to start manager")
os.Exit(1)
}
probes.SetupChecks(mgr, setupLog)
metricsH := runtimeCtrl.NewMetrics(mgr, metrics.MustMakeRecorder(), apiv1.NotificationFinalizer)
var tokenCache *pkgcache.TokenCache
if tokenCacheOptions.MaxSize > 0 {
var err error
tokenCache, err = pkgcache.NewTokenCache(tokenCacheOptions.MaxSize,
pkgcache.WithMaxDuration(tokenCacheOptions.MaxDuration),
pkgcache.WithMetricsRegisterer(ctrlmetrics.Registry),
pkgcache.WithMetricsPrefix("gotk_token_"))
if err != nil {
setupLog.Error(err, "unable to create token cache")
os.Exit(1)
}
}
watchConfigsPredicate, err := runtimeCtrl.GetWatchConfigsPredicate(watchOptions)
if err != nil {
setupLog.Error(err, "unable to configure watch configs label selector for controller")
os.Exit(1)
}
disableConfigWatchers, err := features.Enabled(runtimeCtrl.FeatureGateDisableConfigWatchers)
if err != nil {
setupLog.Error(err, "unable to check feature gate "+runtimeCtrl.FeatureGateDisableConfigWatchers)
os.Exit(1)
}
watchConfigs := !disableConfigWatchers
// eventRecorder records Kubernetes Events for notification-controller's own
// resources. Unlike the other Flux controllers, notification-controller is
// the event sink itself, so the webhook address is left empty to disable
// posting events back to itself; it only emits either core/v1 (default)
// or events/v1 Kubernetes Events.
eventRecorder, err := events.NewRecorder(ctrl.Log, "", controllerName, events.WithManager(mgr))
if err != nil {
setupLog.Error(err, "unable to create event recorder")
os.Exit(1)
}
if err = (&controller.ProviderReconciler{
Client: mgr.GetClient(),
Recorder: eventRecorder,
TokenCache: tokenCache,
}).SetupWithManager(mgr); err != nil {
setupLog.Error(err, "unable to create controller", "controller", "Provider")
os.Exit(1)
}
if err = (&controller.AlertReconciler{
Client: mgr.GetClient(),
ControllerName: controllerName,
Recorder: eventRecorder,
}).SetupWithManager(mgr); err != nil {
setupLog.Error(err, "unable to create controller", "controller", "Alert")
os.Exit(1)
}
if err = (&controller.ReceiverReconciler{
Client: mgr.GetClient(),
ControllerName: controllerName,
Metrics: metricsH,
Recorder: eventRecorder,
}).SetupWithManager(mgr, controller.ReceiverReconcilerOptions{
RateLimiter: runtimeCtrl.GetRateLimiter(rateLimiterOptions),
WatchConfigs: watchConfigs,
WatchConfigsPredicate: watchConfigsPredicate,
}); err != nil {
setupLog.Error(err, "unable to create controller", "controller", "Receiver")
os.Exit(1)
}
// +kubebuilder:scaffold:builder
ctx := ctrl.SetupSignalHandler()
var eventTLSConfig, receiverTLSConfig *tls.Config
var spiffeBroker fluxbroker.Client
if len(authorizedNotifiers) > 0 || len(authorizedReceivers) > 0 ||
spiffeBrokerEndpoint != "" || len(spiffeBrokerIDs) > 0 {
source, err := workloadapi.NewX509Source(ctx)
if err != nil {
setupLog.Error(err, "unable to create SPIFFE X.509 source")
os.Exit(1)
}
defer func() {
if err := source.Close(); err != nil {
setupLog.Error(err, "unable to close SPIFFE X.509 source")
}
}()
if len(authorizedNotifiers) > 0 {
eventTLSConfig, err = fluxspiffe.BuildTLSConfig(source, authorizedNotifiers...)
if err != nil {
setupLog.Error(err, "unable to configure SPIFFE mTLS for the event server")
os.Exit(1)
}
setupLog.Info("event server will use inter-controller mTLS via SPIFFE", "spiffeIDs", authorizedNotifiers)
}
if len(authorizedReceivers) > 0 {
receiverTLSConfig, err = fluxspiffe.BuildTLSConfig(source, authorizedReceivers...)
if err != nil {
setupLog.Error(err, "unable to configure SPIFFE mTLS for the receiver server")
os.Exit(1)
}
setupLog.Info("receiver server will use inter-controller mTLS via SPIFFE", "spiffeIDs", authorizedReceivers)
}
if spiffeBrokerEndpoint != "" || len(spiffeBrokerIDs) > 0 {
spiffeBroker, err = fluxbroker.New(spiffeBrokerEndpoint, spiffeBrokerIDs, source)
if err != nil {
setupLog.Error(err, "unable to create SPIFFE Broker client")
os.Exit(1)
}
defer func() {
if err := spiffeBroker.Close(); err != nil {
setupLog.Error(err, "unable to close SPIFFE Broker client")
}
}()
setupLog.Info("SPIFFE Broker API",
"endpoint", spiffeBrokerEndpoint, "spiffeIDs", spiffeBrokerIDs)
}
}
// Sweep the rate limiter store at every interval and purge entries
// older than two intervals, to bound the memory usage of the store.
// A bucket becomes irrelevant once the rate limit interval has passed,
// as the token gets replenished on the next event.
store, err := memorystore.New(&memorystore.Config{
Interval: rateLimitInterval,
SweepInterval: rateLimitInterval,
SweepMinTTL: 2 * rateLimitInterval,
})
if err != nil {
setupLog.Error(err, "unable to create middleware store")
os.Exit(1)
}
setupLog.Info("starting event server", "addr", eventsAddr)
eventMdlw := middleware.New(middleware.Config{
Recorder: prommetrics.NewRecorder(prommetrics.Config{
Prefix: "gotk_event",
Registry: ctrlmetrics.Registry,
}),
})
eventServer := server.NewEventServer(eventsAddr, ctrl.Log, mgr.GetClient(), eventRecorder, aclOptions.NoCrossNamespaceRefs, exportHTTPPathMetrics, tokenCache, defaultServiceAccount, eventTLSConfig, spiffeBroker)
go eventServer.ListenAndServe(ctx.Done(), eventMdlw, store)
setupLog.Info("starting webhook receiver server", "addr", receiverAddr)
receiverServer := server.NewReceiverServer(receiverAddr, ctrl.Log, mgr.GetClient(), aclOptions.NoCrossNamespaceRefs, exportHTTPPathMetrics, receiverTLSConfig)
receiverMdlw := middleware.New(middleware.Config{
Recorder: prommetrics.NewRecorder(prommetrics.Config{
Prefix: "gotk_receiver",
Registry: ctrlmetrics.Registry,
}),
})
go receiverServer.ListenAndServe(ctx.Done(), receiverMdlw)
setupLog.Info("starting manager")
if err := mgr.Start(ctx); err != nil {
setupLog.Error(err, "problem running manager")
os.Exit(1)
}
}