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

package controller_common

import (
	"context"
	"crypto/sha256"
	"encoding/json"
	"fmt"
25
	"reflect"
26
	"sort"
27
	"strconv"
28

29
30
	"github.com/ai-dynamo/dynamo/deploy/operator/api/v1alpha1"
	"github.com/ai-dynamo/dynamo/deploy/operator/internal/consts"
31
	"github.com/google/go-cmp/cmp"
32
	corev1 "k8s.io/api/core/v1"
33
	"k8s.io/apimachinery/pkg/api/errors"
34
	"k8s.io/apimachinery/pkg/api/resource"
35
36
	"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
	"k8s.io/apimachinery/pkg/runtime"
37
	"k8s.io/apimachinery/pkg/types"
38
39
	"k8s.io/client-go/tools/record"
	ctrl "sigs.k8s.io/controller-runtime"
40
41
	"sigs.k8s.io/controller-runtime/pkg/client"
	"sigs.k8s.io/controller-runtime/pkg/client/apiutil"
42
	"sigs.k8s.io/controller-runtime/pkg/log"
43
44
45
46
47
)

const (
	// NvidiaAnnotationHashKey indicates annotation name for last applied hash by the operator
	NvidiaAnnotationHashKey = "nvidia.com/last-applied-hash"
48
49
50
	// NvidiaAnnotationGenerationKey indicates annotation name for last applied generation by the operator
	// This is used to detect manual changes to resources
	NvidiaAnnotationGenerationKey = "nvidia.com/last-applied-generation"
51
52
)

53
54
55
type Reconciler interface {
	client.Client
	GetRecorder() record.EventRecorder
56
57
}

58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
// ResourceGenerator is a function that generates a resource.
// it must return the resource, a boolean indicating if the resource should be deleted, and an error
// if the resource should be deleted, the returned resource must contain the necessary information to delete it (name and namespace)
type ResourceGenerator[T client.Object] func(ctx context.Context) (T, bool, error)

