-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.go
422 lines (364 loc) · 12.8 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
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
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
package templates
import (
"fmt"
"path/filepath"
"sigs.k8s.io/kubebuilder/v3/pkg/machinery"
)
const defaultMainPath = "main.go"
var _ machinery.Template = &Main{}
// Main scaffolds a file that defines the controller manager entry point
type Main struct {
machinery.TemplateMixin
machinery.BoilerplateMixin
machinery.DomainMixin
machinery.RepositoryMixin
machinery.ComponentConfigMixin
}
// SetTemplateDefaults implements file.Template
func (f *Main) SetTemplateDefaults() error {
if f.Path == "" {
f.Path = filepath.Join(defaultMainPath)
}
f.TemplateBody = fmt.Sprintf(mainTemplate,
machinery.NewMarkerFor(f.Path, importMarker),
machinery.NewMarkerFor(f.Path, addSchemeMarker),
machinery.NewMarkerFor(f.Path, setupMarker),
)
return nil
}
var _ machinery.Inserter = &MainUpdater{}
// MainUpdater updates main.go to run Controllers
type MainUpdater struct { //nolint:maligned
machinery.RepositoryMixin
machinery.MultiGroupMixin
machinery.ResourceMixin
// Flags to indicate which parts need to be included when updating the file
WireResource, WireController, WireWebhook bool
}
// GetPath implements file.Builder
func (*MainUpdater) GetPath() string {
return defaultMainPath
}
// GetIfExistsAction implements file.Builder
func (*MainUpdater) GetIfExistsAction() machinery.IfExistsAction {
return machinery.OverwriteFile
}
const (
importMarker = "imports"
addSchemeMarker = "scheme"
setupMarker = "builder"
)
// GetMarkers implements file.Inserter
func (f *MainUpdater) GetMarkers() []machinery.Marker {
return []machinery.Marker{
machinery.NewMarkerFor(defaultMainPath, importMarker),
machinery.NewMarkerFor(defaultMainPath, addSchemeMarker),
machinery.NewMarkerFor(defaultMainPath, setupMarker),
}
}
const (
apiImportCodeFragment = `%s "%s"
`
controllerImportCodeFragment = `"%s/controllers"
`
multiGroupControllerImportCodeFragment = `%scontrollers "%s/controllers/%s"
`
addschemeCodeFragment = `utilruntime.Must(%s.AddToScheme(scheme))
`
reconcilerSetupCodeFragment = `if err = (&controllers.%sReconciler{
Client: mgr.GetClient(),
Scheme: mgr.GetScheme(),
}).SetupWithManager(mgr); err != nil {
setupLog.Error(err, "unable to create controller", "controller", "%s")
os.Exit(1)
}
`
multiGroupReconcilerSetupCodeFragment = `if err = (&%scontrollers.%sReconciler{
Client: mgr.GetClient(),
Scheme: mgr.GetScheme(),
}).SetupWithManager(mgr); err != nil {
setupLog.Error(err, "unable to create controller", "controller", "%s")
os.Exit(1)
}
`
webhookSetupCodeFragment = `if err = (&%s.%s{}).SetupWebhookWithManager(mgr); err != nil {
setupLog.Error(err, "unable to create webhook", "webhook", "%s")
os.Exit(1)
}
`
)
// GetCodeFragments implements file.Inserter
func (f *MainUpdater) GetCodeFragments() machinery.CodeFragmentsMap {
fragments := make(machinery.CodeFragmentsMap, 3)
// If resource is not being provided we are creating the file, not updating it
if f.Resource == nil {
return fragments
}
// Generate import code fragments
imports := make([]string, 0)
if f.WireResource {
imports = append(imports, fmt.Sprintf(apiImportCodeFragment, f.Resource.ImportAlias(), f.Resource.Path))
}
if f.WireController {
if !f.MultiGroup || f.Resource.Group == "" {
imports = append(imports, fmt.Sprintf(controllerImportCodeFragment, f.Repo))
} else {
imports = append(imports, fmt.Sprintf(multiGroupControllerImportCodeFragment,
f.Resource.PackageName(), f.Repo, f.Resource.Group))
}
}
// Generate add scheme code fragments
addScheme := make([]string, 0)
if f.WireResource {
addScheme = append(addScheme, fmt.Sprintf(addschemeCodeFragment, f.Resource.ImportAlias()))
}
// Generate setup code fragments
setup := make([]string, 0)
if f.WireController {
if !f.MultiGroup || f.Resource.Group == "" {
setup = append(setup, fmt.Sprintf(reconcilerSetupCodeFragment,
f.Resource.Kind, f.Resource.Kind))
} else {
setup = append(setup, fmt.Sprintf(multiGroupReconcilerSetupCodeFragment,
f.Resource.PackageName(), f.Resource.Kind, f.Resource.Kind))
}
}
if f.WireWebhook {
setup = append(setup, fmt.Sprintf(webhookSetupCodeFragment,
f.Resource.ImportAlias(), f.Resource.Kind, f.Resource.Kind))
}
// Only store code fragments in the map if the slices are non-empty
if len(imports) != 0 {
fragments[machinery.NewMarkerFor(defaultMainPath, importMarker)] = imports
}
if len(addScheme) != 0 {
fragments[machinery.NewMarkerFor(defaultMainPath, addSchemeMarker)] = addScheme
}
if len(setup) != 0 {
fragments[machinery.NewMarkerFor(defaultMainPath, setupMarker)] = setup
}
return fragments
}
var mainTemplate = `{{ .Boilerplate }}
package main
import (
"context"
"flag"
"fmt"
"os"
apisv1alpha1 "github.com/kcp-dev/kcp/pkg/apis/apis/v1alpha1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/types"
utilruntime "k8s.io/apimachinery/pkg/util/runtime"
"k8s.io/client-go/discovery"
clientgoscheme "k8s.io/client-go/kubernetes/scheme"
"k8s.io/client-go/rest"
// 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"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/kcp"
"sigs.k8s.io/controller-runtime/pkg/healthz"
"sigs.k8s.io/controller-runtime/pkg/log/zap"
%s
)
var (
scheme = runtime.NewScheme()
setupLog = ctrl.Log.WithName("setup")
)
func init() {
utilruntime.Must(clientgoscheme.AddToScheme(scheme))
%s
}
func main() {
{{- if not .ComponentConfig }}
var metricsAddr string
var enableLeaderElection bool
var probeAddr string
var apiExportName string
flag.StringVar(&apiExportName, "api-export-name", "", "The name of the APIExport.")
flag.StringVar(&metricsAddr, "metrics-bind-address", ":8080", "The address the metric endpoint binds to.")
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.")
{{- else }}
var configFile string
var apiExportName string
flag.StringVar(&apiExportName, "api-export-name", "", "The name of the APIExport.")
flag.StringVar(&configFile, "config", "",
"The controller will load its initial configuration from this file. " +
"Omit this flag to use the default configuration values. " +
"Command-line flags override configuration from this file.")
{{- end }}
opts := zap.Options{
Development: true,
}
opts.BindFlags(flag.CommandLine)
flag.Parse()
ctrl.SetLogger(zap.New(zap.UseFlagOptions(&opts)))
setupLog = setupLog.WithValues("api-export-name", apiExportName)
ctx := ctrl.SetupSignalHandler()
restConfig := ctrl.GetConfigOrDie()
var mgr ctrl.Manager
var err error
if kcpAPIsGroupPresent(restConfig) {
setupLog.Info("Looking up virtual workspace URL")
cfg, err := restConfigForAPIExport(ctx, restConfig, apiExportName)
if err != nil {
setupLog.Error(err, "error looking up virtual workspace URL")
}
setupLog.Info("Using virtual workspace URL", "url", cfg.Host)
{{ if not .ComponentConfig }}
mgr, err = kcp.NewClusterAwareManager(cfg, ctrl.Options{
Scheme: scheme,
MetricsBindAddress: metricsAddr,
Port: 9443,
HealthProbeBindAddress: probeAddr,
LeaderElection: enableLeaderElection,
LeaderElectionID: "{{ hashFNV .Repo }}.{{ .Domain }}",
// LeaderElectionReleaseOnCancel defines if the leader should step down voluntarily
// when the Manager ends. This requires the binary to immediately end when the
// Manager is stopped, otherwise, this setting is unsafe. Setting this significantly
// speeds up voluntary leader transitions as the new leader don't have to wait
// LeaseDuration time first.
//
// In the default scaffold provided, the program ends immediately after
// the manager stops, so would be fine to enable this option. However,
// if you are doing or is intended to do any operation such as perform cleanups
// after the manager stops then its usage might be unsafe.
// LeaderElectionReleaseOnCancel: true,
LeaderElectionConfig: restConfig,
})
{{- else }}
options := ctrl.Options{Scheme: scheme}
options.LeaderElectionConfig = restConfig
if configFile != "" {
options, err = options.AndFrom(ctrl.ConfigFile().AtPath(configFile))
if err != nil {
setupLog.Error(err, "unable to load the config file")
os.Exit(1)
}
}
mgr, err = kcp.NewClusterAwareManager(cfg, options)
{{- end }}
if err != nil {
setupLog.Error(err, "unable to start cluster aware manager")
os.Exit(1)
}
} else {
setupLog.Info("The apis.kcp.dev group is not present - creating standard manager")
{{ if not .ComponentConfig }}
mgr, err = ctrl.NewManager(ctrl.GetConfigOrDie(), ctrl.Options{
Scheme: scheme,
MetricsBindAddress: metricsAddr,
Port: 9443,
HealthProbeBindAddress: probeAddr,
LeaderElection: enableLeaderElection,
LeaderElectionID: "{{ hashFNV .Repo }}.{{ .Domain }}",
// LeaderElectionReleaseOnCancel defines if the leader should step down voluntarily
// when the Manager ends. This requires the binary to immediately end when the
// Manager is stopped, otherwise, this setting is unsafe. Setting this significantly
// speeds up voluntary leader transitions as the new leader don't have to wait
// LeaseDuration time first.
//
// In the default scaffold provided, the program ends immediately after
// the manager stops, so would be fine to enable this option. However,
// if you are doing or is intended to do any operation such as perform cleanups
// after the manager stops then its usage might be unsafe.
// LeaderElectionReleaseOnCancel: true,
})
{{- else }}
options := ctrl.Options{Scheme: scheme}
if configFile != "" {
options, err = options.AndFrom(ctrl.ConfigFile().AtPath(configFile))
if err != nil {
setupLog.Error(err, "unable to load the config file")
os.Exit(1)
}
}
mgr, err = ctrl.NewManager(ctrl.GetConfigOrDie(), options)
{{- end }}
if err != nil {
setupLog.Error(err, "unable to start manager")
os.Exit(1)
}
}
%s
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(ctx); err != nil {
setupLog.Error(err, "problem running manager")
os.Exit(1)
}
}
// +kubebuilder:rbac:groups="apis.kcp.dev",resources=apiexports,verbs=get;list;watch
// restConfigForAPIExport returns a *rest.Config properly configured to communicate with the endpoint for the
// APIExport's virtual workspace.
func restConfigForAPIExport(ctx context.Context, cfg *rest.Config, apiExportName string) (*rest.Config, error) {
scheme := runtime.NewScheme()
if err := apisv1alpha1.AddToScheme(scheme); err != nil {
return nil, fmt.Errorf("error adding apis.kcp.dev/v1alpha1 to scheme: %%w", err)
}
apiExportClient, err := client.New(cfg, client.Options{Scheme: scheme})
if err != nil {
return nil, fmt.Errorf("error creating APIExport client: %%w", err)
}
var apiExport apisv1alpha1.APIExport
if apiExportName != "" {
if err := apiExportClient.Get(ctx, types.NamespacedName{Name: apiExportName}, &apiExport); err != nil {
return nil, fmt.Errorf("error getting APIExport %%q: %%w", apiExportName, err)
}
} else {
setupLog.Info("api-export-name is empty - listing")
exports := &apisv1alpha1.APIExportList{}
if err := apiExportClient.List(ctx, exports); err != nil {
return nil, fmt.Errorf("error listing APIExports: %%w", err)
}
if len(exports.Items) == 0 {
return nil, fmt.Errorf("no APIExport found")
}
if len(exports.Items) > 1 {
return nil, fmt.Errorf("more than one APIExport found")
}
apiExport = exports.Items[0]
}
if len(apiExport.Status.VirtualWorkspaces) < 1 {
return nil, fmt.Errorf("APIExport %%q status.virtualWorkspaces is empty", apiExportName)
}
cfg = rest.CopyConfig(cfg)
// TODO(ncdc): sharding support
cfg.Host = apiExport.Status.VirtualWorkspaces[0].URL
return cfg, nil
}
func kcpAPIsGroupPresent(restConfig *rest.Config) bool {
discoveryClient, err := discovery.NewDiscoveryClientForConfig(restConfig)
if err != nil {
setupLog.Error(err, "failed to create discovery client")
os.Exit(1)
}
apiGroupList, err := discoveryClient.ServerGroups()
if err != nil {
setupLog.Error(err, "failed to get server groups")
os.Exit(1)
}
for _, group := range apiGroupList.Groups {
if group.Name == apisv1alpha1.SchemeGroupVersion.Group {
for _, version := range group.Versions {
if version.Version == apisv1alpha1.SchemeGroupVersion.Version {
return true
}
}
}
}
return false
}
`