• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

NVIDIA / skyhook / 20353746630

18 Dec 2025 10:50PM UTC coverage: 75.716% (-0.2%) from 75.958%
20353746630

Pull #133

github

web-flow
Merge a731af90a into 19dce4787
Pull Request #133: fix: cleanup cli code

29 of 63 new or added lines in 9 files covered. (46.03%)

11 existing lines in 6 files now uncovered.

5818 of 7684 relevant lines covered (75.72%)

1.12 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

84.25
/operator/internal/controller/skyhook_controller.go
1
/*
2
 * SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
3
 * SPDX-License-Identifier: Apache-2.0
4
 *
5
 *
6
 * Licensed under the Apache License, Version 2.0 (the "License");
7
 * you may not use this file except in compliance with the License.
8
 * You may obtain a copy of the License at
9
 *
10
 * http://www.apache.org/licenses/LICENSE-2.0
11
 *
12
 * Unless required by applicable law or agreed to in writing, software
13
 * distributed under the License is distributed on an "AS IS" BASIS,
14
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
 * See the License for the specific language governing permissions and
16
 * limitations under the License.
17
 */
18

19
package controller
20

21
import (
22
        "cmp"
23
        "context"
24
        "crypto/sha256"
25
        "encoding/hex"
26
        "encoding/json"
27
        "errors"
28
        "fmt"
29
        "reflect"
30
        "slices"
31
        "sort"
32
        "strings"
33
        "time"
34

35
        "github.com/NVIDIA/skyhook/operator/api/v1alpha1"
36
        "github.com/NVIDIA/skyhook/operator/internal/dal"
37
        "github.com/NVIDIA/skyhook/operator/internal/version"
38
        "github.com/NVIDIA/skyhook/operator/internal/wrapper"
39
        "github.com/go-logr/logr"
40

41
        corev1 "k8s.io/api/core/v1"
42
        policyv1 "k8s.io/api/policy/v1"
43
        apierrors "k8s.io/apimachinery/pkg/api/errors"
44
        "k8s.io/apimachinery/pkg/api/resource"
45
        metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
46
        "k8s.io/apimachinery/pkg/runtime"
47
        "k8s.io/apimachinery/pkg/types"
48
        utilerrors "k8s.io/apimachinery/pkg/util/errors"
49
        "k8s.io/client-go/tools/record"
50
        "k8s.io/kubernetes/pkg/util/taints"
51
        ctrl "sigs.k8s.io/controller-runtime"
52
        "sigs.k8s.io/controller-runtime/pkg/client"
53
        "sigs.k8s.io/controller-runtime/pkg/controller/controllerutil"
54
        "sigs.k8s.io/controller-runtime/pkg/handler"
55
        "sigs.k8s.io/controller-runtime/pkg/log"
56
        "sigs.k8s.io/controller-runtime/pkg/reconcile"
57
)
58

59
const (
60
        EventsReasonSkyhookApply       = "Apply"
61
        EventsReasonSkyhookInterrupt   = "Interrupt"
62
        EventsReasonSkyhookDrain       = "Drain"
63
        EventsReasonSkyhookStateChange = "State"
64
        EventsReasonNodeReboot         = "Reboot"
65
        EventTypeNormal                = "Normal"
66
        // EventTypeWarning = "Warning"
67
        TaintUnschedulable     = corev1.TaintNodeUnschedulable
68
        InterruptContainerName = "interrupt"
69

70
        SkyhookFinalizer = "skyhook.nvidia.com/skyhook"
71
)
72

73
type SkyhookOperatorOptions struct {
74
        Namespace            string        `env:"NAMESPACE, default=skyhook"`
75
        MaxInterval          time.Duration `env:"DEFAULT_INTERVAL, default=10m"`
76
        ImagePullSecret      string        `env:"IMAGE_PULL_SECRET, default=node-init-secret"` //TODO: should this be defaulted?
77
        CopyDirRoot          string        `env:"COPY_DIR_ROOT, default=/var/lib/skyhook"`
78
        ReapplyOnReboot      bool          `env:"REAPPLY_ON_REBOOT, default=false"`
79
        RuntimeRequiredTaint string        `env:"RUNTIME_REQUIRED_TAINT, default=skyhook.nvidia.com=runtime-required:NoSchedule"`
80
        PauseImage           string        `env:"PAUSE_IMAGE, default=registry.k8s.io/pause:3.10"`
81
        AgentImage           string        `env:"AGENT_IMAGE, default=ghcr.io/nvidia/skyhook/agent:latest"` // TODO: this needs to be updated with a working default
82
        AgentLogRoot         string        `env:"AGENT_LOG_ROOT, default=/var/log/skyhook"`
83
}
84

85
func (o *SkyhookOperatorOptions) Validate() error {
2✔
86

2✔
87
        messages := make([]string, 0)
2✔
88
        if o.Namespace == "" {
2✔
89
                messages = append(messages, "namespace must be set")
×
90
        }
×
91
        if o.CopyDirRoot == "" {
2✔
92
                messages = append(messages, "copy dir root must be set")
×
93
        }
×
94
        if o.RuntimeRequiredTaint == "" {
2✔
95
                messages = append(messages, "runtime required taint must be set")
×
96
        }
×
97
        if o.MaxInterval < time.Minute {
3✔
98
                messages = append(messages, "max interval must be at least 1 minute")
1✔
99
        }
1✔
100

101
        // CopyDirRoot must start with /
102
        if !strings.HasPrefix(o.CopyDirRoot, "/") {
3✔
103
                messages = append(messages, "copy dir root must start with /")
1✔
104
        }
1✔
105

106
        // RuntimeRequiredTaint must be parsable and must not be a deletion
107
        _, delete, err := taints.ParseTaints([]string{o.RuntimeRequiredTaint})
2✔
108
        if err != nil {
3✔
109
                messages = append(messages, fmt.Sprintf("runtime required taint is invalid: %s", err.Error()))
1✔
110
        }
1✔
111
        if len(delete) > 0 {
3✔
112
                messages = append(messages, "runtime required taint must not be a deletion")
1✔
113
        }
1✔
114

115
        if o.AgentImage == "" {
3✔
116
                messages = append(messages, "agent image must be set")
1✔
117
        }
1✔
118

119
        if !strings.Contains(o.AgentImage, ":") {
3✔
120
                messages = append(messages, "agent image must contain a tag")
1✔
121
        }
1✔
122

123
        if o.PauseImage == "" {
3✔
124
                messages = append(messages, "pause image must be set")
1✔
125
        }
1✔
126

127
        if !strings.Contains(o.PauseImage, ":") {
3✔
128
                messages = append(messages, "pause image must contain a tag")
1✔
129
        }
1✔
130

131
        if len(messages) > 0 {
3✔
132
                return errors.New(strings.Join(messages, ", "))
1✔
133
        }
1✔
134

135
        return nil
2✔
136
}
137

138
// AgentVersion returns the image tag portion of AgentImage
139
func (o *SkyhookOperatorOptions) AgentVersion() string {
2✔
140
        parts := strings.Split(o.AgentImage, ":")
2✔
141
        return parts[len(parts)-1]
2✔
142
}
2✔
143

144
func (o *SkyhookOperatorOptions) GetRuntimeRequiredTaint() corev1.Taint {
2✔
145
        to_add, _, _ := taints.ParseTaints([]string{o.RuntimeRequiredTaint})
2✔
146
        return to_add[0]
2✔
147
}
2✔
148

149
func (o *SkyhookOperatorOptions) GetRuntimeRequiredToleration() corev1.Toleration {
2✔
150
        taint := o.GetRuntimeRequiredTaint()
2✔
151
        return corev1.Toleration{
2✔
152
                Key:      taint.Key,
2✔
153
                Operator: corev1.TolerationOpEqual,
2✔
154
                Value:    taint.Value,
2✔
155
                Effect:   taint.Effect,
2✔
156
        }
2✔
157
}
2✔
158

159
// force type checking against this interface
160
var _ reconcile.Reconciler = &SkyhookReconciler{}
161

162
func NewSkyhookReconciler(schema *runtime.Scheme, c client.Client, recorder record.EventRecorder, opts SkyhookOperatorOptions) (*SkyhookReconciler, error) {
2✔
163

2✔
164
        err := opts.Validate()
2✔
165
        if err != nil {
2✔
166
                return nil, fmt.Errorf("invalid skyhook operator options: %w", err)
×
167
        }
×
168

169
        return &SkyhookReconciler{
2✔
170
                Client:   c,
2✔
171
                scheme:   schema,
2✔
172
                recorder: recorder,
2✔
173
                opts:     opts,
2✔
174
                dal:      dal.New(c),
2✔
175
        }, nil
2✔
176
}
177

178
// SkyhookReconciler reconciles a Skyhook object
179
type SkyhookReconciler struct {
180
        client.Client
181
        scheme   *runtime.Scheme
182
        recorder record.EventRecorder
183
        opts     SkyhookOperatorOptions
184
        dal      dal.DAL
185
}
186

187
// SetupWithManager sets up the controller with the Manager.
188
func (r *SkyhookReconciler) SetupWithManager(mgr ctrl.Manager) error {
2✔
189

2✔
190
        // indexes allow for query on fields to use the local cache
2✔
191
        indexer := mgr.GetFieldIndexer()
2✔
192
        err := indexer.
2✔
193
                IndexField(context.TODO(), &corev1.Pod{}, "spec.nodeName", func(o client.Object) []string {
3✔
194
                        pod, ok := o.(*corev1.Pod)
1✔
195
                        if !ok {
1✔
196
                                return nil
×
197
                        }
×
198
                        return []string{pod.Spec.NodeName}
1✔
199
                })
200

201
        if err != nil {
2✔
202
                return err
×
203
        }
×
204

205
        ehandler := &eventHandler{
2✔
206
                logger: mgr.GetLogger(),
2✔
207
                dal:    dal.New(r.Client),
2✔
208
        }
2✔
209

2✔
210
        return ctrl.NewControllerManagedBy(mgr).
2✔
211
                For(&v1alpha1.Skyhook{}).
2✔
212
                Watches(
2✔
213
                        &corev1.Pod{},
2✔
214
                        handler.EnqueueRequestsFromMapFunc(podHandlerFunc),
2✔
215
                ).
2✔
216
                Watches(
2✔
217
                        &corev1.Node{},
2✔
218
                        ehandler,
2✔
219
                ).
2✔
220
                Complete(r)
2✔
221
}
222

223
// CRD Permissions
224
//+kubebuilder:rbac:groups=skyhook.nvidia.com,resources=skyhooks,verbs=get;list;watch;create;update;patch;delete
225
//+kubebuilder:rbac:groups=skyhook.nvidia.com,resources=skyhooks/status,verbs=get;update;patch
226
//+kubebuilder:rbac:groups=skyhook.nvidia.com,resources=skyhooks/finalizers,verbs=update
227

228
// core permissions
229
//+kubebuilder:rbac:groups=core,resources=nodes,verbs=get;list;update;patch;watch
230
//+kubebuilder:rbac:groups=core,resources=nodes/status,verbs=get;update;patch
231
//+kubebuilder:rbac:groups=core,resources=pods/eviction,verbs=create
232
//+kubebuilder:rbac:groups=core,resources=events,verbs=create;patch
233
//+kubebuilder:rbac:groups=core,resources=configmaps,verbs=get;list;watch;create;update;patch;delete
234