//nolint:nakedret
func SyncResource[T client.Object](ctx context.Context, r Reconciler, parentResource client.Object, generateResource ResourceGenerator[T]) (modified bool, res T, err error) {
	logs := log.FromContext(ctx)

	resource, toDelete, err := generateResource(ctx)
	if err != nil {
		return
	}
	resourceNamespace := resource.GetNamespace()
	resourceName := resource.GetName()
	resourceType := reflect.TypeOf(resource).Elem().Name()
	logs = logs.WithValues("namespace", resourceNamespace, "resourceName", resourceName, "resourceType", resourceType)

76
	// Retrieve the GroupVersionKind (GVK) of the desired object
77
	gvk, err := apiutil.GVKForObject(resource, r.Scheme())
78
	if err != nil {
79
80
		logs.Error(err, "Failed to get GVK for object")
		return
81
82
83
	}

	// Create a new instance of the object
84
	obj, err := r.Scheme().New(gvk)
85
	if err != nil {
86
87
		logs.Error(err, "Failed to create a new object for GVK")
		return
88
89
90
	}

	// Type assertion to ensure the object implements client.Object
91
	oldResource, ok := obj.(T)
92
	if !ok {
93
		return
94
	}
95
96
97
98

	err = r.Get(ctx, types.NamespacedName{Name: resourceName, Namespace: resourceNamespace}, oldResource)
	oldResourceIsNotFound := errors.IsNotFound(err)
	if err != nil && !oldResourceIsNotFound {
99
		r.GetRecorder().Eventf(resource, corev1.EventTypeWarning, fmt.Sprintf("Get%s", resourceType), "Failed to get %s %s: %s", resourceType, resourceNamespace, err)
100
101
		logs.Error(err, "Failed to get resource.")
		return
102
	}
103
	err = nil
104

105
106
107
108
109
110
111
	if oldResourceIsNotFound {
		if toDelete {
			logs.Info("Resource not found. Nothing to do.")
			return
		}
		logs.Info("Resource not found. Creating a new one.")

112
113
114
115
116
117
118
119
120
121
122
		// Only set controller reference if parentResource is provided
		// Passing nil as parentResource creates an independent resource (no owner reference)
		if parentResource != nil {
			err = ctrl.SetControllerReference(parentResource, resource, r.Scheme())
			if err != nil {
				logs.Error(err, "Failed to set controller reference.")
				r.GetRecorder().Eventf(resource, corev1.EventTypeWarning, "SetControllerReference", "Failed to set controller reference for %s %s: %s", resourceType, resourceNamespace, err)
				return
			}
		} else {
			logs.Info("No parent resource provided, creating resource without owner reference (independent lifecycle)")
123
124
125
126
127
128
		}

		var hash string
		hash, err = GetSpecHash(resource)
		if err != nil {
			logs.Error(err, "Failed to get spec hash.")
129
			r.GetRecorder().Eventf(resource, corev1.EventTypeWarning, "GetSpecHash", "Failed to get spec hash for %s %s: %s", resourceType, resourceNamespace, err)
130
131
132
			return
		}

133
134
		// On create, set generation to 1 (new resources start at generation 1)
		updateAnnotations(resource, hash, 1)
135

136
		r.GetRecorder().Eventf(resource, corev1.EventTypeNormal, fmt.Sprintf("Create%s", resourceType), "Creating a new %s %s", resourceType, resourceNamespace)
137
138
139
		err = r.Create(ctx, resource)
		if err != nil {
			logs.Error(err, "Failed to create Resource.")
140
			r.GetRecorder().Eventf(resource, corev1.EventTypeWarning, fmt.Sprintf("Create%s", resourceType), "Failed to create %s %s: %s", resourceType, resourceNamespace, err)
141
142
143
			return
		}
		logs.Info(fmt.Sprintf("%s created.", resourceType))
144
		r.GetRecorder().Eventf(resource, corev1.EventTypeNormal, fmt.Sprintf("Create%s", resourceType), "Created %s %s", resourceType, resourceNamespace)
145
146
147
148
149
		modified = true
		res = resource
	} else {
		logs.Info(fmt.Sprintf("%s found.", resourceType))
		if toDelete {
150
			logs.Info(fmt.Sprintf("%s found. Deleting the existing one.", resourceType))
151
152
153
			err = r.Delete(ctx, oldResource)
			if err != nil {
				logs.Error(err, fmt.Sprintf("Failed to delete %s.", resourceType))
154
				r.GetRecorder().Eventf(oldResource, corev1.EventTypeWarning, fmt.Sprintf("Delete%s", resourceType), "Failed to delete %s %s: %s", resourceType, resourceNamespace, err)
155
				return
156
			}
157
			logs.Info(fmt.Sprintf("%s deleted.", resourceType))
158
			r.GetRecorder().Eventf(oldResource, corev1.EventTypeNormal, fmt.Sprintf("Delete%s", resourceType), "Deleted %s %s", resourceType, resourceNamespace)
159
160
161
162
163
			modified = true
			return
		}

		// Check if the Spec has changed and update if necessary
164
165
		var changeResult SpecChangeResult
		changeResult, err = GetSpecChangeResult(oldResource, resource)
166
		if err != nil {
167
			r.GetRecorder().Eventf(resource, corev1.EventTypeWarning, fmt.Sprintf("CalculatePatch%s", resourceType), "Failed to calculate patch for %s %s: %s", resourceType, resourceNamespace, err)
168
			return false, resource, fmt.Errorf("failed to check if spec has changed: %w", err)
169
		}
170

171
		if !changeResult.NeedsUpdate {
172
			logs.Info(fmt.Sprintf("%s spec is the same. Skipping update.", resourceType))
173
			r.GetRecorder().Eventf(oldResource, corev1.EventTypeNormal, fmt.Sprintf("Update%s", resourceType), "Skipping update %s %s", resourceType, resourceNamespace)
174
			res = oldResource
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
			return
		}

		// Log if manual changes were detected
		if changeResult.ManualChangeDetected {
			logs.Info(fmt.Sprintf("Manual changes detected on %s, will be overwritten", resourceType),
				"currentGeneration", oldResource.GetGeneration(),
				"lastAppliedGeneration", getAnnotation(oldResource, NvidiaAnnotationGenerationKey))
		}

		// Generate and log diff before updating
		diff, diffErr := generateSpecDiff(oldResource, resource)
		if diffErr != nil {
			logs.V(1).Info(fmt.Sprintf("Failed to generate diff for %s: %v", resourceType, diffErr))
		} else if diff != "" {
			logs.Info(fmt.Sprintf("%s spec changes detected", resourceType), "diff", diff)
191
		}
192
193
194
195
196

		// Update the spec of the current object with the desired spec
		err = CopySpec(resource, oldResource)
		if err != nil {
			logs.Error(err, fmt.Sprintf("Failed to copy spec for %s.", resourceType))
197
			r.GetRecorder().Eventf(oldResource, corev1.EventTypeWarning, fmt.Sprintf("CopySpec%s", resourceType), "Failed to copy spec for %s %s: %s", resourceType, resourceNamespace, err)
198
199
200
201
202
203
204
205
			return
		}

		updateAnnotations(oldResource, *changeResult.NewHash, changeResult.NewGeneration)

		err = r.Update(ctx, oldResource)
		if err != nil {
			logs.Error(err, fmt.Sprintf("Failed to update %s.", resourceType))
206
			r.GetRecorder().Eventf(oldResource, corev1.EventTypeWarning, fmt.Sprintf("Update%s", resourceType), "Failed to update %s %s: %s", resourceType, resourceNamespace, err)
207
208
209
			return
		}
		logs.Info(fmt.Sprintf("%s updated.", resourceType))
210
		r.GetRecorder().Eventf(oldResource, corev1.EventTypeNormal, fmt.Sprintf("Update%s", resourceType), "Updated %s %s", resourceType, resourceNamespace)
211
212
		modified = true
		res = oldResource
213
214
215
216
217
	}
	return
}

