forked from openshift/machine-config-operator
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpinned_image_set.go
1615 lines (1395 loc) · 44.2 KB
/
pinned_image_set.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 daemon
import (
"bytes"
"context"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"os"
"os/exec"
"reflect"
"sort"
"strings"
"sync"
"syscall"
"time"
"github.com/BurntSushi/toml"
"github.com/containers/image/v5/docker/reference"
"github.com/containers/image/v5/pkg/sysregistriesv2"
"github.com/containers/image/v5/types"
ign3types "github.com/coreos/ignition/v2/config/v3_4/types"
"github.com/golang/groupcache/lru"
ocispec "github.com/opencontainers/image-spec/specs-go/v1"
corev1 "k8s.io/api/core/v1"
apierrors "k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/api/resource"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
utilruntime "k8s.io/apimachinery/pkg/util/runtime"
"k8s.io/apimachinery/pkg/util/wait"
coreinformersv1 "k8s.io/client-go/informers/core/v1"
corev1lister "k8s.io/client-go/listers/core/v1"
"k8s.io/client-go/tools/cache"
"k8s.io/client-go/util/workqueue"
runtimeapi "k8s.io/cri-api/pkg/apis/runtime/v1"
"k8s.io/klog/v2"
"k8s.io/utils/ptr"
mcfgv1 "github.com/openshift/api/machineconfiguration/v1"
mcfgv1alpha1 "github.com/openshift/api/machineconfiguration/v1alpha1"
machineconfigurationalphav1 "github.com/openshift/client-go/machineconfiguration/applyconfigurations/machineconfiguration/v1alpha1"
mcfgclientset "github.com/openshift/client-go/machineconfiguration/clientset/versioned"
mcfginformersv1 "github.com/openshift/client-go/machineconfiguration/informers/externalversions/machineconfiguration/v1"
mcfginformersv1alpha1 "github.com/openshift/client-go/machineconfiguration/informers/externalversions/machineconfiguration/v1alpha1"
mcfglistersv1 "github.com/openshift/client-go/machineconfiguration/listers/machineconfiguration/v1"
mcfglistersv1alpha1 "github.com/openshift/client-go/machineconfiguration/listers/machineconfiguration/v1alpha1"
"github.com/openshift/library-go/pkg/operator/configobserver/featuregates"
ctrlcommon "github.com/openshift/machine-config-operator/pkg/controller/common"
"github.com/openshift/machine-config-operator/pkg/daemon/constants"
"github.com/openshift/machine-config-operator/pkg/daemon/cri"
"github.com/openshift/machine-config-operator/pkg/helpers"
"github.com/openshift/machine-config-operator/pkg/upgrademonitor"
)
const (
// cri gRPC connection parameters taken from kubelet
criPrefetchInterval = 30 * time.Second
defaultPrefetchWorkers = 5
defaultControlPlaneWorkers = 1
defaultPrefetchThrottleDuration = 1 * time.Second
crioPinnedImagesDropInFilePath = "/etc/crio/crio.conf.d/50-pinned-images"
// backoff configuration
maxRetries = 5
retryDuration = 1 * time.Second
retryFactor = 2.0
retryCap = 10 * time.Second
// controller configuration
maxRetriesController = 15
// mcn looks for conditions with this prefix if seen will degrade the pool
degradeMessagePrefix = "Error:"
)
var (
errInsufficientStorage = errors.New("storage available is less than minimum required")
errFailedToPullImage = errors.New("failed to pull image")
errNotFound = errors.New("not found")
errRequeueAfterTimeout = errors.New("requeue: prefetching images incomplete after timeout")
)
// PinnedImageSetManager manages the prefetching of images.
type PinnedImageSetManager struct {
// nodeName is the name of the node.
nodeName string
imageSetLister mcfglistersv1alpha1.PinnedImageSetLister
imageSetSynced cache.InformerSynced
nodeLister corev1lister.NodeLister
nodeListerSynced cache.InformerSynced
mcpLister mcfglistersv1.MachineConfigPoolLister
mcpSynced cache.InformerSynced
mcfgClient mcfgclientset.Interface
prefetchCh chan prefetch
criClient *cri.Client
// minimum storage available after prefetching
minStorageAvailableBytes resource.Quantity
// path to the authfile
authFilePath string
// path to the registry config file
registryCfgPath string
// endpoint of the container runtime service
runtimeEndpoint string
// timeout for the prefetch operation
prefetchTimeout time.Duration
// backoff configuration for retries.
backoff wait.Backoff
// cache for reusable image information
cache *imageCache
syncHandler func(string) error
enqueueMachineConfigPool func(*mcfgv1.MachineConfigPool)
queue workqueue.TypedRateLimitingInterface[string]
featureGatesAccessor featuregates.FeatureGateAccess
// mutex protects cancelFn
mu sync.Mutex
cancelFn context.CancelFunc
once sync.Once
bootstrapped bool
}
// NewPinnedImageSetManager creates a new pinned image set manager.
func NewPinnedImageSetManager(
nodeName string,
criClient *cri.Client,
mcfgClient mcfgclientset.Interface,
imageSetInformer mcfginformersv1alpha1.PinnedImageSetInformer,
nodeInformer coreinformersv1.NodeInformer,
mcpInformer mcfginformersv1.MachineConfigPoolInformer,
minStorageAvailableBytes resource.Quantity,
runtimeEndpoint,
authFilePath,
registryCfgPath string,
prefetchTimeout time.Duration,
featureGatesAccessor featuregates.FeatureGateAccess,
) *PinnedImageSetManager {
p := &PinnedImageSetManager{
nodeName: nodeName,
mcfgClient: mcfgClient,
runtimeEndpoint: runtimeEndpoint,
authFilePath: authFilePath,
registryCfgPath: registryCfgPath,
prefetchTimeout: prefetchTimeout,
minStorageAvailableBytes: minStorageAvailableBytes,
featureGatesAccessor: featureGatesAccessor,
queue: workqueue.NewTypedRateLimitingQueueWithConfig[string](
workqueue.DefaultTypedControllerRateLimiter[string](),
workqueue.TypedRateLimitingQueueConfig[string]{Name: "pinned-image-set-manager"}),
prefetchCh: make(chan prefetch, defaultPrefetchWorkers*2),
criClient: criClient,
backoff: wait.Backoff{
Steps: maxRetries,
Duration: retryDuration,
Factor: retryFactor,
Cap: retryCap,
},
}
p.syncHandler = p.sync
p.enqueueMachineConfigPool = p.enqueue
p.imageSetLister = imageSetInformer.Lister()
p.imageSetSynced = imageSetInformer.Informer().HasSynced
p.nodeLister = nodeInformer.Lister()
p.nodeListerSynced = nodeInformer.Informer().HasSynced
p.mcpLister = mcpInformer.Lister()
p.mcpSynced = mcpInformer.Informer().HasSynced
// this must be done after the enqueueMachineConfigPool is configured to
// avoid panics when the event handler is called.
mcpInformer.Informer().AddEventHandler(cache.ResourceEventHandlerFuncs{
AddFunc: p.addMachineConfigPool,
UpdateFunc: p.updateMachineConfigPool,
DeleteFunc: p.deleteMachineConfigPool,
})
nodeInformer.Informer().AddEventHandler(cache.ResourceEventHandlerFuncs{
AddFunc: p.handleNodeEvent,
UpdateFunc: func(_, newObj interface{}) { p.handleNodeEvent(newObj) },
})
imageSetInformer.Informer().AddEventHandler(cache.ResourceEventHandlerFuncs{
AddFunc: p.addPinnedImageSet,
UpdateFunc: p.updatePinnedImageSet,
DeleteFunc: p.deletePinnedImageSet,
})
p.cache = newImageCache(256)
return p
}
func (p *PinnedImageSetManager) sync(key string) error {
klog.V(4).Infof("Syncing MachineConfigPool %q", key)
node, err := p.getNodeWithRetry(p.nodeName)
if err != nil {
return fmt.Errorf("failed to get node %q: %w", p.nodeName, err)
}
pools, _, err := helpers.GetPoolsForNode(p.mcpLister, node)
if err != nil {
return err
}
if len(pools) == 0 {
return nil
}
ctx, cancel := context.WithTimeout(context.Background(), p.prefetchTimeout)
// cancel any currently running tasks in the worker pool
p.resetWorkload(cancel)
if err := p.updateStatusProgressing(pools); err != nil {
klog.Errorf("failed to update status: %v", err)
}
if err := p.syncMachineConfigPools(ctx, pools); err != nil {
if errors.Is(err, context.DeadlineExceeded) {
ctxErr := fmt.Errorf("%w: %v", errRequeueAfterTimeout, p.prefetchTimeout)
if err := p.updateStatusError(pools, ctxErr); err != nil {
klog.Errorf("failed to update status: %v", err)
}
klog.Info(ctxErr)
return ctxErr
}
klog.Error(err)
if err := p.updateStatusError(pools, err); err != nil {
klog.Errorf("failed to update status: %v", err)
}
return err
}
return p.updateStatusProgressingComplete(pools, "All pinned image sets complete")
}
func (p *PinnedImageSetManager) syncMachineConfigPools(ctx context.Context, pools []*mcfgv1.MachineConfigPool) error {
images := make([]mcfgv1alpha1.PinnedImageRef, 0, 100)
for _, pool := range pools {
if err := p.syncMachineConfigPool(ctx, pool); err != nil {
return err
}
// collect all unique images from all pools
for _, image := range pool.Spec.PinnedImageSets {
imageSet, err := p.imageSetLister.Get(image.Name)
if err != nil {
if apierrors.IsNotFound(err) {
klog.Warningf("PinnedImageSet %q not found", image.Name)
continue
}
return fmt.Errorf("failed to get PinnedImageSet %q: %w", image.Name, err)
}
images = append(images, imageSet.Spec.PinnedImages...)
}
}
// verify all images available if not clear the cache and requeue
imageNames := uniqueSortedImageNames(images)
for _, image := range imageNames {
exists, err := p.criClient.ImageStatus(ctx, image)
if err != nil {
return err
}
if !exists {
p.cache.Clear()
return fmt.Errorf("%w: image removed during sync: %s", errFailedToPullImage, image)
}
}
// write config and reload crio last to allow a window for kubelet to gc
// images in an emergency
if err := ensureCrioPinnedImagesConfigFile(crioPinnedImagesDropInFilePath, imageNames); err != nil {
klog.Errorf("failed to write crio config file: %v", err)
return err
}
return nil
}
func (p *PinnedImageSetManager) syncMachineConfigPool(ctx context.Context, pool *mcfgv1.MachineConfigPool) error {
if pool.Spec.PinnedImageSets == nil {
return nil
}
imageSets := make([]*mcfgv1alpha1.PinnedImageSet, 0, len(pool.Spec.PinnedImageSets))
for _, ref := range pool.Spec.PinnedImageSets {
imageSet, err := p.imageSetLister.Get(ref.Name)
if err != nil {
return fmt.Errorf("failed to get PinnedImageSet %q: %w", ref.Name, err)
}
klog.Infof("Reconciling pinned image set: %s: generation: %d", ref.Name, imageSet.GetGeneration())
// verify storage per image set
if err := p.checkNodeAllocatableStorage(ctx, imageSet); err != nil {
return err
}
imageSets = append(imageSets, imageSet)
}
// images are cached with size information
p.cache.ClearDigests()
return p.prefetchImageSets(ctx, imageSets...)
}
func (p *PinnedImageSetManager) checkNodeAllocatableStorage(ctx context.Context, imageSet *mcfgv1alpha1.PinnedImageSet) error {
node, err := p.nodeLister.Get(p.nodeName)
if err != nil {
return fmt.Errorf("failed to get node %q: %w", p.nodeName, err)
}
// check if the node is ready
if err := checkNodeReady(node); err != nil {
return err
}
storageCapacity, ok := node.Status.Allocatable[corev1.ResourceEphemeralStorage]
if !ok {
return fmt.Errorf("node %q has no ephemeral storage capacity", p.nodeName)
}
capacity := storageCapacity.Value()
if storageCapacity.Cmp(p.minStorageAvailableBytes) < 0 {
return fmt.Errorf("%w capacity: %d, required: %d", errInsufficientStorage, capacity, p.minStorageAvailableBytes.Value())
}
return p.checkImagePayloadStorage(ctx, imageSet.Spec.PinnedImages, capacity)
}
// prefetchImageSets schedules the prefetching of images for the given image sets and waits for completion.
func (p *PinnedImageSetManager) prefetchImageSets(ctx context.Context, imageSets ...*mcfgv1alpha1.PinnedImageSet) error {
registryAuth, err := newRegistryAuth(p.authFilePath, p.registryCfgPath)
if err != nil {
return err
}
// monitor prefetch operations
monitor := newPrefetchMonitor()
for _, imageSet := range imageSets {
// this is forbidden by the API validation rules, but we should check anyway
if len(imageSet.Spec.PinnedImages) == 0 {
continue
}
cachedImage, ok := p.cache.Get(string(imageSet.UID))
if ok {
cachedImageSet := cachedImage.(mcfgv1alpha1.PinnedImageSet)
if imageSet.Generation == cachedImageSet.Generation {
klog.V(4).Infof("Skipping prefetch for image set %q, generation %d already complete", imageSet.Name, imageSet.Generation)
continue
}
}
if err := p.scheduleWork(ctx, p.prefetchCh, registryAuth, imageSet.Spec.PinnedImages, monitor); err != nil {
return err
}
}
if err := monitor.WaitForDone(); err != nil {
return err
}
// cache the completed image sets
for _, imageSet := range imageSets {
imageSetCache := imageSet.DeepCopy()
imageSetCache.Spec.PinnedImages = nil
p.cache.Add(string(imageSet.UID), *imageSet)
}
return nil
}
// scheduleWork schedules the prefetch work for the images and collects the first error encountered.
func (p *PinnedImageSetManager) scheduleWork(ctx context.Context, prefetchCh chan prefetch, registryAuth *registryAuth, prefetchImages []mcfgv1alpha1.PinnedImageRef, monitor *prefetchMonitor) error {
totalImages := len(prefetchImages)
updateIncrement := totalImages / 4
if updateIncrement == 0 {
updateIncrement = 1 // Ensure there's at least one update if the image count is less than 4
}
scheduledImages := 0
for _, imageRef := range prefetchImages {
if monitor.Drain() {
continue
}
select {
case <-ctx.Done():
return ctx.Err()
default:
image := imageRef.Name
// check cache if image is pulled
// this is an optimization to speedup prefetching after requeue
if value, found := p.cache.Get(image); found {
imageInfo, ok := value.(imageInfo)
if ok {
if imageInfo.Pulled {
scheduledImages++
continue
}
}
}
authConfig, err := registryAuth.getAuthConfigForImage(image)
if err != nil {
return fmt.Errorf("failed to get auth config for image %s: %w", image, err)
}
monitor.Add(1)
prefetchCh <- prefetch{
image: image,
auth: authConfig,
monitor: monitor,
}
scheduledImages++
// report status every 25% of images scheduled
if scheduledImages%updateIncrement == 0 {
klog.Infof("Completed scheduling %d%% of images", (scheduledImages*100)/totalImages)
}
}
}
return nil
}
func (p *PinnedImageSetManager) checkImagePayloadStorage(ctx context.Context, images []mcfgv1alpha1.PinnedImageRef, capacity int64) error {
// calculate total required storage for all images.
requiredStorage := int64(0)
for _, image := range images {
imageName := image.Name
// check cache if image is pulled
if value, found := p.cache.Get(imageName); found {
imageInfo, ok := value.(imageInfo)
if ok {
if imageInfo.Pulled {
continue
}
}
}
exists, err := p.criClient.ImageStatus(ctx, imageName)
if err != nil {
return err
}
if exists {
// do not calculate storage if the image already exists.
continue
}
// check if the image is already in the cache before fetching the size
if value, found := p.cache.Get(imageName); found {
imageInfo, ok := value.(imageInfo)
if ok {
requiredStorage += imageInfo.Size * 2
continue
}
// cache is corrupted, delete the key
klog.Warningf("corrupted cache entry for image %q, deleting", imageName)
p.cache.Remove(imageName)
}
size, err := p.getImageSize(ctx, imageName, p.authFilePath)
if err != nil {
return err
}
// cache miss
p.cache.Add(imageName, imageInfo{Name: imageName, Size: size})
// account for decompression
requiredStorage += size * 2
}
minimumStorage := p.minStorageAvailableBytes.Value()
if requiredStorage >= capacity-minimumStorage {
klog.Errorf("%v capacity=%d, required=%d", errInsufficientStorage, capacity, requiredStorage+p.minStorageAvailableBytes.Value())
return errInsufficientStorage
}
return nil
}
// ensureCrioPinnedImagesConfigFile ensures the crio config file is up to date with the pinned images.
func ensureCrioPinnedImagesConfigFile(path string, imageNames []string) error {
cfgExists, err := hasConfigFile(path)
if err != nil {
return fmt.Errorf("failed to check crio config file: %w", err)
}
if cfgExists && len(imageNames) == 0 {
if err := deleteCrioConfigFile(); err != nil {
return fmt.Errorf("failed to remove CRI-O config file: %w", err)
}
return crioReload()
} else if len(imageNames) == 0 {
return nil
}
var existingCfgBytes []byte
if cfgExists {
existingCfgBytes, err = os.ReadFile(path)
if err != nil {
return fmt.Errorf("failed to read CRIO config file: %w", err)
}
}
newCfgBytes, err := createCrioConfigFileBytes(imageNames)
if err != nil {
return fmt.Errorf("failed to create crio config ignition file: %w", err)
}
// if the existing config is the same as the new config, do nothing
if !bytes.Equal(bytes.TrimSpace(existingCfgBytes), bytes.TrimSpace(newCfgBytes)) {
ignFile := ctrlcommon.NewIgnFileBytes(path, newCfgBytes)
if err := writeFiles([]ign3types.File{ignFile}, true); err != nil {
return fmt.Errorf("failed to write CRIO config file: %w", err)
}
return crioReload()
}
klog.Infof("CRI-O config file is up to date, no reload required")
return nil
}
func (p *PinnedImageSetManager) updateStatusProgressing(pools []*mcfgv1.MachineConfigPool) error {
node, err := p.nodeLister.Get(p.nodeName)
if err != nil {
return fmt.Errorf("failed to get node %q: %w", p.nodeName, err)
}
isComplete := false
applyCfg, err := p.getPinnedImageSetApplyConfigsForPools(pools, isComplete, nil)
if err != nil {
return fmt.Errorf("failed to get image set apply configs: %w", err)
}
imageSetSpec := getPinnedImageSetSpecForPools(pools)
// Get MCP associated with node
pool, err := helpers.GetPrimaryPoolNameForMCN(p.mcpLister, node)
if err != nil {
return err
}
return upgrademonitor.UpdateMachineConfigNodeStatus(
&upgrademonitor.Condition{
State: mcfgv1alpha1.MachineConfigNodePinnedImageSetsProgressing,
Reason: "ImagePrefetch",
Message: fmt.Sprintf("node is prefetching images: %s", node.Name),
},
nil,
metav1.ConditionTrue,
metav1.ConditionUnknown,
node,
p.mcfgClient,
applyCfg,
imageSetSpec,
p.featureGatesAccessor,
pool,
)
}
func (p *PinnedImageSetManager) updateStatusProgressingComplete(pools []*mcfgv1.MachineConfigPool, message string) error {
node, err := p.nodeLister.Get(p.nodeName)
if err != nil {
return fmt.Errorf("failed to get node %q: %w", p.nodeName, err)
}
isComplete := true
applyCfg, err := p.getPinnedImageSetApplyConfigsForPools(pools, isComplete, nil)
if err != nil {
return fmt.Errorf("failed to get image set apply configs: %w", err)
}
imageSetSpec := getPinnedImageSetSpecForPools(pools)
// Get MCP associated with node
pool, err := helpers.GetPrimaryPoolNameForMCN(p.mcpLister, node)
if err != nil {
return err
}
err = upgrademonitor.UpdateMachineConfigNodeStatus(
&upgrademonitor.Condition{
State: mcfgv1alpha1.MachineConfigNodePinnedImageSetsProgressing,
Reason: "AsExpected",
Message: message,
},
nil,
metav1.ConditionFalse,
metav1.ConditionUnknown,
node,
p.mcfgClient,
applyCfg,
imageSetSpec,
p.featureGatesAccessor,
pool,
)
if err != nil {
klog.Errorf("Failed to updated machine config node: %v", err)
}
// reset any degraded status
return upgrademonitor.UpdateMachineConfigNodeStatus(
&upgrademonitor.Condition{
State: mcfgv1alpha1.MachineConfigNodePinnedImageSetsDegraded,
Reason: "AsExpected",
Message: "All is good",
},
nil,
metav1.ConditionFalse,
metav1.ConditionUnknown,
node,
p.mcfgClient,
nil,
nil,
p.featureGatesAccessor,
pool,
)
}
func (p *PinnedImageSetManager) updateStatusError(pools []*mcfgv1.MachineConfigPool, statusErr error) error {
node, err := p.nodeLister.Get(p.nodeName)
if err != nil {
return fmt.Errorf("failed to get node %q: %w", p.nodeName, err)
}
isComplete := false
applyCfg, err := p.getPinnedImageSetApplyConfigsForPools(pools, isComplete, statusErr)
if err != nil {
return fmt.Errorf("failed to get image set apply configs: %w", err)
}
imageSetSpec := getPinnedImageSetSpecForPools(pools)
var errMsg string
if isErrNoSpace(statusErr) {
// degrade the pool if there is no space
errMsg = fmt.Sprintf("%s %v", degradeMessagePrefix, statusErr)
} else {
errMsg = statusErr.Error()
}
// Get MCP associated with node
pool, err := helpers.GetPrimaryPoolNameForMCN(p.mcpLister, node)
if err != nil {
return err
}
return upgrademonitor.UpdateMachineConfigNodeStatus(
&upgrademonitor.Condition{
State: mcfgv1alpha1.MachineConfigNodePinnedImageSetsDegraded,
Reason: "PrefetchFailed",
Message: errMsg,
},
nil,
metav1.ConditionTrue,
metav1.ConditionUnknown,
node,
p.mcfgClient,
applyCfg,
imageSetSpec,
p.featureGatesAccessor,
pool,
)
}
// getPinnedImageSetApplyConfigsForPools returns a list of MachineConfigNodeStatusPinnedImageSetApplyConfiguration for the given pools.
func (p *PinnedImageSetManager) getPinnedImageSetApplyConfigsForPools(pools []*mcfgv1.MachineConfigPool, isCompleted bool, statusErr error) ([]*machineconfigurationalphav1.MachineConfigNodeStatusPinnedImageSetApplyConfiguration, error) {
applyConfigs := make([]*machineconfigurationalphav1.MachineConfigNodeStatusPinnedImageSetApplyConfiguration, 0)
for _, pool := range pools {
for _, imageSets := range pool.Spec.PinnedImageSets {
imageSet, err := p.imageSetLister.Get(imageSets.Name)
if err != nil {
if apierrors.IsNotFound(err) {
continue
}
return nil, err
}
config := p.createApplyConfigForImageSet(imageSet, isCompleted, statusErr)
applyConfigs = append(applyConfigs, config)
}
}
return applyConfigs, nil
}
func (p *PinnedImageSetManager) createApplyConfigForImageSet(imageSet *mcfgv1alpha1.PinnedImageSet, isCompleted bool, statusErr error) *machineconfigurationalphav1.MachineConfigNodeStatusPinnedImageSetApplyConfiguration {
imageSetConfig := machineconfigurationalphav1.MachineConfigNodeStatusPinnedImageSet().
WithName(imageSet.Name).
WithDesiredGeneration(int32(imageSet.GetGeneration()))
if cachedImage, ok := p.cache.Get(string(imageSet.UID)); ok {
cachedImageSet := cachedImage.(mcfgv1alpha1.PinnedImageSet)
if imageSet.Generation == cachedImageSet.Generation {
// return cached value
imageSetConfig.CurrentGeneration = ptr.To(int32(imageSet.GetGeneration()))
return imageSetConfig
}
}
if statusErr != nil {
imageSetConfig.LastFailedGeneration = ptr.To(int32(imageSet.GetGeneration()))
imageSetConfig.LastFailedGenerationErrors = []string{statusErr.Error()}
} else if isCompleted {
// only set the current generation if prefetch is complete
imageSetConfig.CurrentGeneration = ptr.To(int32(imageSet.GetGeneration()))
}
return imageSetConfig
}
func checkNodeReady(node *corev1.Node) error {
for i := range node.Status.Conditions {
cond := &node.Status.Conditions[i]
if cond.Type == corev1.NodeReady && cond.Status != corev1.ConditionTrue {
return fmt.Errorf("node %s is reporting NotReady=%v", node.Name, cond.Status)
}
if cond.Type == corev1.NodeDiskPressure && cond.Status != corev1.ConditionFalse {
return fmt.Errorf("node %s is reporting OutOfDisk=%v", node.Name, cond.Status)
}
}
return nil
}
// getWorkerCount returns the number of workers to use for prefetching images.
func (p *PinnedImageSetManager) getWorkerCount() (int, error) {
node, err := p.getNodeWithRetry(p.nodeName)
if err != nil {
return 0, fmt.Errorf("failed to get node %q: %w", p.nodeName, err)
}
// default to 5 workers
workerCount := defaultPrefetchWorkers
// master nodes are a special case and should have a concurrency of 1 to
// mitigate I/O contention with the control plane.
if _, ok := node.ObjectMeta.Labels["node-role.kubernetes.io/master"]; ok {
workerCount = defaultControlPlaneWorkers
}
return workerCount, nil
}
func (p *PinnedImageSetManager) resetWorkload(cancelFn context.CancelFunc) {
p.mu.Lock()
if p.cancelFn != nil {
klog.V(4).Info("Reset workload")
p.cancelFn()
}
p.cancelFn = cancelFn
p.mu.Unlock()
}
func (p *PinnedImageSetManager) cancelWorkload(reason string) {
p.mu.Lock()
if p.cancelFn != nil {
klog.Infof("Cancelling workload: %s", reason)
p.cancelFn()
p.cancelFn = nil
}
p.mu.Unlock()
}
// prefetchWorker is a worker that pulls images from the container runtime.
func (p *PinnedImageSetManager) prefetchWorker(ctx context.Context) {
for task := range p.prefetchCh {
if task.monitor.Drain() {
task.monitor.Done()
continue
}
if err := ensurePullImage(ctx, p.criClient, p.backoff, task.image, task.auth); err != nil {
task.monitor.Error(err)
klog.Warningf("failed to prefetch image %q: %v", task.image, err)
}
task.monitor.Done()
cachedImage, ok := p.cache.Get(task.image)
if ok {
imageInfo, ok := cachedImage.(imageInfo)
if !ok {
klog.Warningf("corrupted cache entry for image %q, deleting", task.image)
p.cache.Remove(task.image)
}
imageInfo.Pulled = true
p.cache.Add(task.image, imageInfo)
} else {
p.cache.Add(task.image, imageInfo{Name: task.image, Pulled: true})
}
// throttle prefetching to avoid overloading the file system
select {
case <-time.After(defaultPrefetchThrottleDuration):
case <-ctx.Done():
return
}
}
}
func (p *PinnedImageSetManager) Run(workers int, stopCh <-chan struct{}) {
ctx, cancel := context.WithCancel(context.Background())
defer func() {
cancel()
utilruntime.HandleCrash()
p.queue.ShutDown()
close(p.prefetchCh)
}()
if !cache.WaitForCacheSync(
stopCh,
p.imageSetSynced,
p.nodeListerSynced,
p.mcpSynced,
) {
klog.Errorf("failed to sync initial listers cache")
return
}
workerCount, err := p.getWorkerCount()
if err != nil {
klog.Fatalf("failed to get worker count: %v", err)
return
}
klog.Infof("Starting PinnedImageSet Manager")
defer klog.Infof("Shutting down PinnedImageSet Manager")
// start image prefetch workers
for i := 0; i < workerCount; i++ {
go p.prefetchWorker(ctx)
}
for i := 0; i < workers; i++ {
go wait.Until(p.worker, time.Second, stopCh)
}
<-stopCh
}
func (p *PinnedImageSetManager) addPinnedImageSet(obj interface{}) {
imageSet := obj.(*mcfgv1alpha1.PinnedImageSet)
if imageSet.DeletionTimestamp != nil {
p.deletePinnedImageSet(imageSet)
return
}
node, err := p.getNodeWithRetry(p.nodeName)
if err != nil {
klog.Errorf("failed to get node %q: %v", p.nodeName, err)
return
}
pools, _, err := helpers.GetPoolsForNode(p.mcpLister, node)
if err != nil {
klog.Errorf("error finding pools for node %s: %v", node.Name, err)
return
}
if pools == nil {
return
}
klog.V(4).Infof("PinnedImageSet %s added", imageSet.Name)
for _, pool := range pools {
if !isImageSetInPool(imageSet.Name, pool) {
continue
}
p.enqueueMachineConfigPool(pool)
}
}
func (p *PinnedImageSetManager) deletePinnedImageSet(obj interface{}) {
imageSet, ok := obj.(*mcfgv1alpha1.PinnedImageSet)
if !ok {
tombstone, ok := obj.(cache.DeletedFinalStateUnknown)
if !ok {
utilruntime.HandleError(fmt.Errorf("couldn't get object from tombstone %#v", obj))
return
}
imageSet, ok = tombstone.Obj.(*mcfgv1alpha1.PinnedImageSet)
if !ok {
utilruntime.HandleError(fmt.Errorf("tombstone contained object that is not a PinnedImageSet %#v", obj))
return
}
}
node, err := p.getNodeWithRetry(p.nodeName)
if err != nil {
klog.Errorf("failed to get node %q: %v", p.nodeName, err)
return
}
pools, _, err := helpers.GetPoolsForNode(p.mcpLister, node)
if err != nil {
klog.Errorf("error finding pools for node %s: %v", node.Name, err)
return
}
if pools == nil {
return
}
klog.V(4).Infof("PinnedImageSet %s delete", imageSet.Name)
for _, pool := range pools {
if !isImageSetInPool(imageSet.Name, pool) {
continue
}
p.enqueueMachineConfigPool(pool)
}
}
// getNodeWithRetry gets the node with retries. This avoids some races when the local node
// is new but not found during startup.
func (p *PinnedImageSetManager) getNodeWithRetry(nodeName string) (*corev1.Node,
error) {
var node *corev1.Node
err := wait.ExponentialBackoff(p.backoff, func() (bool, error) {
var err error
node, err = p.nodeLister.Get(nodeName)
if err != nil {
if apierrors.IsNotFound(err) {
// log warning and retry because we are tolerating unexpected behavior from the informer
klog.Warningf("Node %q not found, retrying", nodeName)
return false, nil
}
return false, err
}
return true, nil
})
return node, err
}
func (p *PinnedImageSetManager) updatePinnedImageSet(oldObj, newObj interface{}) {
oldImageSet := oldObj.(*mcfgv1alpha1.PinnedImageSet)
newImageSet := newObj.(*mcfgv1alpha1.PinnedImageSet)
imageSet, err := p.imageSetLister.Get(newImageSet.Name)
if apierrors.IsNotFound(err) {
return
}
node, err := p.getNodeWithRetry(p.nodeName)
if err != nil {
klog.Errorf("failed to get node %q: %v", p.nodeName, err)
return
}
pools, _, err := helpers.GetPoolsForNode(p.mcpLister, node)
if err != nil {
klog.Errorf("error finding pools for node %s: %v", node.Name, err)
return
}
if pools == nil {
return
}
if triggerPinnedImageSetChange(oldImageSet, newImageSet) {
klog.V(4).Infof("PinnedImageSet %s update", imageSet.Name)
for _, pool := range pools {
if !isImageSetInPool(imageSet.Name, pool) {
continue
}
p.cancelWorkload("PinnedImageSet update")
p.enqueueMachineConfigPool(pool)
}
}
}
func (p *PinnedImageSetManager) handleNodeEvent(newObj interface{}) {
newNode := newObj.(*corev1.Node)
if newNode.Name != p.nodeName {
return
}
pools, _, err := helpers.GetPoolsForNode(p.mcpLister, newNode)
if err != nil {
klog.Errorf("error finding pools for node %s: %v", newNode.Name, err)
return
}
if pools == nil {
return
}
// handle first sync during startup
if !p.isBootstrapped() {
for _, pool := range pools {
p.enqueueMachineConfigPool(pool)
}
}
p.setBootstrapped()
}
func (p *PinnedImageSetManager) isBootstrapped() bool {
return p.bootstrapped
}