-
Notifications
You must be signed in to change notification settings - Fork 25
Expand file tree
/
Copy pathskyhook_controller.go
More file actions
3359 lines (2953 loc) · 122 KB
/
Copy pathskyhook_controller.go
File metadata and controls
3359 lines (2953 loc) · 122 KB
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
/*
* SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
* SPDX-License-Identifier: Apache-2.0
*
*
* 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 controller
import (
"cmp"
"context"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"reflect"
"slices"
"sort"
"strconv"
"strings"
"time"
"github.com/NVIDIA/nodewright/operator/api/nodewright/v1alpha1"
"github.com/NVIDIA/nodewright/operator/internal/dal"
"github.com/NVIDIA/nodewright/operator/internal/drain"
"github.com/NVIDIA/nodewright/operator/internal/version"
"github.com/NVIDIA/nodewright/operator/internal/wrapper"
"github.com/go-logr/logr"
corev1 "k8s.io/api/core/v1"
policyv1 "k8s.io/api/policy/v1"
apierrors "k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/api/resource"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/types"
utilerrors "k8s.io/apimachinery/pkg/util/errors"
"k8s.io/client-go/tools/events"
"k8s.io/kubernetes/pkg/util/taints"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/controller"
"sigs.k8s.io/controller-runtime/pkg/controller/controllerutil"
"sigs.k8s.io/controller-runtime/pkg/handler"
"sigs.k8s.io/controller-runtime/pkg/log"
"sigs.k8s.io/controller-runtime/pkg/reconcile"
)
const (
EventsReasonSkyhookApply = "Apply"
EventsReasonSkyhookInterrupt = "Interrupt"
EventsReasonSkyhookDrain = "Drain"
EventsReasonSkyhookStateChange = "State"
EventsReasonNodeReboot = "Reboot"
EventTypeNormal = "Normal"
// EventTypeWarning = "Warning"
TaintUnschedulable = corev1.TaintNodeUnschedulable
InterruptContainerName = "interrupt"
SkyhookFinalizer = "nodewright.nvidia.com/nodewright"
// Annotation values used as truthy/falsy strings on Skyhook and Node objects.
annotationTrueValue = "true"
annotationFalseValue = "false"
// Field selector keys used when filtering pod lists by node.
fieldSelectorNodeName = "spec.nodeName"
// Volume + mountpath shared by every package container's host-root mount.
volumeNameRootMount = "root-mount"
mountPathRoot = "/root"
// Directory inside package containers where the SCR's configMap is projected.
mountPathConfigMaps = "/skyhook-package/configmaps"
// Environment variable names propagated into package containers.
envSkyhookResourceID = "SKYHOOK_RESOURCE_ID"
envSkyhookNodeOrder = "SKYHOOK_NODE_ORDER"
// globalReconcileName is both the controller's registered name (driving the
// reconcile metric and log labels) and the .Name of the sentinel request the
// heavy reconcile path collapses Skyhook and Node events onto. The sentinel
// value is arbitrary and ignored by Reconcile (which grabs the whole world);
// it only has to be constant and must not collide with the "pod---" dispatch
// prefix.
globalReconcileName = "nodewright"
// globalReconcileDelay is how long Skyhook and Node events wait before the
// global key becomes ready. The bulk of coalescing is already free: a burst
// arriving while a pass is in flight dedups onto one follow-up via the
// priority queue's locked-key handling. This short window only lets a pass's
// own writes propagate to the cache and near-simultaneous events land before
// the follow-up runs. It is kept small on purpose: the interrupt flow
// advances one stage per Node event, so a larger delay (we started at 500ms)
// adds up across stages and blows the interrupt e2e timing budget.
globalReconcileDelay = 50 * time.Millisecond
)
type SkyhookOperatorOptions struct {
Namespace string `env:"NAMESPACE, default=skyhook"`
MaxInterval time.Duration `env:"DEFAULT_INTERVAL, default=10m"`
ImagePullSecret string `env:"IMAGE_PULL_SECRET"`
CopyDirRoot string `env:"COPY_DIR_ROOT, default=/var/lib/skyhook"`
ReapplyOnReboot bool `env:"REAPPLY_ON_REBOOT, default=false"`
RuntimeRequiredTaint string `env:"RUNTIME_REQUIRED_TAINT, default=skyhook.nvidia.com=runtime-required:NoSchedule"`
PauseImage string `env:"PAUSE_IMAGE, default=registry.k8s.io/pause:3.10"`
AgentImage string `env:"AGENT_IMAGE, default=ghcr.io/nvidia/nodewright/agent:latest"` // TODO: pin a released agent version instead of :latest
AgentLogRoot string `env:"AGENT_LOG_ROOT, default=/var/log/skyhook"`
// MIGRATION-SHIM: transition-only for the skyhook.nvidia.com -> nodewright.nvidia.com
// rename. LegacyCleanupDelay is how long after a Skyhook finishes migrating the
// operator keeps its legacy skyhook.nvidia.com node state / pods / ConfigMap labels
// around (a rollback window) before pruning them. 0 or less prunes immediately (no
// rollback window). Remove with the legacy group at the removal release.
LegacyCleanupDelay time.Duration `env:"LEGACY_CLEANUP_DELAY, default=24h"`
}
func (o *SkyhookOperatorOptions) Validate() error {
messages := make([]string, 0)
if o.Namespace == "" {
messages = append(messages, "namespace must be set")
}
if o.CopyDirRoot == "" {
messages = append(messages, "copy dir root must be set")
}
if o.RuntimeRequiredTaint == "" {
messages = append(messages, "runtime required taint must be set")
}
if o.MaxInterval < time.Minute {
messages = append(messages, "max interval must be at least 1 minute")
}
// CopyDirRoot must start with /
if !strings.HasPrefix(o.CopyDirRoot, "/") {
messages = append(messages, "copy dir root must start with /")
}
// RuntimeRequiredTaint must be parsable and must not be a deletion
_, delete, err := taints.ParseTaints([]string{o.RuntimeRequiredTaint})
if err != nil {
messages = append(messages, fmt.Sprintf("runtime required taint is invalid: %s", err.Error()))
}
if len(delete) > 0 {
messages = append(messages, "runtime required taint must not be a deletion")
}
if o.AgentImage == "" {
messages = append(messages, "agent image must be set")
}
if !strings.Contains(o.AgentImage, ":") {
messages = append(messages, "agent image must contain a tag")
}
if o.PauseImage == "" {
messages = append(messages, "pause image must be set")
}
if !strings.Contains(o.PauseImage, ":") {
messages = append(messages, "pause image must contain a tag")
}
if len(messages) > 0 {
return errors.New(strings.Join(messages, ", "))
}
return nil
}
// AgentVersion returns the image tag portion of AgentImage
func (o *SkyhookOperatorOptions) AgentVersion() string {
parts := strings.Split(o.AgentImage, ":")
return parts[len(parts)-1]
}
func (o *SkyhookOperatorOptions) GetRuntimeRequiredTaint() corev1.Taint {
to_add, _, _ := taints.ParseTaints([]string{o.RuntimeRequiredTaint})
return to_add[0]
}
func (o *SkyhookOperatorOptions) GetRuntimeRequiredToleration() corev1.Toleration {
taint := o.GetRuntimeRequiredTaint()
return corev1.Toleration{
Key: taint.Key,
Operator: corev1.TolerationOpEqual,
Value: taint.Value,
Effect: taint.Effect,
}
}
// force type checking against this interface
var _ reconcile.Reconciler = &SkyhookReconciler{}
func NewSkyhookReconciler(schema *runtime.Scheme, c client.Client, recorder events.EventRecorder, opts SkyhookOperatorOptions) (*SkyhookReconciler, error) {
err := opts.Validate()
if err != nil {
return nil, fmt.Errorf("invalid skyhook operator options: %w", err)
}
return &SkyhookReconciler{
Client: c,
scheme: schema,
recorder: recorder,
opts: opts,
dal: dal.New(c),
}, nil
}
// SkyhookReconciler reconciles a Skyhook object
type SkyhookReconciler struct {
client.Client
scheme *runtime.Scheme
recorder events.EventRecorder
opts SkyhookOperatorOptions
dal dal.DAL
}
// SetupWithManager sets up the controller with the Manager.
func (r *SkyhookReconciler) SetupWithManager(mgr ctrl.Manager) error {
// indexes allow for query on fields to use the local cache
indexer := mgr.GetFieldIndexer()
err := indexer.
IndexField(context.TODO(), &corev1.Pod{}, fieldSelectorNodeName, func(o client.Object) []string {
pod, ok := o.(*corev1.Pod)
if !ok {
return nil
}
return []string{pod.Spec.NodeName}
})
if err != nil {
return err
}
globalHandler := &globalDelayHandler{
logger: mgr.GetLogger(),
dal: dal.New(r.Client),
delay: globalReconcileDelay,
}
return ctrl.NewControllerManagedBy(mgr).
Named(globalReconcileName).
WithOptions(controller.Options{
// Only one heavy "grab the world" pass may run at a time: it is a
// centralized scheduler reading across every SCR, Node and Pod, so
// concurrent passes would race each other's writes. This makes the
// global key the single in-flight reconcile.
MaxConcurrentReconciles: 1,
}).
// Heavy path: Skyhook and Node events collapse onto the global key.
Watches(
&v1alpha1.NodeWright{},
globalHandler,
).
Watches(
&corev1.Node{},
globalHandler,
).
// Cheap path: Pod events keep their targeted "pod---<name>" routing,
// dispatched to PodReconcile in Reconcile below.
Watches(
&corev1.Pod{},
handler.EnqueueRequestsFromMapFunc(podHandlerFunc),
).
Complete(r)
}
// CRD Permissions
//+kubebuilder:rbac:groups=skyhook.nvidia.com,resources=skyhooks,verbs=get;list;watch;create;update;patch;delete
//+kubebuilder:rbac:groups=skyhook.nvidia.com,resources=skyhooks/status,verbs=get;update;patch
//+kubebuilder:rbac:groups=skyhook.nvidia.com,resources=skyhooks/finalizers,verbs=update
//+kubebuilder:rbac:groups=skyhook.nvidia.com,resources=deploymentpolicies,verbs=get;list;watch
// core permissions
//+kubebuilder:rbac:groups=core,resources=nodes,verbs=get;list;update;patch;watch
//+kubebuilder:rbac:groups=core,resources=nodes/status,verbs=get;update;patch
//+kubebuilder:rbac:groups=core,resources=pods/eviction,verbs=create
//+kubebuilder:rbac:groups=core,resources=events,verbs=create;patch
// The event recorder writes via the events.k8s.io/v1 API (client-go tools/events,
// wired through mgr.GetEventRecorder), so the core rule above is not sufficient on
// its own — without this rule every recorded event is rejected as forbidden.
//+kubebuilder:rbac:groups=events.k8s.io,resources=events,verbs=create;patch
//+kubebuilder:rbac:groups=core,resources=configmaps,verbs=get;list;watch;create;update;patch;delete
// Reconcile is part of the main kubernetes reconciliation loop which aims to
// move the current state of the cluster closer to the desired state.
// - https://pkg.go.dev/sigs.k8s.io/controller-runtime@v0.16.3/pkg/reconcile
func (r *SkyhookReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {
logger := log.FromContext(ctx)
// split off requests for pods
if strings.HasPrefix(req.Name, "pod---") {
name := strings.Split(req.Name, "pod---")[1]
pod, err := r.dal.GetPod(ctx, req.Namespace, name)
if err == nil && pod != nil { // if pod, then call other wise not a pod
return r.PodReconcile(ctx, pod)
}
return ctrl.Result{}, err
}
// Migration safety interlock: while any legacy skyhook.nvidia.com Skyhook is still
// mid-rollout, hold this NodeWright reconcile and requeue rather than take over a
// node the pre-rename operator may still be mutating. Clears once the legacy
// Skyhooks read complete; fresh clusters and post-migration installs never hold.
if hold := r.legacyMigrationHold(ctx); hold != nil {
return *hold, nil
}
// get all skyhooks (SCR)
skyhooks, err := r.dal.GetSkyhooks(ctx)
if err != nil {
// error, going to requeue and backoff
logger.Error(err, "error getting skyhooks")
return ctrl.Result{}, err
}
// if there are no skyhooks, so actually nothing to do, so don't requeue
if skyhooks == nil || len(skyhooks.Items) == 0 {
return ctrl.Result{}, nil
}
// get all nodes
nodes, err := r.dal.GetNodes(ctx)
if err != nil {
// error, going to requeue and backoff
logger.Error(err, "error getting nodes")
return ctrl.Result{}, err
}
// if no nodes, well not work to do either
if nodes == nil || len(nodes.Items) == 0 {
// no nodes, so nothing to do
return ctrl.Result{}, nil
}
// get all deployment policies
deploymentPolicies, err := r.dal.GetDeploymentPolicies(ctx)
if err != nil {
logger.Error(err, "error getting deployment policies")
return ctrl.Result{}, err
}
// TODO: this build state could error in a lot of ways, and I think we might want to move towards partial state
// mean if we cant get on SCR state, great, process that one and error
// BUILD cluster state from all skyhooks, and all nodes
// this filters and pairs up nodes to skyhooks, also provides help methods for introspection and mutation
clusterState, err := BuildState(skyhooks, nodes, deploymentPolicies)
if err != nil {
// error, going to requeue and backoff
logger.Error(err, "error building cluster state")
return ctrl.Result{}, err
}
// handle auto-tainting new nodes first so it
if yes, result, err := shouldReturn(r.HandleAutoTaint(ctx, clusterState)); yes {
return result, err
}
if yes, result, err := shouldReturn(r.HandleMigrations(ctx, clusterState)); yes {
return result, err
}
if yes, result, err := shouldReturn(r.TrackReboots(ctx, clusterState)); yes {
return result, err
}
// node picker is for selecting nodes to do work, tries maintain a prior of nodes between SCRs
nodePicker := NewNodePicker(logger, r.opts.GetRuntimeRequiredToleration())
errs := make([]error, 0)
var result *ctrl.Result
configSyncPending := false
for _, skyhook := range clusterState.skyhooks {
if err := r.refreshSkyhookConditions(ctx, clusterState, skyhook); err != nil {
return ctrl.Result{RequeueAfter: time.Second * 2}, err
}
if yes, result, err := shouldReturn(r.HandleFinalizer(ctx, skyhook, clusterState)); yes {
return result, err
}
if yes, result, err := shouldReturn(r.ReportState(ctx, clusterState, skyhook)); yes {
return result, err
}
if skyhook.IsPaused() {
if yes, result, err := shouldReturn(r.UpdatePauseStatus(ctx, clusterState, skyhook)); yes {
return result, err
}
continue
}
if yes, pendingSync, result, err := r.validateAndUpsertSkyhookData(ctx, skyhook, clusterState); yes {
return result, err
} else if pendingSync {
configSyncPending = true
}
changed := IntrospectSkyhook(skyhook, clusterState.skyhooks, logger)
if changed {
_, errs := r.SaveNodesAndSkyhook(ctx, clusterState, skyhook)
if len(errs) > 0 {
return ctrl.Result{RequeueAfter: time.Second * 2}, utilerrors.NewAggregate(errs)
}
return ctrl.Result{RequeueAfter: time.Second * 2}, nil
}
_, err := HandleVersionChange(skyhook)
if err != nil {
return ctrl.Result{RequeueAfter: time.Second * 2}, fmt.Errorf("error getting packages to uninstall: %w", err)
}
}
// Process all non-complete, non-disabled skyhooks (in priority order)
// Each skyhook is processed only for nodes that are ready (all higher-priority skyhooks complete on that node)
// This enables per-node priority ordering: nodes can progress independently
result, err = r.processSkyhooksPerNode(ctx, clusterState, nodePicker, logger)
if err != nil {
errs = append(errs, err)
}
err = r.HandleRuntimeRequired(ctx, clusterState)
if err != nil {
errs = append(errs, err)
}
if len(errs) > 0 {
err := utilerrors.NewAggregate(errs)
return ctrl.Result{}, err
}
return reconcileResult(result, configSyncPending, r.opts.MaxInterval), nil
}
// reconcileResult picks the requeue for a completed reconcile pass. Active work
// supplies its own (shorter) result, which is returned untouched. When the pass is
// otherwise idle but an owned ConfigMap write was deferred because the completedNodes
// gate was closed (configSyncPending), retry after configSyncRetryInterval instead of
// the much longer maxInterval so the CM converges promptly rather than appearing stuck
// while status reads complete (issue #245). Otherwise fall back to maxInterval.
func reconcileResult(result *ctrl.Result, configSyncPending bool, maxInterval time.Duration) ctrl.Result {
if result != nil {
return *result
}
if configSyncPending {
return ctrl.Result{RequeueAfter: configSyncRetryInterval}
}
return ctrl.Result{RequeueAfter: maxInterval}
}
// refreshSkyhookConditions updates and persists the per-Skyhook conditions
// that have to stay accurate regardless of pause / disable / delete state:
//
// - NodeStateMalformed surfaces unreadable nodeState annotations BEFORE
// any handler that reads node.State() runs and aborts on parse errors.
// - Blocked + UninstallInProgress + UninstallFailed mirror node state so
// paused or disabled Skyhooks (which short-circuit
// processSkyhooksPerNode) still get current conditions, and so
// HandleFinalizer's deletion-gating logic stays focused on its own
// concern instead of duplicating condition-mirroring work.
//
// UpdateBlockedCondition / UpdateUninstallConditions are tolerant to
// per-node state read errors — they skip unreadable nodes and let
// UpdateNodeStateMalformedCondition (set above) be the user-visible signal.
// This keeps HandleFinalizer's malformed-state branch reachable so its
// DeletionBlocked condition + Warning event fire on CR deletion.
func (r *SkyhookReconciler) refreshSkyhookConditions(ctx context.Context, clusterState *clusterState, skyhook SkyhookNodes) error {
skyhook.UpdateNodeStateMalformedCondition()
if _, saveErrs := r.SaveNodesAndSkyhook(ctx, clusterState, skyhook); len(saveErrs) > 0 {
return utilerrors.NewAggregate(saveErrs)
}
if err := skyhook.UpdateBlockedCondition(); err != nil {
return fmt.Errorf("error updating blocked condition: %w", err)
}
if err := skyhook.UpdateUninstallConditions(); err != nil {
return fmt.Errorf("error updating uninstall conditions: %w", err)
}
return nil
}
// processSkyhooksPerNode processes all skyhooks for nodes that are ready (per-node priority ordering).
// A node is ready for a skyhook if all higher-priority skyhooks are complete on that specific node.
func (r *SkyhookReconciler) processSkyhooksPerNode(ctx context.Context, clusterState *clusterState, nodePicker *NodePicker, logger logr.Logger) (*ctrl.Result, error) {
var result *ctrl.Result
var errs []error
for _, skyhook := range clusterState.skyhooks {
if skyhook.IsDisabled() || skyhook.IsPaused() {
continue
}
hasWork, err := skyhook.HasUninstallWork()
if err != nil {
errs = append(errs, fmt.Errorf("error checking uninstall work for skyhook %s: %w", skyhook.GetSkyhook().Name, err))
continue
}
if skyhook.IsComplete() && !hasWork {
continue
}
// Check if any nodes are ready for this skyhook
ready, err := hasReadyNodesForSkyhook(skyhook, clusterState.skyhooks)
if err != nil {
errs = append(errs, fmt.Errorf("error checking ready nodes for skyhook %s: %w", skyhook.GetSkyhook().Name, err))
continue
}
if !ready {
continue
}
res, err := r.RunSkyhookPackages(ctx, clusterState, nodePicker, skyhook)
if err != nil {
logger.Error(err, "error processing skyhook", "skyhook", skyhook.GetSkyhook().Name)
errs = append(errs, err)
}
if res != nil {
result = res
}
}
if len(errs) > 0 {
return result, utilerrors.NewAggregate(errs)
}
return result, nil
}
// hasReadyNodesForSkyhook checks if any nodes are ready to process this skyhook.
// A node is ready if it's not complete and all higher-priority skyhooks are complete on that node.
func hasReadyNodesForSkyhook(skyhook SkyhookNodes, allSkyhooks []SkyhookNodes) (bool, error) {
pendingUninstall, err := skyhook.HasUninstallWork()
if err != nil {
return false, err
}
for _, node := range skyhook.GetNodes() {
if node.IsComplete() && !pendingUninstall {
continue
}
if IsNodeReadyForSkyhook(node.GetNode().Name, skyhook, allSkyhooks) {
return true, nil
}
}
return false, nil
}
func shouldReturn(updates bool, err error) (bool, ctrl.Result, error) {
if err != nil {
return true, ctrl.Result{}, err
}
if updates {
return true, ctrl.Result{RequeueAfter: time.Second * 2}, nil
}
return false, ctrl.Result{}, nil
}
func (r *SkyhookReconciler) HandleMigrations(ctx context.Context, clusterState *clusterState) (bool, error) {
updates := false
if version.VERSION == "" {
// this means the binary was complied without version information
return false, nil
}
logger := log.FromContext(ctx)
errors := make([]error, 0)
for _, skyhook := range clusterState.skyhooks {
err := skyhook.Migrate(logger)
if err != nil {
return false, fmt.Errorf("error migrating skyhook [%s]: %w", skyhook.GetSkyhook().Name, err)
}
if err := skyhook.GetSkyhook().NodeWright.Validate(); err != nil {
return false, fmt.Errorf("error validating skyhook [%s]: %w", skyhook.GetSkyhook().Name, err)
}
// MIGRATION-SHIM: rollback-safe legacy cleanup. skyhook.Migrate above adopts
// legacy node state ADDITIVELY (keeps the skyhook.nvidia.com keys). We only
// prune those legacy keys/pods/labels once the rollback window has elapsed,
// tracked by the legacy-migrated-at stamp on the NodeWright. See
// docs/plans/2026-07-20-legacy-cleanup-ttl-design.md.
nw := skyhook.GetSkyhook().NodeWright
prune := legacyCleanupShouldPrune(nw.GetAnnotations()[legacyMigratedAtAnnotation], r.opts.LegacyCleanupDelay, time.Now())
if prune {
for _, node := range skyhook.GetNodes() {
node.PruneLegacyMetadata()
}
}
for _, node := range skyhook.GetNodes() {
if node.Changed() {
err := r.Status().Patch(ctx, node.GetNode(), client.MergeFrom(clusterState.tracker.GetOriginal(node.GetNode())))
if err != nil {
errors = append(errors, fmt.Errorf("error patching node [%s]: %w", node.GetNode().Name, err))
}
err = r.Patch(ctx, node.GetNode(), client.MergeFrom(clusterState.tracker.GetOriginal(node.GetNode())))
if err != nil {
errors = append(errors, fmt.Errorf("error patching node [%s]: %w", node.GetNode().Name, err))
}
updates = true
}
}
// Converge (add nodewright labels, keep legacy pods) or prune (delete legacy
// pods, drop legacy labels) the workloads the pre-rename operator created under
// the legacy skyhook.nvidia.com labels.
hadLegacyWorkloads, workloadsChanged, err := r.reconcileLegacyLabeledWorkloads(ctx, skyhook.GetSkyhook().Name, prune)
if err != nil {
return false, fmt.Errorf("error reconciling legacy-labeled workloads for skyhook [%s]: %w", skyhook.GetSkyhook().Name, err)
}
if workloadsChanged {
updates = true
}
if skyhook.GetSkyhook().Updated {
// need to do this because SaveNodesAndSkyhook only saves skyhook status, not the main skyhook object where the annotations are
// additionally it needs to be an update, a patch nils out the annotations for some reason, which the save function does a patch
if err = r.Status().Update(ctx, skyhook.GetSkyhook().NodeWright); err != nil {
return false, fmt.Errorf("error updating during migration skyhook status [%s]: %w", skyhook.GetSkyhook().Name, err)
}
// because of conflict issues (409) we need to do things a bit differently here.
// We might be able to use server side apply in the future, but for now we need to do this
// https://kubernetes.io/docs/reference/using-api/server-side-apply/
// https://github.com/kubernetes-sigs/controller-runtime/issues/347
// work around for now is to grab a new copy of the object, and then patch it
newskyhook, err := r.dal.GetSkyhook(ctx, skyhook.GetSkyhook().Name)
if err != nil {
return false, fmt.Errorf("error getting skyhook to migrate [%s]: %w", skyhook.GetSkyhook().Name, err)
}
newPatch := client.MergeFrom(newskyhook.DeepCopy())
// set version
wrapper.NewSkyhookWrapper(newskyhook).SetVersion()
if err = r.Patch(ctx, newskyhook, newPatch); err != nil {
return false, fmt.Errorf("error updating during migration skyhook [%s]: %w", skyhook.GetSkyhook().Name, err)
}
updates = true
}
// Manage the rollback-window stamp LAST: it re-gets and patches the NodeWright,
// bumping its resourceVersion. Running it after the status/version writes above
// (which submit the in-memory copy) avoids a stale-RV 409 on the first migration
// reconcile. Set the stamp on the first converge that finds legacy artifacts
// (unless pruning immediately); clear it once a prune has removed everything.
if stampChanged, err := r.reconcileLegacyMigratedStamp(ctx, skyhook, prune, hadLegacyWorkloads); err != nil {
return false, err
} else if stampChanged {
updates = true
}
}
if len(errors) > 0 {
return false, utilerrors.NewAggregate(errors)
}
return updates, nil
}
// MIGRATION-SHIM: transition-only for the skyhook.nvidia.com -> nodewright.nvidia.com
// rename. Delete everything tagged MIGRATION-SHIM together with the legacy
// skyhook.nvidia.com group in the removal release (see docs/plans Phase 10).
//
// legacyMetadataPrefix is the metadata prefix the pre-rename operator stamped on
// package pods and per-node metadata ConfigMaps. It is intentionally hardcoded (a
// one-shot migration constant whose value can never change) so the controller keeps
// depending only on the new nodewright api group.
const legacyMetadataPrefix = "skyhook.nvidia.com"
// legacyMigratedAtAnnotation is stamped on a NodeWright (RFC3339) the first time its
// legacy skyhook.nvidia.com artifacts are adopted. The prune of those artifacts is
// deferred until LegacyCleanupDelay has elapsed since this time, giving a rollback
// window. MIGRATION-SHIM: remove with the legacy group.
const legacyMigratedAtAnnotation = v1alpha1.METADATA_PREFIX + "/legacy-migrated-at"
// legacyCleanupShouldPrune reports whether the legacy skyhook.nvidia.com artifacts for
// a NodeWright may be pruned yet. delay <= 0 prunes immediately (no rollback window).
// Otherwise a NodeWright is prunable only once delay has elapsed since its stamp; an
// absent stamp means "not yet adopted, converge first", and an unparseable stamp fails
// toward prune so a corrupt value cannot pin legacy state forever.
func legacyCleanupShouldPrune(stamp string, delay time.Duration, now time.Time) bool {
if delay <= 0 {
return true
}
if stamp == "" {
return false
}
t, err := time.Parse(time.RFC3339, stamp)
if err != nil {
return true
}
return !now.Before(t.Add(delay))
}
// MIGRATION-SHIM (see legacyMetadataPrefix): remove with the legacy group.
// reconcileLegacyLabeledWorkloads converges or prunes the workloads the pre-rename
// operator created under the legacy skyhook.nvidia.com labels for the named skyhook.
// Converge (prune=false) adds the nodewright label to the per-node metadata ConfigMaps
// alongside the legacy one and leaves the legacy package pods in place, so a rolled-back
// pre-rename operator still owns its workloads. Prune (prune=true) graceful-deletes the
// legacy package pods and drops the legacy ConfigMap label. Returns whether any legacy
// artifact was found and whether anything was written. Level-triggered and idempotent.
func (r *SkyhookReconciler) reconcileLegacyLabeledWorkloads(ctx context.Context, skyhookName string, prune bool) (bool, bool, error) {
hadLegacy := false
changed := false
pods := &corev1.PodList{}
if err := r.List(ctx, pods, client.InNamespace(r.opts.Namespace),
client.MatchingLabels{fmt.Sprintf("%s/name", legacyMetadataPrefix): skyhookName}); err != nil {
return false, false, fmt.Errorf("listing legacy-labeled pods for skyhook [%s]: %w", skyhookName, err)
}
if len(pods.Items) > 0 {
hadLegacy = true
}
if prune {
for i := range pods.Items {
// Graceful delete: honor the pod's terminationGracePeriodSeconds. Single-writer
// safety comes from the migration hold (the legacy Skyhook is complete, so its
// pods are no longer mutating the host), not from the grace period.
if err := r.Delete(ctx, &pods.Items[i]); err != nil && !apierrors.IsNotFound(err) {
return false, false, fmt.Errorf("deleting legacy-labeled pod [%s]: %w", pods.Items[i].Name, err)
}
changed = true
}
}
cms := &corev1.ConfigMapList{}
if err := r.List(ctx, cms, client.InNamespace(r.opts.Namespace),
client.MatchingLabels{fmt.Sprintf("%s/skyhook-node-meta", legacyMetadataPrefix): skyhookName}); err != nil {
return false, false, fmt.Errorf("listing legacy-labeled configmaps for skyhook [%s]: %w", skyhookName, err)
}
if len(cms.Items) > 0 {
hadLegacy = true
}
for i := range cms.Items {
cm := &cms.Items[i]
var mutated bool
if prune {
mutated = relabelLegacyMetadataPrefix(cm.Labels)
} else {
mutated = addNodeWrightMetaLabel(cm.Labels)
}
if mutated {
if err := r.Update(ctx, cm); err != nil {
return false, false, fmt.Errorf("updating legacy configmap labels [%s]: %w", cm.Name, err)
}
changed = true
}
}
return hadLegacy, changed, nil
}
// MIGRATION-SHIM (see legacyMetadataPrefix): remove with the legacy group.
// reconcileLegacyMigratedStamp stamps the NodeWright's legacy-migrated-at annotation
// the first time a converge finds legacy artifacts (starting the rollback window), and
// clears it once a prune has removed everything legacy. Returns whether it wrote.
func (r *SkyhookReconciler) reconcileLegacyMigratedStamp(ctx context.Context, skyhook SkyhookNodes, prune, hadLegacyWorkloads bool) (bool, error) {
nw := skyhook.GetSkyhook().NodeWright
stamp := nw.GetAnnotations()[legacyMigratedAtAnnotation]
name := skyhook.GetSkyhook().Name
if prune {
if stamp != "" && !hadLegacyWorkloads && !anyNodeHasLegacyMetadata(skyhook.GetNodes()) {
return true, r.patchLegacyMigratedStamp(ctx, name, "", true)
}
return false, nil
}
if stamp == "" && (hadLegacyWorkloads || anyNodeHasLegacyMetadata(skyhook.GetNodes())) {
return true, r.patchLegacyMigratedStamp(ctx, name, time.Now().Format(time.RFC3339), false)
}
return false, nil
}
// patchLegacyMigratedStamp sets or removes the legacy-migrated-at annotation on the
// NodeWright with a focused merge patch (re-read then patch, to avoid clobbering other
// concurrent writers and the annotation-nilling gotcha of a full update).
func (r *SkyhookReconciler) patchLegacyMigratedStamp(ctx context.Context, name, value string, remove bool) error {
nw, err := r.dal.GetSkyhook(ctx, name)
if err != nil {
return fmt.Errorf("getting nodewright to update legacy-migrated-at stamp [%s]: %w", name, err)
}
before := nw.DeepCopy()
annotations := nw.GetAnnotations()
if remove {
if annotations == nil {
return nil
}
delete(annotations, legacyMigratedAtAnnotation)
} else {
if annotations == nil {
annotations = map[string]string{}
}
annotations[legacyMigratedAtAnnotation] = value
}
nw.SetAnnotations(annotations)
if err := r.Patch(ctx, nw, client.MergeFrom(before)); err != nil {
return fmt.Errorf("patching legacy-migrated-at stamp on [%s]: %w", name, err)
}
return nil
}
// anyNodeHasLegacyMetadata reports whether any node still carries a legacy
// skyhook.nvidia.com-prefixed annotation, label, or condition.
func anyNodeHasLegacyMetadata(nodes []wrapper.SkyhookNode) bool {
for _, node := range nodes {
n := node.GetNode()
for k := range n.Annotations {
if strings.HasPrefix(k, legacyMetadataPrefix+"/") {
return true
}
}
for k := range n.Labels {
if strings.HasPrefix(k, legacyMetadataPrefix+"/") {
return true
}
}
for _, c := range n.Status.Conditions {
if strings.HasPrefix(string(c.Type), legacyMetadataPrefix+"/") {
return true
}
}
}
return false
}
// addNodeWrightMetaLabel adds a nodewright.nvidia.com-prefixed copy of each legacy
// skyhook.nvidia.com label, keeping the legacy label. Returns true if it added any.
func addNodeWrightMetaLabel(labels map[string]string) bool {
changed := false
var legacy []string
for k := range labels {
if strings.HasPrefix(k, legacyMetadataPrefix+"/") {
legacy = append(legacy, k)
}
}
for _, k := range legacy {
suffix := strings.TrimPrefix(k, legacyMetadataPrefix+"/")
newKey := fmt.Sprintf("%s/%s", v1alpha1.METADATA_PREFIX, suffix)
if _, exists := labels[newKey]; !exists {
labels[newKey] = labels[k]
changed = true
}
}
return changed
}
// MIGRATION-SHIM (see legacyMetadataPrefix): remove with the legacy group.
// relabelLegacyMetadataPrefix rewrites, in place, any label key under the legacy
// skyhook.nvidia.com prefix to the current nodewright.nvidia.com prefix, preserving
// the value. It returns true if it changed anything. Safe to mutate the map during
// the range: rewritten keys carry the new prefix, so CutPrefix skips them if the
// iteration happens to visit them.
func relabelLegacyMetadataPrefix(labels map[string]string) bool {
changed := false
for k, v := range labels {
suffix, ok := strings.CutPrefix(k, legacyMetadataPrefix+"/")
if !ok {
continue
}
delete(labels, k)
labels[fmt.Sprintf("%s/%s", v1alpha1.METADATA_PREFIX, suffix)] = v
changed = true
}
return changed
}
// ReportState computes and puts important information into the skyhook status so that monitoring tools such as k9s
// can see the information at a glance. For example, the number of completed nodes and the list of packages in the skyhook.
func (r *SkyhookReconciler) ReportState(ctx context.Context, clusterState *clusterState, skyhook SkyhookNodes) (bool, error) {
// save updated state to skyhook status
skyhook.ReportState()
if skyhook.GetSkyhook().Updated {
_, errs := r.SaveNodesAndSkyhook(ctx, clusterState, skyhook)
if len(errs) > 0 {
return false, utilerrors.NewAggregate(errs)
}
return true, nil
}
return false, nil
}
func (r *SkyhookReconciler) UpdatePauseStatus(ctx context.Context, clusterState *clusterState, skyhook SkyhookNodes) (bool, error) {
changed := UpdateSkyhookPauseStatus(skyhook, log.FromContext(ctx))
if changed {
_, errs := r.SaveNodesAndSkyhook(ctx, clusterState, skyhook)
if len(errs) > 0 {
return false, utilerrors.NewAggregate(errs)
}
return true, nil
}
return false, nil
}
func (r *SkyhookReconciler) TrackReboots(ctx context.Context, clusterState *clusterState) (bool, error) {
updates := false
errs := make([]error, 0)
for _, skyhook := range clusterState.skyhooks {
if skyhook.GetSkyhook().Status.NodeBootIds == nil {
skyhook.GetSkyhook().Status.NodeBootIds = make(map[string]string)
}
for _, node := range skyhook.GetNodes() {
id, ok := skyhook.GetSkyhook().Status.NodeBootIds[node.GetNode().Name]
if !ok { // new node
skyhook.GetSkyhook().Status.NodeBootIds[node.GetNode().Name] = node.GetNode().Status.NodeInfo.BootID
skyhook.GetSkyhook().Updated = true
}
if id != "" && id != node.GetNode().Status.NodeInfo.BootID { // node rebooted
if r.opts.ReapplyOnReboot {
r.recorder.Eventf(skyhook.GetSkyhook().NodeWright, nil, EventTypeNormal, EventsReasonNodeReboot, "ResetNodeState", "detected reboot, resetting node [%s] to be reapplied", node.GetNode().Name)
r.recorder.Eventf(node.GetNode(), nil, EventTypeNormal, EventsReasonNodeReboot, "ResetNodeState", "detected reboot, resetting node for [%s] to be reapplied", node.GetSkyhook().Name)
node.Reset()
// Re-apply the runtime-required taint so workloads cannot schedule on the
// rebooted node until Skyhook finishes re-applying. The original auto-taint
// annotation survives Reset() and remains the record that this taint is
// operator-managed; no annotation update is needed.
if skyhook.GetSkyhook().Spec.RuntimeRequired && skyhook.GetSkyhook().Spec.AutoTaintNewNodes {
taintToAdd := r.opts.GetRuntimeRequiredTaint()
newNode, updated, _ := taints.AddOrUpdateTaint(node.GetNode(), &taintToAdd)
if updated {
node.GetNode().Spec.Taints = newNode.Spec.Taints
log.FromContext(ctx).Info("re-applying runtime-required taint after reboot", "node", node.GetNode().Name, "taint", taintToAdd.Key)
}
}
// Persist the reset before recording the new boot id. We Patch rather than
// Update because a busy node's resourceVersion churns constantly under other
// controllers, and a full Update would lose that optimistic-concurrency race; a
// strategic merge of only our annotation/label changes does not. And we advance
// NodeBootIds only after the write is durable: if the reset never lands, leaving
// the boot id unchanged keeps the reboot pending so it is re-detected and retried
// next reconcile, instead of being silently consumed while the node's stale
// "complete" state remains and the package is never reapplied.
if node.Changed() {
updates = true
patch := client.StrategicMergeFrom(clusterState.tracker.GetOriginal(node.GetNode()))
if err := r.Patch(ctx, node.GetNode(), patch); err != nil {
errs = append(errs, fmt.Errorf("error patching node after reboot [%s]: %w", node.GetNode().Name, err))
continue
}
}
}
skyhook.GetSkyhook().Status.NodeBootIds[node.GetNode().Name] = node.GetNode().Status.NodeInfo.BootID
skyhook.GetSkyhook().Updated = true
}
}
if skyhook.GetSkyhook().Updated { // update
updates = true
err := r.Status().Update(ctx, skyhook.GetSkyhook().NodeWright)
if err != nil {
errs = append(errs, fmt.Errorf("error updating skyhook status after reboot [%s]: %w", skyhook.GetSkyhook().Name, err))
}
}
}
return updates, utilerrors.NewAggregate(errs)
}
// RunSkyhookPackages runs all skyhook packages then saves and requeues if changes were made
func (r *SkyhookReconciler) RunSkyhookPackages(ctx context.Context, clusterState *clusterState, nodePicker *NodePicker, skyhook SkyhookNodes) (*ctrl.Result, error) {
logger := log.FromContext(ctx)
requeue := false
beingDeleted := !skyhook.GetSkyhook().DeletionTimestamp.IsZero()
toExplicitUninstall, err := HandleUninstallRequests(skyhook)