235
// Reconcile is part of the main kubernetes reconciliation loop which aims to
236
// move the current state of the cluster closer to the desired state.
237
// - https://pkg.go.dev/sigs.k8s.io/controller-runtime@v0.16.3/pkg/reconcile
238
func (r *SkyhookReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {
2✔
239
        logger := log.FromContext(ctx)
2✔
240
        // split off requests for pods
2✔
241
        if strings.HasPrefix(req.Name, "pod---") {
3✔
242
                name := strings.Split(req.Name, "pod---")[1]
1✔
243
                pod, err := r.dal.GetPod(ctx, req.Namespace, name)
1✔
244
                if err == nil && pod != nil { // if pod, then call other wise not a pod
2✔
245
                        return r.PodReconcile(ctx, pod)
1✔
246
                }
1✔
247
                return ctrl.Result{}, err
1✔
248
        }
249

250
        // get all skyhooks (SCR)
251
        skyhooks, err := r.dal.GetSkyhooks(ctx)
2✔
252
        if err != nil {
2✔
253
                // error, going to requeue and backoff
×
254
                logger.Error(err, "error getting skyhooks")
×
255
                return ctrl.Result{}, err
×
256
        }
×
257

258
        // if there are no skyhooks, so actually nothing to do, so don't requeue
259
        if skyhooks == nil || len(skyhooks.Items) == 0 {
4✔
260
                return ctrl.Result{}, nil
2✔
261
        }
2✔
262

263
        // get all nodes
264
        nodes, err := r.dal.GetNodes(ctx)
1✔
265
        if err != nil {
1✔
266
                // error, going to requeue and backoff
×
267
                logger.Error(err, "error getting nodes")
×
268
                return ctrl.Result{}, err
×
269
        }
×
270

271
        // if no nodes, well not work to do either
272
        if nodes == nil || len(nodes.Items) == 0 {
1✔
273
                // no nodes, so nothing to do
×
274
                return ctrl.Result{}, nil
×
275
        }
×
276

277
        // get all deployment policies
278
        deploymentPolicies, err := r.dal.GetDeploymentPolicies(ctx)
1✔
279
        if err != nil {
1✔
280
                logger.Error(err, "error getting deployment policies")
×
281
                return ctrl.Result{}, err
×
282
        }
×
283

284
        // TODO: this build state could error in a lot of ways, and I think we might want to move towards partial state
285
        // mean if we cant get on SCR state, great, process that one and error
286

287
        // BUILD cluster state from all skyhooks, and all nodes
288
        // this filters and pairs up nodes to skyhooks, also provides help methods for introspection and mutation
289
        clusterState, err := BuildState(skyhooks, nodes, deploymentPolicies)
1✔
290
        if err != nil {
1✔
291
                // error, going to requeue and backoff
×
292
                logger.Error(err, "error building cluster state")
×
293
                return ctrl.Result{}, err
×
294
        }
×
295

296
        if yes, result, err := shouldReturn(r.HandleMigrations(ctx, clusterState)); yes {
2✔
297
                return result, err
1✔
298
        }
1✔
299

300
        if yes, result, err := shouldReturn(r.TrackReboots(ctx, clusterState)); yes {
2✔
301
                return result, err
1✔
302
        }
1✔
303

304
        // node picker is for selecting nodes to do work, tries maintain a prior of nodes between SCRs
305
        nodePicker := NewNodePicker(r.opts.GetRuntimeRequiredToleration())
1✔
306

1✔
307
        errs := make([]error, 0)
1✔
308
        var result *ctrl.Result
1✔
309

1✔
310
        for _, skyhook := range clusterState.skyhooks {
2✔
311
                if yes, result, err := shouldReturn(r.HandleFinalizer(ctx, skyhook)); yes {
2✔
312
                        return result, err
1✔
313
                }
1✔
314

315
                if yes, result, err := shouldReturn(r.ReportState(ctx, clusterState, skyhook)); yes {
2✔
316
                        return result, err
1✔
317
                }
1✔
318

319
                if skyhook.IsPaused() {
2✔
320
                        if yes, result, err := shouldReturn(r.UpdatePauseStatus(ctx, clusterState, skyhook)); yes {
2✔
321
                                return result, err
1✔
322
                        }
1✔
323
                        continue
1✔
324
                }
325

326
                if yes, result, err := r.validateAndUpsertSkyhookData(ctx, skyhook, clusterState); yes {
2✔
327
                        return result, err
1✔
328
                }
1✔
329

330
                changed := IntrospectSkyhook(skyhook, clusterState.skyhooks)
1✔
331
                if changed {
2✔
332
                        _, errs := r.SaveNodesAndSkyhook(ctx, clusterState, skyhook)
1✔
333
                        if len(errs) > 0 {
2✔
334
                                return ctrl.Result{RequeueAfter: time.Second * 2}, utilerrors.NewAggregate(errs)
1✔
335
                        }
1✔
336
                        return ctrl.Result{RequeueAfter: time.Second * 2}, nil
1✔
337
                }
338

339
                _, err := HandleVersionChange(skyhook)
1✔
340
                if err != nil {
1✔
341
                        return ctrl.Result{RequeueAfter: time.Second * 2}, fmt.Errorf("error getting packages to uninstall: %w", err)
×
342
                }
×
343
        }
344

345
        skyhook := GetNextSkyhook(clusterState.skyhooks)
1✔
346
        if skyhook != nil && !skyhook.IsPaused() {
2✔
347

1✔
348
                result, err = r.RunSkyhookPackages(ctx, clusterState, nodePicker, skyhook)
1✔
349
                if err != nil {
2✔
350
                        logger.Error(err, "error processing skyhook", "skyhook", skyhook.GetSkyhook().Name)
1✔
351
                        errs = append(errs, err)
1✔
352
                }
1✔
353
        }
354

355
        err = r.HandleRuntimeRequired(ctx, clusterState)
1✔
356
        if err != nil {
1✔
357
                errs = append(errs, err)
×
358
        }
×
359

360
        if len(errs) > 0 {
2✔
361
                err := utilerrors.NewAggregate(errs)
1✔
362
                return ctrl.Result{}, err
1✔
363
        }
1✔
364

365
        if result != nil {
2✔
366
                return *result, nil
1✔
367
        }
1✔
368

369
        // default happy retry after max
370
        return ctrl.Result{RequeueAfter: r.opts.MaxInterval}, nil
1✔
371
}
372

373
func shouldReturn(updates bool, err error) (bool, ctrl.Result, error) {
1✔
374
        if err != nil {
2✔
375
                return true, ctrl.Result{}, err
1✔
376
        }
1✔
377
        if updates {
2✔
378
                return true, ctrl.Result{RequeueAfter: time.Second * 2}, nil
1✔
379
        }
1✔
380
        return false, ctrl.Result{}, nil
1✔
381
}
382

383
func (r *SkyhookReconciler) HandleMigrations(ctx context.Context, clusterState *clusterState) (bool, error) {
1✔
384

1✔
385
        updates := false
1✔
386

1✔
387
        if version.VERSION == "" {
1✔
388
                // this means the binary was complied without version information
×
389
                return false, nil
×
390
        }
×
391

392
        logger := log.FromContext(ctx)
1✔
393
        errors := make([]error, 0)
1✔
394
        for _, skyhook := range clusterState.skyhooks {
2✔
395

1✔
396
                err := skyhook.Migrate(logger)
1✔
397
                if err != nil {
1✔
398
                        return false, fmt.Errorf("error migrating skyhook [%s]: %w", skyhook.GetSkyhook().Name, err)
×
399
                }
×
400

401
                if err := skyhook.GetSkyhook().Skyhook.Validate(); err != nil {
1✔
402
                        return false, fmt.Errorf("error validating skyhook [%s]: %w", skyhook.GetSkyhook().Name, err)
×
403
                }
×
404

405
                for _, node := range skyhook.GetNodes() {
2✔
406
                        if node.Changed() {
2✔
407
                                err := r.Status().Patch(ctx, node.GetNode(), client.MergeFrom(clusterState.tracker.GetOriginal(node.GetNode())))
1✔
408
                                if err != nil {
1✔
409
                                        errors = append(errors, fmt.Errorf("error patching node [%s]: %w", node.GetNode().Name, err))
×
410
                                }
×
411

412
                                err = r.Patch(ctx, node.GetNode(), client.MergeFrom(clusterState.tracker.GetOriginal(node.GetNode())))
1✔
413
                                if err != nil {
1✔
UNCOV
414
                                        errors = append(errors, fmt.Errorf("error patching node [%s]: %w", node.GetNode().Name, err))
×
UNCOV
415
                                }
×
416
                                updates = true
1✔
417
                        }
418
                }
419

420
                if skyhook.GetSkyhook().Updated {
2✔
421
                        // need to do this because SaveNodesAndSkyhook only saves skyhook status, not the main skyhook object where the annotations are
1✔
422
                        // additionally it needs to be an update, a patch nils out the annotations for some reason, which the save function does a patch
1✔
423

1✔
424
                        if err = r.Status().Update(ctx, skyhook.GetSkyhook().Skyhook); err != nil {
2✔
425
                                return false, fmt.Errorf("error updating during migration skyhook status [%s]: %w", skyhook.GetSkyhook().Name, err)
1✔
426
                        }
1✔
427

428
                        // because of conflict issues (409) we need to do things a bit differently here.
429
                        // We might be able to use server side apply in the future, but for now we need to do this
430
                        // https://kubernetes.io/docs/reference/using-api/server-side-apply/
431
                        // https://github.com/kubernetes-sigs/controller-runtime/issues/347
432

433
                        // work around for now is to grab a new copy of the object, and then patch it
434

435
                        newskyhook, err := r.dal.GetSkyhook(ctx, skyhook.GetSkyhook().Name)
1✔
436
                        if err != nil {
1✔
437
                                return false, fmt.Errorf("error getting skyhook to migrate [%s]: %w", skyhook.GetSkyhook().Name, err)
×
438
                        }
×
439
                        newPatch := client.MergeFrom(newskyhook.DeepCopy())
1✔
440

1✔
441
                        // set version
1✔
442
                        wrapper.NewSkyhookWrapper(newskyhook).SetVersion()
1✔
443

1✔
444
                        if err = r.Patch(ctx, newskyhook, newPatch); err != nil {
1✔
445
                                return false, fmt.Errorf("error updating during migration skyhook [%s]: %w", skyhook.GetSkyhook().Name, err)
×
446
                        }
×
447

448
                        updates = true
1✔
449
                }
450
        }
451

452
        if len(errors) > 0 {
1✔
UNCOV
453
                return false, utilerrors.NewAggregate(errors)
×
UNCOV
454
        }
×
455

456
        return updates, nil
1✔
457
}
458

459
// ReportState computes and puts important information into the skyhook status so that monitoring tools such as k9s
460
// can see the information at a glance. For example, the number of completed nodes and the list of packages in the skyhook.
461
func (r *SkyhookReconciler) ReportState(ctx context.Context, clusterState *clusterState, skyhook SkyhookNodes) (bool, error) {
1✔
462

1✔
463
        // save updated state to skyhook status
1✔
464
        skyhook.ReportState()
1✔
465

1✔
466
        if skyhook.GetSkyhook().Updated {
2✔
467
                _, errs := r.SaveNodesAndSkyhook(ctx, clusterState, skyhook)
1✔
468
                if len(errs) > 0 {
1✔
469
                        return false, utilerrors.NewAggregate(errs)
×
470
                }
×
471
                return true, nil
1✔
472
        }
473

474
        return false, nil
1✔
475
}
476

477
func (r *SkyhookReconciler) UpdatePauseStatus(ctx context.Context, clusterState *clusterState, skyhook SkyhookNodes) (bool, error) {
1✔
478
        changed := UpdateSkyhookPauseStatus(skyhook)
1✔
479

1✔
480
        if changed {
2✔
481
                _, errs := r.SaveNodesAndSkyhook(ctx, clusterState, skyhook)
1✔
482
                if len(errs) > 0 {
1✔
483
                        return false, utilerrors.NewAggregate(errs)
×
484
                }
×
485
                return true, nil
1✔
486
        }
487

488
        return false, nil
1✔
489
}
490

491
func (r *SkyhookReconciler) TrackReboots(ctx context.Context, clusterState *clusterState) (bool, error) {
1✔
492

1✔
493
        updates := false
1✔
494
        errs := make([]error, 0)
1✔
495

1✔
496
        for _, skyhook := range clusterState.skyhooks {
2✔
497
                if skyhook.GetSkyhook().Status.NodeBootIds == nil {
2✔
498
                        skyhook.GetSkyhook().Status.NodeBootIds = make(map[string]string)
1✔
499
                }
1✔
500

501
                for _, node := range skyhook.GetNodes() {
2✔
502
                        id, ok := skyhook.GetSkyhook().Status.NodeBootIds[node.GetNode().Name]
1✔
503

1✔
504
                        if !ok { // new node
2✔
505
                                skyhook.GetSkyhook().Status.NodeBootIds[node.GetNode().Name] = node.GetNode().Status.NodeInfo.BootID
1✔
506
                                skyhook.GetSkyhook().Updated = true
1✔
507
                        }
1✔
508

509
                        if id != "" && id != node.GetNode().Status.NodeInfo.BootID { // node rebooted
1✔
510
                                if r.opts.ReapplyOnReboot {
×
511
                                        r.recorder.Eventf(skyhook.GetSkyhook().Skyhook, EventTypeNormal, EventsReasonNodeReboot, "detected reboot, resetting node [%s] to be reapplied", node.GetNode().Name)
×
512
                                        r.recorder.Eventf(node.GetNode(), EventTypeNormal, EventsReasonNodeReboot, "detected reboot, resetting node for [%s] to be reapplied", node.GetSkyhook().Name)
×
513
                                        node.Reset()
×
514
                                }
×
515
                                skyhook.GetSkyhook().Status.NodeBootIds[node.GetNode().Name] = node.GetNode().Status.NodeInfo.BootID
×
516
                                skyhook.GetSkyhook().Updated = true
×
517
                        }
518

519
                        if node.Changed() { // update
1✔
520
                                updates = true
×
521
                                err := r.Update(ctx, node.GetNode())
×
522
                                if err != nil {
×
523
                                        errs = append(errs, fmt.Errorf("error updating node after reboot [%s]: %w", node.GetNode().Name, err))
×
524
                                }
×
525
                        }
526
                }
527
                if skyhook.GetSkyhook().Updated { // update
2✔
528
                        updates = true
1✔
529
                        err := r.Status().Update(ctx, skyhook.GetSkyhook().Skyhook)
1✔
530
                        if err != nil {
2✔
531
                                errs = append(errs, fmt.Errorf("error updating skyhook status after reboot [%s]: %w", skyhook.GetSkyhook().Name, err))
1✔
532
                        }
1✔
533
                }
534
        }
535

536
        return updates, utilerrors.NewAggregate(errs)
1✔
537
}
538

539
// RunSkyhookPackages runs all skyhook packages then saves and requeues if changes were made
540
func (r *SkyhookReconciler) RunSkyhookPackages(ctx context.Context, clusterState *clusterState, nodePicker *NodePicker, skyhook SkyhookNodes) (*ctrl.Result, error) {
1✔
541

1✔
542
        logger := log.FromContext(ctx)
1✔
543
        requeue := false
1✔
544

1✔
545
        toUninstall, err := HandleVersionChange(skyhook)
1✔
546
        if err != nil {
1✔
547
                return nil, fmt.Errorf("error getting packages to uninstall: %w", err)
×
548
        }
×
549

550
        changed := IntrospectSkyhook(skyhook, clusterState.skyhooks)
1✔
551
        if !changed && skyhook.IsComplete() {
1✔
552
                return nil, nil
×
553
        }
×
554

555
        selectedNode := nodePicker.SelectNodes(skyhook)
1✔
556

1✔
557
        for _, node := range selectedNode {
2✔
558

1✔
559
                if node.IsComplete() && !node.Changed() {
1✔
560
                        continue
×
561
                }
562

563
                toRun, err := node.RunNext()
1✔
564
                if err != nil {
1✔
565
                        return nil, fmt.Errorf("error getting next packages to run: %w", err)
×
566
                }
×
567

568
                // prepend the uninstall packages so they are ran first
569
                toRun = append(toUninstall, toRun...)
1✔
570

1✔
571
                interrupt, pack := fudgeInterruptWithPriority(toRun, skyhook.GetSkyhook().GetConfigUpdates(), skyhook.GetSkyhook().GetConfigInterrupts())
1✔
572

1✔
573
                for _, f := range toRun {
2✔
574

1✔
575
                        ok, err := r.ProcessInterrupt(ctx, node, f, interrupt, interrupt != nil && f.Name == pack)
1✔
576
                        if err != nil {
1✔
577
                                // TODO: error handle
×
578
                                return nil, fmt.Errorf("error processing if we should interrupt [%s:%s]: %w", f.Name, f.Version, err)
×
579
                        }
×
580
                        if !ok {
2✔
581
                                requeue = true
1✔
582
                                continue
1✔
583
                        }
584

585
                        err = r.ApplyPackage(ctx, logger, clusterState, node, f, interrupt != nil && f.Name == pack)
1✔
586
                        if err != nil {
1✔
587
                                return nil, fmt.Errorf("error applying package [%s:%s]: %w", f.Name, f.Version, err)
×
588
                        }
×
589

590
                        // process one package at a time
591
                        if skyhook.GetSkyhook().Spec.Serial {
1✔
592
                                return &ctrl.Result{Requeue: true}, nil
×
593
                        }
×
594
                }
595
        }
596

597
        saved, errs := r.SaveNodesAndSkyhook(ctx, clusterState, skyhook)
1✔
598
        if len(errs) > 0 {
2✔
599
                return &ctrl.Result{}, utilerrors.NewAggregate(errs)
1✔
600
        }
1✔
601
        if saved {
2✔
602
                requeue = true
1✔
603
        }
1✔
604

605
        if !skyhook.IsComplete() || requeue {
2✔
606
                return &ctrl.Result{RequeueAfter: time.Second * 2}, nil // not sure this is better then just requeue bool
1✔
607
        }
1✔
608

609
        return nil, utilerrors.NewAggregate(errs)
×
610
}
611

612
// SaveNodesAndSkyhook saves nodes and skyhook and will update the events if the skyhook status changes
613
func (r *SkyhookReconciler) SaveNodesAndSkyhook(ctx context.Context, clusterState *clusterState, skyhook SkyhookNodes) (bool, []error) {
1✔
614
        saved := false
1✔
615
        errs := make([]error, 0)
1✔
616

1✔
617
        for _, node := range skyhook.GetNodes() {
2✔
618
                patch := client.StrategicMergeFrom(clusterState.tracker.GetOriginal(node.GetNode()))
1✔
619
                if node.Changed() {
2✔
620
                        err := r.Patch(ctx, node.GetNode(), patch)
1✔
621
                        if err != nil {
1✔
622
                                errs = append(errs, fmt.Errorf("error patching node [%s]: %w", node.GetNode().Name, err))
×
623
                        }
×
624
                        saved = true
1✔
625

1✔
626
                        err = r.UpsertNodeLabelsAnnotationsPackages(ctx, skyhook.GetSkyhook(), node.GetNode())
1✔
627
                        if err != nil {
1✔
628
                                errs = append(errs, fmt.Errorf("error upserting labels, annotations, and packages config map for node [%s]: %w", node.GetNode().Name, err))
×
629
                        }
×
630

631
                        if node.IsComplete() {
2✔
632
                                r.recorder.Eventf(node.GetNode(), EventTypeNormal, EventsReasonSkyhookStateChange, "Skyhook [%s] complete.", skyhook.GetSkyhook().Name)
1✔
633

1✔
634
                                // since node is complete remove from priority
1✔
635
                                if _, ok := skyhook.GetSkyhook().Status.NodePriority[node.GetNode().Name]; ok {
2✔
636
                                        delete(skyhook.GetSkyhook().Status.NodePriority, node.GetNode().Name)
1✔
637
                                        skyhook.GetSkyhook().Updated = true
1✔
638
                                }
1✔
639
                        }
640
                }
641

642
                // updates node's condition
643
                node.UpdateCondition()
1✔
644
                if node.Changed() {
2✔
645
                        // conditions are in status
1✔
646
                        err := r.Status().Patch(ctx, node.GetNode(), patch)
1✔
647
                        if err != nil {
2✔
648
                                errs = append(errs, fmt.Errorf("error patching node status [%s]: %w", node.GetNode().Name, err))
1✔
649
                        }
1✔
650
                        saved = true
1✔
651
                }
652

653
                if node.GetSkyhook() != nil && node.GetSkyhook().Updated {
2✔
654
                        skyhook.GetSkyhook().Updated = true
1✔
655
                }
1✔
656
        }
657

658
        if skyhook.GetSkyhook().Updated {
2✔
659
                patch := client.MergeFrom(clusterState.tracker.GetOriginal(skyhook.GetSkyhook().Skyhook))
1✔
660
                err := r.Status().Patch(ctx, skyhook.GetSkyhook().Skyhook, patch)
1✔
661
                if err != nil {
1✔
662
                        errs = append(errs, err)
×
663
                }
×
664
                saved = true
1✔
665

1✔
666
                if skyhook.GetPriorStatus() != "" && skyhook.GetPriorStatus() != skyhook.Status() {
2✔
667
                        // we transitioned, fire event
1✔
668
                        r.recorder.Eventf(skyhook.GetSkyhook(), EventTypeNormal, EventsReasonSkyhookStateChange, "Skyhook transitioned [%s] -> [%s]", skyhook.GetPriorStatus(), skyhook.Status())
1✔
669
                }
1✔
670
        }
671

672
        if len(errs) > 0 {
2✔
673
                saved = false
1✔
674
        }
1✔
675
        return saved, errs
1✔
676
}
677

678
// HandleVersionChange updates the state for the node or skyhook if a version is changed on a package
679
func HandleVersionChange(skyhook SkyhookNodes) ([]*v1alpha1.Package, error) {
1✔
680
        toUninstall := make([]*v1alpha1.Package, 0)
1✔
681

1✔
682
        for _, node := range skyhook.GetNodes() {
2✔
683
                nodeState, err := node.State()
1✔
684
                if err != nil {
1✔
685
                        return nil, err
×
686
                }
×
687

688
                for _, packageStatus := range nodeState {
2✔
689
                        upgrade := false
1✔
690

1✔
691
                        _package, exists := skyhook.GetSkyhook().Spec.Packages[packageStatus.Name]
1✔
692
                        if exists && _package.Version == packageStatus.Version {
2✔
693
                                continue // no uninstall needed for package
1✔
694
                        }
695

696
                        packageStatusRef := v1alpha1.PackageRef{
1✔
697
                                Name:    packageStatus.Name,
1✔
698
                                Version: packageStatus.Version,
1✔
699
                        }
1✔
700

1✔
701
                        if !exists && packageStatus.Stage != v1alpha1.StageUninstall {
2✔
702
                                // Start uninstall of old package
1✔
703
                                err := node.Upsert(packageStatusRef, packageStatus.Image, v1alpha1.StateInProgress, v1alpha1.StageUninstall, 0, "")
1✔
704
                                if err != nil {
1✔
705
                                        return nil, fmt.Errorf("error updating node status: %w", err)
×
706
                                }
×
707
                        } else if exists && _package.Version != packageStatus.Version {
2✔
708
                                comparison := version.Compare(_package.Version, packageStatus.Version)
1✔
709
                                if comparison == -2 {
1✔
710
                                        return nil, errors.New("error comparing package versions: invalid version string provided enabling webhooks validates versions before being applied")
×
711
                                }
×
712

713
                                if comparison == 1 {
2✔
714
                                        _packageStatus, found := node.PackageStatus(_package.GetUniqueName())
1✔
715
                                        if found && _packageStatus.Stage == v1alpha1.StageUpgrade {
2✔
716
                                                continue
1✔
717
                                        }
718

719
                                        // start upgrade of package
720
                                        err := node.Upsert(_package.PackageRef, _package.Image, v1alpha1.StateInProgress, v1alpha1.StageUpgrade, 0, _package.ContainerSHA)
1✔
721
                                        if err != nil {
1✔
722
                                                return nil, fmt.Errorf("error updating node status: %w", err)
×
723
                                        }
×
724

725
                                        upgrade = true
1✔
726
                                } else if comparison == -1 && packageStatus.Stage != v1alpha1.StageUninstall {
2✔
727
                                        // Start uninstall of old package
1✔
728
                                        err := node.Upsert(packageStatusRef, packageStatus.Image, v1alpha1.StateInProgress, v1alpha1.StageUninstall, 0, "")
1✔
729
                                        if err != nil {
1✔
730
                                                return nil, fmt.Errorf("error updating node status: %w", err)
×
731
                                        }
×
732

733
                                        // If version changed then update new version to wait
734
                                        err = node.Upsert(_package.PackageRef, _package.Image, v1alpha1.StateSkipped, v1alpha1.StageUninstall, 0, _package.ContainerSHA)
1✔
735
                                        if err != nil {
1✔
736
                                                return nil, fmt.Errorf("error updating node status: %w", err)
×
737
                                        }
×
738
                                }
739
                        }
740

741
                        // only need to create a feaux package for uninstall since it won't be in the DAG (Upgrade will)
742
                        newPackageStatus, found := node.PackageStatus(packageStatusRef.GetUniqueName())
1✔
743
                        if !upgrade && found && newPackageStatus.Stage == v1alpha1.StageUninstall && newPackageStatus.State == v1alpha1.StateInProgress {
2✔
744
                                // create fake package with the info we can salvage from the node state
1✔
745
                                newPackage := &v1alpha1.Package{
1✔
746
                                        PackageRef: packageStatusRef,
1✔
747
                                        Image:      packageStatus.Image,
1✔
748
                                }
1✔
749

1✔
750
                                // Add package to uninstall list if it's not already present
1✔
751
                                found := false
1✔
752
                                for _, uninstallPackage := range toUninstall {
2✔
753
                                        if reflect.DeepEqual(uninstallPackage, newPackage) {
1✔
754
                                                found = true
×
755
                                        }
×
756
                                }
757

758
                                if !found {
2✔
759
                                        toUninstall = append(toUninstall, newPackage)
1✔
760
                                }
1✔
761
                        }
762

763
                        // remove all config updates for the package since it's being uninstalled or
764
                        // upgraded. NOTE: The config updates must be removed whenever the version changes
765
                        // or else the package interrupt may be skipped if there is one
766
                        skyhook.GetSkyhook().RemoveConfigUpdates(_package.Name)
1✔
767

1✔
768
                        // set the node and skyhook status to in progress
1✔
769
                        node.SetStatus(v1alpha1.StatusInProgress)
1✔
770
                }
771
        }
772

773
        return toUninstall, nil
1✔
774
}
775

776
// helper for get a point to a ref
777
func ptr[E any](e E) *E {
2✔
778
        return &e
2✔
779
}
2✔
780

781
// generateSafeName generates a consistent name for Kubernetes resources that is unique
782
// while staying within the specified character limit
783
func generateSafeName(maxLen int, nameParts ...string) string {
2✔
784
        name := strings.Join(nameParts, "-")
2✔
785
        // Replace dots with dashes as they're not allowed in resource names
2✔
786
        name = strings.ReplaceAll(name, ".", "-")
2✔
787

2✔
788
        unique := sha256.Sum256([]byte(name))
2✔
789
        uniqueStr := hex.EncodeToString(unique[:])[:8]
2✔
790

2✔
791
        maxlen := maxLen - len(uniqueStr) - 1
2✔
792
        if len(name) > maxlen {
4✔
793
                name = name[:maxlen]
2✔
794
        }
2✔
795

796
        return strings.ToLower(fmt.Sprintf("%s-%s", name, uniqueStr))
2✔
797
}
798

799
func (r *SkyhookReconciler) UpsertNodeLabelsAnnotationsPackages(ctx context.Context, skyhook *wrapper.Skyhook, node *corev1.Node) error {
2✔
800
        // No work to do if there is no labels or annotations for node
2✔
801
        if len(node.Labels) == 0 && len(node.Annotations) == 0 {
2✔
802
                return nil
×
803
        }
×
804

805
        annotations, err := json.Marshal(node.Annotations)
2✔
806
        if err != nil {
2✔
807
                return fmt.Errorf("error converting annotations into byte array: %w", err)
×
808
        }
×
809

810
        labels, err := json.Marshal(node.Labels)
2✔
811
        if err != nil {
2✔
812
                return fmt.Errorf("error converting labels into byte array: %w", err)
×
813
        }
×
814

815
        // marshal intermediary package metadata for the agent
816
        metadata := NewSkyhookMetadata(r.opts, skyhook)
2✔
817
        packages, err := metadata.Marshal()
2✔
818
        if err != nil {
2✔
819
                return fmt.Errorf("error converting packages into byte array: %w", err)
×
820
        }
×
821

822
        configMapName := generateSafeName(253, skyhook.Name, node.Name, "metadata")
2✔
823
        newCM := &corev1.ConfigMap{
2✔
824
                ObjectMeta: metav1.ObjectMeta{
2✔
825
                        Name:      configMapName,
2✔
826
                        Namespace: r.opts.Namespace,
2✔
827
                        Labels: map[string]string{
2✔
828
                                fmt.Sprintf("%s/skyhook-node-meta", v1alpha1.METADATA_PREFIX): skyhook.Name,
2✔
829
                        },
2✔
830
                        Annotations: map[string]string{
2✔
831
                                fmt.Sprintf("%s/name", v1alpha1.METADATA_PREFIX):      skyhook.Name,
2✔
832
                                fmt.Sprintf("%s/Node.name", v1alpha1.METADATA_PREFIX): node.Name,
2✔
833
                        },
2✔
834
                },
2✔
835
                Data: map[string]string{
2✔
836
                        "annotations.json": string(annotations),
2✔
837
                        "labels.json":      string(labels),
2✔
838
                        "packages.json":    string(packages),
2✔
839
                },
2✔
840
        }
2✔
841

2✔
842
        if err := ctrl.SetControllerReference(skyhook.Skyhook, newCM, r.scheme); err != nil {
2✔
843
                return fmt.Errorf("error setting ownership: %w", err)
×
844
        }
×
845

846
        existingConfigMap := &corev1.ConfigMap{}
2✔
847
        err = r.Get(ctx, client.ObjectKey{Namespace: r.opts.Namespace, Name: configMapName}, existingConfigMap)
2✔
848
        if err != nil {
4✔
849
                if apierrors.IsNotFound(err) {
4✔
850
                        // create
2✔
851
                        err := r.Create(ctx, newCM)
2✔
852
                        if err != nil {
2✔
853
                                return fmt.Errorf("error creating config map [%s]: %w", newCM.Name, err)
×
854
                        }
×
855
                } else {
×
856
                        return fmt.Errorf("error getting config map: %w", err)
×
857
                }
×
858
        } else {
1✔
859
                if !reflect.DeepEqual(existingConfigMap.Data, newCM.Data) {
2✔
860
                        // update
1✔
861
                        err := r.Update(ctx, newCM)
1✔
862
                        if err != nil {
1✔
863
                                return fmt.Errorf("error updating config map [%s]: %w", newCM.Name, err)
×
864
                        }
×
865
                }
866
        }
867

868
        return nil
2✔
869
}
870

871
// HandleConfigUpdates checks whether the configMap on a package was updated and if it was the configmap will
872
// be updated and the package will be put into config mode if the package is complete or erroring
873
func (r *SkyhookReconciler) HandleConfigUpdates(ctx context.Context, clusterState *clusterState, skyhook SkyhookNodes, _package v1alpha1.Package, oldConfigMap, newConfigMap *corev1.ConfigMap) (bool, error) {
1✔
874
        completedNodes, nodeCount := 0, len(skyhook.GetNodes())
1✔
875
        erroringNode := false
1✔
876

1✔
877
        // if configmap changed
1✔
878
        if !reflect.DeepEqual(oldConfigMap.Data, newConfigMap.Data) {
2✔
879
                for _, node := range skyhook.GetNodes() {
2✔
880
                        exists, err := r.PodExists(ctx, node.GetNode().Name, skyhook.GetSkyhook().Name, &_package)
1✔
881
                        if err != nil {
1✔
882
                                return false, err
×
883
                        }
×
884

885
                        if !exists && node.IsPackageComplete(_package) {
2✔
886
                                completedNodes++
1✔
887
                        }
1✔
888

889
                        // if we have an erroring node in the config, interrupt, or post-interrupt mode
890
                        // then we will restart the config changes
891
                        if packageStatus, found := node.PackageStatus(_package.GetUniqueName()); found {
2✔
892
                                switch packageStatus.Stage {
1✔
893
                                case v1alpha1.StageConfig, v1alpha1.StageInterrupt, v1alpha1.StagePostInterrupt:
1✔
894
                                        if packageStatus.State == v1alpha1.StateErroring {
1✔
895
                                                erroringNode = true
×
896

×
897
                                                // delete the erroring pod from the node so that it can be recreated
×
898
                                                // with the updated configmap
×
899
                                                pods, err := r.dal.GetPods(ctx,
×
900
                                                        client.MatchingFields{
×
901
                                                                "spec.nodeName": node.GetNode().Name,
×
902
                                                        },
×
903
                                                        client.MatchingLabels{
×
904
                                                                fmt.Sprintf("%s/name", v1alpha1.METADATA_PREFIX):    skyhook.GetSkyhook().Name,
×
905
                                                                fmt.Sprintf("%s/package", v1alpha1.METADATA_PREFIX): fmt.Sprintf("%s-%s", _package.Name, _package.Version),
×
906
                                                        },
×
907
                                                )
×
908
                                                if err != nil {
×
909
                                                        return false, err
×
910
                                                }
×
911

912
                                                if pods != nil {
×
913
                                                        for _, pod := range pods.Items {
×
914
                                                                err := r.Delete(ctx, &pod)
×
915
                                                                if err != nil {
×
916
                                                                        return false, err
×
917
                                                                }
×
918
                                                        }
919
                                                }
920
                                        }
921
                                }
922
                        }
923
                }
924

925
                // if the update is complete or there is an erroring node put the package back into
926
                // the config mode and update the config map
927
                if completedNodes == nodeCount || erroringNode {
2✔
928
                        // get the keys in the configmap that changed
1✔
929
                        newConfigUpdates := make([]string, 0)
1✔
930
                        for key, new_val := range newConfigMap.Data {
2✔
931
                                if old_val, exists := oldConfigMap.Data[key]; !exists || old_val != new_val {
2✔
932
                                        newConfigUpdates = append(newConfigUpdates, key)
1✔
933
                                }
1✔
934
                        }
935

936
                        // if updates completed then clear out old config updates as they are finished
937
                        if completedNodes == nodeCount {
2✔
938
                                skyhook.GetSkyhook().RemoveConfigUpdates(_package.Name)
1✔
939
                        }
1✔
940

941
                        // Add the new changed keys to the config updates
942
                        skyhook.GetSkyhook().AddConfigUpdates(_package.Name, newConfigUpdates...)
1✔
943

1✔
944
                        for _, node := range skyhook.GetNodes() {
2✔
945
                                err := node.Upsert(_package.PackageRef, _package.Image, v1alpha1.StateInProgress, v1alpha1.StageConfig, 0, _package.ContainerSHA)
1✔
946
                                if err != nil {
1✔
947
                                        return false, fmt.Errorf("error upserting node status [%s]: %w", node.GetNode().Name, err)
×
948
                                }
×
949

950
                                node.SetStatus(v1alpha1.StatusInProgress)
1✔
951
                        }
952

953
                        _, errs := r.SaveNodesAndSkyhook(ctx, clusterState, skyhook)
1✔
954
                        if len(errs) > 0 {
1✔
955
                                return false, utilerrors.NewAggregate(errs)
×
956
                        }
×
957

958
                        // update config map
959
                        err := r.Update(ctx, newConfigMap)
1✔
960
                        if err != nil {
1✔
961
                                return false, fmt.Errorf("error updating config map [%s]: %w", newConfigMap.Name, err)
×
962
                        }
×
963

964
                        return true, nil
1✔
965
                }
966
        }
967

968
        return false, nil
1✔
969
}
970

971
func (r *SkyhookReconciler) UpsertConfigmaps(ctx context.Context, skyhook SkyhookNodes, clusterState *clusterState) (bool, error) {
1✔
972
        updated := false
1✔
973

1✔
974
        var list corev1.ConfigMapList
1✔
975
        err := r.List(ctx, &list, client.InNamespace(r.opts.Namespace), client.MatchingLabels{fmt.Sprintf("%s/name", v1alpha1.METADATA_PREFIX): skyhook.GetSkyhook().Name})
1✔
976
        if err != nil {
1✔
977
                return false, fmt.Errorf("error listing config maps while upserting: %w", err)
×
978
        }
×
979

980
        existingCMs := make(map[string]corev1.ConfigMap)
1✔
981
        for _, cm := range list.Items {
2✔
982
                existingCMs[cm.Name] = cm
1✔
983
        }
1✔
984

985
        // clean up from an update
986
        shouldExist := make(map[string]struct{})
1✔
987
        for _, _package := range skyhook.GetSkyhook().Spec.Packages {
2✔
988
                shouldExist[strings.ToLower(fmt.Sprintf("%s-%s-%s", skyhook.GetSkyhook().Name, _package.Name, _package.Version))] = struct{}{}
1✔
989
        }
1✔
990

991
        for k, v := range existingCMs {
2✔
992
                if _, ok := shouldExist[k]; !ok {
2✔
993
                        // delete
1✔
994
                        err := r.Delete(ctx, &v)
1✔
995
                        if err != nil {
1✔
996
                                return false, fmt.Errorf("error deleting existing config map [%s] while upserting: %w", v.Name, err)
×
997
                        }
×
998
                }
999
        }
1000

1001
        for _, _package := range skyhook.GetSkyhook().Spec.Packages {
2✔
1002
                if len(_package.ConfigMap) > 0 {
2✔
1003

1✔
1004
                        newCM := &corev1.ConfigMap{
1✔
1005
                                ObjectMeta: metav1.ObjectMeta{
1✔
1006
                                        Name:      strings.ToLower(fmt.Sprintf("%s-%s-%s", skyhook.GetSkyhook().Name, _package.Name, _package.Version)),
1✔
1007
                                        Namespace: r.opts.Namespace,
1✔
1008
                                        Labels: map[string]string{
1✔
1009
                                                fmt.Sprintf("%s/name", v1alpha1.METADATA_PREFIX): skyhook.GetSkyhook().Name,
1✔
1010
                                        },
1✔
1011
                                        Annotations: map[string]string{
1✔
1012
                                                fmt.Sprintf("%s/name", v1alpha1.METADATA_PREFIX):            skyhook.GetSkyhook().Name,
1✔
1013
                                                fmt.Sprintf("%s/Package.Name", v1alpha1.METADATA_PREFIX):    _package.Name,
1✔
1014
                                                fmt.Sprintf("%s/Package.Version", v1alpha1.METADATA_PREFIX): _package.Version,
1✔
1015
                                        },
1✔
1016
                                },
1✔
1017
                                Data: _package.ConfigMap,
1✔
1018
                        }
1✔
1019
                        // set owner of CM to the SCR, which will clean up the CM in delete of the SCR
1✔
1020
                        if err := ctrl.SetControllerReference(skyhook.GetSkyhook().Skyhook, newCM, r.scheme); err != nil {
1✔
1021
                                return false, fmt.Errorf("error setting ownership of cm: %w", err)
×
1022
                        }
×
1023

1024
                        if existingCM, ok := existingCMs[strings.ToLower(fmt.Sprintf("%s-%s-%s", skyhook.GetSkyhook().Name, _package.Name, _package.Version))]; ok {
2✔
1025
                                updatedConfigMap, err := r.HandleConfigUpdates(ctx, clusterState, skyhook, _package, &existingCM, newCM)
1✔
1026
                                if err != nil {
1✔
1027
                                        return false, fmt.Errorf("error updating config map [%s]: %s", newCM.Name, err)
×
1028
                                }
×
1029
                                if updatedConfigMap {
2✔
1030
                                        updated = true
1✔
1031
                                }
1✔
1032
                        } else {
1✔
1033
                                // create
1✔
1034
                                err := r.Create(ctx, newCM)
1✔
1035
                                if err != nil {
1✔
1036
                                        return false, fmt.Errorf("error creating config map [%s]: %w", newCM.Name, err)
×
1037
                                }
×
1038
                        }
1039
                }
1040
        }
1041

1042
        return updated, nil
1✔
1043
}
1044

1045
func (r *SkyhookReconciler) IsDrained(ctx context.Context, skyhookNode wrapper.SkyhookNode) (bool, error) {
1✔
1046

1✔
1047
        pods, err := r.dal.GetPods(ctx, client.MatchingFields{
1✔
1048
                "spec.nodeName": skyhookNode.GetNode().Name,
1✔
1049
        })
1✔
1050
        if err != nil {
1✔
1051
                return false, err
×
1052
        }
×
1053

1054
        if pods == nil || len(pods.Items) == 0 {
1✔
1055
                return true, nil
×
1056
        }
×
1057

1058
        // checking for any running or pending pods with no toleration to unschedulable
1059
        // if its has an unschedulable toleration we can ignore
1060
        for _, pod := range pods.Items {
2✔
1061

1✔
1062
                if ShouldEvict(&pod) {
2✔
1063
                        return false, nil
1✔
1064
                }
1✔
1065

1066
        }
1067

1068
        return true, nil
1✔
1069
}
1070

1071
func ShouldEvict(pod *corev1.Pod) bool {
1✔
1072
        switch pod.Status.Phase {
1✔
1073
        case corev1.PodRunning, corev1.PodPending:
1✔
1074

1✔
1075
                for _, taint := range pod.Spec.Tolerations {
2✔
1076
                        switch taint.Key {
1✔
1077
                        case "node.kubernetes.io/unschedulable": // ignoring
1✔
1078
                                return false
1✔
1079
                        }
1080
                }
1081

1082
                if len(pod.ObjectMeta.OwnerReferences) > 1 {
1✔
1083
                        for _, owner := range pod.ObjectMeta.OwnerReferences {
×
1084
                                if owner.Kind == "DaemonSet" { // ignoring
×
1085
                                        return false
×
1086
                                }
×
1087
                        }
1088
                }
1089

1090
                if pod.GetNamespace() == "kube-system" {
1✔
1091
                        return false
×
1092
                }
×
1093

1094
                return true
1✔
1095
        }
1096
        return false
1✔
1097
}
1098

1099
// HandleFinalizer returns true only if we container is deleted and we handled it completely, else false
1100
func (r *SkyhookReconciler) HandleFinalizer(ctx context.Context, skyhook SkyhookNodes) (bool, error) {
1✔
1101
        if skyhook.GetSkyhook().DeletionTimestamp.IsZero() { // if not deleted, and does not have our finalizer, add it
2✔
1102
                if !controllerutil.ContainsFinalizer(skyhook.GetSkyhook().Skyhook, SkyhookFinalizer) {
2✔
1103
                        controllerutil.AddFinalizer(skyhook.GetSkyhook().Skyhook, SkyhookFinalizer)
1✔
1104

1✔
1105
                        if err := r.Update(ctx, skyhook.GetSkyhook().Skyhook); err != nil {
1✔
1106
                                return false, fmt.Errorf("error updating skyhook to add finalizer: %w", err)
×
1107
                        }
×
1108
                }
1109
        } else { // being delete, time to handle our
1✔
1110
                if controllerutil.ContainsFinalizer(skyhook.GetSkyhook().Skyhook, SkyhookFinalizer) {
2✔
1111

1✔
1112
                        errs := make([]error, 0)
1✔
1113

1✔
1114
                        // zero out all the metrics related to this skyhook both skyhook and packages
1✔
1115
                        zeroOutSkyhookMetrics(skyhook)
1✔
1116

1✔
1117
                        for _, node := range skyhook.GetNodes() {
2✔
1118
                                patch := client.StrategicMergeFrom(node.GetNode().DeepCopy())
1✔
1119

1✔
1120
                                node.Uncordon()
1✔
1121

1✔
1122
                                // if this doesn't change the node then don't patch
1✔
1123
                                if !node.Changed() {
2✔
1124
                                        continue
1✔
1125
                                }
1126

UNCOV
1127
                                err := r.Patch(ctx, node.GetNode(), patch)
×
UNCOV
1128
                                if err != nil {
×
1129
                                        errs = append(errs, fmt.Errorf("error patching node [%s] in finalizer: %w", node.GetNode().Name, err))
×
1130
                                }
×
1131
                        }
1132

1133
                        if len(errs) > 0 { // we errored, so we need to return error, otherwise we would release the skyhook when we didnt finish
1✔
1134
                                return false, utilerrors.NewAggregate(errs)
×
1135
                        }
×
1136

1137
                        controllerutil.RemoveFinalizer(skyhook.GetSkyhook().Skyhook, SkyhookFinalizer)
1✔
1138
                        if err := r.Update(ctx, skyhook.GetSkyhook().Skyhook); err != nil {
2✔
1139
                                return false, fmt.Errorf("error updating skyhook removing finalizer: %w", err)
1✔
1140
                        }
1✔
1141
                        // should be 1, and now 2. we want to set ObservedGeneration up to not trigger an logic from this update adding the finalizer
1142
                        skyhook.GetSkyhook().Status.ObservedGeneration = skyhook.GetSkyhook().Status.ObservedGeneration + 1
1✔
1143

1✔
1144
                        if err := r.Status().Update(ctx, skyhook.GetSkyhook().Skyhook); err != nil {
2✔
1145
                                return false, fmt.Errorf("error updating skyhook status: %w", err)
1✔
1146
                        }
1✔
1147

1148
                        return true, nil
×
1149
                }
1150
        }
1151
        return false, nil
1✔
1152
}
1153

1154
// HasNonInterruptWork returns true if pods are running on the node that are either packages, or matches the SCR selector
1155
func (r *SkyhookReconciler) HasNonInterruptWork(ctx context.Context, skyhookNode wrapper.SkyhookNode) (bool, error) {
1✔
1156

1✔
1157
        selector, err := metav1.LabelSelectorAsSelector(&skyhookNode.GetSkyhook().Spec.PodNonInterruptLabels)
1✔
1158
        if err != nil {
1✔
1159
                return false, fmt.Errorf("error creating selector: %w", err)
×
1160
        }
×
1161

1162
        if selector.Empty() { // when selector is empty it does not do any selecting, ie will return all pods on node.
2✔
1163
                return false, nil
1✔
1164
        }
1✔
1165

1166
        pods, err := r.dal.GetPods(ctx,
1✔
1167
                client.MatchingLabelsSelector{Selector: selector},
1✔
1168
                client.MatchingFields{
1✔
1169
                        "spec.nodeName": skyhookNode.GetNode().Name,
1✔
1170
                },
1✔
1171
        )
1✔
1172
        if err != nil {
1✔
1173
                return false, fmt.Errorf("error getting pods: %w", err)
×
1174
        }
×
1175

1176
        if pods == nil || len(pods.Items) == 0 {
2✔
1177
                return false, nil
1✔
1178
        }
1✔
1179

1180
        for _, pod := range pods.Items {
2✔
1181
                switch pod.Status.Phase {
1✔
1182
                case corev1.PodRunning, corev1.PodPending:
1✔
1183
                        return true, nil
1✔
1184
                }
1185
        }
1186

1187
        return false, nil
×
1188
}
1189

1190
func (r *SkyhookReconciler) HasRunningPackages(ctx context.Context, skyhookNode wrapper.SkyhookNode) (bool, error) {
1✔
1191
        pods, err := r.dal.GetPods(ctx,
1✔
1192
                client.HasLabels{fmt.Sprintf("%s/name", v1alpha1.METADATA_PREFIX)},
1✔
1193
                client.MatchingFields{
1✔
1194
                        "spec.nodeName": skyhookNode.GetNode().Name,
1✔
1195
                },
1✔
1196
        )
1✔
1197
        if err != nil {
1✔
1198
                return false, fmt.Errorf("error getting pods: %w", err)
×
1199
        }
×
1200

1201
        return pods != nil && len(pods.Items) > 0, nil
1✔
1202
}
1203

1204
func (r *SkyhookReconciler) DrainNode(ctx context.Context, skyhookNode wrapper.SkyhookNode, _package *v1alpha1.Package) (bool, error) {
1✔
1205
        drained, err := r.IsDrained(ctx, skyhookNode)
1✔
1206
        if err != nil {
1✔
1207
                return false, err
×
1208
        }
×
1209
        if drained {
2✔
1210
                return true, nil
1✔
1211
        }
1✔
1212

1213
        pods, err := r.dal.GetPods(ctx, client.MatchingFields{
1✔
1214
                "spec.nodeName": skyhookNode.GetNode().Name,
1✔
1215
        })
1✔
1216
        if err != nil {
1✔
1217
                return false, err
×
1218
        }
×
1219

1220
        if pods == nil || len(pods.Items) == 0 {
1✔
1221
                return true, nil
×
1222
        }
×
1223

1224
        r.recorder.Eventf(skyhookNode.GetNode(), EventTypeNormal, EventsReasonSkyhookInterrupt,
1✔
1225
                "draining node [%s] package [%s:%s] from [skyhook:%s]",
1✔
1226
                skyhookNode.GetNode().Name,
1✔
1227
                _package.Name,
1✔
1228
                _package.Version,
1✔
1229
                skyhookNode.GetSkyhook().Name,
1✔
1230
        )
1✔
1231

1✔
1232
        errs := make([]error, 0)
1✔
1233
        for _, pod := range pods.Items {
2✔
1234

1✔
1235
                if ShouldEvict(&pod) {
2✔
1236
                        eviction := policyv1.Eviction{}
1✔
1237
                        err := r.Client.SubResource("eviction").Create(ctx, &pod, &eviction)
1✔
1238
                        if err != nil {
1✔
1239
                                errs = append(errs, fmt.Errorf("error evicting pod [%s:%s]: %w", pod.Namespace, pod.Name, err))
×
1240
                        }
×
1241
                }
1242
        }
1243

1244
        return len(errs) == 0, utilerrors.NewAggregate(errs)
1✔
1245
}
1246

1247
// Interrupt should not be called unless safe to do so, IE already cordoned and drained
1248
func (r *SkyhookReconciler) Interrupt(ctx context.Context, skyhookNode wrapper.SkyhookNode, _package *v1alpha1.Package, _interrupt *v1alpha1.Interrupt) error {
1✔
1249

1✔
1250
        hasPackagesRunning, err := r.HasRunningPackages(ctx, skyhookNode)
1✔
1251
        if err != nil {
1✔
1252
                return err
×
1253
        }
×
1254

1255
        if hasPackagesRunning { // keep waiting...
2✔
1256
                return nil
1✔
1257
        }
1✔
1258

1259
        exists, err := r.PodExists(ctx, skyhookNode.GetNode().Name, skyhookNode.GetSkyhook().Name, _package)
1✔
1260
        if err != nil {
1✔
1261
                return err
×
1262
        }
×
1263
        if exists {
1✔
1264
                // nothing to do here, already running
×
1265
                return nil
×
1266
        }
×
1267

1268
        argEncode, err := _interrupt.ToArgs()
1✔
1269
        if err != nil {
1✔
1270
                return fmt.Errorf("error creating interrupt args: %w", err)
×
1271
        }
×
1272

1273
        pod := createInterruptPodForPackage(r.opts, _interrupt, argEncode, _package, skyhookNode.GetSkyhook(), skyhookNode.GetNode().Name)
1✔
1274

1✔
1275
        if err := SetPackages(pod, skyhookNode.GetSkyhook().Skyhook, _package.Image, v1alpha1.StageInterrupt, _package); err != nil {
1✔
1276
                return fmt.Errorf("error setting package on interrupt: %w", err)
×
1277
        }
×
1278

1279
        if err := ctrl.SetControllerReference(skyhookNode.GetSkyhook().Skyhook, pod, r.scheme); err != nil {
1✔
1280
                return fmt.Errorf("error setting ownership: %w", err)
×
1281
        }
×
1282

1283
        if err := r.Create(ctx, pod); err != nil {
1✔
1284
                return fmt.Errorf("error creating interruption pod: %w", err)
×
1285
        }
×
1286

1287
        _ = skyhookNode.Upsert(_package.PackageRef, _package.Image, v1alpha1.StateInProgress, v1alpha1.StageInterrupt, 0, _package.ContainerSHA)
1✔
1288

1✔
1289
        r.recorder.Eventf(skyhookNode.GetSkyhook().Skyhook, EventTypeNormal, EventsReasonSkyhookInterrupt,
1✔
1290
                "Interrupting node [%s] package [%s:%s] from [skyhook:%s]",
1✔
1291
                skyhookNode.GetNode().Name,
1✔
1292
                _package.Name,
1✔
1293
                _package.Version,
1✔
1294
                skyhookNode.GetSkyhook().Name)
1✔
1295

1✔
1296
        return nil
1✔
1297
}
1298

1299
// fudgeInterruptWithPriority takes a list of packages, interrupts, and configUpdates and returns the correct merged interrupt to run to handle all the packages
1300
func fudgeInterruptWithPriority(next []*v1alpha1.Package, configUpdates map[string][]string, interrupts map[string][]*v1alpha1.Interrupt) (*v1alpha1.Interrupt, string) {
2✔
1301
        var ret *v1alpha1.Interrupt
2✔
1302
        var pack string
2✔
1303

2✔
1304
        // map interrupt to priority
2✔
1305
        // A lower priority value means a higher priority and will be used in favor of anything with a higher value
2✔
1306
        var priorities = map[v1alpha1.InterruptType]int{
2✔
1307
                v1alpha1.REBOOT:               0,
2✔
1308
                v1alpha1.RESTART_ALL_SERVICES: 1,
2✔
1309
                v1alpha1.SERVICE:              2,
2✔
1310
                v1alpha1.NOOP:                 3,
2✔
1311
        }
2✔
1312

2✔
1313
        for _, _package := range next {
4✔
1314

2✔
1315
                if len(configUpdates[_package.Name]) == 0 {
4✔
1316
                        interrupts[_package.Name] = []*v1alpha1.Interrupt{}
2✔
1317
                        if _package.HasInterrupt() {
4✔
1318
                                interrupts[_package.Name] = append(interrupts[_package.Name], _package.Interrupt)
2✔
1319
                        }
2✔
1320
                }
1321
        }
1322

1323
        packageNames := make([]string, 0)
2✔
1324
        for _, pkg := range next {
4✔
1325
                packageNames = append(packageNames, pkg.Name)
2✔
1326
        }
2✔
1327
        sort.Strings(packageNames)
2✔
1328

2✔
1329
        for _, _package := range packageNames {
4✔
1330
                _interrupts, ok := interrupts[_package]
2✔
1331
                if !ok {
4✔
1332
                        continue
2✔
1333
                }
1334

1335
                for _, interrupt := range _interrupts {
4✔
1336
                        if ret == nil { // prime ret, base case
4✔
1337
                                ret = interrupt
2✔
1338
                                pack = _package
2✔
1339
                        }
2✔
1340

1341
                        // short circuit, reboot has highest priority
1342
                        switch interrupt.Type {
2✔
1343
                        case v1alpha1.REBOOT:
2✔
1344
                                return interrupt, _package
2✔
1345
                        }
1346

1347
                        // check if interrupt is higher priority using the priority_order
1348
                        // A lower priority value means a higher priority
1349
                        if priorities[interrupt.Type] < priorities[ret.Type] {
3✔
1350
                                ret = interrupt
1✔
1351
                                pack = _package
1✔
1352
                        } else if priorities[interrupt.Type] == priorities[ret.Type] {
5✔
1353
                                mergeInterrupt(ret, interrupt)
2✔
1354
                        }
2✔
1355
                }
1356
        }
1357

1358
        return ret, pack // return merged interrupt and package
2✔
1359
}
1360

1361
func mergeInterrupt(left, right *v1alpha1.Interrupt) {
2✔
1362

2✔
1363
        // make sure both are of type service
2✔
1364
        if left.Type != v1alpha1.SERVICE || right.Type != v1alpha1.SERVICE {
3✔
1365
                return
1✔
1366
        }
1✔
1367

1368
        left.Services = merge(left.Services, right.Services)
2✔
1369
}
1370

1371
func merge[T cmp.Ordered](left, right []T) []T {
2✔
1372
        for _, r := range right {
4✔
1373
                if !slices.Contains(left, r) {
4✔
1374
                        left = append(left, r)
2✔
1375
                }
2✔
1376
        }
1377
        slices.Sort(left)
2✔
1378
        return left
2✔
1379
}
1380

1381
// ValidateNodeConfigmaps validates that there are no orphaned or stale config maps for a node
1382
func (r *SkyhookReconciler) ValidateNodeConfigmaps(ctx context.Context, skyhookName string, nodes []wrapper.SkyhookNode) (bool, error) {
1✔
1383
        var list corev1.ConfigMapList
1✔
1384
        err := r.List(ctx, &list, client.InNamespace(r.opts.Namespace), client.MatchingLabels{fmt.Sprintf("%s/skyhook-node-meta", v1alpha1.METADATA_PREFIX): skyhookName})
1✔
1385
        if err != nil {
1✔
1386
                return false, fmt.Errorf("error listing config maps: %w", err)
×
1387
        }
×
1388

1389
        // No configmaps created by this skyhook, no work needs to be done
1390
        if len(list.Items) == 0 {
2✔
1391
                return false, nil
1✔
1392
        }
1✔
1393

1394
        existingCMs := make(map[string]corev1.ConfigMap)
1✔
1395
        for _, cm := range list.Items {
2✔
1396
                existingCMs[cm.Name] = cm
1✔
1397
        }
1✔
1398

1399
        shouldExist := make(map[string]struct{})
1✔
1400
        for _, node := range nodes {
2✔
1401
                shouldExist[generateSafeName(253, skyhookName, node.GetNode().Name, "metadata")] = struct{}{}
1✔
1402
        }
1✔
1403

1404
        update := false
1✔
1405
        errs := make([]error, 0)
1✔
1406
        for k, v := range existingCMs {
2✔
1407
                if _, ok := shouldExist[k]; !ok {
1✔
1408
                        update = true
×
1409
                        err := r.Delete(ctx, &v)
×
1410
                        if err != nil {
×
1411
                                errs = append(errs, fmt.Errorf("error deleting existing config map [%s]: %w", v.Name, err))
×
1412
                        }
×
1413
                }
1414
        }
1415

1416
        // Ensure packages.json is present and up-to-date for expected configmaps
1417
        skyhookCR, err := r.dal.GetSkyhook(ctx, skyhookName)
1✔
1418
        if err != nil {
1✔
1419
                return update, fmt.Errorf("error getting skyhook for metadata validation: %w", err)
×
1420
        }
×
1421
        skyhookWrapper := wrapper.NewSkyhookWrapper(skyhookCR)
1✔
1422
        metadata := NewSkyhookMetadata(r.opts, skyhookWrapper)
1✔
1423
        expectedBytes, err := metadata.Marshal()
1✔
1424
        if err != nil {
1✔
1425
                return update, fmt.Errorf("error marshalling metadata for validation: %w", err)
×
1426
        }
×
1427
        expected := string(expectedBytes)
1✔
1428

1✔
1429
        for i := range list.Items {
2✔
1430
                cm := &list.Items[i]
1✔
1431
                if _, ok := shouldExist[cm.Name]; !ok {
1✔
1432
                        continue
×
1433
                }
1434
                if cm.Data == nil {
1✔
1435
                        cm.Data = make(map[string]string)
×
1436
                }
×
1437
                if cm.Data["packages.json"] != expected {
2✔
1438
                        cm.Data["packages.json"] = expected
1✔
1439
                        if err := r.Update(ctx, cm); err != nil {
1✔
1440
                                errs = append(errs, fmt.Errorf("error updating packages.json on config map [%s]: %w", cm.Name, err))
×
1441
                        } else {
1✔
1442
                                update = true
1✔
1443
                        }
1✔
1444
                }
1445
        }
1446

1447
        return update, utilerrors.NewAggregate(errs)
1✔
1448
}
1449

1450
// PodExists tests if this package is exists on a node.
1451
func (r *SkyhookReconciler) PodExists(ctx context.Context, nodeName, skyhookName string, _package *v1alpha1.Package) (bool, error) {
1✔
1452

1✔
1453
        pods, err := r.dal.GetPods(ctx,
1✔
1454
                client.MatchingFields{
1✔
1455
                        "spec.nodeName": nodeName,
1✔
1456
                },
1✔
1457
                client.MatchingLabels{
1✔
1458
                        fmt.Sprintf("%s/name", v1alpha1.METADATA_PREFIX):    skyhookName,
1✔
1459
                        fmt.Sprintf("%s/package", v1alpha1.METADATA_PREFIX): fmt.Sprintf("%s-%s", _package.Name, _package.Version),
1✔
1460
                },
1✔
1461
        )
1✔
1462
        if err != nil {
1✔
1463
                return false, fmt.Errorf("error check from existing pods: %w", err)
×
1464
        }
×
1465

1466
        if pods == nil || len(pods.Items) == 0 {
2✔
1467
                return false, nil
1✔
1468
        }
1✔
1469
        return true, nil
1✔
1470
}
1471

1472
// createInterruptPodForPackage returns the pod spec for an interrupt pod given an package
1473
func createInterruptPodForPackage(opts SkyhookOperatorOptions, _interrupt *v1alpha1.Interrupt, argEncode string, _package *v1alpha1.Package, skyhook *wrapper.Skyhook, nodeName string) *corev1.Pod {
2✔
1474
        copyDir := fmt.Sprintf("%s/%s/%s-%s-%s-%d",
2✔
1475
                opts.CopyDirRoot,
2✔
1476
                skyhook.Name,
2✔
1477
                _package.Name,
2✔
1478
                _package.Version,
2✔
1479
                skyhook.UID,
2✔
1480
                skyhook.Generation,
2✔
1481
        )
2✔
1482

2✔
1483
        volumes := []corev1.Volume{
2✔
1484
                {
2✔
1485
                        Name: "root-mount",
2✔
1486
                        VolumeSource: corev1.VolumeSource{
2✔
1487
                                HostPath: &corev1.HostPathVolumeSource{
2✔
1488
                                        Path: "/",
2✔
1489
                                },
2✔
1490
                        },
2✔
1491
                },
2✔
1492
                {
2✔
1493
                        // node names in different CSPs might include dots which isn't allowed in volume names
2✔
1494
                        // so we have to replace all dots with dashes
2✔
1495
                        Name: generateSafeName(63, skyhook.Name, nodeName, "metadata"),
2✔
1496
                        VolumeSource: corev1.VolumeSource{
2✔
1497
                                ConfigMap: &corev1.ConfigMapVolumeSource{
2✔
1498
                                        LocalObjectReference: corev1.LocalObjectReference{
2✔
1499
                                                Name: strings.ReplaceAll(fmt.Sprintf("%s-%s-metadata", skyhook.Name, nodeName), ".", "-"),
2✔
1500
                                        },
2✔
1501
                                },
2✔
1502
                        },
2✔
1503
                },
2✔
1504
        }
2✔
1505
        volumeMounts := []corev1.VolumeMount{
2✔
1506
                {
2✔
1507
                        Name:             "root-mount",
2✔
1508
                        MountPath:        "/root",
2✔
1509
                        MountPropagation: ptr(corev1.MountPropagationHostToContainer),
2✔
1510
                },
2✔
1511
        }
2✔
1512

2✔
1513
        pod := &corev1.Pod{
2✔
1514
                ObjectMeta: metav1.ObjectMeta{
2✔
1515
                        Name:      generateSafeName(63, skyhook.Name, "interrupt", string(_interrupt.Type), nodeName),
2✔
1516
                        Namespace: opts.Namespace,
2✔
1517
                        Labels: map[string]string{
2✔
1518
                                fmt.Sprintf("%s/name", v1alpha1.METADATA_PREFIX):      skyhook.Name,
2✔
1519
                                fmt.Sprintf("%s/package", v1alpha1.METADATA_PREFIX):   fmt.Sprintf("%s-%s", _package.Name, _package.Version),
2✔
1520
                                fmt.Sprintf("%s/interrupt", v1alpha1.METADATA_PREFIX): "True",
2✔
1521
                        },
2✔
1522
                },
2✔
1523
                Spec: corev1.PodSpec{
2✔
1524
                        NodeName:      nodeName,
2✔
1525
                        RestartPolicy: corev1.RestartPolicyOnFailure,
2✔
1526
                        InitContainers: []corev1.Container{
2✔
1527
                                {
2✔
1528
                                        Name:  InterruptContainerName,
2✔
1529
                                        Image: getAgentImage(opts, _package),
2✔
1530
                                        Args:  []string{"interrupt", "/root", copyDir, argEncode},
2✔
1531
                                        Env:   getAgentConfigEnvVars(opts, _package.Name, _package.Version, skyhook.ResourceID(), skyhook.Name),
2✔
1532
                                        SecurityContext: &corev1.SecurityContext{
2✔
1533
                                                Privileged: ptr(true),
2✔
1534
                                        },
2✔
1535
                                        VolumeMounts: volumeMounts,
2✔
1536
                                        Resources: corev1.ResourceRequirements{
2✔
1537
                                                Limits: corev1.ResourceList{
2✔
1538
                                                        corev1.ResourceCPU:    resource.MustParse("500m"),
2✔
1539
                                                        corev1.ResourceMemory: resource.MustParse("64Mi"),
2✔
1540
                                                },
2✔
1541
                                                Requests: corev1.ResourceList{
2✔
1542
                                                        corev1.ResourceCPU:    resource.MustParse("500m"),
2✔
1543
                                                        corev1.ResourceMemory: resource.MustParse("64Mi"),
2✔
1544
                                                },
2✔
1545
                                        },
2✔
1546
                                },
2✔
1547
                        },
2✔
1548
                        Containers: []corev1.Container{
2✔
1549
                                {
2✔
1550
                                        Name:  "pause",
2✔
1551
                                        Image: opts.PauseImage,
2✔
1552
                                        Resources: corev1.ResourceRequirements{
2✔
1553
                                                Limits: corev1.ResourceList{
2✔
1554
                                                        corev1.ResourceCPU:    resource.MustParse("100m"),
2✔
1555
                                                        corev1.ResourceMemory: resource.MustParse("20Mi"),
2✔
1556
                                                },
2✔
1557
                                                Requests: corev1.ResourceList{
2✔
1558
                                                        corev1.ResourceCPU:    resource.MustParse("100m"),
2✔
1559
                                                        corev1.ResourceMemory: resource.MustParse("20Mi"),
2✔
1560
                                                },
2✔
1561
                                        },
2✔
1562
                                },
2✔
1563
                        },
2✔
1564
                        ImagePullSecrets: []corev1.LocalObjectReference{
2✔
1565
                                {
2✔
1566
                                        Name: opts.ImagePullSecret,
2✔
1567
                                },
2✔
1568
                        },
2✔
1569
                        HostPID:     true,
2✔
1570
                        HostNetwork: true,
2✔
1571
                        // If you change these go change the SelectNode toleration in cluster_state.go
2✔
1572
                        Tolerations: append([]corev1.Toleration{ // tolerate all cordon
2✔
1573
                                {
2✔
1574
                                        Key:      TaintUnschedulable,
2✔
1575
                                        Operator: corev1.TolerationOpExists,
2✔
1576
                                },
2✔
1577
                                opts.GetRuntimeRequiredToleration(),
2✔
1578
                        }, skyhook.Spec.AdditionalTolerations...),
2✔
1579
                        Volumes: volumes,
2✔
1580
                },
2✔
1581
        }
2✔
1582
        return pod
2✔
1583
}
2✔
1584

1585
func trunstr(str string, length int) string {
2✔
1586
        if len(str) > length {
2✔
1587
                return str[:length]
×
1588
        }
×
1589
        return str
2✔
1590
}
1591

1592
func getAgentImage(opts SkyhookOperatorOptions, _package *v1alpha1.Package) string {
2✔
1593
        if _package.AgentImageOverride != "" {
3✔
1594
                return _package.AgentImageOverride
1✔
1595
        }
1✔
1596
        return opts.AgentImage
2✔
1597
}
1598

1599
// getPackageImage returns the full image reference for a package, using the digest if specified
1600
func getPackageImage(_package *v1alpha1.Package) string {
2✔
1601
        if _package.ContainerSHA != "" {
3✔
1602
                // When containerSHA is specified, use it instead of the version tag for immutable image reference
1✔
1603
                return fmt.Sprintf("%s@%s", _package.Image, _package.ContainerSHA)
1✔
1604
        }
1✔
1605
        // Fall back to version tag
1606
        return fmt.Sprintf("%s:%s", _package.Image, _package.Version)
2✔
1607
}
1608

1609
func getAgentConfigEnvVars(opts SkyhookOperatorOptions, packageName string, packageVersion string, resourceID string, skyhookName string) []corev1.EnvVar {
2✔
1610
        return []corev1.EnvVar{
2✔
1611
                {
2✔
1612
                        Name:  "SKYHOOK_LOG_DIR",
2✔
1613
                        Value: fmt.Sprintf("%s/%s", opts.AgentLogRoot, skyhookName),
2✔
1614
                },
2✔
1615
                {
2✔
1616
                        Name:  "SKYHOOK_ROOT_DIR",
2✔
1617
                        Value: fmt.Sprintf("%s/%s", opts.CopyDirRoot, skyhookName),
2✔
1618
                },
2✔
1619
                {
2✔
1620
                        Name:  "COPY_RESOLV",
2✔
1621
                        Value: "false",
2✔
1622
                },
2✔
1623
                {
2✔
1624
                        Name:  "SKYHOOK_RESOURCE_ID",
2✔
1625
                        Value: fmt.Sprintf("%s_%s_%s", resourceID, packageName, packageVersion),
2✔
1626
                },
2✔
1627
        }
2✔
1628
}
2✔
1629

1630
// createPodFromPackage creates a pod spec for a skyhook pod for a given package
1631
func createPodFromPackage(opts SkyhookOperatorOptions, _package *v1alpha1.Package, skyhook *wrapper.Skyhook, nodeName string, stage v1alpha1.Stage) *corev1.Pod {
2✔
1632
        // Generate consistent names that won't exceed k8s limits
2✔
1633
        volumeName := generateSafeName(63, "metadata", nodeName)
2✔
1634
        configMapName := generateSafeName(253, skyhook.Name, nodeName, "metadata")
2✔
1635

2✔
1636
        volumes := []corev1.Volume{
2✔
1637
                {
2✔
1638
                        Name: "root-mount",
2✔
1639
                        VolumeSource: corev1.VolumeSource{
2✔
1640
                                HostPath: &corev1.HostPathVolumeSource{
2✔
1641
                                        Path: "/",
2✔
1642
                                },
2✔
1643
                        },
2✔
1644
                },
2✔
1645
                {
2✔
1646
                        Name: volumeName,
2✔
1647
                        VolumeSource: corev1.VolumeSource{
2✔
1648
                                ConfigMap: &corev1.ConfigMapVolumeSource{
2✔
1649
                                        LocalObjectReference: corev1.LocalObjectReference{
2✔
1650
                                                Name: configMapName,
2✔
1651
                                        },
2✔
1652
                                },
2✔
1653
                        },
2✔
1654
                },
2✔
1655
        }
2✔
1656

2✔
1657
        volumeMounts := []corev1.VolumeMount{
2✔
1658
                {
2✔
1659
                        Name:             "root-mount",
2✔
1660
                        MountPath:        "/root",
2✔
1661
                        MountPropagation: ptr(corev1.MountPropagationHostToContainer),
2✔
1662
                },
2✔
1663
                {
2✔
1664
                        Name:      volumeName,
2✔
1665
                        MountPath: "/skyhook-package/node-metadata",
2✔
1666
                },
2✔
1667
        }
2✔
1668

2✔
1669
        if len(_package.ConfigMap) > 0 {
3✔
1670
                volumeMounts = append(volumeMounts, corev1.VolumeMount{
1✔
1671
                        Name:      _package.Name,
1✔
1672
                        MountPath: "/skyhook-package/configmaps",
1✔
1673
                })
1✔
1674

1✔
1675
                volumes = append(volumes, corev1.Volume{
1✔
1676
                        Name: _package.Name,
1✔
1677
                        VolumeSource: corev1.VolumeSource{
1✔
1678
                                ConfigMap: &corev1.ConfigMapVolumeSource{
1✔
1679
                                        LocalObjectReference: corev1.LocalObjectReference{
1✔
1680
                                                Name: strings.ToLower(fmt.Sprintf("%s-%s-%s", skyhook.Name, _package.Name, _package.Version)),
1✔
1681
                                        },
1✔
1682
                                },
1✔
1683
                        },
1✔
1684
                })
1✔
1685
        }
1✔
1686

1687
        copyDir := fmt.Sprintf("%s/%s/%s-%s-%s-%d",
2✔
1688
                opts.CopyDirRoot,
2✔
1689
                skyhook.Name,
2✔
1690
                _package.Name,
2✔
1691
                _package.Version,
2✔
1692
                skyhook.UID,
2✔
1693
                skyhook.Generation,
2✔
1694
        )
2✔
1695
        applyargs := []string{strings.ToLower(string(stage)), "/root", copyDir}
2✔
1696
        checkargs := []string{strings.ToLower(string(stage) + "-check"), "/root", copyDir}
2✔
1697

2✔
1698
        agentEnvs := append(
2✔
1699
                _package.Env,
2✔
1700
                getAgentConfigEnvVars(opts, _package.Name, _package.Version, skyhook.ResourceID(), skyhook.Name)...,
2✔
1701
        )
2✔
1702

2✔
1703
        pod := &corev1.Pod{
2✔
1704
                ObjectMeta: metav1.ObjectMeta{
2✔
1705
                        Name:      generateSafeName(63, skyhook.Name, _package.Name, _package.Version, string(stage), nodeName),
2✔
1706
                        Namespace: opts.Namespace,
2✔
1707
                        Labels: map[string]string{
2✔
1708
                                fmt.Sprintf("%s/name", v1alpha1.METADATA_PREFIX):    skyhook.Name,
2✔
1709
                                fmt.Sprintf("%s/package", v1alpha1.METADATA_PREFIX): fmt.Sprintf("%s-%s", _package.Name, _package.Version),
2✔
1710
                        },
2✔
1711
                },
2✔
1712
                Spec: corev1.PodSpec{
2✔
1713
                        NodeName:      nodeName,
2✔
1714
                        RestartPolicy: corev1.RestartPolicyOnFailure,
2✔
1715
                        InitContainers: []corev1.Container{
2✔
1716
                                {
2✔
1717
                                        Name:            fmt.Sprintf("%s-init", trunstr(_package.Name, 43)),
2✔
1718
                                        Image:           getPackageImage(_package),
2✔
1719
                                        ImagePullPolicy: "Always",
2✔
1720
                                        Command:         []string{"/bin/sh"},
2✔
1721
                                        Args: []string{
2✔
1722
                                                "-c",
2✔
1723
                                                "mkdir -p /root/${SKYHOOK_DIR} && cp -r /skyhook-package/* /root/${SKYHOOK_DIR}",
2✔
1724
                                        },
2✔
1725
                                        Env: []corev1.EnvVar{
2✔
1726
                                                {
2✔
1727
                                                        Name:  "SKYHOOK_DIR",
2✔
1728
                                                        Value: copyDir,
2✔
1729
                                                },
2✔
1730
                                        },
2✔
1731
                                        SecurityContext: &corev1.SecurityContext{
2✔
1732
                                                Privileged: ptr(true),
2✔
1733
                                        },
2✔
1734
                                        VolumeMounts: volumeMounts,
2✔
1735
                                },
2✔
1736
                                {
2✔
1737
                                        Name:            fmt.Sprintf("%s-%s", trunstr(_package.Name, 43), stage),
2✔
1738
                                        Image:           getAgentImage(opts, _package),
2✔
1739
                                        ImagePullPolicy: "Always",
2✔
1740
                                        Args:            applyargs,
2✔
1741
                                        Env:             agentEnvs,
2✔
1742
                                        SecurityContext: &corev1.SecurityContext{
2✔
1743
                                                Privileged: ptr(true),
2✔
1744
                                        },
2✔
1745
                                        VolumeMounts: volumeMounts,
2✔
1746
                                },
2✔
1747
                                {
2✔
1748
                                        Name:            fmt.Sprintf("%s-%scheck", trunstr(_package.Name, 43), stage),
2✔
1749
                                        Image:           getAgentImage(opts, _package),
2✔
1750
                                        ImagePullPolicy: "Always",
2✔
1751
                                        Args:            checkargs,
2✔
1752
                                        Env:             agentEnvs,
2✔
1753
                                        SecurityContext: &corev1.SecurityContext{
2✔
1754
                                                Privileged: ptr(true),
2✔
1755
                                        },
2✔
1756
                                        VolumeMounts: volumeMounts,
2✔
1757
                                },
2✔
1758
                        },
2✔
1759
                        Containers: []corev1.Container{
2✔
1760
                                {
2✔
1761
                                        Name:  "pause",
2✔
1762
                                        Image: opts.PauseImage,
2✔
1763
                                        Resources: corev1.ResourceRequirements{
2✔
1764
                                                Limits: corev1.ResourceList{
2✔
1765
                                                        corev1.ResourceCPU:    resource.MustParse("100m"),
2✔
1766
                                                        corev1.ResourceMemory: resource.MustParse("20Mi"),
2✔
1767
                                                },
2✔
1768
                                                Requests: corev1.ResourceList{
2✔
1769
                                                        corev1.ResourceCPU:    resource.MustParse("100m"),
2✔
1770
                                                        corev1.ResourceMemory: resource.MustParse("20Mi"),
2✔
1771
                                                },
2✔
1772
                                        },
2✔
1773
                                },
2✔
1774
                        },
2✔
1775
                        ImagePullSecrets: []corev1.LocalObjectReference{
2✔
1776
                                {
2✔
1777
                                        Name: opts.ImagePullSecret,
2✔
1778
                                },
2✔
1779
                        },
2✔
1780
                        Volumes:     volumes,
2✔
1781
                        HostPID:     true,
2✔
1782
                        HostNetwork: true,
2✔
1783
                        // If you change these go change the SelectNode toleration in cluster_state.go
2✔
1784
                        Tolerations: append([]corev1.Toleration{ // tolerate all cordon
2✔
1785
                                {
2✔
1786
                                        Key:      TaintUnschedulable,
2✔
1787
                                        Operator: corev1.TolerationOpExists,
2✔
1788
                                },
2✔
1789
                                opts.GetRuntimeRequiredToleration(),
2✔
1790
                        }, skyhook.Spec.AdditionalTolerations...),
2✔
1791
                },
2✔
1792
        }
2✔
1793
        if _package.GracefulShutdown != nil {
3✔
1794
                pod.Spec.TerminationGracePeriodSeconds = ptr(int64(_package.GracefulShutdown.Duration.Seconds()))
1✔
1795
        }
1✔
1796
        setPodResources(pod, _package.Resources)
2✔
1797
        return pod
2✔
1798
}
1799

1800
// FilterEnv removes the environment variables passed into exlude
1801
func FilterEnv(envs []corev1.EnvVar, exclude ...string) []corev1.EnvVar {
2✔
1802
        var filteredEnv []corev1.EnvVar
2✔
1803

2✔
1804
        // build map of exclude strings for faster lookup
2✔
1805
        excludeMap := make(map[string]struct{})
2✔
1806
        for _, name := range exclude {
4✔
1807
                excludeMap[name] = struct{}{}
2✔
1808
        }
2✔
1809

1810
        // If the environment variable name is in the exclude list, skip it
1811
        // otherwise append it to the final list
1812
        for _, env := range envs {
4✔
1813
                if _, found := excludeMap[env.Name]; !found {
4✔
1814
                        filteredEnv = append(filteredEnv, env)
2✔
1815
                }
2✔
1816
        }
1817

1818
        return filteredEnv
2✔
1819
}
1820

1821
// PodMatchesPackage asserts that a given pod matches the given pod spec
1822
func podMatchesPackage(opts SkyhookOperatorOptions, _package *v1alpha1.Package, pod corev1.Pod, skyhook *wrapper.Skyhook, stage v1alpha1.Stage) bool {
2✔
1823
        var expectedPod *corev1.Pod
2✔
1824

2✔
1825
        // need to differentiate whether the pod is for an interrupt or not so we know
2✔
1826
        // what to expect and how to compare them
2✔
1827
        isInterrupt := false
2✔
1828
        _, limitRange := pod.Annotations["kubernetes.io/limit-ranger"]
2✔
1829

2✔
1830
        if pod.Labels[fmt.Sprintf("%s/interrupt", v1alpha1.METADATA_PREFIX)] == "True" {
4✔
1831
                expectedPod = createInterruptPodForPackage(opts, &v1alpha1.Interrupt{}, "", _package, skyhook, "")
2✔
1832
                isInterrupt = true
2✔
1833
        } else {
4✔
1834
                expectedPod = createPodFromPackage(opts, _package, skyhook, "", stage)
2✔
1835
        }
2✔
1836

1837
        actualPod := pod.DeepCopy()
2✔
1838

2✔
1839
        // check to see whether the name or the version of the package changed
2✔
1840
        packageLabel := fmt.Sprintf("%s/package", v1alpha1.METADATA_PREFIX)
2✔
1841
        if actualPod.Labels[packageLabel] != expectedPod.Labels[packageLabel] {
4✔
1842
                return false
2✔
1843
        }
2✔
1844

1845
        // compare initContainers since this is where a lot of the important info lives
1846
        for i := range actualPod.Spec.InitContainers {
4✔
1847
                expectedContainer := expectedPod.Spec.InitContainers[i]
2✔
1848
                actualContainer := actualPod.Spec.InitContainers[i]
2✔
1849

2✔
1850
                if expectedContainer.Name != actualContainer.Name {
3✔
1851
                        return false
1✔
1852
                }
1✔
1853

1854
                if expectedContainer.Image != actualContainer.Image {
2✔
1855
                        return false
×
1856
                }
×
1857

1858
                // compare the containers env vars except for the ones that are inserted
1859
                // by the operator by default as the SKYHOOK_RESOURCE_ID will change every
1860
                // time the skyhook is updated and would cause every pod to be removed
1861
                // TODO: This is ignoring all the static env vars that are set by operator config.
1862
                // It probably should be just SKYHOOK_RESOURCE_ID that is ignored. Otherwise,
1863
                // a user will have to manually delete the pod to update the package when operator is updated.
1864
                dummyAgentEnv := getAgentConfigEnvVars(opts, "", "", "", "")
2✔
1865
                excludedEnvs := make([]string, len(dummyAgentEnv))
2✔
1866
                for i, env := range dummyAgentEnv {
4✔
1867
                        excludedEnvs[i] = env.Name
2✔
1868
                }
2✔
1869
                expectedFilteredEnv := FilterEnv(expectedContainer.Env, excludedEnvs...)
2✔
1870
                actualFilteredEnv := FilterEnv(actualContainer.Env, excludedEnvs...)
2✔
1871
                if !reflect.DeepEqual(expectedFilteredEnv, actualFilteredEnv) {
4✔
1872
                        return false
2✔
1873
                }
2✔
1874

1875
                if !isInterrupt { // dont compare these since they are not configured on interrupt
4✔
1876
                        // compare resource requests and limits (CPU, memory, etc.)
2✔
1877
                        expectedResources := expectedContainer.Resources
2✔
1878
                        actualResources := actualContainer.Resources
2✔
1879
                        if skyhook.Spec.Packages[_package.Name].Resources != nil {
4✔
1880
                                // If CR has resources specified, they should match exactly
2✔
1881
                                if !reflect.DeepEqual(expectedResources, actualResources) {
3✔
1882
                                        return false
1✔
1883
                                }
1✔
1884
                        } else {
2✔
1885
                                // If CR has no resources specified, ensure pod has no resource overrides
2✔
1886
                                if !limitRange {
4✔
1887
                                        if actualResources.Requests != nil || actualResources.Limits != nil {
3✔
1888
                                                return false
1✔
1889
                                        }
1✔
1890
                                }
1891
                        }
1892
                }
1893
        }
1894

1895
        return true
2✔
1896
}
1897

1898
// ValidateRunningPackages deletes pods that don't match the current spec and checks if there are pods running
1899
// that don't match the node state and removes them if they exist
1900
func (r *SkyhookReconciler) ValidateRunningPackages(ctx context.Context, skyhook SkyhookNodes) (bool, error) {
1✔
1901

1✔
1902
        update := false
1✔
1903
        errs := make([]error, 0)
1✔
1904
        // get all pods for this skyhook packages
1✔
1905
        pods, err := r.dal.GetPods(ctx,
1✔
1906
                client.MatchingLabels{
1✔
1907
                        fmt.Sprintf("%s/name", v1alpha1.METADATA_PREFIX): skyhook.GetSkyhook().Name,
1✔
1908
                },
1✔
1909
        )
1✔
1910
        if err != nil {
1✔
1911
                return false, fmt.Errorf("error getting pods while validating packages: %w", err)
×
1912
        }
×
1913
        if pods == nil || len(pods.Items) == 0 {
2✔
1914
                return false, nil // nothing running for this skyhook on this node
1✔
1915
        }
1✔
1916

1917
        // Initialize metrics for each stage
1918
        stages := make(map[string]map[string]map[v1alpha1.Stage]int)
1✔
1919

1✔
1920
        // group pods by node
1✔
1921
        podsbyNode := make(map[string][]corev1.Pod)
1✔
1922
        for _, pod := range pods.Items {
2✔
1923
                podsbyNode[pod.Spec.NodeName] = append(podsbyNode[pod.Spec.NodeName], pod)
1✔
1924
        }
1✔
1925

1926
        for _, node := range skyhook.GetNodes() {
2✔
1927
                nodeState, err := node.State()
1✔
1928
                if err != nil {
1✔
1929
                        return false, fmt.Errorf("error getting node state: %w", err)
×
1930
                }
×
1931

1932
                for _, pod := range podsbyNode[node.GetNode().Name] {
2✔
1933
                        found := false
1✔
1934

1✔
1935
                        runningPackage, err := GetPackage(&pod)
1✔
1936
                        if err != nil {
1✔
1937
                                errs = append(errs, fmt.Errorf("error getting package from pod [%s:%s] while validating packages: %w", pod.Namespace, pod.Name, err))
×
1938
                        }
×
1939

1940
                        // check if the package is part of the skyhook spec, if not we need to delete it
1941
                        for _, v := range skyhook.GetSkyhook().Spec.Packages {
2✔
1942
                                if podMatchesPackage(r.opts, &v, pod, skyhook.GetSkyhook(), runningPackage.Stage) {
2✔
1943
                                        found = true
1✔
1944
                                }
1✔
1945
                        }
1946

1947
                        // Increment the stage count for metrics
1948
                        if _, ok := stages[runningPackage.Name]; !ok {
2✔
1949
                                stages[runningPackage.Name] = make(map[string]map[v1alpha1.Stage]int)
1✔
1950
                                if _, ok := stages[runningPackage.Name][runningPackage.Version]; !ok {
2✔
1951
                                        stages[runningPackage.Name][runningPackage.Version] = make(map[v1alpha1.Stage]int)
1✔
1952
                                        for _, stage := range v1alpha1.Stages {
2✔
1953
                                                stages[runningPackage.Name][runningPackage.Version][stage] = 0
1✔
1954
                                        }
1✔
1955
                                }
1956
                        }
1957
                        stages[runningPackage.Name][runningPackage.Version][runningPackage.Stage]++
1✔
1958

1✔
1959
                        // uninstall is by definition not part of the skyhook spec, so we cant delete it (because it used to be but was removed, hence uninstalling it)
1✔
1960
                        if runningPackage.Stage == v1alpha1.StageUninstall {
2✔
1961
                                found = true
1✔
1962
                        }
1✔
1963

1964
                        if !found {
2✔
1965
                                update = true
1✔
1966

1✔
1967
                                err := r.InvalidPackage(ctx, &pod)
1✔
1968
                                if err != nil {
2✔
1969
                                        errs = append(errs, fmt.Errorf("error invalidating package: %w", err))
1✔
1970
                                }
1✔
1971
                                continue
1✔
1972
                        }
1973

1974
                        // Check if package exists in node state, ie a package running that the node state doesn't know about
1975
                        // something that is often done to try to fix bad node state is to clear the node state completely
1976
                        // which if a package is running, we want to terminate it gracefully. Ofthen what leads to this is
1977
                        // the package is in a crashloop and the operator want to restart it the whole package.
1978
                        // when we apply a package it just check if there is a running package on the node for the state of the package
1979
                        // this can cause to leave a pod running in say config mode, and it there is a depends on you might not correctly
1980
                        // run thins in the correct order.
1981
                        deleteMe := false
1✔
1982
                        packageStatus, exists := nodeState[runningPackage.GetUniqueName()]
1✔
1983
                        if !exists { // package not in node state, so we need to delete it
2✔
1984
                                deleteMe = true
1✔
1985
                        } else { // package in node state, so we need to check if it's running
2✔
1986
                                // need check if the stats match, if not we need to delete it
1✔
1987
                                if packageStatus.Stage != runningPackage.Stage {
2✔
1988
                                        deleteMe = true
1✔
1989
                                }
1✔
1990
                        }
1991

1992
                        if deleteMe {
2✔
1993
                                update = true
1✔
1994
                                err := r.InvalidPackage(ctx, &pod)
1✔
1995
                                if err != nil {
2✔
1996
                                        errs = append(errs, fmt.Errorf("error invalidating package: %w", err))
1✔
1997
                                }
1✔
1998
                        }
1999
                }
2000
        }
2001

2002
        return update, utilerrors.NewAggregate(errs)
1✔
2003
}
2004

2005
// InvalidPackage invalidates a package and updates the pod, which will trigger the pod to be deleted
2006
func (r *SkyhookReconciler) InvalidPackage(ctx context.Context, pod *corev1.Pod) error {
1✔
2007
        err := InvalidatePackage(pod)
1✔
2008
        if err != nil {
1✔
2009
                return fmt.Errorf("error invalidating package: %w", err)
×
2010
        }
×
2011

2012
        err = r.Update(ctx, pod)
1✔
2013
        if err != nil {
2✔
2014
                return fmt.Errorf("error updating pod: %w", err)
1✔
2015
        }
1✔
2016

2017
        return nil
1✔
2018
}
2019

2020
// ProcessInterrupt will check and do the interrupt if need, and returns
2021
// false means we are waiting
2022
// true means we are good to proceed
2023
func (r *SkyhookReconciler) ProcessInterrupt(ctx context.Context, skyhookNode wrapper.SkyhookNode, _package *v1alpha1.Package, interrupt *v1alpha1.Interrupt, runInterrupt bool) (bool, error) {
1✔
2024

1✔
2025
        if !skyhookNode.HasInterrupt(*_package) {
2✔
2026
                return true, nil
1✔
2027
        }
1✔
2028

2029
        // default starting stage
2030
        stage := v1alpha1.StageApply
1✔
2031
        nextStage := skyhookNode.NextStage(_package)
1✔
2032
        if nextStage != nil {
2✔
2033
                stage = *nextStage
1✔
2034
        }
1✔
2035

2036
        // wait tell this is done if its happening
2037
        status, found := skyhookNode.PackageStatus(_package.GetUniqueName())
1✔
2038
        if found && status.State == v1alpha1.StateSkipped {
2✔
2039
                return false, nil
1✔
2040
        }
1✔
2041

2042
        // Theres is a race condition when a node reboots and api cleans up the interrupt pod
2043
        // so we need to check if the pod exists and if it does, we need to recreate it
2044
        if status != nil && (status.State == v1alpha1.StateInProgress || status.State == v1alpha1.StateErroring) && status.Stage == v1alpha1.StageInterrupt {
2✔
2045
                // call interrupt to recreate the pod if missing
1✔
2046
                err := r.Interrupt(ctx, skyhookNode, _package, interrupt)
1✔
2047
                if err != nil {
1✔
2048
                        return false, err
×
2049
                }
×
2050
        }
2051

2052
        // drain and cordon node before applying package that has an interrupt
2053
        if stage == v1alpha1.StageApply {
2✔
2054
                ready, err := r.EnsureNodeIsReadyForInterrupt(ctx, skyhookNode, _package)
1✔
2055
                if err != nil {
1✔
2056
                        return false, err
×
2057
                }
×
2058

2059
                if !ready {
2✔
2060
                        return false, nil
1✔
2061
                }
1✔
2062
        }
2063

2064
        // time to interrupt (once other packages have finished)
2065
        if stage == v1alpha1.StageInterrupt && runInterrupt {
2✔
2066
                err := r.Interrupt(ctx, skyhookNode, _package, interrupt)
1✔
2067
                if err != nil {
1✔
2068
                        return false, err
×
2069
                }
×
2070

2071
                return false, nil
1✔
2072
        }
2073

2074
        //skipping
2075
        if stage == v1alpha1.StageInterrupt && !runInterrupt {
2✔
2076
                err := skyhookNode.Upsert(_package.PackageRef, _package.Image, v1alpha1.StateSkipped, stage, 0, _package.ContainerSHA)
1✔
2077
                if err != nil {
1✔
2078
                        return false, fmt.Errorf("error upserting to skip interrupt: %w", err)
×
2079
                }
×
2080
                return false, nil
1✔
2081
        }
2082

2083
        // wait tell this is done if its happening
2084
        if status != nil && status.Stage == v1alpha1.StageInterrupt && status.State != v1alpha1.StateComplete {
2✔
2085
                return false, nil
1✔
2086
        }
1✔
2087

2088
        return true, nil
1✔
2089
}
2090

2091
func (r *SkyhookReconciler) EnsureNodeIsReadyForInterrupt(ctx context.Context, skyhookNode wrapper.SkyhookNode, _package *v1alpha1.Package) (bool, error) {
1✔
2092
        // cordon node
1✔
2093
        skyhookNode.Cordon()
1✔
2094

1✔
2095
        hasWork, err := r.HasNonInterruptWork(ctx, skyhookNode)
1✔
2096
        if err != nil {
1✔
2097
                return false, err
×
2098
        }
×
2099
        if hasWork { // keep waiting...
2✔
2100
                return false, nil
1✔
2101
        }
1✔
2102

2103
        ready, err := r.DrainNode(ctx, skyhookNode, _package)
1✔
2104
        if err != nil {
1✔
2105
                return false, fmt.Errorf("error draining node [%s]: %w", skyhookNode.GetNode().Name, err)
×
2106
        }
×
2107

2108
        return ready, nil
1✔
2109
}
2110

2111
// ApplyPackage starts a pod on node for the package
2112
func (r *SkyhookReconciler) ApplyPackage(ctx context.Context, logger logr.Logger, clusterState *clusterState, skyhookNode wrapper.SkyhookNode, _package *v1alpha1.Package, runInterrupt bool) error {
1✔
2113

1✔
2114
        if _package == nil {
1✔
2115
                return errors.New("can not apply nil package")
×
2116
        }
×
2117

2118
        // default starting stage
2119
        stage := v1alpha1.StageApply
1✔
2120

1✔
2121
        // These modes don't have anything that comes before them so we must specify them as the
1✔
2122
        // starting point. The next stage function will return nil until these modes complete.
1✔
2123
        // Config is a special case as sometimes apply will come before it and other times it wont
1✔
2124
        // which is why it needs to be here as well
1✔
2125
        if packageStatus, found := skyhookNode.PackageStatus(_package.GetUniqueName()); found {
2✔
2126
                switch packageStatus.Stage {
1✔
2127
                case v1alpha1.StageConfig, v1alpha1.StageUpgrade, v1alpha1.StageUninstall:
1✔
2128
                        stage = packageStatus.Stage
1✔
2129
                }
2130
        }
2131

2132
        // if stage != v1alpha1.StageApply {
2133
        //         // If a node gets rest by a user, the about method will return the wrong node state. Above sources it from the skyhook status.
2134
        //         // check if the node has nothing, reset it then apply the package.
2135
        //         nodeState, err := skyhookNode.State()
2136
        //         if err != nil {
2137
        //                 return fmt.Errorf("error getting node state: %w", err)
2138
        //         }
2139

2140
        //         _, found := nodeState[_package.GetUniqueName()]
2141
        //         if !found {
2142
        //                 stage = v1alpha1.StageApply
2143
        //         }
2144
        // }
2145

2146
        nextStage := skyhookNode.NextStage(_package)
1✔
2147
        if nextStage != nil {
2✔
2148
                stage = *nextStage
1✔
2149
        }
1✔
2150

2151
        // test if pod exists, if so, bailout
2152
        exists, err := r.PodExists(ctx, skyhookNode.GetNode().Name, skyhookNode.GetSkyhook().Name, _package)
1✔
2153
        if err != nil {
1✔
2154
                return err
×
2155
        }
×
2156

2157
        // wait tell this is done if its happening
2158
        status, found := skyhookNode.PackageStatus(_package.GetUniqueName())
1✔
2159

1✔
2160
        if found && status.State == v1alpha1.StateSkipped { // skipped, so nothing to do
1✔
2161
                return nil
×
2162
        }
×
2163

2164
        if found && status.State == v1alpha1.StateInProgress { // running, so do nothing atm
2✔
2165
                if exists {
2✔
2166
                        return nil
1✔
2167
                }
1✔
2168
        }
2169

2170
        if exists {
2✔
2171
                // nothing to do here, already running
1✔
2172
                return nil
1✔
2173
        }
1✔
2174

2175
        pod := createPodFromPackage(r.opts, _package, skyhookNode.GetSkyhook(), skyhookNode.GetNode().Name, stage)
1✔
2176

1✔
2177
        if err := SetPackages(pod, skyhookNode.GetSkyhook().Skyhook, _package.Image, stage, _package); err != nil {
1✔
2178
                return fmt.Errorf("error setting package on pod: %w", err)
×
2179
        }
×
2180

2181
        // setup ownership of the pod we created
2182
        // helps run time know what to do when something happens to this pod we are about to create
2183
        if err := ctrl.SetControllerReference(skyhookNode.GetSkyhook().Skyhook, pod, r.scheme); err != nil {
1✔
2184
                return fmt.Errorf("error setting ownership: %w", err)
×
2185
        }
×
2186

2187
        if err := r.Create(ctx, pod); err != nil {
1✔
2188
                return fmt.Errorf("error creating pod: %w", err)
×
2189
        }
×
2190

2191
        if err = skyhookNode.Upsert(_package.PackageRef, _package.Image, v1alpha1.StateInProgress, stage, 0, _package.ContainerSHA); err != nil {
1✔
2192
                err = fmt.Errorf("error upserting package: %w", err) // want to keep going in this case, but don't want to lose the err
×
2193
        }
×
2194

2195
        skyhookNode.SetStatus(v1alpha1.StatusInProgress)
1✔
2196

1✔
2197
        skyhookNode.GetSkyhook().AddCondition(metav1.Condition{
1✔
2198
                Type:               fmt.Sprintf("%s/ApplyPackage", v1alpha1.METADATA_PREFIX),
1✔
2199
                Status:             metav1.ConditionTrue,
1✔
2200
                ObservedGeneration: skyhookNode.GetSkyhook().Generation,
1✔
2201
                LastTransitionTime: metav1.Now(),
1✔
2202
                Reason:             "ApplyPackage",
1✔
2203
                Message:            fmt.Sprintf("Applying package [%s:%s] to node [%s]", _package.Name, _package.Version, skyhookNode.GetNode().Name),
1✔
2204
        })
1✔
2205

1✔
2206
        r.recorder.Eventf(skyhookNode.GetNode(), EventTypeNormal, EventsReasonSkyhookApply, "Applying package [%s:%s] from [skyhook:%s] stage [%s]", _package.Name, _package.Version, skyhookNode.GetSkyhook().Name, stage)
1✔
2207
        r.recorder.Eventf(skyhookNode.GetSkyhook(), EventTypeNormal, EventsReasonSkyhookApply, "Applying package [%s:%s] to node [%s] stage [%s]", _package.Name, _package.Version, skyhookNode.GetNode().Name, stage)
1✔
2208

1✔
2209
        skyhookNode.GetSkyhook().Updated = true
1✔
2210

1✔
2211
        return err
1✔
2212
}
2213

2214
// HandleRuntimeRequired finds any nodes for which all runtime required Skyhooks are complete and remove their runtime required taint
2215
// Will return an error if the patching of the nodes is not possible
2216
func (r *SkyhookReconciler) HandleRuntimeRequired(ctx context.Context, clusterState *clusterState) error {
1✔
2217
        node_to_skyhooks, skyhook_node_map := groupSkyhooksByNode(clusterState)
1✔
2218
        to_remove := getRuntimeRequiredTaintCompleteNodes(node_to_skyhooks, skyhook_node_map)
1✔
2219
        // Remove the runtime required taint from nodes in to_remove
1✔
2220
        taint_to_remove := r.opts.GetRuntimeRequiredTaint()
1✔
2221
        errs := make([]error, 0)
1✔
2222
        for _, node := range to_remove {
2✔
2223
                // check before removing taint that it even exists to begin with
1✔
2224
                if !taints.TaintExists(node.Spec.Taints, &taint_to_remove) {
2✔
2225
                        continue
1✔
2226
                }
2227
                // RemoveTaint will ALWAYS return nil for its error so no need to check it
2228
                new_node, updated, _ := taints.RemoveTaint(node, &taint_to_remove)
1✔
2229
                if updated {
2✔
2230
                        err := r.Patch(ctx, new_node, client.MergeFrom(node))
1✔
2231
                        if err != nil {
1✔
2232
                                errs = append(errs, err)
×
2233
                        }
×
2234
                }
2235
        }
2236
        if len(errs) > 0 {
1✔
2237
                return utilerrors.NewAggregate(errs)
×
2238
        }
×
2239
        return nil
1✔
2240
}
2241

2242
// Group Skyhooks by what node they target
2243
func groupSkyhooksByNode(clusterState *clusterState) (map[types.UID][]SkyhookNodes, map[types.UID]*corev1.Node) {
2✔
2244
        node_to_skyhooks := make(map[types.UID][]SkyhookNodes)
2✔
2245
        nodes := make(map[types.UID]*corev1.Node)
2✔
2246
        for _, skyhook := range clusterState.skyhooks {
4✔
2247
                // Ignore skyhooks that don't have runtime required
2✔
2248
                if !skyhook.GetSkyhook().Spec.RuntimeRequired {
4✔
2249
                        continue
2✔
2250
                }
2251
                for _, node := range skyhook.GetNodes() {
4✔
2252
                        if _, ok := node_to_skyhooks[node.GetNode().UID]; !ok {
4✔
2253
                                node_to_skyhooks[node.GetNode().UID] = make([]SkyhookNodes, 0)
2✔
2254
                                nodes[node.GetNode().UID] = node.GetNode()
2✔
2255
                        }
2✔
2256
                        node_to_skyhooks[node.GetNode().UID] = append(node_to_skyhooks[node.GetNode().UID], skyhook)
2✔
2257
                }
2258

2259
        }
2260
        return node_to_skyhooks, nodes
2✔
2261
}
2262

2263
// Get the nodes to remove runtime required taint from node that all skyhooks targeting that node have completed
2264
func getRuntimeRequiredTaintCompleteNodes(node_to_skyhooks map[types.UID][]SkyhookNodes, nodes map[types.UID]*corev1.Node) []*corev1.Node {
2✔
2265
        to_remove := make([]*corev1.Node, 0)
2✔
2266
        for node_uid, skyhooks := range node_to_skyhooks {
4✔
2267
                all_complete := true
2✔
2268
                for _, skyhook := range skyhooks {
4✔
2269
                        if !skyhook.IsComplete() {
4✔
2270
                                all_complete = false
2✔
2271
                                break
2✔
2272
                        }
2273
                }
2274
                if all_complete {
4✔
2275
                        to_remove = append(to_remove, nodes[node_uid])
2✔
2276
                }
2✔
2277
        }
2278
        return to_remove
2✔
2279
}
2280

2281
// setPodResources sets resources for all containers and init containers in the pod if override is set, else leaves empty for LimitRange
2282
func setPodResources(pod *corev1.Pod, res *v1alpha1.ResourceRequirements) {
2✔
2283
        if res == nil {
4✔
2284
                return
2✔
2285
        }
2✔
2286
        if !res.CPURequest.IsZero() || !res.CPULimit.IsZero() || !res.MemoryRequest.IsZero() || !res.MemoryLimit.IsZero() {
4✔
2287
                for i := range pod.Spec.InitContainers {
4✔
2288
                        pod.Spec.InitContainers[i].Resources = corev1.ResourceRequirements{
2✔
2289
                                Limits: corev1.ResourceList{
2✔
2290
                                        corev1.ResourceCPU:    res.CPULimit,
2✔
2291
                                        corev1.ResourceMemory: res.MemoryLimit,
2✔
2292
                                },
2✔
2293
                                Requests: corev1.ResourceList{
2✔
2294
                                        corev1.ResourceCPU:    res.CPURequest,
2✔
2295
                                        corev1.ResourceMemory: res.MemoryRequest,
2✔
2296
                                },
2✔
2297
                        }
2✔
2298
                }
2✔
2299
        }
2300
}
2301

2302
// PartitionNodesIntoCompartments partitions nodes for each skyhook that uses deployment policies.
2303
func partitionNodesIntoCompartments(clusterState *clusterState) error {
2✔
2304
        for _, skyhook := range clusterState.skyhooks {
4✔
2305
                // Skip skyhooks without a deployment policy (they use the default compartment created in BuildState)
2✔
2306
                if skyhook.GetSkyhook().Spec.DeploymentPolicy == "" {
4✔
2307
                        continue
2✔
2308
                }
2309

2310
                // Clear all compartments before reassigning nodes to prevent stale nodes
2311
                // This ensures nodes are only in their current compartment based on current labels
2312
                for _, compartment := range skyhook.GetCompartments() {
2✔
2313
                        compartment.ClearNodes()
1✔
2314
                }
1✔
2315

2316
                for _, node := range skyhook.GetNodes() {
2✔
2317
                        compartmentName, err := skyhook.AssignNodeToCompartment(node)
1✔
2318
                        if err != nil {
1✔
2319
                                return fmt.Errorf("error assigning node %s: %w", node.GetNode().Name, err)
×
2320
                        }
×
2321
                        skyhook.AddCompartmentNode(compartmentName, node)
1✔
2322
                }
2323
        }
2324

2325
        return nil
2✔
2326
}
2327

2328
// validateAndUpsertSkyhookData performs validation and configmap operations for a skyhook
2329
func (r *SkyhookReconciler) validateAndUpsertSkyhookData(ctx context.Context, skyhook SkyhookNodes, clusterState *clusterState) (bool, ctrl.Result, error) {
1✔
2330
        if yes, result, err := shouldReturn(r.ValidateRunningPackages(ctx, skyhook)); yes {
2✔
2331
                return yes, result, err
1✔
2332
        }
1✔
2333

2334
        if yes, result, err := shouldReturn(r.ValidateNodeConfigmaps(ctx, skyhook.GetSkyhook().Name, skyhook.GetNodes())); yes {
2✔
2335
                return yes, result, err
1✔
2336
        }
1✔
2337

2338
        if yes, result, err := shouldReturn(r.UpsertConfigmaps(ctx, skyhook, clusterState)); yes {
2✔
2339
                return yes, result, err
1✔
2340
        }
1✔
2341

2342
        return false, ctrl.Result{}, nil
1✔
2343
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc