generated from vshn/go-bootstrap
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
280 lines (239 loc) · 9.48 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
280
package main
import (
"context"
"flag"
"os"
"time"
controlv1 "github.com/appuio/control-api/apis/v1"
projectv1 "github.com/openshift/api/project/v1"
userv1 "github.com/openshift/api/user/v1"
"go.uber.org/multierr"
"k8s.io/apimachinery/pkg/runtime"
utilruntime "k8s.io/apimachinery/pkg/util/runtime"
clientgoscheme "k8s.io/client-go/kubernetes/scheme"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/healthz"
"sigs.k8s.io/controller-runtime/pkg/log/zap"
"sigs.k8s.io/controller-runtime/pkg/webhook"
"sigs.k8s.io/controller-runtime/pkg/webhook/admission"
agentv1 "github.com/appuio/appuio-cloud-agent/api/v1"
"github.com/appuio/appuio-cloud-agent/controllers"
"github.com/appuio/appuio-cloud-agent/controllers/clustersource"
"github.com/appuio/appuio-cloud-agent/controllers/transformers"
"github.com/appuio/appuio-cloud-agent/ratio"
"github.com/appuio/appuio-cloud-agent/skipper"
"github.com/appuio/appuio-cloud-agent/webhooks"
)
var (
// these variables are populated by Goreleaser when releasing
version = "unknown"
commit = "-dirty-"
date = time.Now().Format("2006-01-02")
appName = "appuio-cloud-agent"
appLongName = "agent running on every APPUiO Cloud Zone"
scheme = runtime.NewScheme()
setupLog = ctrl.Log.WithName("setup").WithValues("version", version, "commit", commit, "date", date)
)
//go:generate go run sigs.k8s.io/controller-tools/cmd/controller-gen object paths="./..."
func init() {
utilruntime.Must(clientgoscheme.AddToScheme(scheme))
utilruntime.Must(userv1.AddToScheme(scheme))
utilruntime.Must(projectv1.AddToScheme(scheme))
utilruntime.Must(agentv1.AddToScheme(scheme))
utilruntime.Must(controlv1.AddToScheme(scheme))
//+kubebuilder:scaffold:scheme
}
func main() {
metricsAddr := flag.String("metrics-bind-address", ":8080", "The address the metric endpoint binds to.")
enableLeaderElection := flag.Bool("leader-elect", false,
"Enable leader election for controller manager. "+
"Enabling this will ensure there is only one active controller manager.")
probeAddr := flag.String("health-probe-bind-address", ":8082", "The address the probe endpoint binds to.")
webhookCertDir := flag.String("webhook-cert-dir", "", "Directory holding TLS certificate and key for the webhook server. If left empty, {TempDir}/k8s-webhook-server/serving-certs is used")
webhookPort := flag.Int("webhook-port", 9443, "The port on which the admission webhooks are served")
configFilePath := flag.String("config-file", "./config.yaml", "Path to the configuration file")
var controlAPIKubeconfig string
flag.StringVar(&controlAPIKubeconfig, "kubeconfig-control-api", "kubeconfig-control-api", "Path to the kubeconfig file to query the control API")
var controlAPIURL string
flag.StringVar(&controlAPIURL, "control-api-url", "", "URL of the control API. If set agent does not use `-kubeconfig-control-api`. Expects a bearer token in `CONTROL_API_BEARER_TOKEN` env var.")
var selectedUsageProfile string
flag.StringVar(&selectedUsageProfile, "usage-profile", "", "UsageProfile to use. Applies all profiles if empty. Dynamic selection is not supported yet.")
var qps, burst int
flag.IntVar(&qps, "qps", 20, "QPS to use for the controller-runtime client")
flag.IntVar(&burst, "burst", 100, "Burst to use for the controller-runtime client")
opts := zap.Options{}
opts.BindFlags(flag.CommandLine)
flag.Parse()
ctrl.SetLogger(zap.New(zap.UseFlagOptions(&opts)))
conf, warnings, err := ConfigFromFile(*configFilePath)
if err != nil {
setupLog.Error(err, "unable to read config file")
os.Exit(1)
}
for _, warning := range warnings {
setupLog.Info("WARNING " + warning)
}
if err := conf.Validate(); err != nil {
setupLog.Error(err, "invalid configuration")
os.Exit(1)
}
var controlAPICluster clustersource.ClusterSource
if controlAPIURL != "" {
tk := os.Getenv("CONTROL_API_BEARER_TOKEN")
if tk == "" {
setupLog.Error(err, "CONTROL_API_BEARER_TOKEN env var not set")
os.Exit(1)
}
cl, err := clustersource.FromURLAndBearerToken(controlAPIURL, tk, scheme)
if err != nil {
setupLog.Error(err, "unable to setup control-api manager")
os.Exit(1)
}
controlAPICluster = cl
} else {
cac, err := os.ReadFile(controlAPIKubeconfig)
if err != nil {
setupLog.Error(err, "unable to read control API kubeconfig")
os.Exit(1)
}
cl, err := clustersource.FromKubeConfig(cac, scheme)
if err != nil {
setupLog.Error(err, "unable to setup control-api manager")
os.Exit(1)
}
controlAPICluster = cl
}
lconf := ctrl.GetConfigOrDie()
lconf.QPS = float32(qps)
lconf.Burst = burst
mgr, err := ctrl.NewManager(lconf, ctrl.Options{
Scheme: scheme,
MetricsBindAddress: *metricsAddr,
Port: *webhookPort,
HealthProbeBindAddress: *probeAddr,
LeaderElection: *enableLeaderElection,
LeaderElectionID: "f2g2bc31.appuio-cloud-agent.appuio.io",
CertDir: *webhookCertDir,
})
if err != nil {
setupLog.Error(err, "unable to setup manager")
os.Exit(1)
}
registerRatioController(mgr, conf, conf.OrganizationLabel)
registerOrganizationRBACController(mgr, conf.OrganizationLabel, conf.DefaultOrganizationClusterRoles)
if err := (&controllers.ZoneUsageProfileSyncReconciler{
Client: mgr.GetClient(),
Scheme: mgr.GetScheme(),
Recorder: mgr.GetEventRecorderFor("usage-profile-sync-controller"),
ForeignClient: controlAPICluster.GetClient(),
}).SetupWithManagerAndForeignCluster(mgr, controlAPICluster); err != nil {
setupLog.Error(err, "unable to create controller", "controller", "ratio")
os.Exit(1)
}
if err := (&controllers.ZoneUsageProfileApplyReconciler{
Client: mgr.GetClient(),
Scheme: mgr.GetScheme(),
Recorder: mgr.GetEventRecorderFor("usage-profile-apply-controller"),
Cache: mgr.GetCache(),
OrganizationLabel: conf.OrganizationLabel,
Transformers: []transformers.Transformer{
transformers.NewResourceQuotaTransformer("resourcequota.appuio.io"),
},
SelectedProfile: selectedUsageProfile,
}).SetupWithManager(mgr); err != nil {
setupLog.Error(err, "unable to create controller", "controller", "ratio")
os.Exit(1)
}
psk := &skipper.PrivilegedUserSkipper{
Client: mgr.GetClient(),
PrivilegedUsers: conf.PrivilegedUsers,
PrivilegedGroups: conf.PrivilegedGroups,
PrivilegedClusterRoles: conf.PrivilegedClusterRoles,
}
registerNodeSelectorValidationWebhooks(mgr, conf)
mgr.GetWebhookServer().Register("/validate-namespace-quota", &webhook.Admission{
Handler: &webhooks.NamespaceQuotaValidator{
Client: mgr.GetClient(),
Decoder: admission.NewDecoder(mgr.GetScheme()),
Skipper: psk,
OrganizationLabel: conf.OrganizationLabel,
UserDefaultOrganizationAnnotation: conf.UserDefaultOrganizationAnnotation,
SelectedProfile: selectedUsageProfile,
QuotaOverrideNamespace: conf.QuotaOverrideNamespace,
},
})
if err := mgr.AddHealthzCheck("healthz", healthz.Ping); err != nil {
setupLog.Error(err, "unable to setup health endpoint")
os.Exit(1)
}
if err := mgr.AddReadyzCheck("readyz", healthz.Ping); err != nil {
setupLog.Error(err, "unable to setup ready endpoint")
os.Exit(1)
}
ctx, cancel := context.WithCancel(ctrl.SetupSignalHandler())
shutdown := make(chan error)
go func() {
defer cancel()
setupLog.Info("starting control-api manager")
shutdown <- controlAPICluster.Start(ctx)
}()
go func() {
defer cancel()
setupLog.Info("starting manager")
shutdown <- mgr.Start(ctx)
}()
if err := multierr.Combine(<-shutdown, <-shutdown); err != nil {
setupLog.Error(err, "failed to start")
os.Exit(1)
}
}
func registerNodeSelectorValidationWebhooks(mgr ctrl.Manager, conf Config) {
mgr.GetWebhookServer().Register("/mutate-pod-node-selector", &webhook.Admission{
Handler: &webhooks.PodNodeSelectorMutator{
Client: mgr.GetClient(),
Decoder: admission.NewDecoder(mgr.GetScheme()),
Skipper: skipper.StaticSkipper{ShouldSkip: false},
DefaultNodeSelector: conf.DefaultNodeSelector,
DefaultNamespaceNodeSelectorAnnotation: conf.DefaultNamespaceNodeSelectorAnnotation,
},
})
}
func registerOrganizationRBACController(mgr ctrl.Manager, orgLabel string, defaultClusterRoles map[string]string) {
if err := (&controllers.OrganizationRBACReconciler{
Client: mgr.GetClient(),
Recorder: mgr.GetEventRecorderFor("organization-rbac-controller"),
Scheme: mgr.GetScheme(),
OrganizationLabel: orgLabel,
DefaultClusterRoles: defaultClusterRoles,
}).SetupWithManager(mgr); err != nil {
setupLog.Error(err, "unable to create controller", "controller", "ratio")
os.Exit(1)
}
}
func registerRatioController(mgr ctrl.Manager, conf Config, orgLabel string) {
mgr.GetWebhookServer().Register("/validate-request-ratio", &webhook.Admission{
Handler: &webhooks.RatioValidator{
DefaultNodeSelector: conf.DefaultNodeSelector,
DefaultNamespaceNodeSelectorAnnotation: conf.DefaultNamespaceNodeSelectorAnnotation,
Decoder: admission.NewDecoder(mgr.GetScheme()),
Client: mgr.GetClient(),
RatioLimits: conf.MemoryPerCoreLimits,
Ratio: &ratio.Fetcher{
Client: mgr.GetClient(),
},
},
})
if err := (&controllers.RatioReconciler{
Client: mgr.GetClient(),
Recorder: mgr.GetEventRecorderFor("resource-ratio-controller"),
Scheme: mgr.GetScheme(),
RatioLimits: conf.MemoryPerCoreLimits,
Ratio: &ratio.Fetcher{
Client: mgr.GetClient(),
OrganizationLabel: orgLabel,
},
}).SetupWithManager(mgr); err != nil {
setupLog.Error(err, "unable to create controller", "controller", "ratio")
os.Exit(1)
}
}