forked from longhorn/longhorn-manager
-
Notifications
You must be signed in to change notification settings - Fork 1
/
backing_image_controller.go
1774 lines (1533 loc) · 65.1 KB
/
backing_image_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
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package controller
import (
"fmt"
"net"
"net/url"
"reflect"
"regexp"
"strconv"
"time"
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/util/wait"
"k8s.io/client-go/tools/cache"
"k8s.io/client-go/tools/record"
"k8s.io/client-go/util/flowcontrol"
"k8s.io/kubernetes/pkg/controller"
corev1 "k8s.io/api/core/v1"
apierrors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
utilruntime "k8s.io/apimachinery/pkg/util/runtime"
clientset "k8s.io/client-go/kubernetes"
typedv1core "k8s.io/client-go/kubernetes/typed/core/v1"
"github.com/longhorn/longhorn-manager/constant"
"github.com/longhorn/longhorn-manager/datastore"
"github.com/longhorn/longhorn-manager/engineapi"
"github.com/longhorn/longhorn-manager/types"
"github.com/longhorn/longhorn-manager/util"
longhorn "github.com/longhorn/longhorn-manager/k8s/pkg/apis/longhorn/v1beta2"
)
type BackingImageController struct {
*baseController
// which namespace controller is running with
namespace string
// use as the OwnerID of the backing image
controllerID string
serviceAccount string
bimImageName string
kubeClient clientset.Interface
eventRecorder record.EventRecorder
ds *datastore.DataStore
cacheSyncs []cache.InformerSynced
v2CopyBackoff *flowcontrol.Backoff
proxyConnCounter util.Counter
}
func NewBackingImageController(
logger logrus.FieldLogger,
ds *datastore.DataStore,
scheme *runtime.Scheme,
kubeClient clientset.Interface,
namespace string, controllerID, serviceAccount, backingImageManagerImage string,
proxyConnCounter util.Counter) (*BackingImageController, error) {
eventBroadcaster := record.NewBroadcaster()
eventBroadcaster.StartLogging(logrus.Infof)
// TODO: remove the wrapper when every clients have moved to use the clientset.
eventBroadcaster.StartRecordingToSink(&typedv1core.EventSinkImpl{Interface: typedv1core.New(kubeClient.CoreV1().RESTClient()).Events("")})
bic := &BackingImageController{
baseController: newBaseController("longhorn-backing-image", logger),
namespace: namespace,
controllerID: controllerID,
serviceAccount: serviceAccount,
bimImageName: backingImageManagerImage,
kubeClient: kubeClient,
eventRecorder: eventBroadcaster.NewRecorder(scheme, corev1.EventSource{Component: "longhorn-backing-image-controller"}),
ds: ds,
v2CopyBackoff: flowcontrol.NewBackOff(time.Minute, time.Minute*5),
proxyConnCounter: proxyConnCounter,
}
var err error
if _, err = ds.BackingImageInformer.AddEventHandler(cache.ResourceEventHandlerFuncs{
AddFunc: bic.enqueueBackingImage,
UpdateFunc: func(old, cur interface{}) { bic.enqueueBackingImage(cur) },
DeleteFunc: bic.enqueueBackingImage,
}); err != nil {
return nil, err
}
bic.cacheSyncs = append(bic.cacheSyncs, ds.BackingImageInformer.HasSynced)
if _, err = ds.BackingImageManagerInformer.AddEventHandlerWithResyncPeriod(cache.ResourceEventHandlerFuncs{
AddFunc: bic.enqueueBackingImageForBackingImageManager,
UpdateFunc: func(old, cur interface{}) { bic.enqueueBackingImageForBackingImageManager(cur) },
DeleteFunc: bic.enqueueBackingImageForBackingImageManager,
}, 0); err != nil {
return nil, err
}
bic.cacheSyncs = append(bic.cacheSyncs, ds.BackingImageManagerInformer.HasSynced)
if _, err = ds.BackingImageDataSourceInformer.AddEventHandlerWithResyncPeriod(cache.ResourceEventHandlerFuncs{
AddFunc: bic.enqueueBackingImageForBackingImageDataSource,
UpdateFunc: func(old, cur interface{}) { bic.enqueueBackingImageForBackingImageDataSource(cur) },
DeleteFunc: bic.enqueueBackingImageForBackingImageDataSource,
}, 0); err != nil {
return nil, err
}
bic.cacheSyncs = append(bic.cacheSyncs, ds.BackingImageDataSourceInformer.HasSynced)
if _, err = ds.ReplicaInformer.AddEventHandlerWithResyncPeriod(cache.ResourceEventHandlerFuncs{
AddFunc: bic.enqueueBackingImageForReplica,
UpdateFunc: func(old, cur interface{}) { bic.enqueueBackingImageForReplica(cur) },
DeleteFunc: bic.enqueueBackingImageForReplica,
}, 0); err != nil {
return nil, err
}
bic.cacheSyncs = append(bic.cacheSyncs, ds.ReplicaInformer.HasSynced)
if _, err = ds.NodeInformer.AddEventHandlerWithResyncPeriod(cache.ResourceEventHandlerFuncs{
UpdateFunc: bic.enqueueBackingImageForNodeUpdate,
}, 0); err != nil {
return nil, err
}
bic.cacheSyncs = append(bic.cacheSyncs, ds.NodeInformer.HasSynced)
if _, err = ds.InstanceManagerInformer.AddEventHandlerWithResyncPeriod(cache.ResourceEventHandlerFuncs{
AddFunc: bic.enqueueBackingImageForInstanceManagerUpdate,
UpdateFunc: func(old, cur interface{}) { bic.enqueueBackingImageForInstanceManagerUpdate(cur) },
DeleteFunc: bic.enqueueBackingImageForInstanceManagerUpdate,
}, 0); err != nil {
return nil, err
}
bic.cacheSyncs = append(bic.cacheSyncs, ds.InstanceManagerInformer.HasSynced)
return bic, nil
}
func (bic *BackingImageController) Run(workers int, stopCh <-chan struct{}) {
defer utilruntime.HandleCrash()
defer bic.queue.ShutDown()
bic.logger.Info("Starting Longhorn Backing Image controller")
defer bic.logger.Info("Shut down Longhorn Backing Image controller")
if !cache.WaitForNamedCacheSync("longhorn backing images", stopCh, bic.cacheSyncs...) {
return
}
for i := 0; i < workers; i++ {
go wait.Until(bic.worker, time.Second, stopCh)
}
<-stopCh
}
func (bic *BackingImageController) worker() {
for bic.processNextWorkItem() {
}
}
func (bic *BackingImageController) processNextWorkItem() bool {
key, quit := bic.queue.Get()
if quit {
return false
}
defer bic.queue.Done(key)
err := bic.syncBackingImage(key.(string))
bic.handleErr(err, key)
return true
}
func (bic *BackingImageController) handleErr(err error, key interface{}) {
if err == nil {
bic.queue.Forget(key)
return
}
log := bic.logger.WithField("BackingImage", key)
if bic.queue.NumRequeues(key) < maxRetries {
handleReconcileErrorLogging(log, err, "Failed to sync Longhorn backing image")
bic.queue.AddRateLimited(key)
return
}
utilruntime.HandleError(err)
handleReconcileErrorLogging(log, err, "Dropping Longhorn backing image out of the queue")
bic.queue.Forget(key)
}
func getLoggerForBackingImage(logger logrus.FieldLogger, bi *longhorn.BackingImage) *logrus.Entry {
return logger.WithFields(
logrus.Fields{
"backingImageName": bi.Name,
},
)
}
func (bic *BackingImageController) syncBackingImage(key string) (err error) {
defer func() {
err = errors.Wrapf(err, "failed to sync backing image for %v", key)
}()
namespace, name, err := cache.SplitMetaNamespaceKey(key)
if err != nil {
return err
}
if namespace != bic.namespace {
return nil
}
backingImage, err := bic.ds.GetBackingImage(name)
if err != nil {
if datastore.ErrorIsNotFound(err) {
return nil
}
return errors.Wrapf(err, "failed to get backing image %v", name)
}
log := getLoggerForBackingImage(bic.logger, backingImage)
if !bic.isResponsibleFor(backingImage) {
return nil
}
if backingImage.Status.OwnerID != bic.controllerID {
backingImage.Status.OwnerID = bic.controllerID
backingImage, err = bic.ds.UpdateBackingImageStatus(backingImage)
if err != nil {
// we don't mind others coming first
if apierrors.IsConflict(errors.Cause(err)) {
return nil
}
return err
}
log.Infof("Backing image got new owner %v", bic.controllerID)
}
// UUID is immutable once it's set.
// Should make sure UUID is not empty before syncing with other resources.
if backingImage.Status.UUID == "" {
backingImage.Status.UUID = util.RandomID()
if backingImage, err = bic.ds.UpdateBackingImageStatus(backingImage); err != nil {
if !apierrors.IsConflict(errors.Cause(err)) {
return err
}
log.WithError(err).Debugf("Requeue %v due to conflict", key)
bic.enqueueBackingImage(backingImage)
return nil
}
bic.eventRecorder.Eventf(backingImage, corev1.EventTypeNormal, constant.EventReasonUpdate, "Initialized UUID to %v", backingImage.Status.UUID)
}
existingBackingImage := backingImage.DeepCopy()
defer func() {
if err != nil {
return
}
if !reflect.DeepEqual(existingBackingImage.Spec, backingImage.Spec) {
if _, err := bic.ds.UpdateBackingImage(backingImage); err != nil && apierrors.IsConflict(errors.Cause(err)) {
log.WithError(err).Debugf("Requeue %v due to conflict", key)
bic.enqueueBackingImage(backingImage)
}
}
if reflect.DeepEqual(existingBackingImage.Status, backingImage.Status) {
return
}
if _, err := bic.ds.UpdateBackingImageStatus(backingImage); err != nil && apierrors.IsConflict(errors.Cause(err)) {
log.WithError(err).Debugf("Requeue %v due to conflict", key)
bic.enqueueBackingImage(backingImage)
}
}()
if backingImage.DeletionTimestamp != nil {
replicas, err := bic.ds.ListReplicasByBackingImage(backingImage.Name)
if err != nil {
return err
}
if len(replicas) != 0 {
log.Warn("Waiting for all replicas stopping using this backing image before removing the finalizer")
return nil
}
if _, err := bic.IsBackingImageDataSourceCleaned(backingImage); err != nil {
log.WithError(err).Warn("Waiting until backing image data source is cleaned before removing the finalizer")
return nil
}
log.Info("Cleaning up the record for backing image managers and remove the finalizer")
if err := bic.cleanupBackingImageManagers(backingImage); err != nil {
return err
}
// delete all the v2 backing image in the instance-manager
if types.IsDataEngineV2(backingImage.Spec.DataEngine) {
cleaned, err := bic.cleanupAllV2BackingImageCopies(backingImage)
if err != nil {
return err
}
if !cleaned {
log.Warn("Waiting until all v2 backing image copies are cleaned up before removing the finalizer")
return nil
}
}
return bic.ds.RemoveFinalizerForBackingImage(backingImage)
}
if backingImage.Status.DiskFileStatusMap == nil {
backingImage.Status.DiskFileStatusMap = map[string]*longhorn.BackingImageDiskFileStatus{}
}
if backingImage.Status.DiskLastRefAtMap == nil {
backingImage.Status.DiskLastRefAtMap = map[string]string{}
}
if err := bic.handleBackingImageDataSource(backingImage); err != nil {
return err
}
// We cannot continue without `Spec.DiskFileSpecMap`. The backing image data source controller can update it.
if backingImage.Spec.DiskFileSpecMap == nil {
return nil
}
if err := bic.handleBackingImageManagers(backingImage); err != nil {
return err
}
if err := bic.syncBackingImageFileInfo(backingImage); err != nil {
return err
}
if err := bic.updateDiskLastReferenceMap(backingImage); err != nil {
return err
}
if err := bic.replenishBackingImageCopies(backingImage); err != nil {
return err
}
bic.cleanupEvictionRequestedBackingImageCopies(backingImage)
if types.IsDataEngineV2(backingImage.Spec.DataEngine) {
return bic.handleV2BackingImage(backingImage)
}
return nil
}
func (bic *BackingImageController) handleV2BackingImage(bi *longhorn.BackingImage) (err error) {
if err := bic.prepareFirstV2Copy(bi); err != nil {
return errors.Wrapf(err, "failed to prepare the first v2 backing image")
}
if err := bic.syncV2StatusWithInstanceManager(bi); err != nil {
return errors.Wrapf(err, "failed to sync v2 backing image status from instance manager")
}
if err := bic.deleteInvalidV2Copy(bi); err != nil {
return errors.Wrapf(err, "failed to delete invalid v2 backing image")
}
if err := bic.prepareV2Copy(bi); err != nil {
return errors.Wrapf(err, "failed to prepare v2 backing image")
}
return nil
}
func (bic *BackingImageController) isFirstV2CopyInState(bi *longhorn.BackingImage, state longhorn.BackingImageState) bool {
if bi.Status.V2FirstCopyDisk != "" && bi.Status.V2FirstCopyStatus == state {
return true
}
if bi.Status.V2FirstCopyDisk != "" {
if status, exists := bi.Status.DiskFileStatusMap[bi.Status.V2FirstCopyDisk]; exists && status.State == state {
return true
}
}
return false
}
func (bic *BackingImageController) cleanupFirstFailedV2Copy(bi *longhorn.BackingImage) (err error) {
if bi.Status.V2FirstCopyDisk == "" {
return nil
}
log := getLoggerForBackingImage(bic.logger, bi)
node, _, err := bic.ds.GetReadyDiskNodeRO(bi.Status.V2FirstCopyDisk)
if err != nil {
return errors.Wrapf(err, "failed to get the ready disk node for disk %v", bi.Status.V2FirstCopyDisk)
}
engineClientProxy, err := bic.getEngineClientProxy(node.Name, longhorn.DataEngineTypeV2, log)
if err != nil {
return errors.Wrapf(err, "failed to get the engine client proxy for node %v", node.Name)
}
defer engineClientProxy.Close()
// clean up the failed first v2 copy
err = engineClientProxy.SPDKBackingImageDelete(bi.Name, bi.Status.V2FirstCopyDisk)
if err != nil {
return errors.Wrapf(err, "failed to delete the failed v2 copy on the disk %v", bi.Status.V2FirstCopyDisk)
}
delete(bi.Spec.DiskFileSpecMap, bi.Status.V2FirstCopyDisk)
delete(bi.Status.DiskFileStatusMap, bi.Status.V2FirstCopyDisk)
bi.Status.V2FirstCopyDisk = ""
bi.Status.V2FirstCopyStatus = longhorn.BackingImageStatePending
return nil
}
func (bic *BackingImageController) deleteAllV1FileCopies(bi *longhorn.BackingImage) {
for diskUUID, fileSpec := range bi.Spec.DiskFileSpecMap {
if types.IsDataEngineV1(fileSpec.DataEngine) {
delete(bi.Spec.DiskFileSpecMap, diskUUID)
}
}
}
func (bic *BackingImageController) prepareFirstV2Copy(bi *longhorn.BackingImage) (err error) {
log := getLoggerForBackingImage(bic.logger, bi)
// The preparation state transition: Pending -> InProgress -> Ready/Failed
// we retry when failed by deleting the failed copy and cleanup the state.
// If the first v2 copy is ready, we can delete all the v1 file copies and return.
isPrepared := bic.isFirstV2CopyInState(bi, longhorn.BackingImageStateReady)
if isPrepared {
bi.Status.V2FirstCopyStatus = longhorn.BackingImageStateReady
bic.deleteAllV1FileCopies(bi)
bic.v2CopyBackoff.DeleteEntry(bi.Status.V2FirstCopyDisk)
return nil
}
// If the first v2 copy is failed, we cleanup the failed copy and retry the preparation.
// If the first v2 copy is in unknown, that means the instance manager may crahsh when creating the first v2 copy.
// We cleanup the unknown copy and retry the preparation.
isFailedToPrepare := bic.isFirstV2CopyInState(bi, longhorn.BackingImageStateFailed)
isUnknown := bic.isFirstV2CopyInState(bi, longhorn.BackingImageStateUnknown)
if isFailedToPrepare || isUnknown {
bi.Status.V2FirstCopyStatus = longhorn.BackingImageStateFailed
return bic.cleanupFirstFailedV2Copy(bi)
}
// If the first v2 copy is in progress, we wait for the next reconciliation
isInProgress := bic.isFirstV2CopyInState(bi, longhorn.BackingImageStateInProgress)
if isInProgress {
bi.Status.V2FirstCopyStatus = longhorn.BackingImageStateInProgress
bi.Spec.DiskFileSpecMap[bi.Status.V2FirstCopyDisk] = &longhorn.BackingImageDiskFileSpec{DataEngine: longhorn.DataEngineTypeV2}
return nil
}
// Wait for the first v1 file to be ready.
bids, err := bic.ds.GetBackingImageDataSource(bi.Name)
if err != nil {
if apierrors.IsNotFound(err) {
log.Warn("Backing image data source not found when preparing first v2 copy, reconcile later")
return nil
}
return errors.Wrap(err, "failed to get the backing image data source when preparing first v2 copy")
}
if !bids.Spec.FileTransferred {
log.Info("Backing image data source has not prepared the first v1 file, reconcile later")
return nil
}
firstV1FileDiskUUID := bids.Spec.DiskUUID
if status, exists := bi.Status.DiskFileStatusMap[firstV1FileDiskUUID]; exists && status.State != longhorn.BackingImageStateReady {
log.Infof("The first v1 file copy is not ready, reconcile later")
return nil
}
firstV2CopyNode, firstV2CopyDiskName, err := bic.findReadyNodeAndDiskForFirstV2Copy(bi, firstV1FileDiskUUID, log)
if err != nil {
return errors.Wrap(err, "failed to find a ready disk for the first v2 backing image copy")
}
firstV2CopyNodeName := firstV2CopyNode.Name
firstV2CopyDiskUUID := firstV2CopyNode.Status.DiskStatus[firstV2CopyDiskName].DiskUUID
log.Infof("Found the ready node %v disk %v for the first v2 backing image copy", firstV2CopyNodeName, firstV2CopyDiskUUID)
if bic.v2CopyBackoff.IsInBackOffSinceUpdate(firstV2CopyDiskUUID, time.Now()) {
log.Debugf("Skip preparing first v2 backing image copy to disk %v since it is still in the backoff window", firstV2CopyDiskUUID)
return nil
}
// Get proxy client for creating v2 backing image copy
engineClientProxy, err := bic.getEngineClientProxy(firstV2CopyNodeName, longhorn.DataEngineTypeV2, log)
if err != nil {
return errors.Wrapf(err, "failed to get the engine client proxy for node %v", firstV2CopyNodeName)
}
defer engineClientProxy.Close()
// Create v2 backing image copy by downloading the data from first file copy
fileDownloadAddress, err := bic.getFileDownloadAddress(bi, firstV1FileDiskUUID)
if err != nil {
return errors.Wrap(err, "failed to get the v1 file download address when preparing first v2 copy")
}
_, err = engineClientProxy.SPDKBackingImageCreate(bi.Name, bi.Status.UUID, firstV2CopyDiskUUID, bi.Status.Checksum, fileDownloadAddress, "", uint64(bi.Status.Size))
if err != nil {
if types.ErrorAlreadyExists(err) {
log.Infof("backing image already exists when preparing first v2 copy on disk %v", firstV2CopyDiskUUID)
}
bic.v2CopyBackoff.Next(firstV2CopyDiskUUID, time.Now())
return errors.Wrapf(err, "failed to create backing image on disk %v when preparing first v2 copy for backing image %v", firstV2CopyDiskUUID, bi.Name)
}
bi.Status.V2FirstCopyDisk = firstV2CopyDiskUUID
bi.Status.V2FirstCopyStatus = longhorn.BackingImageStateInProgress
bic.v2CopyBackoff.Next(firstV2CopyDiskUUID, time.Now())
return nil
}
func (bic *BackingImageController) getFileDownloadAddress(bi *longhorn.BackingImage, diskUUID string) (string, error) {
bimName := types.GetBackingImageManagerName(bic.bimImageName, diskUUID)
bim, err := bic.ds.GetBackingImageManager(bimName)
if err != nil {
return "", err
}
bimCli, err := engineapi.NewBackingImageManagerClient(bim)
if err != nil {
return "", err
}
// get the file download address of sync server in the backing image manager
filePath, addr, err := bimCli.PrepareDownload(bi.Name, bi.Status.UUID)
if err != nil {
return "", err
}
fileDownloadAddress := fmt.Sprintf("http://%s/v1/files/%s/download", addr, url.PathEscape(filePath))
return fileDownloadAddress, nil
}
func (bic *BackingImageController) deleteInvalidV2Copy(bi *longhorn.BackingImage) (err error) {
log := getLoggerForBackingImage(bic.logger, bi)
if bi.Status.V2FirstCopyStatus != longhorn.BackingImageStateReady {
return nil
}
v2CopiesUnknown := []string{}
v2CopiesFailed := []string{}
missingSpecV2Copies := []string{}
hasReadyV2BackingImage := false
for v2DiskUUID, copyStatus := range bi.Status.DiskFileStatusMap {
// only handle v2 copy in this function
if types.IsDataEngineV1(copyStatus.DataEngine) {
continue
}
// Delete the v2 copy if the spec record is removed
if _, exists := bi.Spec.DiskFileSpecMap[v2DiskUUID]; !exists {
missingSpecV2Copies = append(missingSpecV2Copies, v2DiskUUID)
continue
}
if copyStatus.State == longhorn.BackingImageStateReady {
hasReadyV2BackingImage = true
continue
}
if copyStatus.State == longhorn.BackingImageStateFailed {
v2CopiesFailed = append(v2CopiesFailed, v2DiskUUID)
continue
}
if copyStatus.State == longhorn.BackingImageStateUnknown {
v2CopiesUnknown = append(v2CopiesUnknown, v2DiskUUID)
continue
}
}
if err := bic.cleanupMissingSpecV2Copies(bi, missingSpecV2Copies, log); err != nil {
return errors.Wrap(err, "failed to delete the missing spec v2 copies")
}
if err := bic.cleanupUnknownV2Copies(bi, v2CopiesUnknown, hasReadyV2BackingImage, log); err != nil {
return errors.Wrap(err, "failed to delete the unknown v2 copies")
}
if err := bic.cleanupFailedV2Copies(bi, v2CopiesFailed, hasReadyV2BackingImage, log); err != nil {
return errors.Wrap(err, "failed to delete the failed v2 copies")
}
return nil
}
func (bic *BackingImageController) cleanupAllV2BackingImageCopies(bi *longhorn.BackingImage) (cleaned bool, err error) {
log := getLoggerForBackingImage(bic.logger, bi)
if err := bic.syncV2StatusWithInstanceManager(bi); err != nil {
return false, errors.Wrapf(err, "failed to sync v2 backing image status from instance manager")
}
// we can delete the backing image when all the v2 copies are deleted
if len(bi.Status.DiskFileStatusMap) == 0 {
return true, nil
}
allV2CopiesCleaned := true
for diskUUID := range bi.Status.DiskFileStatusMap {
// The v1 backing image file will be cleaned up in cleanupBackingImageManagers
if fileSpec, exists := bi.Spec.DiskFileSpecMap[diskUUID]; exists && !types.IsDataEngineV2(fileSpec.DataEngine) {
continue
}
allV2CopiesCleaned = false
node, _, err := bic.ds.GetReadyDiskNodeRO(diskUUID)
if err != nil {
return false, errors.Wrapf(err, "failed to get the ready disk node for disk %v", diskUUID)
}
log.Infof("Deleting the v2 copy on node %v disk %v for backing image %v", node.Name, diskUUID, bi.Name)
if err := bic.deleteV2Copy(bi, diskUUID, node, log); err != nil {
return false, errors.Wrapf(err, "failed to delete the v2 copy on disk %v", diskUUID)
}
delete(bi.Status.DiskFileStatusMap, diskUUID)
bic.eventRecorder.Eventf(bi, corev1.EventTypeNormal, constant.EventReasonDelete, "Deleted v2 backing image %v on disk %v on node %v", bi.Name, diskUUID, node.Name)
}
// only return true when there is no v2 disk file status after syncing the status from instance manager
return allV2CopiesCleaned, nil
}
func (bic *BackingImageController) prepareV2Copy(bi *longhorn.BackingImage) (err error) {
log := getLoggerForBackingImage(bic.logger, bi)
if bi.Status.V2FirstCopyStatus != longhorn.BackingImageStateReady {
return nil
}
readyV2CopyDiskUUIDs := []string{}
requireV2CopyDiskUUIDs := []string{}
for v2DiskUUID := range bi.Spec.DiskFileSpecMap {
biStatus, exists := bi.Status.DiskFileStatusMap[v2DiskUUID]
if exists {
if biStatus.State == longhorn.BackingImageStateReady {
readyV2CopyDiskUUIDs = append(readyV2CopyDiskUUIDs, v2DiskUUID)
}
if backingImageInProgress(biStatus.State) {
log.Info("There is one v2 backing image copy in progress, prepare the backing image one at a time")
return nil
}
} else {
requireV2CopyDiskUUIDs = append(requireV2CopyDiskUUIDs, v2DiskUUID)
}
}
if len(readyV2CopyDiskUUIDs) == 0 {
log.Infof("Only sync the backing image to other disks when there is one ready v2 backing image copy")
return nil
}
sourceV2DiskUUID := readyV2CopyDiskUUIDs[0]
// Only sync one backing image copy at a time, so we can control the concurrent limit of syncing for the backing image manager.
for _, v2DiskUUID := range requireV2CopyDiskUUIDs {
if bic.v2CopyBackoff.IsInBackOffSinceUpdate(v2DiskUUID, time.Now()) {
log.Debugf("Skip syncing backing image copy to disk %v immediately since it is still in the backoff window", v2DiskUUID)
continue
}
node, _, err := bic.ds.GetReadyDiskNodeRO(v2DiskUUID)
if err != nil {
bic.v2CopyBackoff.Next(v2DiskUUID, time.Now())
return errors.Wrapf(err, "failed to get the ready disk node for disk %v", v2DiskUUID)
}
if err := bic.syncV2Copies(bi, sourceV2DiskUUID, v2DiskUUID, node, log); err != nil {
return errors.Wrapf(err, "failed to sync the backing image to disk %v", v2DiskUUID)
}
// To prevent it from requesting the same disk again, the status will be updated later based on the status from the instance manager
bi.Status.DiskFileStatusMap[v2DiskUUID] = &longhorn.BackingImageDiskFileStatus{
State: longhorn.BackingImageStateInProgress,
}
bic.v2CopyBackoff.Next(v2DiskUUID, time.Now())
bic.eventRecorder.Eventf(bi, corev1.EventTypeNormal, constant.EventReasonCreate, "Created v2 backing image %v on disk %v on node %v", bi.Name, v2DiskUUID, node.Name)
return nil
}
return nil
}
// ExtractBackingImageAndDiskUUID extracts the BackingImageName and DiskUUID from the string pattern "bi-${BackingImageName}-disk-${DiskUUID}"
func extractBackingImageAndDiskUUID(biNameDiskUUID string) (string, string, error) {
// Define the regular expression pattern
// This captures the BackingImageName and DiskUUID while allowing for hyphens in both.
re := regexp.MustCompile(`^bi-([a-zA-Z0-9-]+)-disk-([a-zA-Z0-9-]+)$`)
// Try to find a match
matches := re.FindStringSubmatch(biNameDiskUUID)
if matches == nil {
return "", "", fmt.Errorf("biNameDiskUUID does not match the expected pattern")
}
// Extract BackingImageName and DiskUUID from the matches
backingImageName := matches[1]
diskUUID := matches[2]
return backingImageName, diskUUID, nil
}
func (bic *BackingImageController) syncV2StatusWithInstanceManager(bi *longhorn.BackingImage) error {
ims, err := bic.ds.ListInstanceManagersRO()
if err != nil {
return err
}
updatedCopyDiskUUIDs := map[string]bool{}
for _, im := range ims {
if !types.IsDataEngineV2(im.Spec.DataEngine) {
continue
}
if im.DeletionTimestamp != nil {
continue
}
// If the instance manager is not in ready state
// update the v2 copy in that instance manager to unknown.
if im.Status.CurrentState != longhorn.InstanceManagerStateRunning {
continue
}
for biNameDiskUUID, statusInfo := range im.Status.BackingImages {
biName, diskUUID, err := extractBackingImageAndDiskUUID(biNameDiskUUID)
if err != nil {
logrus.WithError(err).Warnf("failed to parse the backing image name and disk uuid from %v", biNameDiskUUID)
continue
}
if biName != bi.Name {
continue
}
if statusInfo.UUID != bi.Status.UUID {
continue
}
if err := bic.updateStatusWithFileInfo(bi,
diskUUID, statusInfo.Message, statusInfo.CurrentChecksum, statusInfo.State, statusInfo.Progress, longhorn.DataEngineTypeV2); err != nil {
return err
}
if statusInfo.Size > 0 {
if bi.Status.Size == 0 {
bi.Status.Size = statusInfo.Size
bic.eventRecorder.Eventf(bi, corev1.EventTypeNormal, constant.EventReasonUpdate, "Set size to %v", bi.Status.Size)
}
if bi.Status.Size != statusInfo.Size {
if bi.Status.DiskFileStatusMap[diskUUID].State != longhorn.BackingImageStateFailed {
msg := fmt.Sprintf("found mismatching size %v reported by instance manager %v in disk %v, the size recorded in status is %v",
statusInfo.Size, im.Name, diskUUID, bi.Status.Size)
bic.eventRecorder.Eventf(bi, corev1.EventTypeWarning, constant.EventReasonUpdate, msg)
bi.Status.DiskFileStatusMap[diskUUID].State = longhorn.BackingImageStateFailed
bi.Status.DiskFileStatusMap[diskUUID].Message = msg
}
}
}
updatedCopyDiskUUIDs[diskUUID] = true
}
}
for diskUUID, copyStatus := range bi.Status.DiskFileStatusMap {
// only handle v2 copies
if fileSpec, exists := bi.Spec.DiskFileSpecMap[diskUUID]; exists && !types.IsDataEngineV2(fileSpec.DataEngine) {
continue
}
if copyStatus.State == longhorn.BackingImageStateReady {
bic.v2CopyBackoff.DeleteEntry(diskUUID)
}
// Update the status to unknown if the instance manager is unknown or the status is not found from the instance manager
if _, exists := updatedCopyDiskUUIDs[diskUUID]; !exists {
bi.Status.DiskFileStatusMap[diskUUID].State = longhorn.BackingImageStateUnknown
bi.Status.DiskFileStatusMap[diskUUID].Message = "The copy status is unknown because the status is not found from the instance manager"
}
}
return nil
}
func (bic *BackingImageController) replenishBackingImageCopies(bi *longhorn.BackingImage) (err error) {
biDataEngine := bi.Spec.DataEngine
bids, err := bic.ds.GetBackingImageDataSource(bi.Name)
if err != nil {
if apierrors.IsNotFound(err) {
return nil
}
return errors.Wrap(err, "failed to get the backing image data source")
}
// Only maintain the minNumberOfReplicas after BackingImage is transferred to BackingImageManager
if !bids.Spec.FileTransferred {
return nil
}
// Only maintain the minNumberOfReplicas after v2 BackingImage is prepared
if types.IsDataEngineV2(bi.Spec.DataEngine) {
if bi.Status.V2FirstCopyDisk == "" || bi.Status.V2FirstCopyStatus != longhorn.BackingImageStateReady {
return nil
}
}
concurrentReplenishLimit, err := bic.ds.GetSettingAsInt(types.SettingNameConcurrentBackingImageCopyReplenishPerNodeLimit)
if err != nil {
return err
}
// If disabled backing image replenishing, skip all the replenish except first copy.
if concurrentReplenishLimit == 0 {
return nil
}
nonFailedCopies := 0
for diskUUID := range bi.Spec.DiskFileSpecMap {
fileStatus, exists := bi.Status.DiskFileStatusMap[diskUUID]
if !exists || (fileStatus.State != longhorn.BackingImageStateFailed &&
fileStatus.State != longhorn.BackingImageStateFailedAndCleanUp &&
fileStatus.State != longhorn.BackingImageStateUnknown) {
// Non-existing file in status could due to not being synced from backing image manager yet.
// Consider it as newly created copy and count it as non-failed copies.
// So we don't create extra copy when handling copies evictions.
nonFailedCopies += 1
}
}
// Need to count the evicted copies in the nonFailedCopies then handle it in handleBackingImageCopiesEvictions
// so we can distinguish the case of "0 healthy copy" and "there is 1 copy but being evicted".
if nonFailedCopies == 0 {
return nil
} else {
nonEvictingCount := nonFailedCopies
for _, fileSpec := range bi.Spec.DiskFileSpecMap {
if fileSpec.EvictionRequested {
nonEvictingCount--
}
}
if nonEvictingCount < bi.Spec.MinNumberOfCopies {
readyNode, readyDiskName, err := bic.ds.GetReadyNodeDiskForBackingImage(bi, biDataEngine, nil)
logrus.Infof("replicate the copy to node: %v, disk: %v", readyNode, readyDiskName)
if err != nil {
logrus.WithError(err).Warnf("failed to create the backing image copy")
return nil
}
// BackingImageManager will then sync the BackingImage to the disk
bi.Spec.DiskFileSpecMap[readyNode.Status.DiskStatus[readyDiskName].DiskUUID] = &longhorn.BackingImageDiskFileSpec{
DataEngine: biDataEngine,
}
}
}
return nil
}
func (bic *BackingImageController) cleanupEvictionRequestedBackingImageCopies(bi *longhorn.BackingImage) {
log := getLoggerForBackingImage(bic.logger, bi)
// If there is no non-evicting healthy backing image copy,
// Longhorn should retain one evicting healthy backing image copy for replenishing.
hasNonEvictingHealthyBackingImageCopy := false
evictingHealthyBackingImageCopyDiskUUID := ""
for diskUUID, fileSpec := range bi.Spec.DiskFileSpecMap {
fileStatus := bi.Status.DiskFileStatusMap[diskUUID]
if fileStatus == nil { // it is newly added, consider it as non healthy
continue
} else {
if fileStatus.State != longhorn.BackingImageStateReady {
continue
}
}
if !fileSpec.EvictionRequested {
hasNonEvictingHealthyBackingImageCopy = true
break
}
evictingHealthyBackingImageCopyDiskUUID = diskUUID
}
for diskUUID, fileSpec := range bi.Spec.DiskFileSpecMap {
if !fileSpec.EvictionRequested {
continue
}
if !hasNonEvictingHealthyBackingImageCopy && diskUUID == evictingHealthyBackingImageCopyDiskUUID {
msg := fmt.Sprintf("Failed to evict backing image copy on disk %v for now since there is no other healthy backing image copy", diskUUID)
log.Warn(msg)
bic.eventRecorder.Event(bi, corev1.EventTypeNormal, constant.EventReasonFailedDeleting, msg)
continue
}
// Backing image controller update the spec here because
// only this controller can gather all the information of all the copies of this backing image at once.
// By deleting the disk from the spec, backing image manager controller will delete the copy on that disk.
// TODO: introduce a new CRD for the backing image copy so we can delete the copy like volume controller deletes replicas.
delete(bi.Spec.DiskFileSpecMap, diskUUID)
log.Infof("Evicted backing image copy on disk %v", diskUUID)
}
}
func (bic *BackingImageController) IsBackingImageDataSourceCleaned(bi *longhorn.BackingImage) (cleaned bool, err error) {
bids, err := bic.ds.GetBackingImageDataSource(bi.Name)
if err != nil {
if apierrors.IsNotFound(err) {
return true, nil
}
return false, errors.Wrap(err, "failed to get the backing image data source")
}
if bids.Spec.FileTransferred {
return true, nil
}
if bids.Status.CurrentState == longhorn.BackingImageStateFailedAndCleanUp {
return true, nil
}
return false, fmt.Errorf("backing image data source status is %v not %v", bids.Status.CurrentState, longhorn.BackingImageStateFailedAndCleanUp)
}
func (bic *BackingImageController) cleanupBackingImageManagers(bi *longhorn.BackingImage) (err error) {
log := getLoggerForBackingImage(bic.logger, bi)
bimMap, err := bic.ds.ListBackingImageManagers()
if err != nil {
return err
}
for _, bim := range bimMap {
if bim.DeletionTimestamp != nil {
continue
}
bimLog := log.WithField("backingImageManager", bim.Name)
// Directly clean up old backing image managers (including incompatible managers).
// New backing image managers can detect and reuse the existing backing image files if necessary.
if bim.Spec.Image != bic.bimImageName {
bimLog.Info("Deleting old/non-default backing image manager")
if err := bic.ds.DeleteBackingImageManager(bim.Name); err != nil && !apierrors.IsNotFound(err) {
return err
}
bic.eventRecorder.Eventf(bi, corev1.EventTypeNormal, constant.EventReasonDelete, "deleted old/non-default backing image manager %v in disk %v on node %v", bim.Name, bim.Spec.DiskUUID, bim.Spec.NodeID)
continue
}
// This sync loop cares about the backing image managers related to the current backing image only.
if _, isRelatedToCurrentBI := bim.Spec.BackingImages[bi.Name]; !isRelatedToCurrentBI {
continue
}
// The entry in the backing image manager matches the current backing image.
if _, isStillRequiredByCurrentBI := bi.Spec.DiskFileSpecMap[bim.Spec.DiskUUID]; isStillRequiredByCurrentBI && bi.DeletionTimestamp == nil {
if bim.Spec.BackingImages[bi.Name] == bi.Status.UUID {
continue
}
}
// The current backing image doesn't require this manager any longer, or the entry in backing image manager doesn't match the backing image uuid.
delete(bim.Spec.BackingImages, bi.Name)
if bim, err = bic.ds.UpdateBackingImageManager(bim); err != nil {
return err
}
if len(bim.Spec.BackingImages) == 0 {
if err := bic.ds.DeleteBackingImageManager(bim.Name); err != nil && !apierrors.IsNotFound(err) {
return err
}
bic.eventRecorder.Eventf(bi, corev1.EventTypeNormal, constant.EventReasonDelete, "deleting unused backing image manager %v in disk %v on node %v", bim.Name, bim.Spec.DiskUUID, bim.Spec.NodeID)
continue
}
}
return nil
}
func (bic *BackingImageController) handleBackingImageDataSource(bi *longhorn.BackingImage) (err error) {
log := getLoggerForBackingImage(bic.logger, bi)
bids, err := bic.ds.GetBackingImageDataSource(bi.Name)
if err != nil && !apierrors.IsNotFound(err) {
return err
}
if bids == nil {
log.Info("Creating backing image data source")
var readyDiskUUID, readyDiskPath, readyNodeID string
isReadyFile := false
foundReadyDisk := false
if bi.Spec.DiskFileSpecMap != nil {
for diskUUID := range bi.Spec.DiskFileSpecMap {
node, diskName, err := bic.ds.GetReadyDiskNode(diskUUID)
if err != nil {
if !types.ErrorIsNotFound(err) {
return err
}
continue
}
foundReadyDisk = true