-
Notifications
You must be signed in to change notification settings - Fork 184
/
main.go
305 lines (273 loc) · 11 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
/*
Copyright 2020 Red Hat OpenShift Container Storage.
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 (
"context"
"flag"
"fmt"
"os"
"runtime"
nadscheme "github.com/k8snetworkplumbingwg/network-attachment-definition-client/pkg/client/clientset/versioned/scheme"
snapapi "github.com/kubernetes-csi/external-snapshotter/client/v8/apis/volumesnapshot/v1"
nbapis "github.com/noobaa/noobaa-operator/v5/pkg/apis"
openshiftConfigv1 "github.com/openshift/api/config/v1"
quotav1 "github.com/openshift/api/quota/v1"
routev1 "github.com/openshift/api/route/v1"
openshiftv1 "github.com/openshift/api/template/v1"
secv1client "github.com/openshift/client-go/security/clientset/versioned/typed/security/v1"
operatorsv1alpha1 "github.com/operator-framework/api/pkg/operators/v1alpha1"
apiv2 "github.com/operator-framework/api/pkg/operators/v2"
"github.com/operator-framework/operator-lib/conditions"
monitoringv1 "github.com/prometheus-operator/prometheus-operator/pkg/apis/monitoring/v1"
ocsclientv1a1 "github.com/red-hat-storage/ocs-client-operator/api/v1alpha1"
ocsv1 "github.com/red-hat-storage/ocs-operator/api/v4/v1"
ocsv1alpha1 "github.com/red-hat-storage/ocs-operator/api/v4/v1alpha1"
cephv1 "github.com/rook/rook/pkg/apis/ceph.rook.io/v1"
batchv1 "k8s.io/api/batch/v1"
corev1 "k8s.io/api/core/v1"
storagev1 "k8s.io/api/storage/v1"
extv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1"
"k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
apiruntime "k8s.io/apimachinery/pkg/runtime"
utilruntime "k8s.io/apimachinery/pkg/util/runtime"
"k8s.io/apimachinery/pkg/util/wait"
clientgoscheme "k8s.io/client-go/kubernetes/scheme"
_ "k8s.io/client-go/plugin/pkg/client/auth/gcp"
"k8s.io/client-go/util/retry"
clusterv1alpha1 "open-cluster-management.io/api/cluster/v1alpha1"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/cache"
apiclient "sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/log/zap"
metrics "sigs.k8s.io/controller-runtime/pkg/metrics/server"
"github.com/red-hat-storage/ocs-operator/v4/controllers/ocsinitialization"
"github.com/red-hat-storage/ocs-operator/v4/controllers/platform"
"github.com/red-hat-storage/ocs-operator/v4/controllers/storagecluster"
"github.com/red-hat-storage/ocs-operator/v4/controllers/storageclusterpeer"
controllers "github.com/red-hat-storage/ocs-operator/v4/controllers/storageconsumer"
"github.com/red-hat-storage/ocs-operator/v4/controllers/storagerequest"
"github.com/red-hat-storage/ocs-operator/v4/controllers/util"
// +kubebuilder:scaffold:imports
)
var (
scheme = apiruntime.NewScheme()
setupLog = ctrl.Log.WithName("cmd")
)
func init() {
utilruntime.Must(clientgoscheme.AddToScheme(scheme))
utilruntime.Must(apiv2.AddToScheme(scheme))
utilruntime.Must(ocsv1.AddToScheme(scheme))
utilruntime.Must(cephv1.AddToScheme(scheme))
utilruntime.Must(storagev1.AddToScheme(scheme))
utilruntime.Must(nbapis.AddToScheme(scheme))
utilruntime.Must(monitoringv1.AddToScheme(scheme))
utilruntime.Must(batchv1.AddToScheme(scheme))
utilruntime.Must(corev1.AddToScheme(scheme))
utilruntime.Must(openshiftv1.AddToScheme(scheme))
utilruntime.Must(snapapi.AddToScheme(scheme))
utilruntime.Must(openshiftConfigv1.AddToScheme(scheme))
utilruntime.Must(extv1.AddToScheme(scheme))
utilruntime.Must(routev1.AddToScheme(scheme))
utilruntime.Must(quotav1.AddToScheme(scheme))
utilruntime.Must(ocsv1alpha1.AddToScheme(scheme))
utilruntime.Must(clusterv1alpha1.AddToScheme(scheme))
utilruntime.Must(operatorsv1alpha1.AddToScheme(scheme))
utilruntime.Must(nadscheme.AddToScheme(scheme))
utilruntime.Must(ocsclientv1a1.AddToScheme(scheme))
// +kubebuilder:scaffold:scheme
}
func printVersion() {
setupLog.Info(fmt.Sprintf("Go Version: %s", runtime.Version()))
setupLog.Info(fmt.Sprintf("Go OS/Arch: %s/%s", runtime.GOOS, runtime.GOARCH))
}
func main() {
var probeAddr string
var metricsAddr string
var enableLeaderElection bool
flag.StringVar(&metricsAddr, "metrics-addr", ":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, "enable-leader-election", false,
"Enable leader election for controller manager. "+
"Enabling this will ensure there is only one active controller manager.")
loggerOpts := zap.Options{}
loggerOpts.BindFlags(flag.CommandLine)
flag.Parse()
logger := zap.New(zap.UseFlagOptions(&loggerOpts))
ctrl.SetLogger(logger)
printVersion()
if loggerOpts.Development {
setupLog.Info("running in development mode")
}
operatorNamespace, err := util.GetOperatorNamespace()
if err != nil {
setupLog.Error(err, "unable to get operator namespace")
os.Exit(1)
}
defaultNamespaces := map[string]cache.Config{
operatorNamespace: {},
"openshift-storage-extended": {},
}
platform.Detect()
isOpenShift, err := platform.IsPlatformOpenShift()
if err != nil {
setupLog.Error(err, "unable to detect platform")
os.Exit(1)
}
if isOpenShift {
setupLog.Info("Cluster is running on OpenShift.")
} else {
setupLog.Info("Cluster is not running on OpenShift.")
}
cfg := ctrl.GetConfigOrDie()
mgr, err := ctrl.NewManager(cfg, ctrl.Options{
Scheme: scheme,
Metrics: metrics.Options{BindAddress: metricsAddr},
HealthProbeBindAddress: probeAddr,
LeaderElection: enableLeaderElection,
LeaderElectionID: "ab76f4c9.openshift.io",
LeaderElectionNamespace: operatorNamespace,
Cache: cache.Options{DefaultNamespaces: defaultNamespaces},
})
if err != nil {
setupLog.Error(err, "unable to start manager")
os.Exit(1)
}
condition, err := storagecluster.NewUpgradeable(mgr.GetClient())
if err != nil {
setupLog.Error(err, "Unable to get OperatorCondition")
os.Exit(1)
}
// apiclient.New() returns a client without cache.
// cache is not initialized before mgr.Start()
// we need this because we need to interact with OperatorCondition
apiClient, err := apiclient.New(mgr.GetConfig(), apiclient.Options{
Scheme: mgr.GetScheme(),
})
if err != nil {
setupLog.Error(err, "Unable to get Client")
os.Exit(1)
}
availCrds, err := getAvailableCRDNames(context.Background(), apiClient)
if err != nil {
setupLog.Error(err, "Unable get a list of available CRD names")
os.Exit(1)
}
if err = (&ocsinitialization.OCSInitializationReconciler{
Client: mgr.GetClient(),
Log: ctrl.Log.WithName("controllers").WithName("OCSInitialization"),
Scheme: mgr.GetScheme(),
SecurityClient: secv1client.NewForConfigOrDie(mgr.GetConfig()),
OperatorNamespace: operatorNamespace,
AvailableCrds: availCrds,
}).SetupWithManager(mgr); err != nil {
setupLog.Error(err, "unable to create controller", "controller", "OCSInitialization")
os.Exit(1)
}
if err = (&storagecluster.StorageClusterReconciler{
Client: mgr.GetClient(),
Log: ctrl.Log.WithName("controllers").WithName("StorageCluster"),
Scheme: mgr.GetScheme(),
OperatorNamespace: operatorNamespace,
OperatorCondition: condition,
AvailableCrds: availCrds,
}).SetupWithManager(mgr); err != nil {
setupLog.Error(err, "unable to create controller", "controller", "StorageCluster")
os.Exit(1)
}
if err = (&controllers.StorageConsumerReconciler{
Client: mgr.GetClient(),
Log: ctrl.Log.WithName("controllers").WithName("StorageConsumer"),
Scheme: mgr.GetScheme(),
}).SetupWithManager(mgr); err != nil {
setupLog.Error(err, "unable to create controller", "controller", "StorageConsumer")
os.Exit(1)
}
if err = (&storagerequest.StorageRequestReconciler{
Cache: mgr.GetCache(),
Client: mgr.GetClient(),
Scheme: mgr.GetScheme(),
OperatorNamespace: operatorNamespace,
}).SetupWithManager(mgr); err != nil {
setupLog.Error(err, "unable to create controller", "controller", "StorageRequest")
os.Exit(1)
}
if err = (&storageclusterpeer.StorageClusterPeerReconciler{
Client: mgr.GetClient(),
Scheme: mgr.GetScheme(),
}).SetupWithManager(mgr); err != nil {
setupLog.Error(err, "unable to create controller", "controller", "StorageClusterPeer")
os.Exit(1)
}
// +kubebuilder:scaffold:builder
// Create OCSInitialization CR if it's not present
ocsNamespacedName := ocsinitialization.InitNamespacedName()
client := mgr.GetClient()
err = client.Create(context.TODO(), &ocsv1.OCSInitialization{
ObjectMeta: metav1.ObjectMeta{
Name: ocsNamespacedName.Name,
Namespace: ocsNamespacedName.Namespace,
},
})
switch {
case err == nil:
setupLog.Info("created OCSInitialization resource")
case errors.IsAlreadyExists(err):
setupLog.Info("OCSInitialization resource already exists")
default:
setupLog.Error(err, "failed to create OCSInitialization custom resource")
os.Exit(1)
}
// Add readiness probe
if err := mgr.AddReadyzCheck("readyz", storagecluster.ReadinessChecker); err != nil {
setupLog.Error(err, "unable add a readiness check")
os.Exit(1)
}
// Set OperatorCondition Upgradeable to True
// We have to at least default the condition to True or
// OLM will use the Readiness condition via our readiness probe instead:
// https://olm.operatorframework.io/docs/advanced-tasks/communicating-operator-conditions-to-olm/#setting-defaults
condition, err = storagecluster.NewUpgradeable(apiClient)
if err != nil {
setupLog.Error(err, "Unable to get OperatorCondition")
os.Exit(1)
}
// retry for sometime till OperatorCondition CR is available
err = wait.ExponentialBackoff(retry.DefaultRetry, func() (bool, error) {
err = condition.Set(context.TODO(), metav1.ConditionTrue, conditions.WithMessage("Operator is ready"), conditions.WithReason("Ready"))
return err == nil, err
})
if err != nil {
setupLog.Error(err, "Unable to update OperatorCondition")
os.Exit(1)
}
storagecluster.ReadinessSet()
setupLog.Info("starting manager")
if err := mgr.Start(ctrl.SetupSignalHandler()); err != nil {
setupLog.Error(err, "problem running manager")
os.Exit(1)
}
}
func getAvailableCRDNames(ctx context.Context, cl apiclient.Client) (map[string]bool, error) {
crdExist := map[string]bool{}
crdList := &metav1.PartialObjectMetadataList{}
crdList.SetGroupVersionKind(extv1.SchemeGroupVersion.WithKind("CustomResourceDefinitionList"))
if err := cl.List(ctx, crdList); err != nil {
return nil, fmt.Errorf("error listing CRDs, %v", err)
}
// Iterate over the list and populate the map
for i := range crdList.Items {
crdExist[crdList.Items[i].Name] = true
}
return crdExist, nil
}