// CopySpec copies only the Spec field from source to destination using Unstructured
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258

// kubeEnvelopeFields are standard top-level Kubernetes fields that don't
// represent the resource's desired state. Everything else (spec, data,
// rules, roleRef, subjects, etc.) is considered content.
var kubeEnvelopeFields = map[string]bool{
	"apiVersion": true,
	"kind":       true,
	"metadata":   true,
	"status":     true,
}

// nonEnvelopeFields returns all top-level fields from an unstructured map
// except the Kubernetes envelope (apiVersion, kind, metadata, status).
func nonEnvelopeFields(obj map[string]interface{}) map[string]interface{} {
	content := make(map[string]interface{}, len(obj))
	for k, v := range obj {
		if kubeEnvelopeFields[k] {
			continue
		}
		content[k] = v
	}
	return content
}

// getContentFields returns all content fields from an unstructured object,
// i.e. everything except the Kubernetes envelope (apiVersion, kind, metadata, status).
// For resources with a "spec" field, it returns the spec directly for
// backward-compatible hashing. For spec-less resources (ConfigMaps, Secrets,
// Roles, etc.), it returns a map of all content fields.
func getContentFields(u *unstructured.Unstructured) (any, bool) {
	if spec, found, err := unstructured.NestedFieldCopy(u.Object, "spec"); err == nil && found {
		return spec, true
	}

	content := nonEnvelopeFields(u.Object)
	if len(content) == 0 {
		return nil, false
	}
	return content, true
}

259
260
261
262
263
264
265
266
267
268
269
270
271
func CopySpec(source, destination client.Object) error {
	sourceMap, err := runtime.DefaultUnstructuredConverter.ToUnstructured(source)
	if err != nil {
		return err
	}
	sourceUnstructured := &unstructured.Unstructured{Object: sourceMap}

	destMap, err := runtime.DefaultUnstructuredConverter.ToUnstructured(destination)
	if err != nil {
		return err
	}
	destUnstructured := &unstructured.Unstructured{Object: destMap}

272
273
274
275
276
	if spec, found, err := unstructured.NestedFieldCopy(sourceUnstructured.Object, "spec"); err == nil && found {
		if err := unstructured.SetNestedField(destUnstructured.Object, spec, "spec"); err != nil {
			return err
		}
		return runtime.DefaultUnstructuredConverter.FromUnstructured(destUnstructured.Object, destination)
277
278
	}

279
280
	for k, v := range nonEnvelopeFields(sourceUnstructured.Object) {
		destUnstructured.Object[k] = v
281
282
	}

283
284
285
286
287
288
289
290
291
	return runtime.DefaultUnstructuredConverter.FromUnstructured(destUnstructured.Object, destination)
}

func getSpec(obj client.Object) (any, error) {
	sourceMap, err := runtime.DefaultUnstructuredConverter.ToUnstructured(obj)
	if err != nil {
		return nil, err
	}
	sourceUnstructured := &unstructured.Unstructured{Object: sourceMap}
292
293

	content, found := getContentFields(sourceUnstructured)
294
295
296
	if !found {
		return nil, nil
	}
297
	return content, nil
298
299
}

300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
// SpecChangeResult contains the result of spec change detection
type SpecChangeResult struct {
	// NewHash is the hash to set in the annotation (nil if no update needed)
	NewHash *string
	// NewGeneration is the generation to set in the annotation
	NewGeneration int64
	// NeedsUpdate indicates whether the resource needs to be updated
	NeedsUpdate bool
	// ManualChangeDetected indicates whether a manual change was detected
	ManualChangeDetected bool
}

