This repository was archived by the owner on Dec 22, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathmain.go
279 lines (238 loc) · 9.19 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
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
/*
MIT License
Copyright (c) 2018 Martin Linkhorst
Copyright (c) 2022 Stephen Cuppett
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
package main
import (
"crypto/tls"
"flag"
"sigs.k8s.io/controller-runtime/pkg/webhook"
cfv1alpha1 "github.com/cuppett/aws-cloudformation-operator/apis/cloudformation.services.k8s.aws/v1alpha1"
configv1alpha1 "github.com/cuppett/aws-cloudformation-operator/apis/services.k8s.aws/v1alpha1"
"github.com/cuppett/aws-cloudformation-operator/controllers/cloudformation.services.k8s.aws"
servicesk8saws "github.com/cuppett/aws-cloudformation-operator/controllers/services.k8s.aws"
configv1 "github.com/openshift/api/config/v1"
operatorv1 "github.com/openshift/api/operator/v1"
apiextensions "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1"
clientgoscheme "k8s.io/client-go/kubernetes/scheme"
"os"
"strings"
"github.com/prometheus/client_golang/prometheus"
"sigs.k8s.io/controller-runtime/pkg/metrics"
"github.com/spf13/pflag"
"sigs.k8s.io/controller-runtime/pkg/cache"
// Import all Kubernetes client auth plugins (e.g. Azure, GCP, OIDC, etc.)
// to ensure that exec-entrypoint and run can make use of them.
_ "k8s.io/client-go/plugin/pkg/client/auth"
"k8s.io/apimachinery/pkg/runtime"
utilruntime "k8s.io/apimachinery/pkg/util/runtime"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/healthz"
"sigs.k8s.io/controller-runtime/pkg/log/zap"
metricsServer "sigs.k8s.io/controller-runtime/pkg/metrics/server"
//+kubebuilder:scaffold:imports
)
var (
scheme = runtime.NewScheme()
setupLog = ctrl.Log.WithName("setup")
StackFlagSet *pflag.FlagSet
)
func init() {
utilruntime.Must(clientgoscheme.AddToScheme(scheme))
utilruntime.Must(apiextensions.AddToScheme(scheme))
utilruntime.Must(configv1.Install(scheme))
utilruntime.Must(operatorv1.Install(scheme))
utilruntime.Must(cfv1alpha1.AddToScheme(scheme))
utilruntime.Must(configv1alpha1.AddToScheme(scheme))
//+kubebuilder:scaffold:scheme
StackFlagSet = pflag.NewFlagSet("stack", pflag.ExitOnError)
StackFlagSet.Bool("dry-run", false, "If true, don't actually do anything.")
StackFlagSet.Bool("no-webhook", false, "If true, don't run the webhook server.")
}
func main() {
var namespace string
var watchNamespaces []string
var metricsAddr string
var enableHTTP2 bool
var secureMetrics bool
var enableLeaderElection bool
var probeAddr string
var err error
flag.StringVar(&namespace, "namespace", "", "The Kubernetes namespace to watch")
flag.StringVar(&metricsAddr, "metrics-bind-address", ":8080", "The address the metric endpoint binds to.")
flag.BoolVar(&secureMetrics, "metrics-secure", secureMetrics, "If the metrics endpoint should be served securely.")
flag.StringVar(&probeAddr, "health-probe-bind-address", ":8081", "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.")
flag.BoolVar(&enableHTTP2, "enable-http2", enableHTTP2, "If HTTP/2 should be enabled for the metrics and webhook servers.")
opts := zap.Options{
Development: true,
}
opts.BindFlags(flag.CommandLine)
pflag.CommandLine.AddGoFlagSet(flag.CommandLine)
pflag.CommandLine.AddFlagSet(StackFlagSet)
pflag.Parse()
if namespace == "" {
namespace = os.Getenv("WATCH_NAMESPACE")
}
if namespace != "" {
watchNamespaces = strings.Split(namespace, ",")
}
ctrl.SetLogger(zap.New(zap.UseFlagOptions(&opts)))
disableHTTP2 := func(c *tls.Config) {
if enableHTTP2 {
return
}
c.NextProtos = []string{"http/1.1"}
}
webhookServerOptions := webhook.Options{
TLSOpts: []func(config *tls.Config){disableHTTP2},
}
webhookServer := webhook.NewServer(webhookServerOptions)
metricsOptions := metricsServer.Options{
BindAddress: metricsAddr,
SecureServing: secureMetrics,
TLSOpts: []func(*tls.Config){disableHTTP2},
}
options := ctrl.Options{
Scheme: scheme,
Metrics: metricsOptions,
WebhookServer: webhookServer,
HealthProbeBindAddress: probeAddr,
LeaderElection: enableLeaderElection,
LeaderElectionID: "3680e595.cuppett.dev", // namespaced-scope when the value is not an empty string
}
// Add support for MultiNamespace set in WATCH_NAMESPACE (e.g ns1,ns2)
if len(watchNamespaces) > 0 {
setupLog.Info("manager set up with multiple namespaces", "namespaces", namespace)
defaultNamespaces := make(map[string]cache.Config)
for _, ns := range watchNamespaces {
defaultNamespaces[ns] = cache.Config{}
}
configNamespace, exists := os.LookupEnv("POD_NAMESPACE")
if exists {
defaultNamespaces[configNamespace] = cache.Config{}
}
options.Cache = cache.Options{
DefaultNamespaces: defaultNamespaces,
}
}
mgr, err := ctrl.NewManager(ctrl.GetConfigOrDie(), options)
if err != nil {
setupLog.Error(err, "unable to start manager")
os.Exit(1)
}
dryRun, err := StackFlagSet.GetBool("dry-run")
if err != nil {
setupLog.Error(err, "error parsing flag")
os.Exit(1)
}
configReconciler := servicesk8saws.InitializeConfigReconciler(
mgr.GetClient(),
ctrl.Log.WithName("workers").WithName("Config"),
mgr.GetScheme(),
)
if err = configReconciler.SetupWithManager(mgr); err != nil {
setupLog.Error(err, "unable to create controller", "controller", "Config")
os.Exit(1)
}
if err = (&servicesk8saws.SecretReconciler{
Client: mgr.GetClient(),
Log: ctrl.Log.WithName("controllers").WithName("Secret"),
Scheme: mgr.GetScheme(),
ConfigReconciler: configReconciler,
}).SetupWithManager(mgr); err != nil {
setupLog.Error(err, "unable to create controller", "controller", "Secret")
os.Exit(1)
}
cfHelper := &cloudformation_services_k8s_aws.CloudFormationHelper{
ConfigReconciler: configReconciler,
}
channelHub := &cloudformation_services_k8s_aws.ChannelHub{
MappingChannel: make(chan *cfv1alpha1.Stack),
FollowChannel: make(chan *cfv1alpha1.Stack),
}
mapWriter := &cloudformation_services_k8s_aws.MapWriter{
Client: mgr.GetClient(),
Log: ctrl.Log.WithName("workers").WithName("Stack"),
ChannelHub: *channelHub,
Scheme: mgr.GetScheme(),
}
go mapWriter.Worker()
stackFollower := &cloudformation_services_k8s_aws.StackFollower{
Client: mgr.GetClient(),
Log: ctrl.Log.WithName("workers").WithName("Stack"),
ChannelHub: *channelHub,
CloudFormationHelper: cfHelper,
StacksFollowing: prometheus.NewGauge(
prometheus.GaugeOpts{
Name: "cloudformation_stacks_following",
Help: "Number of CloudFormation stacks being followed currently",
},
),
StacksFollowed: prometheus.NewCounter(
prometheus.CounterOpts{
Name: "cloudformation_stacks_followed",
Help: "Total number of CloudFormation stacks followed (lifetime)",
},
),
}
go stackFollower.Receiver()
go stackFollower.Worker()
metrics.Registry.MustRegister(stackFollower.StacksFollowing)
metrics.Registry.MustRegister(stackFollower.StacksFollowed)
if err = (&cloudformation_services_k8s_aws.StackReconciler{
Client: mgr.GetClient(),
ChannelHub: *channelHub,
Log: ctrl.Log.WithName("controllers").WithName("Stack"),
Scheme: mgr.GetScheme(),
WatchNamespaces: watchNamespaces,
CloudFormationHelper: cfHelper,
DryRun: dryRun,
}).SetupWithManager(mgr); err != nil {
setupLog.Error(err, "unable to create controller", "controller", "Stack")
os.Exit(1)
}
noWebHook, err := StackFlagSet.GetBool("no-webhook")
if err != nil {
setupLog.Error(err, "error parsing flag")
os.Exit(1)
}
if !noWebHook {
if err = (&cfv1alpha1.Stack{}).SetupWebhookWithManager(mgr); err != nil {
setupLog.Error(err, "unable to create webhook", "webhook", "Stack")
os.Exit(1)
}
}
// +kubebuilder:scaffold:builder
if err := mgr.AddHealthzCheck("healthz", healthz.Ping); 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)
}
}