-
Notifications
You must be signed in to change notification settings - Fork 113
/
blockdeviceclaim_controller.go
412 lines (353 loc) · 14.6 KB
/
blockdeviceclaim_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
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
/*
Copyright 2019 The OpenEBS Authors
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 blockdeviceclaim
import (
"context"
"fmt"
ndm "github.com/openebs/node-disk-manager/cmd/ndm_daemonset/controller"
"github.com/openebs/node-disk-manager/db/kubernetes"
apis "github.com/openebs/node-disk-manager/pkg/apis/openebs/v1alpha1"
controllerutil "github.com/openebs/node-disk-manager/pkg/controller/util"
"github.com/openebs/node-disk-manager/pkg/select/blockdevice"
"github.com/openebs/node-disk-manager/pkg/select/verify"
"github.com/openebs/node-disk-manager/pkg/util"
corev1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/api/errors"
v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/client-go/tools/record"
"k8s.io/client-go/tools/reference"
"k8s.io/klog"
"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"
)
// Add creates a new BlockDeviceClaim 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) error {
return add(mgr, newReconciler(mgr))
}
// newReconciler returns a new reconcile.Reconciler
func newReconciler(mgr manager.Manager) reconcile.Reconciler {
return &ReconcileBlockDeviceClaim{client: mgr.GetClient(), scheme: mgr.GetScheme(), recorder: mgr.GetRecorder("blockdeviceclaim-operator")}
}
// add adds a new Controller to mgr with r as the reconcile.Reconciler
func add(mgr manager.Manager, r reconcile.Reconciler) error {
// Create a new controller
c, err := controller.New("blockdeviceclaim-controller", mgr, controller.Options{Reconciler: r})
if err != nil {
return err
}
// Watch for changes to primary resource BlockDeviceClaim
err = c.Watch(&source.Kind{Type: &apis.BlockDeviceClaim{}}, &handler.EnqueueRequestForObject{})
if err != nil {
return err
}
return nil
}
var _ reconcile.Reconciler = &ReconcileBlockDeviceClaim{}
// ReconcileBlockDeviceClaim reconciles a BlockDeviceClaim object
type ReconcileBlockDeviceClaim struct {
// This client, initialized using mgr.Client() above, is a split client
// that reads objects from the cache and writes to the apiserver
client client.Client
scheme *runtime.Scheme
recorder record.EventRecorder
}
// Reconcile reads that state of the cluster for a BlockDeviceClaim object and makes changes based on the state read
// and what is in the BlockDeviceClaim.Spec
// Note:
// 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 *ReconcileBlockDeviceClaim) Reconcile(request reconcile.Request) (reconcile.Result, error) {
// Fetch the BlockDeviceClaim instance
instance := &apis.BlockDeviceClaim{}
err := r.client.Get(context.TODO(), request.NamespacedName, instance)
if err != nil {
if errors.IsNotFound(err) {
// Request object not found, could have been deleted after reconcile request.
// Owned objects are automatically garbage collected. For additional cleanup logic use finalizers.
// Return and don't requeue
return reconcile.Result{}, nil
}
// Error reading the object - requeue the request.
return reconcile.Result{}, err
}
// check if reconciliation is disabled for this resource
if IsReconcileDisabled(instance) {
return reconcile.Result{}, nil
}
switch instance.Status.Phase {
case apis.BlockDeviceClaimStatusPending:
fallthrough
case apis.BlockDeviceClaimStatusEmpty:
klog.Infof("BDC %s claim phase is: %s", instance.Name, instance.Status.Phase)
// claim the BD only if deletion time stamp is not set.
// since BDC can now have multiple finalizers, we should not claim a
// BD if its deletiontime stamp is set.
if instance.DeletionTimestamp.IsZero() {
err := r.claimDeviceForBlockDeviceClaim(instance)
if err != nil {
klog.Errorf("%s failed to claim: %v", instance.Name, err)
return reconcile.Result{}, err
}
}
case apis.BlockDeviceClaimStatusInvalidCapacity:
// migrating state to Pending if in InvalidCapacity state.
// The InvalidCapacityState is deprecated and pending will be used.
// InvalidCapacity will be the reason for why the BDC is in Pending state.
instance.Status.Phase = apis.BlockDeviceClaimStatusPending
err := r.updateClaimStatus(apis.BlockDeviceClaimStatusPending, instance)
if err != nil {
klog.Errorf("error in updating phase to pending from invalid capacity for %s: %v", instance.Name, err)
}
klog.Infof("%s claim phase is: %s", instance.Name, instance.Status.Phase)
case apis.BlockDeviceClaimStatusDone:
err := r.FinalizerHandling(instance)
if err != nil {
klog.Errorf("Finalizer handling failed for %s: %v", instance.Name, err)
return reconcile.Result{}, err
}
}
return reconcile.Result{}, nil
}
// claimDeviceForBlockDeviceClaim is created, try to determine blockdevice which is
// free and has size equal/greater than BlockDeviceClaim request.
func (r *ReconcileBlockDeviceClaim) claimDeviceForBlockDeviceClaim(instance *apis.BlockDeviceClaim) error {
config := blockdevice.NewConfig(&instance.Spec, r.client)
// check for capacity only in auto selection
if !config.ManualSelection {
// perform verification of the claim, like capacity
// Get the capacity requested in the claim
_, err := verify.GetRequestedCapacity(instance.Spec.Resources.Requests)
if err != nil {
r.recorder.Eventf(instance, corev1.EventTypeWarning, "InvalidCapacity", "Invalid Capacity requested")
//Update deviceClaim CR with pending status
instance.Status.Phase = apis.BlockDeviceClaimStatusPending
err1 := r.updateClaimStatus(instance.Status.Phase, instance)
if err1 != nil {
klog.Errorf("%s requested an invalid capacity: %v", instance.Name, err1)
return err1
}
klog.Infof("%s set to Pending due to invalid capacity request", instance.Name)
return err
}
}
// create selector from the label selector given in BDC spec.
selector := generateSelector(*instance)
// get list of block devices.
bdList, err := r.getListofDevices(selector)
if err != nil {
return err
}
selectedDevice, err := config.Filter(bdList)
if err != nil {
klog.Errorf("Error selecting device for %s: %v", instance.Name, err)
r.recorder.Eventf(instance, corev1.EventTypeWarning, "SelectionFailed", err.Error())
instance.Status.Phase = apis.BlockDeviceClaimStatusPending
} else {
instance.Spec.BlockDeviceName = selectedDevice.Name
instance.Status.Phase = apis.BlockDeviceClaimStatusDone
err = r.claimBlockDevice(selectedDevice, instance)
if err != nil {
return err
}
r.recorder.Eventf(selectedDevice, corev1.EventTypeNormal, "BlockDeviceClaimed", "BlockDevice claimed by %v", instance.Name)
r.recorder.Eventf(instance, corev1.EventTypeNormal, "BlockDeviceClaimed", "BlockDevice: %v claimed", instance.Spec.BlockDeviceName)
}
err = r.updateClaimStatus(instance.Status.Phase, instance)
if err != nil {
return err
}
return nil
}
// FinalizerHandling removes the finalizer from the claim resource
func (r *ReconcileBlockDeviceClaim) FinalizerHandling(instance *apis.BlockDeviceClaim) error {
if instance.ObjectMeta.DeletionTimestamp.IsZero() {
return nil
}
// The object is being deleted
// Check if the BDC has only NDM finalizer present. If yes, it means that the BDC
// was deleted by the owner itself, and NDM can proceed with releasing the BD and
// removing the NDM finalizer
if len(instance.ObjectMeta.Finalizers) == 1 &&
util.Contains(instance.ObjectMeta.Finalizers, controllerutil.BlockDeviceClaimFinalizer) {
// Finalizer is set, lets handle external dependency
if err := r.releaseClaimedBlockDevice(instance); err != nil {
klog.Errorf("Error releasing claimed block device %s from %s: %v",
instance.Spec.BlockDeviceName, instance.Name, err)
return err
}
r.recorder.Eventf(instance, corev1.EventTypeNormal, "BlockDeviceReleased", "BlockDevice: %v is released", instance.Spec.BlockDeviceName)
// Remove finalizer from list and update it.
instance.ObjectMeta.Finalizers = util.RemoveString(instance.ObjectMeta.Finalizers, controllerutil.BlockDeviceClaimFinalizer)
if err := r.client.Update(context.TODO(), instance); err != nil {
klog.Errorf("Error removing finalizer from %s", instance.Name)
r.recorder.Eventf(instance, corev1.EventTypeWarning, "UpdateOperationFailed", "Unable to remove Finalizer, due to error: %v", err.Error())
return err
}
}
return nil
}
func (r *ReconcileBlockDeviceClaim) updateClaimStatus(phase apis.DeviceClaimPhase,
instance *apis.BlockDeviceClaim) error {
switch phase {
case apis.BlockDeviceClaimStatusDone:
instance.ObjectMeta.Finalizers = append(instance.ObjectMeta.Finalizers, controllerutil.BlockDeviceClaimFinalizer)
r.recorder.Eventf(instance, corev1.EventTypeNormal, "BlockDeviceClaimBound", "BlockDeviceClaim is bound to %v", instance.Spec.BlockDeviceName)
}
// Update BlockDeviceClaim CR
err := r.client.Update(context.TODO(), instance)
if err != nil {
return fmt.Errorf("error updating status of BDC : %s, %v", instance.ObjectMeta.Name, err)
}
return nil
}
// isDeviceRequestedByThisDeviceClaim checks whether a claimed block device belongs to the given BDC
func (r *ReconcileBlockDeviceClaim) isDeviceRequestedByThisDeviceClaim(
instance *apis.BlockDeviceClaim, item apis.BlockDevice) bool {
if item.Status.ClaimState != apis.BlockDeviceClaimed {
return false
}
if item.Spec.ClaimRef.Name != instance.ObjectMeta.Name {
return false
}
if item.Spec.ClaimRef.UID != instance.ObjectMeta.UID {
return false
}
if item.Spec.ClaimRef.Kind != instance.TypeMeta.Kind {
return false
}
return true
}
// releaseClaimedBlockDevice releases the block device claimed by this BlockDeviceClaim
func (r *ReconcileBlockDeviceClaim) releaseClaimedBlockDevice(
instance *apis.BlockDeviceClaim) error {
klog.Infof("Releasing claimed block device %s from %s", instance.Spec.BlockDeviceName, instance.Name)
//Get BlockDevice list on all nodes
//empty selector is used to select everything.
selector := &v1.LabelSelector{}
bdList, err := r.getListofDevices(selector)
if err != nil {
return err
}
// Check if same deviceclaim holding the ObjRef
var claimedBd *apis.BlockDevice
for _, item := range bdList.Items {
// Found a blockdevice ObjRef with BlockDeviceClaim, Clear
// ObjRef and mark blockdevice released in etcd
if r.isDeviceRequestedByThisDeviceClaim(instance, item) {
claimedBd = &item
break
}
}
dvr := claimedBd.DeepCopy()
dvr.Spec.ClaimRef = nil
dvr.Status.ClaimState = apis.BlockDeviceReleased
err = r.client.Update(context.TODO(), dvr)
if err != nil {
klog.Errorf("Error updating ClaimRef of %s: %v", dvr.Name, err)
return err
}
r.recorder.Eventf(dvr, corev1.EventTypeNormal, "BlockDeviceCleanUpInProgress", "Released from BDC: %v", instance.Name)
return nil
}
// claimBlockDevice is used to claim the passed on blockdevice
func (r *ReconcileBlockDeviceClaim) claimBlockDevice(bd *apis.BlockDevice, instance *apis.BlockDeviceClaim) error {
claimRef, err := reference.GetReference(r.scheme, instance)
if err != nil {
return fmt.Errorf("error getting claim reference for BDC:%s, %v", instance.ObjectMeta.Name, err)
}
// add finalizer to BlockDevice to prevent accidental deletion of BD
bd.Finalizers = append(bd.Finalizers, controllerutil.BlockDeviceFinalizer)
bd.Spec.ClaimRef = claimRef
bd.Status.ClaimState = apis.BlockDeviceClaimed
err = r.client.Update(context.TODO(), bd)
if err != nil {
return fmt.Errorf("error while updating BD:%s, %v", bd.ObjectMeta.Name, err)
}
klog.Infof("%s claimed by %s", bd.Name, instance.Name)
return nil
}
// GetBlockDevice get block device resource from etcd
func (r *ReconcileBlockDeviceClaim) GetBlockDevice(name string) (*apis.BlockDevice, error) {
bd := &apis.BlockDevice{}
err := r.client.Get(context.TODO(),
client.ObjectKey{Namespace: "", Name: name}, bd)
if err != nil {
return nil, err
}
return bd, nil
}
// getListofDevices gets the list of block devices on the node to which BlockDeviceClaim is made
// TODO:
// ListBlockDeviceResource in package cmd/ndm_daemonset/controller has the same functionality.
// Need to merge these 2 functions.
func (r *ReconcileBlockDeviceClaim) getListofDevices(selector *v1.LabelSelector) (*apis.BlockDeviceList, error) {
//Initialize a deviceList object.
listBlockDevice := &apis.BlockDeviceList{
TypeMeta: v1.TypeMeta{
Kind: "BlockDevice",
APIVersion: "openebs.io/v1alpha1",
},
}
opts := &client.ListOptions{}
if sel, err := v1.LabelSelectorAsSelector(selector); err != nil {
// if conversion of selector errors out, the list call will be errored
return nil, err
} else {
opts.LabelSelector = sel
}
//Fetch deviceList with matching criteria
err := r.client.List(context.TODO(), opts, listBlockDevice)
if err != nil {
return nil, err
}
return listBlockDevice, nil
}
// IsReconcileDisabled is used to check if reconciliation is disabled for
// BlockDeviceClaim
func IsReconcileDisabled(bdc *apis.BlockDeviceClaim) bool {
return bdc.Annotations[ndm.OpenEBSReconcile] == "false"
}
// generateSelector creates the label selector for BlockDevices from
// the BlockDeviceClaim spec
func generateSelector(bdc apis.BlockDeviceClaim) *v1.LabelSelector {
var hostName string
// get the hostname
if len(bdc.Spec.HostName) != 0 {
hostName = bdc.Spec.HostName
}
// the hostname in NodeAttribute will override the hostname in spec, since spec.hostName
// will be deprecated shortly
if len(bdc.Spec.BlockDeviceNodeAttributes.HostName) != 0 {
hostName = bdc.Spec.BlockDeviceNodeAttributes.HostName
}
// the hostname label is added into the user given list of labels. If the user hasn't
// given any selector, then the selector object is initialized.
selector := bdc.Spec.Selector.DeepCopy()
if selector == nil {
selector = &v1.LabelSelector{}
}
if selector.MatchLabels == nil {
selector.MatchLabels = make(map[string]string)
}
// if any hostname is provided, add it to selector
if len(hostName) != 0 {
selector.MatchLabels[kubernetes.KubernetesHostNameLabel] = hostName
}
return selector
}