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

NVIDIA / skyhook / 20356483807

19 Dec 2025 01:12AM UTC coverage: 75.906% (-0.05%) from 75.958%
20356483807

Pull #135

github

web-flow
Merge 2a99285b9 into 19dce4787
Pull Request #135: fix(chart): add missing rbac for deploymentpolicies

5822 of 7670 relevant lines covered (75.91%)

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
//+kubebuilder:rbac:groups=skyhook.nvidia.com,resources=deploymentpolicies,verbs=get;list;watch
228

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1✔
386
        updates := false
1✔
387

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

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

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

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

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

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

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

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

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

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

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

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

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

449
                        updates = true
1✔
450
                }
451
        }
452

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

457
        return updates, nil
1✔
458
}
459

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

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

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

475
        return false, nil
1✔
476
}
477

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

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

489
        return false, nil
1✔
490
}
491

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

774
        return toUninstall, nil
1✔
775
}
776

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

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

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

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

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

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

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

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

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

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

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

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

869
        return nil
2✔
870
}
871

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

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

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

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

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

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

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

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

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

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

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

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

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

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

969
        return false, nil
1✔
970
}
971

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

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

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

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

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

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

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

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

1043
        return updated, nil
1✔
1044
}
1045

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

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

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

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

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

1067
        }
1068

1069
        return true, nil
1✔
1070
}
1071

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

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

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

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

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

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

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

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

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

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

1✔
1121
                                node.Uncordon()
1✔
1122

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

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

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

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

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

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

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

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

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

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

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

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

1188
        return false, nil
×
1189
}
1190

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1✔
1297
        return nil
1✔
1298
}
1299

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1819
        return filteredEnv
2✔
1820
}
1821

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

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

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

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

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

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

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

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

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

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

1896
        return true
2✔
1897
}
1898

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

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

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

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

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

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

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

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

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

1✔
1960
                        // 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✔
1961
                        if runningPackage.Stage == v1alpha1.StageUninstall {
2✔
1962
                                found = true
1✔
1963
                        }
1✔
1964

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

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

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

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

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

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

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

2018
        return nil
1✔
2019
}
2020

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

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

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

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

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

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

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

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

2072
                return false, nil
1✔
2073
        }
2074

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

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

2089
        return true, nil
1✔
2090
}
2091

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

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

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

2109
        return ready, nil
1✔
2110
}
2111

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1✔
2207
        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✔
2208
        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✔
2209

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

1✔
2212
        return err
1✔
2213
}
2214

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

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

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

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

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

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

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

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

2326
        return nil
2✔
2327
}
2328

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

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

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

2343
        return false, ctrl.Result{}, nil
1✔
2344
}
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

© 2025 Coveralls, Inc