-
Notifications
You must be signed in to change notification settings - Fork 2.7k
/
controller.go
343 lines (298 loc) · 12.9 KB
/
controller.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
/*
Copyright 2019 The Rook Authors. All rights reserved.
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 nfs
import (
"context"
"fmt"
"reflect"
"strings"
"github.com/coreos/pkg/capnslog"
"github.com/pkg/errors"
cephv1 "github.com/rook/rook/pkg/apis/ceph.rook.io/v1"
"github.com/rook/rook/pkg/clusterd"
cephclient "github.com/rook/rook/pkg/daemon/ceph/client"
"github.com/rook/rook/pkg/operator/ceph/cluster/mon"
opconfig "github.com/rook/rook/pkg/operator/ceph/config"
opcontroller "github.com/rook/rook/pkg/operator/ceph/controller"
"github.com/rook/rook/pkg/operator/ceph/reporting"
"github.com/rook/rook/pkg/operator/ceph/version"
"github.com/rook/rook/pkg/operator/k8sutil"
appsv1 "k8s.io/api/apps/v1"
v1 "k8s.io/api/core/v1"
kerrors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/types"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/controller"
"sigs.k8s.io/controller-runtime/pkg/handler"
"sigs.k8s.io/controller-runtime/pkg/manager"
"sigs.k8s.io/controller-runtime/pkg/reconcile"
"sigs.k8s.io/controller-runtime/pkg/source"
)
const (
controllerName = "ceph-nfs-controller"
)
// Version of Ceph where NFS default pool name changes to ".nfs"
var cephNFSChangeVersion = version.CephVersion{Major: 16, Minor: 2, Extra: 7}
var logger = capnslog.NewPackageLogger("github.com/rook/rook", controllerName)
// List of object resources to watch by the controller
var objectsToWatch = []client.Object{
&v1.Service{TypeMeta: metav1.TypeMeta{Kind: "Service", APIVersion: v1.SchemeGroupVersion.String()}},
&v1.ConfigMap{TypeMeta: metav1.TypeMeta{Kind: "ConfigMap", APIVersion: v1.SchemeGroupVersion.String()}},
&appsv1.Deployment{TypeMeta: metav1.TypeMeta{Kind: "Deployment", APIVersion: appsv1.SchemeGroupVersion.String()}},
}
var cephNFSKind = reflect.TypeOf(cephv1.CephNFS{}).Name()
// Sets the type meta for the controller main object
var controllerTypeMeta = metav1.TypeMeta{
Kind: cephNFSKind,
APIVersion: fmt.Sprintf("%s/%s", cephv1.CustomResourceGroup, cephv1.Version),
}
// ReconcileCephNFS reconciles a cephNFS object
type ReconcileCephNFS struct {
client client.Client
scheme *runtime.Scheme
context *clusterd.Context
cephClusterSpec *cephv1.ClusterSpec
clusterInfo *cephclient.ClusterInfo
}
// Add creates a new cephNFS Controller and adds it to the Manager. The Manager will set fields on the Controller
// and Start it when the Manager is Started.
func Add(mgr manager.Manager, context *clusterd.Context) error {
return add(mgr, newReconciler(mgr, context))
}
// newReconciler returns a new reconcile.Reconciler
func newReconciler(mgr manager.Manager, context *clusterd.Context) reconcile.Reconciler {
// Add the cephv1 scheme to the manager scheme so that the controller knows about it
mgrScheme := mgr.GetScheme()
if err := cephv1.AddToScheme(mgr.GetScheme()); err != nil {
panic(err)
}
return &ReconcileCephNFS{
client: mgr.GetClient(),
scheme: mgrScheme,
context: context,
}
}
func add(mgr manager.Manager, r reconcile.Reconciler) error {
// Create a new controller
c, err := controller.New(controllerName, mgr, controller.Options{Reconciler: r})
if err != nil {
return err
}
logger.Info("successfully started")
// Watch for changes on the cephNFS CRD object
err = c.Watch(&source.Kind{Type: &cephv1.CephNFS{TypeMeta: controllerTypeMeta}}, &handler.EnqueueRequestForObject{}, opcontroller.WatchControllerPredicate())
if err != nil {
return err
}
// Watch all other resources
for _, t := range objectsToWatch {
err = c.Watch(&source.Kind{Type: t}, &handler.EnqueueRequestForOwner{
IsController: true,
OwnerType: &cephv1.CephNFS{},
}, opcontroller.WatchPredicateForNonCRDObject(&cephv1.CephNFS{TypeMeta: controllerTypeMeta}, mgr.GetScheme()))
if err != nil {
return err
}
}
return nil
}
// Reconcile reads that state of the cluster for a cephNFS object and makes changes based on the state read
// and what is in the cephNFS.Spec
// The Controller will requeue the Request to be processed again if the returned error is non-nil or
// Result.Requeue is true, otherwise upon completion it will remove the work from the queue.
func (r *ReconcileCephNFS) Reconcile(context context.Context, request reconcile.Request) (reconcile.Result, error) {
// workaround because the rook logging mechanism is not compatible with the controller-runtime logging interface
reconcileResponse, err := r.reconcile(request)
if err != nil {
logger.Errorf("failed to reconcile %v", err)
}
return reconcileResponse, err
}
func (r *ReconcileCephNFS) reconcile(request reconcile.Request) (reconcile.Result, error) {
// Fetch the cephNFS instance
cephNFS := &cephv1.CephNFS{}
err := r.client.Get(context.TODO(), request.NamespacedName, cephNFS)
if err != nil {
if kerrors.IsNotFound(err) {
logger.Debug("cephNFS resource not found. Ignoring since object must be deleted.")
return reconcile.Result{}, nil
}
// Error reading the object - requeue the request.
return reconcile.Result{}, errors.Wrap(err, "failed to get cephNFS")
}
// Set a finalizer so we can do cleanup before the object goes away
err = opcontroller.AddFinalizerIfNotPresent(r.client, cephNFS)
if err != nil {
return reconcile.Result{}, errors.Wrap(err, "failed to add finalizer")
}
// The CR was just created, initializing status fields
if cephNFS.Status == nil {
updateStatus(r.client, request.NamespacedName, k8sutil.EmptyStatus)
}
// Make sure a CephCluster is present otherwise do nothing
cephCluster, isReadyToReconcile, cephClusterExists, reconcileResponse := opcontroller.IsReadyToReconcile(r.client, request.NamespacedName, controllerName)
if !isReadyToReconcile {
// This handles the case where the Ceph Cluster is gone and we want to delete that CR
// We skip the deleteStore() function since everything is gone already
//
// Also, only remove the finalizer if the CephCluster is gone
// If not, we should wait for it to be ready
// This handles the case where the operator is not ready to accept Ceph command but the cluster exists
if !cephNFS.GetDeletionTimestamp().IsZero() && !cephClusterExists {
// Remove finalizer
err := opcontroller.RemoveFinalizer(r.client, cephNFS)
if err != nil {
return reconcile.Result{}, errors.Wrap(err, "failed to remove finalizer")
}
// Return and do not requeue. Successful deletion.
return reconcile.Result{}, nil
}
return reconcileResponse, nil
}
r.cephClusterSpec = &cephCluster.Spec
// Populate clusterInfo
// Always populate it during each reconcile
r.clusterInfo, _, _, err = mon.LoadClusterInfo(r.context, request.NamespacedName.Namespace)
if err != nil {
return reconcile.Result{}, errors.Wrap(err, "failed to populate cluster info")
}
// Populate CephVersion
currentCephVersion, err := cephclient.LeastUptodateDaemonVersion(r.context, r.clusterInfo, opconfig.MonType)
if err != nil {
if strings.Contains(err.Error(), opcontroller.UninitializedCephConfigError) {
logger.Info(opcontroller.OperatorNotInitializedMessage)
return opcontroller.WaitForRequeueIfOperatorNotInitialized, nil
}
return reconcile.Result{}, errors.Wrapf(err, "failed to retrieve current ceph %q version", opconfig.MonType)
}
r.clusterInfo.CephVersion = currentCephVersion
// DELETE: the CR was deleted
if !cephNFS.GetDeletionTimestamp().IsZero() {
logger.Infof("deleting ceph nfs %q", cephNFS.Name)
err := r.removeServersFromDatabase(cephNFS, 0)
if err != nil {
return reconcile.Result{}, errors.Wrapf(err, "failed to delete filesystem %q. ", cephNFS.Name)
}
// Remove finalizer
err = opcontroller.RemoveFinalizer(r.client, cephNFS)
if err != nil {
return reconcile.Result{}, errors.Wrap(err, "failed to remove finalizer")
}
// Return and do not requeue. Successful deletion.
return reconcile.Result{}, nil
}
// Octopus: Customization is allowed, so don't change the pool and namespace
// Pacific before 16.2.7: No customization, default pool name is nfs-ganesha
// Pacific after 16.2.7: No customization, default pool name is .nfs
// This code is changes the pool and namespace to the correct values if the version is Pacific.
// If the version precedes Pacific it doesn't change it at all and the values used are what the user provided in the spec.
if r.clusterInfo.CephVersion.IsAtLeastPacific() {
if r.clusterInfo.CephVersion.IsAtLeast(cephNFSChangeVersion) {
cephNFS.Spec.RADOS.Pool = postNFSChangeDefaultPoolName
} else {
cephNFS.Spec.RADOS.Pool = preNFSChangeDefaultPoolName
}
cephNFS.Spec.RADOS.Namespace = cephNFS.Name
} else {
// This handles the case where the user has not provided a pool name and the cluster version
// is Octopus. We need to do this since the pool name is optional in the API due to the
// changes in Pacific defaulting to the ".nfs" pool.
// We default to the new name so that nothing will break on upgrades
if cephNFS.Spec.RADOS.Pool == "" {
cephNFS.Spec.RADOS.Pool = postNFSChangeDefaultPoolName
}
}
// validate the store settings
if err := validateGanesha(r.context, r.clusterInfo, cephNFS); err != nil {
return reconcile.Result{}, errors.Wrapf(err, "invalid ceph nfs %q arguments", cephNFS.Name)
}
// Always create the default pool
err = r.createDefaultNFSRADOSPool(cephNFS)
if err != nil {
return reconcile.Result{}, errors.Wrapf(err, "failed to create default pool %q", cephNFS.Spec.RADOS.Pool)
}
// CREATE/UPDATE
logger.Debug("reconciling ceph nfs deployments")
_, err = r.reconcileCreateCephNFS(cephNFS)
if err != nil {
updateStatus(r.client, request.NamespacedName, k8sutil.FailedStatus)
return reconcile.Result{}, errors.Wrap(err, "failed to create ceph nfs deployments")
}
// Set Ready status, we are done reconciling
updateStatus(r.client, request.NamespacedName, k8sutil.ReadyStatus)
// Return and do not requeue
logger.Debug("done reconciling ceph nfs")
return reconcile.Result{}, nil
}
func (r *ReconcileCephNFS) reconcileCreateCephNFS(cephNFS *cephv1.CephNFS) (reconcile.Result, error) {
ctx := context.TODO()
if r.cephClusterSpec.External.Enable {
_, err := opcontroller.ValidateCephVersionsBetweenLocalAndExternalClusters(r.context, r.clusterInfo)
if err != nil {
// This handles the case where the operator is running, the external cluster has been upgraded and a CR creation is called
// If that's a major version upgrade we fail, if it's a minor version, we continue, it's not ideal but not critical
return reconcile.Result{}, errors.Wrap(err, "refusing to run new crd")
}
}
deployments, err := r.context.Clientset.AppsV1().Deployments(cephNFS.Namespace).List(ctx, metav1.ListOptions{LabelSelector: fmt.Sprintf("app=%s", AppName)})
if err != nil {
if kerrors.IsNotFound(err) {
logger.Infof("creating ceph nfs %q", cephNFS.Name)
err := r.upCephNFS(cephNFS)
if err != nil {
return reconcile.Result{}, errors.Wrapf(err, "failed to create ceph nfs %q", cephNFS.Name)
}
return reconcile.Result{}, nil
}
return reconcile.Result{}, errors.Wrap(err, "failed to list ceph nfs deployments")
}
nfsServerListNum := len(deployments.Items)
// Scale down case (CR value cephNFS.Spec.Server.Active changed)
if nfsServerListNum > cephNFS.Spec.Server.Active {
logger.Infof("scaling down ceph nfs %q from %d to %d", cephNFS.Name, nfsServerListNum, cephNFS.Spec.Server.Active)
err := r.downCephNFS(cephNFS, nfsServerListNum)
if err != nil {
return reconcile.Result{}, errors.Wrapf(err, "failed to scale down ceph nfs %q", cephNFS.Name)
}
}
// Update existing deployments and create new ones in the scale up case
logger.Infof("updating ceph nfs %q", cephNFS.Name)
err = r.upCephNFS(cephNFS)
if err != nil {
return reconcile.Result{}, errors.Wrapf(err, "failed to update ceph nfs %q", cephNFS.Name)
}
return reconcile.Result{}, nil
}
// updateStatus updates an object with a given status
func updateStatus(client client.Client, name types.NamespacedName, status string) {
nfs := &cephv1.CephNFS{}
err := client.Get(context.TODO(), name, nfs)
if err != nil {
if kerrors.IsNotFound(err) {
logger.Debug("CephNFS resource not found. Ignoring since object must be deleted.")
return
}
logger.Warningf("failed to retrieve nfs %q to update status to %q. %v", name, status, err)
return
}
if nfs.Status == nil {
nfs.Status = &cephv1.Status{}
}
nfs.Status.Phase = status
if err := reporting.UpdateStatus(client, nfs); err != nil {
logger.Errorf("failed to set nfs %q status to %q. %v", nfs.Name, status, err)
}
logger.Debugf("nfs %q status updated to %q", name, status)
}