// GetSpecChangeResult determines if a resource needs to be updated by comparing the desired spec hash
// with the last applied hash annotation. It also tracks generation to detect manual changes.
//
// Returns:
//   - SpecChangeResult with update information
//   - error if hash computation fails
func GetSpecChangeResult(current client.Object, desired client.Object) (SpecChangeResult, error) {
319
	desiredHash, err := GetSpecHash(desired)
320
	if err != nil {
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
		return SpecChangeResult{}, err
	}

	lastAppliedHash := getAnnotation(current, NvidiaAnnotationHashKey)
	lastAppliedGenStr := getAnnotation(current, NvidiaAnnotationGenerationKey)
	currentGen := current.GetGeneration()

	// Case 1: Hash annotation missing (external create or pre-upgrade resource)
	// Note: This is not first-time CREATE (handled separately in SyncResource with generation=1).
	// This handles existing resources without our annotations - we're about to update them,
	// so NewGeneration = currentGen + 1 is correct.
	if lastAppliedHash == "" {
		return SpecChangeResult{
			NewHash:       &desiredHash,
			NewGeneration: currentGen + 1,
			NeedsUpdate:   true,
		}, nil
338
	}
339

340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
	// Case 2: Hash different (spec changed)
	if desiredHash != lastAppliedHash {
		return SpecChangeResult{
			NewHash:       &desiredHash,
			NewGeneration: currentGen + 1,
			NeedsUpdate:   true,
		}, nil
	}

	// Case 3: Hash same, but generation annotation missing (upgrade scenario)
	// Do a full update to ensure spec is exactly what we want - there could have been
	// manual edits before we added generation tracking. The cost is one extra Update
	// per resource during upgrade, but on next reconcile generations will match.
	if lastAppliedGenStr == "" {
		return SpecChangeResult{
			NewHash:       &desiredHash,
			NewGeneration: currentGen + 1,
			NeedsUpdate:   true,
		}, nil
	}

	// Case 4: Both annotations exist, check for manual changes
	lastAppliedGen, err := strconv.ParseInt(lastAppliedGenStr, 10, 64)
363
	if err != nil {
364
365
366
367
368
369
		// Corrupted annotation, force update to fix
		return SpecChangeResult{
			NewHash:       &desiredHash,
			NewGeneration: currentGen + 1,
			NeedsUpdate:   true,
		}, nil
370
	}
371

372
373
374
375
376
377
378
379
380
	// Detect manual changes: if current generation > last applied generation,
	// someone else modified the resource after our last update
	if currentGen > 0 && currentGen > lastAppliedGen {
		return SpecChangeResult{
			NewHash:              &desiredHash,
			NewGeneration:        currentGen + 1,
			NeedsUpdate:          true,
			ManualChangeDetected: true,
		}, nil
381
382
	}

383
384
385
386
387
388
389
390
391
392
393
394
395
	// No update needed
	return SpecChangeResult{
		NeedsUpdate: false,
	}, nil
}

// getAnnotation safely retrieves an annotation value from an object
func getAnnotation(obj client.Object, key string) string {
	annotations := obj.GetAnnotations()
	if annotations == nil {
		return ""
	}
	return annotations[key]
396
}
397

398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
// generateSpecDiff creates a unified diff showing changes between old and new resource specs
func generateSpecDiff(oldResource, newResource client.Object) (string, error) {
	oldSpec, err := getSpec(oldResource)
	if err != nil {
		return "", fmt.Errorf("failed to get old spec: %w", err)
	}

	newSpec, err := getSpec(newResource)
	if err != nil {
		return "", fmt.Errorf("failed to get new spec: %w", err)
	}

	// Generate diff using cmp
	diff := cmp.Diff(oldSpec, newSpec)
	if diff == "" {
		return "", nil
	}

	return diff, nil
}

419
420
421
422
423
424
425
426
func GetSpecHash(obj client.Object) (string, error) {
	spec, err := getSpec(obj)
	if err != nil {
		return "", err
	}
	return GetResourceHash(spec)
}

427
428
// updateAnnotations sets both hash and generation annotations on an object
func updateAnnotations(obj client.Object, hash string, generation int64) {
429
430
431
432
433
	annotations := obj.GetAnnotations()
	if annotations == nil {
		annotations = map[string]string{}
	}
	annotations[NvidiaAnnotationHashKey] = hash
434
	annotations[NvidiaAnnotationGenerationKey] = strconv.FormatInt(generation, 10)
435
	obj.SetAnnotations(annotations)
436
437
438
}

