Skip to content

Commit b4e0e2a

Browse files
authored
Rearrange main.go and use same context for manager and controller (#1768)
1 parent 0d56e7a commit b4e0e2a

File tree

3 files changed

+89
-83
lines changed

3 files changed

+89
-83
lines changed

controllers/ibmpowervscluster_controller.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -454,9 +454,9 @@ func (c clusterDescendants) filterOwnedDescendants(cluster *infrav1beta2.IBMPowe
454454
}
455455

456456
// SetupWithManager creates a new IBMPowerVSCluster controller for a manager.
457-
func (r *IBMPowerVSClusterReconciler) SetupWithManager(mgr ctrl.Manager) error {
457+
func (r *IBMPowerVSClusterReconciler) SetupWithManager(ctx context.Context, mgr ctrl.Manager) error {
458458
return ctrl.NewControllerManagedBy(mgr).
459459
For(&infrav1beta2.IBMPowerVSCluster{}).
460-
WithEventFilter(predicates.ResourceIsNotExternallyManaged(ctrl.LoggerFrom(context.TODO()))).
460+
WithEventFilter(predicates.ResourceIsNotExternallyManaged(ctrl.LoggerFrom(ctx))).
461461
Complete(r)
462462
}

controllers/ibmvpccluster_controller.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -265,9 +265,9 @@ func (r *IBMVPCClusterReconciler) reconcileLBState(clusterScope *scope.ClusterSc
265265
}
266266

267267
// SetupWithManager creates a new IBMVPCCluster controller for a manager.
268-
func (r *IBMVPCClusterReconciler) SetupWithManager(mgr ctrl.Manager) error {
268+
func (r *IBMVPCClusterReconciler) SetupWithManager(ctx context.Context, mgr ctrl.Manager) error {
269269
return ctrl.NewControllerManagedBy(mgr).
270270
For(&infrav1beta2.IBMVPCCluster{}).
271-
WithEventFilter(predicates.ResourceIsNotExternallyManaged(ctrl.LoggerFrom(context.TODO()))).
271+
WithEventFilter(predicates.ResourceIsNotExternallyManaged(ctrl.LoggerFrom(ctx))).
272272
Complete(r)
273273
}

main.go

Lines changed: 85 additions & 79 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ limitations under the License.
1818
package main
1919

2020
import (
21+
"context"
2122
"flag"
2223
"fmt"
2324
"os"
@@ -56,14 +57,16 @@ var (
5657
healthAddr string
5758
syncPeriod time.Duration
5859
diagnosticsOptions = flags.DiagnosticsOptions{}
60+
webhookPort int
61+
webhookCertDir string
5962

60-
scheme = runtime.NewScheme()
61-
setupLog = ctrl.Log.WithName("setup")
62-
webhookPort int
63-
webhookCertDir string
63+
scheme = runtime.NewScheme()
64+
setupLog = ctrl.Log.WithName("setup")
6465
)
6566

6667
func init() {
68+
klog.InitFlags(nil)
69+
6770
_ = clientgoscheme.AddToScheme(scheme)
6871

6972
_ = infrav1beta1.AddToScheme(scheme)
@@ -72,13 +75,79 @@ func init() {
7275
// +kubebuilder:scaffold:scheme
7376
}
7477

78+
func initFlags(fs *pflag.FlagSet) {
79+
fs.BoolVar(
80+
&enableLeaderElection,
81+
"leader-elect",
82+
false,
83+
"Enable leader election for controller manager. "+
84+
"Enabling this will ensure there is only one active controller manager.",
85+
)
86+
87+
fs.StringVar(
88+
&watchNamespace,
89+
"namespace",
90+
"",
91+
"Namespace that the controller watches to reconcile cluster-api objects. If unspecified, the controller watches for cluster-api objects across all namespaces.",
92+
)
93+
94+
fs.StringVar(
95+
&healthAddr,
96+
"health-addr",
97+
":9440",
98+
"The address the health endpoint binds to.",
99+
)
100+
101+
fs.DurationVar(
102+
&syncPeriod,
103+
"sync-period",
104+
10*time.Minute,
105+
"The minimum interval at which watched resources are reconciled.",
106+
)
107+
108+
fs.StringVar(
109+
&options.ProviderIDFormat,
110+
"provider-id-fmt",
111+
string(options.ProviderIDFormatV1),
112+
"ProviderID format is used set the Provider ID format for Machine",
113+
)
114+
115+
fs.StringVar(
116+
&endpoints.ServiceEndpointFormat,
117+
"service-endpoint",
118+
"",
119+
"Set custom service endpoint in semi-colon separated format: ${ServiceRegion1}:${ServiceID1}=${URL1},${ServiceID2}=${URL2};${ServiceRegion2}:${ServiceID1}=${URL1}",
120+
)
121+
122+
fs.IntVar(&webhookPort,
123+
"webhook-port",
124+
9443,
125+
"The webhook server port the manager will listen on.",
126+
)
127+
128+
fs.StringVar(&webhookCertDir, "webhook-cert-dir", "/tmp/k8s-webhook-server/serving-certs/",
129+
"The webhook certificate directory, where the server should find the TLS certificate and key.")
130+
131+
flags.AddDiagnosticsOptions(fs, &diagnosticsOptions)
132+
}
133+
134+
func validateFlags() error {
135+
switch options.ProviderIDFormatType(options.ProviderIDFormat) {
136+
case options.ProviderIDFormatV1:
137+
setupLog.Info("Using v1 version of ProviderID format")
138+
case options.ProviderIDFormatV2:
139+
setupLog.Info("Using v2 version of ProviderID format")
140+
default:
141+
return fmt.Errorf("invalid value for flag provider-id-fmt: %s, Supported values: %s, %s ", options.ProviderIDFormat, options.ProviderIDFormatV1, options.ProviderIDFormatV2)
142+
}
143+
return nil
144+
}
145+
75146
// Add RBAC for the authorized diagnostics endpoint.
76147
// +kubebuilder:rbac:groups=authentication.k8s.io,resources=tokenreviews,verbs=create
77148
// +kubebuilder:rbac:groups=authorization.k8s.io,resources=subjectaccessreviews,verbs=create
78149

79150
func main() {
80-
klog.InitFlags(nil)
81-
82151
initFlags(pflag.CommandLine)
83152
pflag.CommandLine.AddGoFlagSet(flag.CommandLine)
84153
pflag.Parse()
@@ -134,6 +203,8 @@ func main() {
134203
Client: client.Options{
135204
Cache: &client.CacheOptions{
136205
DisableFor: []client.Object{
206+
// We want to avoid use of cache for IBMPowerVSCluster as we exclusively depend on IBMPowerVSCluster.Status.[Resource].ControllerCreated
207+
// to mark resources created by controller.
137208
&infrav1beta2.IBMPowerVSCluster{},
138209
},
139210
},
@@ -147,94 +218,29 @@ func main() {
147218
// Initialize event recorder.
148219
record.InitFromRecorder(mgr.GetEventRecorderFor("ibmcloud-controller"))
149220

150-
setupReconcilers(mgr, serviceEndpoint)
221+
// Setup the context that's going to be used in controllers and for the manager.
222+
ctx := ctrl.SetupSignalHandler()
223+
224+
setupReconcilers(ctx, mgr, serviceEndpoint)
151225
setupWebhooks(mgr)
152226
setupChecks(mgr)
153227

154228
// +kubebuilder:scaffold:builder
155229
setupLog.Info("starting manager")
156-
if err := mgr.Start(ctrl.SetupSignalHandler()); err != nil {
230+
if err := mgr.Start(ctx); err != nil {
157231
setupLog.Error(err, "problem running manager")
158232
os.Exit(1)
159233
}
160234
}
161235

162-
func initFlags(fs *pflag.FlagSet) {
163-
fs.BoolVar(
164-
&enableLeaderElection,
165-
"leader-elect",
166-
false,
167-
"Enable leader election for controller manager. "+
168-
"Enabling this will ensure there is only one active controller manager.",
169-
)
170-
171-
fs.StringVar(
172-
&watchNamespace,
173-
"namespace",
174-
"",
175-
"Namespace that the controller watches to reconcile cluster-api objects. If unspecified, the controller watches for cluster-api objects across all namespaces.",
176-
)
177-
178-
fs.StringVar(
179-
&healthAddr,
180-
"health-addr",
181-
":9440",
182-
"The address the health endpoint binds to.",
183-
)
184-
185-
fs.DurationVar(
186-
&syncPeriod,
187-
"sync-period",
188-
10*time.Minute,
189-
"The minimum interval at which watched resources are reconciled.",
190-
)
191-
192-
fs.StringVar(
193-
&options.ProviderIDFormat,
194-
"provider-id-fmt",
195-
string(options.ProviderIDFormatV1),
196-
"ProviderID format is used set the Provider ID format for Machine",
197-
)
198-
199-
fs.StringVar(
200-
&endpoints.ServiceEndpointFormat,
201-
"service-endpoint",
202-
"",
203-
"Set custom service endpoint in semi-colon separated format: ${ServiceRegion1}:${ServiceID1}=${URL1},${ServiceID2}=${URL2};${ServiceRegion2}:${ServiceID1}=${URL1}",
204-
)
205-
206-
fs.IntVar(&webhookPort,
207-
"webhook-port",
208-
9443,
209-
"The webhook server port the manager will listen on.",
210-
)
211-
212-
fs.StringVar(&webhookCertDir, "webhook-cert-dir", "/tmp/k8s-webhook-server/serving-certs/",
213-
"The webhook certificate directory, where the server should find the TLS certificate and key.")
214-
215-
flags.AddDiagnosticsOptions(fs, &diagnosticsOptions)
216-
}
217-
218-
func validateFlags() error {
219-
switch options.ProviderIDFormatType(options.ProviderIDFormat) {
220-
case options.ProviderIDFormatV1:
221-
setupLog.Info("Using v1 version of ProviderID format")
222-
case options.ProviderIDFormatV2:
223-
setupLog.Info("Using v2 version of ProviderID format")
224-
default:
225-
return fmt.Errorf("invalid value for flag provider-id-fmt: %s, Supported values: %s, %s ", options.ProviderIDFormat, options.ProviderIDFormatV1, options.ProviderIDFormatV2)
226-
}
227-
return nil
228-
}
229-
230-
func setupReconcilers(mgr ctrl.Manager, serviceEndpoint []endpoints.ServiceEndpoint) {
236+
func setupReconcilers(ctx context.Context, mgr ctrl.Manager, serviceEndpoint []endpoints.ServiceEndpoint) {
231237
if err := (&controllers.IBMVPCClusterReconciler{
232238
Client: mgr.GetClient(),
233239
Log: ctrl.Log.WithName("controllers").WithName("IBMVPCCluster"),
234240
Recorder: mgr.GetEventRecorderFor("ibmvpccluster-controller"),
235241
ServiceEndpoint: serviceEndpoint,
236242
Scheme: mgr.GetScheme(),
237-
}).SetupWithManager(mgr); err != nil {
243+
}).SetupWithManager(ctx, mgr); err != nil {
238244
setupLog.Error(err, "unable to create controller", "controller", "IBMVPCCluster")
239245
os.Exit(1)
240246
}
@@ -255,7 +261,7 @@ func setupReconcilers(mgr ctrl.Manager, serviceEndpoint []endpoints.ServiceEndpo
255261
Recorder: mgr.GetEventRecorderFor("ibmpowervscluster-controller"),
256262
ServiceEndpoint: serviceEndpoint,
257263
Scheme: mgr.GetScheme(),
258-
}).SetupWithManager(mgr); err != nil {
264+
}).SetupWithManager(ctx, mgr); err != nil {
259265
setupLog.Error(err, "unable to create controller", "controller", "IBMPowerVSCluster")
260266
os.Exit(1)
261267
}

0 commit comments

Comments
 (0)