// GetResourceHash returns a consistent hash for the given object spec
439
func GetResourceHash(obj any) (string, error) {
440
441
442
	// Convert obj to a map[string]interface{}
	objMap, err := json.Marshal(obj)
	if err != nil {
443
		return "", err
444
445
446
447
	}

	var objData map[string]interface{}
	if err := json.Unmarshal(objMap, &objData); err != nil {
448
		return "", err
449
450
451
452
453
454
455
456
	}

	// Sort keys to ensure consistent serialization
	sortedObjData := SortKeys(objData)

	// Serialize to JSON
	serialized, err := json.Marshal(sortedObjData)
	if err != nil {
457
		return "", err
458
459
460
461
462
	}

	// Compute the hash
	hasher := sha256.New()
	hasher.Write(serialized)
463
	return fmt.Sprintf("%x", hasher.Sum(nil)), nil
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
}

// SortKeys recursively sorts the keys of a map to ensure consistent serialization
func SortKeys(obj interface{}) interface{} {
	switch obj := obj.(type) {
	case map[string]interface{}:
		sortedMap := make(map[string]interface{})
		keys := make([]string, 0, len(obj))
		for k := range obj {
			keys = append(keys, k)
		}
		sort.Strings(keys)
		for _, k := range keys {
			sortedMap[k] = SortKeys(obj[k])
		}
		return sortedMap
	case []interface{}:
		// Check if the slice contains maps and sort them by the "name" field or the first available field
		if len(obj) > 0 {

			if _, ok := obj[0].(map[string]interface{}); ok {
				sort.SliceStable(obj, func(i, j int) bool {
					iMap, iOk := obj[i].(map[string]interface{})
					jMap, jOk := obj[j].(map[string]interface{})
					if iOk && jOk {
						// Try to sort by "name" if present
						iName, iNameOk := iMap["name"].(string)
						jName, jNameOk := jMap["name"].(string)
						if iNameOk && jNameOk {
							return iName < jName
						}

						// If "name" is not available, sort by the first key in each map
						if len(iMap) > 0 && len(jMap) > 0 {
							iFirstKey := firstKey(iMap)
							jFirstKey := firstKey(jMap)
							return iFirstKey < jFirstKey
						}
					}
					// If no valid comparison is possible, maintain the original order
					return false
				})
			}
		}
		for i, v := range obj {
			obj[i] = SortKeys(v)
		}
	}
	return obj
}

// Helper function to get the first key of a map (alphabetically sorted)
func firstKey(m map[string]interface{}) string {
	keys := make([]string, 0, len(m))
	for k := range m {
		keys = append(keys, k)
	}
	sort.Strings(keys)
	return keys[0]
}
524

525
func GetResourcesConfig(resources *v1alpha1.Resources) (*corev1.ResourceRequirements, error) {
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561

	if resources == nil {
		return nil, nil
	}

	currentResources := &corev1.ResourceRequirements{}

	if resources.Limits != nil {
		if resources.Limits.CPU != "" {
			q, err := resource.ParseQuantity(resources.Limits.CPU)
			if err != nil {
				return nil, fmt.Errorf("parse limits cpu quantity: %w", err)
			}
			if currentResources.Limits == nil {
				currentResources.Limits = make(corev1.ResourceList)
			}
			currentResources.Limits[corev1.ResourceCPU] = q
		}
		if resources.Limits.Memory != "" {
			q, err := resource.ParseQuantity(resources.Limits.Memory)
			if err != nil {
				return nil, fmt.Errorf("parse limits memory quantity: %w", err)
			}
			if currentResources.Limits == nil {
				currentResources.Limits = make(corev1.ResourceList)
			}
			currentResources.Limits[corev1.ResourceMemory] = q
		}
		if resources.Limits.GPU != "" {
			q, err := resource.ParseQuantity(resources.Limits.GPU)
			if err != nil {
				return nil, fmt.Errorf("parse limits gpu quantity: %w", err)
			}
			if currentResources.Limits == nil {
				currentResources.Limits = make(corev1.ResourceList)
			}
562
			currentResources.Limits[getGPUResourceName(resources.Limits)] = q
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
		}
		for k, v := range resources.Limits.Custom {
			q, err := resource.ParseQuantity(v)
			if err != nil {
				return nil, fmt.Errorf("parse limits %s quantity: %w", k, err)
			}
			if currentResources.Limits == nil {
				currentResources.Limits = make(corev1.ResourceList)
			}
			currentResources.Limits[corev1.ResourceName(k)] = q
		}
	}
	if resources.Requests != nil {
		if resources.Requests.CPU != "" {
			q, err := resource.ParseQuantity(resources.Requests.CPU)
			if err != nil {
				return nil, fmt.Errorf("parse requests cpu quantity: %w", err)
			}
			if currentResources.Requests == nil {
				currentResources.Requests = make(corev1.ResourceList)
			}
			currentResources.Requests[corev1.ResourceCPU] = q
		}
		if resources.Requests.Memory != "" {
			q, err := resource.ParseQuantity(resources.Requests.Memory)
			if err != nil {
				return nil, fmt.Errorf("parse requests memory quantity: %w", err)
			}
			if currentResources.Requests == nil {
				currentResources.Requests = make(corev1.ResourceList)
			}
			currentResources.Requests[corev1.ResourceMemory] = q
		}
		for k, v := range resources.Requests.Custom {
			q, err := resource.ParseQuantity(v)
			if err != nil {
				return nil, fmt.Errorf("parse requests %s quantity: %w", k, err)
			}
			if currentResources.Requests == nil {
				currentResources.Requests = make(corev1.ResourceList)
			}
			currentResources.Requests[corev1.ResourceName(k)] = q
		}
	}
607
608
609
610
611
612
	if resources.Claims != nil {
		if currentResources.Claims == nil {
			currentResources.Claims = make([]corev1.ResourceClaim, 0)
		}
		currentResources.Claims = append(currentResources.Claims, resources.Claims...)
	}
613
614
615
	return currentResources, nil
}

616
617
618
619
620
621
622
623
624
625
func getGPUResourceName(resourceItem *v1alpha1.ResourceItem) corev1.ResourceName {
	if resourceItem == nil {
		return corev1.ResourceName(consts.KubeResourceGPUNvidia)
	}
	if resourceItem.GPUType != "" {
		return corev1.ResourceName(resourceItem.GPUType)
	}
	return corev1.ResourceName(consts.KubeResourceGPUNvidia)
}

626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
// AppendUniqueImagePullSecrets appends secrets to existing, skipping any that already exist by name.
func AppendUniqueImagePullSecrets(existing, additional []corev1.LocalObjectReference) []corev1.LocalObjectReference {
	if len(additional) == 0 {
		return existing
	}
	seen := make(map[string]bool, len(existing))
	for _, s := range existing {
		seen[s.Name] = true
	}
	for _, s := range additional {
		if !seen[s.Name] {
			existing = append(existing, s)
			seen[s.Name] = true
		}
	}
	return existing
}

644
type Resource struct {
645
646
647
648
	object          client.Object
	isReady         bool
	readyReason     string
	serviceStatuses map[string]v1alpha1.ServiceReplicaStatus
649
650
}

651
652
653
654
655
656
657
func NewResource[T client.Object](resource T, isReady func() (bool, string)) (*Resource, error) {
	v := reflect.ValueOf(resource)
	// handles untype nil and typed nil
	if !v.IsValid() || v.IsNil() {
		return nil, fmt.Errorf("resource is nil")
	}
	ready, reason := isReady()
658
	return &Resource{
659
660
661
662
663
664
665
666
667
668
669
		object:      resource,
		isReady:     ready,
		readyReason: reason,
	}, nil
}

func NewResourceWithServiceStatuses[T client.Object](resource T, isReadyAndServiceStatuses func() (bool, string, map[string]v1alpha1.ServiceReplicaStatus)) (*Resource, error) {
	v := reflect.ValueOf(resource)
	// handles untype nil and typed nil
	if !v.IsValid() || v.IsNil() {
		return nil, fmt.Errorf("resource is nil")
670
	}
671
672
673
674
675
676
677
	ready, reason, serviceStatuses := isReadyAndServiceStatuses()
	return &Resource{
		object:          resource,
		isReady:         ready,
		readyReason:     reason,
		serviceStatuses: serviceStatuses,
	}, nil
678
679
}

680
func (r *Resource) IsReady() (bool, string) {
681
	return r.isReady, r.readyReason
682
}
683
684

func (r *Resource) GetName() string {
685
686
687
688
689
	return r.object.GetName()
}

func (r *Resource) GetServiceStatuses() map[string]v1alpha1.ServiceReplicaStatus {
	return r.serviceStatuses
690
}