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

package controller

import (
	"bytes"
	"context"
	"crypto/md5"
	"encoding/base64"
	"encoding/hex"
	"encoding/json"
	"fmt"
	"os"
	"path/filepath"
	"strconv"
	"strings"
	"text/template"
	"time"

	"emperror.dev/errors"
38
39
40
41
	commonconfig "github.com/ai-dynamo/dynamo/deploy/cloud/operator/internal/config"
	"github.com/ai-dynamo/dynamo/deploy/cloud/operator/internal/consts"
	commonconsts "github.com/ai-dynamo/dynamo/deploy/cloud/operator/internal/consts"
	"github.com/ai-dynamo/dynamo/deploy/cloud/operator/internal/controller_common"
42
	"github.com/apparentlymart/go-shquot/shquot"
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
	"github.com/huandu/xstrings"
	"github.com/mitchellh/hashstructure/v2"
	"github.com/prune998/docker-registry-client/registry"
	"github.com/rs/xid"
	"github.com/sergeymakinen/go-quote/unix"
	"github.com/sirupsen/logrus"
	"gopkg.in/yaml.v2"
	batchv1 "k8s.io/api/batch/v1"
	corev1 "k8s.io/api/core/v1"
	k8serrors "k8s.io/apimachinery/pkg/api/errors"
	"k8s.io/apimachinery/pkg/api/meta"
	"k8s.io/apimachinery/pkg/api/resource"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/apimachinery/pkg/runtime"
	"k8s.io/apimachinery/pkg/types"
	"k8s.io/client-go/tools/record"
	"k8s.io/utils/ptr"
	ctrl "sigs.k8s.io/controller-runtime"
	"sigs.k8s.io/controller-runtime/pkg/builder"
	"sigs.k8s.io/controller-runtime/pkg/client"
	"sigs.k8s.io/controller-runtime/pkg/log"
	"sigs.k8s.io/controller-runtime/pkg/predicate"

66
67
68
69
	apiStoreClient "github.com/ai-dynamo/dynamo/deploy/cloud/operator/api/dynamo/api_store_client"
	dynamoCommon "github.com/ai-dynamo/dynamo/deploy/cloud/operator/api/dynamo/common"
	"github.com/ai-dynamo/dynamo/deploy/cloud/operator/api/dynamo/schemas"
	nvidiacomv1alpha1 "github.com/ai-dynamo/dynamo/deploy/cloud/operator/api/v1alpha1"
70
71
)

72
73
74
75
76
77
const (
	dockerConfigSecretKey = ".dockerconfigjson"
)

// DynamoComponentReconciler reconciles a DynamoComponent object
type DynamoComponentReconciler struct {
78
79
80
81
82
83
	client.Client
	Scheme   *runtime.Scheme
	Recorder record.EventRecorder
	Config   controller_common.Config
}

84
85
86
// +kubebuilder:rbac:groups=nvidia.com,resources=dynamocomponents,verbs=get;list;watch;create;update;patch;delete
// +kubebuilder:rbac:groups=nvidia.com,resources=dynamocomponents/status,verbs=get;update;patch
// +kubebuilder:rbac:groups=nvidia.com,resources=dynamocomponents/finalizers,verbs=update
87
88
//+kubebuilder:rbac:groups=nvidia.com,resources=dynamocomponents,verbs=get;list;watch;create;update;patch;delete
//+kubebuilder:rbac:groups=nvidia.com,resources=dynamocomponents/status,verbs=get;update;patch
89
90
91
92
93
94
95
96
97
98
99
//+kubebuilder:rbac:groups=events.k8s.io,resources=events,verbs=get;list;watch;create;update;patch;delete
//+kubebuilder:rbac:groups=core,resources=events,verbs=get;list;watch;create;update;patch;delete
//+kubebuilder:rbac:groups=core,resources=pods,verbs=get;list;watch;create;update;patch;delete
//+kubebuilder:rbac:groups=core,resources=configmaps,verbs=get;list;watch;create;update;patch;delete
//+kubebuilder:rbac:groups=core,resources=secrets,verbs=get;list;watch;create;update;patch;delete
//+kubebuilder:rbac:groups=core,resources=serviceaccounts,verbs=get;list;watch
//+kubebuilder:rbac:groups=coordination.k8s.io,resources=leases,verbs=get;list;watch;create;update;patch;delete

// Reconcile is part of the main kubernetes reconciliation loop which aims to
// move the current state of the cluster closer to the desired state.
// TODO(user): Modify the Reconcile function to compare the state specified by
100
// the DynamoComponent object against the actual cluster state, and then
101
102
103
104
105
106
107
// perform operations to make the cluster state reflect the state specified by
// the user.
//
// For more details, check Reconcile and its Result here:
// - https://pkg.go.dev/sigs.k8s.io/controller-runtime@v0.18.2/pkg/reconcile
//
//nolint:gocyclo,nakedret
108
func (r *DynamoComponentReconciler) Reconcile(ctx context.Context, req ctrl.Request) (result ctrl.Result, err error) {
109
110
	logs := log.FromContext(ctx)

111
	DynamoComponent := &nvidiacomv1alpha1.DynamoComponent{}
112

113
	err = r.Get(ctx, req.NamespacedName, DynamoComponent)
114
115
116
117
118

	if err != nil {
		if k8serrors.IsNotFound(err) {
			// Object not found, return.  Created objects are automatically garbage collected.
			// For additional cleanup logic use finalizers.
119
			logs.Info("DynamoComponent resource not found. Ignoring since object must be deleted")
120
121
122
123
			err = nil
			return
		}
		// Error reading the object - requeue the request.
124
		logs.Error(err, "Failed to get DynamoComponent")
125
126
127
		return
	}

128
129
130
	if DynamoComponent.IsReady() {
		logs.Info("Skip available DynamoComponent")
		return
131
132
	}

133
134
	if len(DynamoComponent.Status.Conditions) == 0 {
		DynamoComponent, err = r.setStatusConditions(ctx, req,
135
			metav1.Condition{
136
				Type:    nvidiacomv1alpha1.DynamoComponentConditionTypeImageBuilding,
137
138
				Status:  metav1.ConditionUnknown,
				Reason:  "Reconciling",
139
				Message: "Starting to reconcile DynamoComponent",
140
141
			},
			metav1.Condition{
142
				Type:    nvidiacomv1alpha1.DynamoComponentConditionTypeImageExists,
143
144
				Status:  metav1.ConditionUnknown,
				Reason:  "Reconciling",
145
				Message: "Starting to reconcile DynamoComponent",
146
147
			},
			metav1.Condition{
148
				Type:    nvidiacomv1alpha1.DynamoComponentConditionTypeDynamoComponentAvailable,
149
150
				Status:  metav1.ConditionUnknown,
				Reason:  "Reconciling",
151
				Message: "Reconciling",
152
153
154
155
156
157
158
			},
		)
		if err != nil {
			return
		}
	}

159
	logs = logs.WithValues("DynamoComponent", DynamoComponent.Name, "DynamoComponentNamespace", DynamoComponent.Namespace)
160
161
162
163
164
165

	defer func() {
		if err == nil {
			logs.Info("Reconcile success")
			return
		}
166
167
		logs.Error(err, "Failed to reconcile DynamoComponent.")
		r.Recorder.Eventf(DynamoComponent, corev1.EventTypeWarning, "ReconcileError", "Failed to reconcile DynamoComponent: %v", err)
168
169
		_, err_ := r.setStatusConditions(ctx, req,
			metav1.Condition{
170
				Type:    nvidiacomv1alpha1.DynamoComponentConditionTypeDynamoComponentAvailable,
171
172
173
174
175
176
				Status:  metav1.ConditionFalse,
				Reason:  "Reconciling",
				Message: err.Error(),
			},
		)
		if err_ != nil {
177
			logs.Error(err_, "Failed to update DynamoComponent status")
178
179
180
181
			return
		}
	}()

182
183
184
	DynamoComponent, _, imageExists, imageExistsResult, err := r.ensureImageExists(ctx, ensureImageExistsOption{
		DynamoComponent: DynamoComponent,
		req:             req,
185
186
187
188
189
190
191
192
193
	})

	if err != nil {
		err = errors.Wrapf(err, "ensure image exists")
		return
	}

	if !imageExists {
		result = imageExistsResult
194
		DynamoComponent, err = r.setStatusConditions(ctx, req,
195
			metav1.Condition{
196
				Type:    nvidiacomv1alpha1.DynamoComponentConditionTypeDynamoComponentAvailable,
197
198
				Status:  metav1.ConditionUnknown,
				Reason:  "Reconciling",
199
				Message: "DynamoComponent image is building",
200
201
202
203
204
205
206
207
			},
		)
		if err != nil {
			return
		}
		return
	}

208
	DynamoComponent, err = r.setStatusConditions(ctx, req,
209
		metav1.Condition{
210
			Type:    nvidiacomv1alpha1.DynamoComponentConditionTypeDynamoComponentAvailable,
211
212
			Status:  metav1.ConditionTrue,
			Reason:  "Reconciling",
213
			Message: "DynamoComponent image is generated",
214
215
216
217
218
219
220
221
222
223
224
225
226
227
		},
	)
	if err != nil {
		return
	}

	return
}

func isEstargzEnabled() bool {
	return os.Getenv("ESTARGZ_ENABLED") == commonconsts.KubeLabelValueTrue
}

type ensureImageExistsOption struct {
228
229
	DynamoComponent *nvidiacomv1alpha1.DynamoComponent
	req             ctrl.Request
230
231
232
}

//nolint:gocyclo,nakedret
233
func (r *DynamoComponentReconciler) ensureImageExists(ctx context.Context, opt ensureImageExistsOption) (DynamoComponent *nvidiacomv1alpha1.DynamoComponent, imageInfo ImageInfo, imageExists bool, result ctrl.Result, err error) { // nolint: unparam
234
235
	logs := log.FromContext(ctx)

236
	DynamoComponent = opt.DynamoComponent
237
238
239
	req := opt.req

	imageInfo, err = r.getImageInfo(ctx, GetImageInfoOption{
240
		DynamoComponent: DynamoComponent,
241
242
243
244
245
246
	})
	if err != nil {
		err = errors.Wrap(err, "get image info")
		return
	}

247
248
	imageExistsCheckedCondition := meta.FindStatusCondition(DynamoComponent.Status.Conditions, nvidiacomv1alpha1.DynamoComponentConditionTypeImageExistsChecked)
	imageExistsCondition := meta.FindStatusCondition(DynamoComponent.Status.Conditions, nvidiacomv1alpha1.DynamoComponentConditionTypeImageExists)
249
250
	if imageExistsCheckedCondition == nil || imageExistsCheckedCondition.Status != metav1.ConditionTrue || imageExistsCheckedCondition.Message != imageInfo.ImageName {
		imageExistsCheckedCondition = &metav1.Condition{
251
			Type:    nvidiacomv1alpha1.DynamoComponentConditionTypeImageExistsChecked,
252
253
254
255
			Status:  metav1.ConditionUnknown,
			Reason:  "Reconciling",
			Message: imageInfo.ImageName,
		}
256
		dynamoComponentAvailableCondition := &metav1.Condition{
257
			Type:    nvidiacomv1alpha1.DynamoComponentConditionTypeDynamoComponentAvailable,
258
259
260
261
			Status:  metav1.ConditionUnknown,
			Reason:  "Reconciling",
			Message: "Checking image exists",
		}
262
		DynamoComponent, err = r.setStatusConditions(ctx, req, *imageExistsCheckedCondition, *dynamoComponentAvailableCondition)
263
264
265
		if err != nil {
			return
		}
266
267
		r.Recorder.Eventf(DynamoComponent, corev1.EventTypeNormal, "CheckingImage", "Checking image exists: %s", imageInfo.ImageName)
		imageExists, err = checkImageExists(DynamoComponent, imageInfo.DockerRegistry, imageInfo.ImageName)
268
269
270
271
272
		if err != nil {
			err = errors.Wrapf(err, "check image %s exists", imageInfo.ImageName)
			return
		}

273
		err = r.Get(ctx, req.NamespacedName, DynamoComponent)
274
		if err != nil {
275
			logs.Error(err, "Failed to re-fetch DynamoComponent")
276
277
278
279
			return
		}

		if imageExists {
280
			r.Recorder.Eventf(DynamoComponent, corev1.EventTypeNormal, "CheckingImage", "Image exists: %s", imageInfo.ImageName)
281
			imageExistsCheckedCondition = &metav1.Condition{
282
				Type:    nvidiacomv1alpha1.DynamoComponentConditionTypeImageExistsChecked,
283
284
285
286
287
				Status:  metav1.ConditionTrue,
				Reason:  "Reconciling",
				Message: imageInfo.ImageName,
			}
			imageExistsCondition = &metav1.Condition{
288
				Type:    nvidiacomv1alpha1.DynamoComponentConditionTypeImageExists,
289
290
291
292
				Status:  metav1.ConditionTrue,
				Reason:  "Reconciling",
				Message: imageInfo.ImageName,
			}
293
			DynamoComponent, err = r.setStatusConditions(ctx, req, *imageExistsCondition, *imageExistsCheckedCondition)
294
295
296
297
			if err != nil {
				return
			}
		} else {
298
			r.Recorder.Eventf(DynamoComponent, corev1.EventTypeNormal, "CheckingImage", "Image not exists: %s", imageInfo.ImageName)
299
			imageExistsCheckedCondition = &metav1.Condition{
300
				Type:    nvidiacomv1alpha1.DynamoComponentConditionTypeImageExistsChecked,
301
302
303
304
305
				Status:  metav1.ConditionFalse,
				Reason:  "Reconciling",
				Message: fmt.Sprintf("Image not exists: %s", imageInfo.ImageName),
			}
			imageExistsCondition = &metav1.Condition{
306
				Type:    nvidiacomv1alpha1.DynamoComponentConditionTypeImageExists,
307
308
309
310
				Status:  metav1.ConditionFalse,
				Reason:  "Reconciling",
				Message: fmt.Sprintf("Image %s is not exists", imageInfo.ImageName),
			}
311
			DynamoComponent, err = r.setStatusConditions(ctx, req, *imageExistsCondition, *imageExistsCheckedCondition)
312
313
314
315
316
317
			if err != nil {
				return
			}
		}
	}

318
319
	var DynamoComponentHashStr string
	DynamoComponentHashStr, err = r.getHashStr(DynamoComponent)
320
	if err != nil {
321
		err = errors.Wrapf(err, "get DynamoComponent %s/%s hash string", DynamoComponent.Namespace, DynamoComponent.Name)
322
323
324
325
326
327
328
329
330
		return
	}

	imageExists = imageExistsCondition != nil && imageExistsCondition.Status == metav1.ConditionTrue && imageExistsCondition.Message == imageInfo.ImageName
	if imageExists {
		return
	}

	jobLabels := map[string]string{
331
332
		commonconsts.KubeLabelDynamoComponent:      DynamoComponent.Name,
		commonconsts.KubeLabelIsDynamoImageBuilder: commonconsts.KubeLabelValueTrue,
333
334
335
336
337
338
339
340
341
342
343
344
345
	}

	jobs := &batchv1.JobList{}
	err = r.List(ctx, jobs, client.InNamespace(req.Namespace), client.MatchingLabels(jobLabels))
	if err != nil {
		err = errors.Wrap(err, "list jobs")
		return
	}

	reservedJobs := make([]*batchv1.Job, 0)
	for _, job_ := range jobs.Items {
		job_ := job_

346
347
348
		oldHash := job_.Annotations[consts.KubeAnnotationDynamoComponentHash]
		if oldHash != DynamoComponentHashStr {
			logs.Info("Because hash changed, delete old job", "job", job_.Name, "oldHash", oldHash, "newHash", DynamoComponentHashStr)
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
			// --cascade=foreground
			err = r.Delete(ctx, &job_, &client.DeleteOptions{
				PropagationPolicy: &[]metav1.DeletionPropagation{metav1.DeletePropagationForeground}[0],
			})
			if err != nil {
				err = errors.Wrapf(err, "delete job %s", job_.Name)
				return
			}
			return
		} else {
			reservedJobs = append(reservedJobs, &job_)
		}
	}

	var job *batchv1.Job
	if len(reservedJobs) > 0 {
		job = reservedJobs[0]
	}

	if len(reservedJobs) > 1 {
		for _, job_ := range reservedJobs[1:] {
			logs.Info("Because has more than one job, delete old job", "job", job_.Name)
			// --cascade=foreground
			err = r.Delete(ctx, job_, &client.DeleteOptions{
				PropagationPolicy: &[]metav1.DeletionPropagation{metav1.DeletePropagationForeground}[0],
			})
			if err != nil {
				err = errors.Wrapf(err, "delete job %s", job_.Name)
				return
			}
		}
	}

	if job == nil {
		job, err = r.generateImageBuilderJob(ctx, GenerateImageBuilderJobOption{
384
385
			ImageInfo:       imageInfo,
			DynamoComponent: DynamoComponent,
386
387
388
389
390
		})
		if err != nil {
			err = errors.Wrap(err, "generate image builder job")
			return
		}
391
		r.Recorder.Eventf(DynamoComponent, corev1.EventTypeNormal, "GenerateImageBuilderJob", "Creating image builder job: %s", job.Name)
392
393
394
395
396
		err = r.Create(ctx, job)
		if err != nil {
			err = errors.Wrapf(err, "create image builder job %s", job.Name)
			return
		}
397
		r.Recorder.Eventf(DynamoComponent, corev1.EventTypeNormal, "GenerateImageBuilderJob", "Created image builder job: %s", job.Name)
398
399
400
		return
	}

401
	r.Recorder.Eventf(DynamoComponent, corev1.EventTypeNormal, "CheckingImageBuilderJob", "Found image builder job: %s", job.Name)
402

403
	err = r.Get(ctx, req.NamespacedName, DynamoComponent)
404
	if err != nil {
405
		logs.Error(err, "Failed to re-fetch DynamoComponent")
406
407
		return
	}
408
	imageBuildingCondition := meta.FindStatusCondition(DynamoComponent.Status.Conditions, nvidiacomv1alpha1.DynamoComponentConditionTypeImageBuilding)
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432

	isJobFailed := false
	isJobRunning := true

	if job.Spec.Completions != nil {
		if job.Status.Succeeded != *job.Spec.Completions {
			if job.Status.Failed > 0 {
				for _, condition := range job.Status.Conditions {
					if condition.Type == batchv1.JobFailed && condition.Status == corev1.ConditionTrue {
						isJobFailed = true
						break
					}
				}
			}
			isJobRunning = !isJobFailed
		} else {
			isJobRunning = false
		}
	}

	if isJobRunning {
		conditions := make([]metav1.Condition, 0)
		if job.Status.Active > 0 {
			conditions = append(conditions, metav1.Condition{
433
				Type:    nvidiacomv1alpha1.DynamoComponentConditionTypeImageBuilding,
434
435
436
437
438
439
				Status:  metav1.ConditionTrue,
				Reason:  "Reconciling",
				Message: fmt.Sprintf("Image building job %s is running", job.Name),
			})
		} else {
			conditions = append(conditions, metav1.Condition{
440
				Type:    nvidiacomv1alpha1.DynamoComponentConditionTypeImageBuilding,
441
442
443
444
445
				Status:  metav1.ConditionUnknown,
				Reason:  "Reconciling",
				Message: fmt.Sprintf("Image building job %s is waiting", job.Name),
			})
		}
446
447
		if DynamoComponent.Spec.ImageBuildTimeout != nil {
			if imageBuildingCondition != nil && imageBuildingCondition.LastTransitionTime.Add(time.Duration(*DynamoComponent.Spec.ImageBuildTimeout)).Before(time.Now()) {
448
				conditions = append(conditions, metav1.Condition{
449
					Type:    nvidiacomv1alpha1.DynamoComponentConditionTypeImageBuilding,
450
451
452
453
454
455
456
457
458
459
460
461
					Status:  metav1.ConditionFalse,
					Reason:  "Timeout",
					Message: fmt.Sprintf("Image building job %s is timeout", job.Name),
				})
				if _, err = r.setStatusConditions(ctx, req, conditions...); err != nil {
					return
				}
				err = errors.New("image build timeout")
				return
			}
		}

462
		if DynamoComponent, err = r.setStatusConditions(ctx, req, conditions...); err != nil {
463
464
465
466
			return
		}

		if imageBuildingCondition != nil && imageBuildingCondition.Status != metav1.ConditionTrue && isJobRunning {
467
			r.Recorder.Eventf(DynamoComponent, corev1.EventTypeNormal, "DynamoComponentImageBuilder", "Image is building now")
468
469
470
471
472
473
		}

		return
	}

	if isJobFailed {
474
		DynamoComponent, err = r.setStatusConditions(ctx, req,
475
			metav1.Condition{
476
				Type:    nvidiacomv1alpha1.DynamoComponentConditionTypeImageBuilding,
477
478
479
480
481
				Status:  metav1.ConditionFalse,
				Reason:  "Reconciling",
				Message: fmt.Sprintf("Image building job %s is failed.", job.Name),
			},
			metav1.Condition{
482
				Type:    nvidiacomv1alpha1.DynamoComponentConditionTypeDynamoComponentAvailable,
483
484
485
486
487
488
489
490
491
492
493
				Status:  metav1.ConditionFalse,
				Reason:  "Reconciling",
				Message: fmt.Sprintf("Image building job %s is failed.", job.Name),
			},
		)
		if err != nil {
			return
		}
		return
	}

494
	DynamoComponent, err = r.setStatusConditions(ctx, req,
495
		metav1.Condition{
496
			Type:    nvidiacomv1alpha1.DynamoComponentConditionTypeImageBuilding,
497
498
499
500
501
			Status:  metav1.ConditionFalse,
			Reason:  "Reconciling",
			Message: fmt.Sprintf("Image building job %s is succeeded.", job.Name),
		},
		metav1.Condition{
502
			Type:    nvidiacomv1alpha1.DynamoComponentConditionTypeImageExists,
503
504
505
506
507
508
509
510
511
			Status:  metav1.ConditionTrue,
			Reason:  "Reconciling",
			Message: imageInfo.ImageName,
		},
	)
	if err != nil {
		return
	}

512
	r.Recorder.Eventf(DynamoComponent, corev1.EventTypeNormal, "DynamoComponentImageBuilder", "Image has been built successfully")
513
514
515
516
517
518

	imageExists = true

	return
}

519
520
func (r *DynamoComponentReconciler) setStatusConditions(ctx context.Context, req ctrl.Request, conditions ...metav1.Condition) (DynamoComponent *nvidiacomv1alpha1.DynamoComponent, err error) {
	DynamoComponent = &nvidiacomv1alpha1.DynamoComponent{}
521
522
523
524
525
526
	/*
		Please don't blame me when you see this kind of code,
		this is to avoid "the object has been modified; please apply your changes to the latest version and try again" when updating CR status,
		don't doubt that almost all CRD operators (e.g. cert-manager) can't avoid this stupid error and can only try to avoid this by this stupid way.
	*/
	for i := 0; i < 3; i++ {
527
528
		if err = r.Get(ctx, req.NamespacedName, DynamoComponent); err != nil {
			err = errors.Wrap(err, "Failed to re-fetch DynamoComponent")
529
530
531
			return
		}
		for _, condition := range conditions {
532
			meta.SetStatusCondition(&DynamoComponent.Status.Conditions, condition)
533
		}
534
		if err = r.Status().Update(ctx, DynamoComponent); err != nil {
535
536
537
538
539
540
			time.Sleep(100 * time.Millisecond)
		} else {
			break
		}
	}
	if err != nil {
541
		err = errors.Wrap(err, "Failed to update DynamoComponent status")
542
543
		return
	}
544
545
	if err = r.Get(ctx, req.NamespacedName, DynamoComponent); err != nil {
		err = errors.Wrap(err, "Failed to re-fetch DynamoComponent")
546
547
548
549
550
		return
	}
	return
}

551
type DynamoComponentImageBuildEngine string
552
553

const (
554
555
556
	DynamoComponentImageBuildEngineKaniko           DynamoComponentImageBuildEngine = "kaniko"
	DynamoComponentImageBuildEngineBuildkit         DynamoComponentImageBuildEngine = "buildkit"
	DynamoComponentImageBuildEngineBuildkitRootless DynamoComponentImageBuildEngine = "buildkit-rootless"
557
558
559
)

const (
560
	EnvDynamoImageBuildEngine = "DYNAMO_IMAGE_BUILD_ENGINE"
561
562
)

563
func getDynamoComponentImageBuildEngine() DynamoComponentImageBuildEngine {
564
	engine := os.Getenv(EnvDynamoImageBuildEngine)
565
	if engine == "" {
566
		return DynamoComponentImageBuildEngineKaniko
567
	}
568
	return DynamoComponentImageBuildEngine(engine)
569
570
571
}

//nolint:nakedret
572
func (r *DynamoComponentReconciler) getApiStoreClient(ctx context.Context) (*apiStoreClient.ApiStoreClient, *commonconfig.ApiStoreConfig, error) {
573
	apiStoreConf, err := commonconfig.GetApiStoreConfig(ctx)
574
575
	isNotFound := k8serrors.IsNotFound(err)
	if err != nil && !isNotFound {
576
577
		err = errors.Wrap(err, "get api store config")
		return nil, nil, err
578
579
580
	}

	if isNotFound {
581
		return nil, nil, err
582
583
	}

584
585
	if apiStoreConf.Endpoint == "" {
		return nil, nil, err
586
587
	}

588
589
	if apiStoreConf.ClusterName == "" {
		apiStoreConf.ClusterName = "default"
590
591
	}

592
	apiStoreClient := apiStoreClient.NewApiStoreClient(apiStoreConf.Endpoint)
593

594
	return apiStoreClient, apiStoreConf, nil
595
596
}

597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
func (r *DynamoComponentReconciler) RetrieveDockerRegistrySecret(ctx context.Context, secretName string, namespace string, dockerRegistry *schemas.DockerRegistrySchema) error {
	secret := &corev1.Secret{}
	err := r.Get(ctx, types.NamespacedName{
		Namespace: namespace,
		Name:      secretName,
	}, secret)
	if err != nil {
		err = errors.Wrapf(err, "get docker config json secret %s", secretName)
		return err
	}
	configJSON, ok := secret.Data[dockerConfigSecretKey]
	if !ok {
		err = errors.Errorf("docker config json secret %s does not have %s key", secretName, dockerConfigSecretKey)
		return err
	}
	var configObj struct {
		Auths map[string]struct {
			Auth string `json:"auth"`
		} `json:"auths"`
	}
	err = json.Unmarshal(configJSON, &configObj)
	if err != nil {
		err = errors.Wrapf(err, "unmarshal docker config json secret %s", secretName)
		return err
	}
	var server string
	var auth string
	if dockerRegistry.Server != "" {
		for k, v := range configObj.Auths {
			if k == dockerRegistry.Server {
				server = k
				auth = v.Auth
				break
			}
631
		}
632
		if server == "" {
633
			for k, v := range configObj.Auths {
634
				if strings.Contains(k, dockerRegistry.Server) {
635
636
637
638
639
640
641
					server = k
					auth = v.Auth
					break
				}
			}
		}
	}
642
643
644
645
646
647
	if server == "" {
		err = errors.Errorf("no auth in docker config json secret %s for server %s", secretName, dockerRegistry.Server)
		return err
	}
	var credentials []byte
	credentials, err = base64.StdEncoding.DecodeString(auth)
648
	if err != nil {
649
650
		err = errors.Wrapf(err, "cannot base64 decode auth in docker config json secret %s", secretName)
		return err
651
	}
652
653
654
655
656
657
658
659
	dockerRegistry.Username, _, dockerRegistry.Password = xstrings.Partition(string(credentials), ":")
	return nil
}

//nolint:nakedret
func (r *DynamoComponentReconciler) getDockerRegistry(ctx context.Context, DynamoComponent *nvidiacomv1alpha1.DynamoComponent) (dockerRegistry *schemas.DockerRegistrySchema, err error) {

	dockerRegistryConfig := commonconfig.GetDockerRegistryConfig()
660

661
662
663
	dynamoRepositoryName := "dynamo-components"
	if dockerRegistryConfig.DynamoComponentsRepositoryName != "" {
		dynamoRepositoryName = dockerRegistryConfig.DynamoComponentsRepositoryName
664
	}
665
	dynamoRepositoryURI := fmt.Sprintf("%s/%s", strings.TrimRight(dockerRegistryConfig.Server, "/"), dynamoRepositoryName)
666
	if strings.Contains(dockerRegistryConfig.Server, "docker.io") {
667
		dynamoRepositoryURI = fmt.Sprintf("docker.io/%s", dynamoRepositoryName)
668
	}
669
670
671

	if DynamoComponent != nil && DynamoComponent.Spec.DockerConfigJSONSecretName != "" {
		dockerRegistryConfig.SecretName = DynamoComponent.Spec.DockerConfigJSONSecretName
672
	}
673
674
675
676
677
678
679
680
681
682
683
684

	dockerRegistry = &schemas.DockerRegistrySchema{
		Server:              dockerRegistryConfig.Server,
		Secure:              dockerRegistryConfig.Secure,
		DynamoRepositoryURI: dynamoRepositoryURI,
		SecretName:          dockerRegistryConfig.SecretName,
	}

	err = r.RetrieveDockerRegistrySecret(ctx, dockerRegistryConfig.SecretName, DynamoComponent.Namespace, dockerRegistry)
	if err != nil {
		err = errors.Wrap(err, "retrieve docker registry secret")
		return
685
686
687
688
689
690
691
692
693
	}

	return
}

func isAddNamespacePrefix() bool {
	return os.Getenv("ADD_NAMESPACE_PREFIX_TO_IMAGE_NAME") == trueStr
}

694
695
func getDynamoComponentImagePrefix(DynamoComponent *nvidiacomv1alpha1.DynamoComponent) string {
	if DynamoComponent == nil {
696
697
		return ""
	}
698
	prefix, exist := DynamoComponent.Annotations[consts.KubeAnnotationDynamoComponentStorageNS]
699
700
701
702
	if exist && prefix != "" {
		return fmt.Sprintf("%s.", prefix)
	}
	if isAddNamespacePrefix() {
703
		return fmt.Sprintf("%s.", DynamoComponent.Namespace)
704
705
706
707
	}
	return ""
}

708
709
710
func getDynamoComponentImageName(DynamoComponent *nvidiacomv1alpha1.DynamoComponent, dockerRegistry schemas.DockerRegistrySchema, dynamoComponentRepositoryName, dynamoComponentVersion string) string {
	if DynamoComponent != nil && DynamoComponent.Spec.Image != "" {
		return DynamoComponent.Spec.Image
711
712
	}
	var uri, tag string
713
	uri = dockerRegistry.DynamoRepositoryURI
714
	tail := fmt.Sprintf("%s.%s", dynamoComponentRepositoryName, dynamoComponentVersion)
715
716
717
718
	if isEstargzEnabled() {
		tail += ".esgz"
	}

719
	tag = fmt.Sprintf("dynamo.%s%s", getDynamoComponentImagePrefix(DynamoComponent), tail)
720
721
722

	if len(tag) > 128 {
		hashStr := hash(tail)
723
		tag = fmt.Sprintf("dynamo.%s%s", getDynamoComponentImagePrefix(DynamoComponent), hashStr)
724
		if len(tag) > 128 {
725
			tag = fmt.Sprintf("dynamo.%s", hash(fmt.Sprintf("%s%s", getDynamoComponentImagePrefix(DynamoComponent), tail)))[:128]
726
727
728
729
730
		}
	}
	return fmt.Sprintf("%s:%s", uri, tag)
}

731
732
func checkImageExists(DynamoComponent *nvidiacomv1alpha1.DynamoComponent, dockerRegistry schemas.DockerRegistrySchema, imageName string) (bool, error) {
	if DynamoComponent.Annotations["nvidia.com/force-build-image"] == commonconsts.KubeLabelValueTrue {
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
		return false, nil
	}

	server, _, imageName := xstrings.Partition(imageName, "/")
	if strings.Contains(server, "docker.io") {
		server = "index.docker.io"
	}
	if dockerRegistry.Secure {
		server = fmt.Sprintf("https://%s", server)
	} else {
		server = fmt.Sprintf("http://%s", server)
	}
	hub, err := registry.New(server, dockerRegistry.Username, dockerRegistry.Password, logrus.Debugf)
	if err != nil {
		err = errors.Wrapf(err, "create docker registry client for %s", server)
		return false, err
	}
	imageName, _, tag := xstrings.LastPartition(imageName, ":")
	tags, err := hub.Tags(imageName)
	isNotFound := err != nil && strings.Contains(err.Error(), "404")
	if isNotFound {
		return false, nil
	}
	if err != nil {
		err = errors.Wrapf(err, "get tags for docker image %s", imageName)
		return false, err
	}
	for _, tag_ := range tags {
		if tag_ == tag {
			return true, nil
		}
	}
	return false, nil
}

type ImageInfo struct {
769
	DockerRegistry             schemas.DockerRegistrySchema
770
771
772
773
774
775
	DockerConfigJSONSecretName string
	ImageName                  string
	DockerRegistryInsecure     bool
}

type GetImageInfoOption struct {
776
	DynamoComponent *nvidiacomv1alpha1.DynamoComponent
777
778
779
}

//nolint:nakedret
780
781
782
func (r *DynamoComponentReconciler) getImageInfo(ctx context.Context, opt GetImageInfoOption) (imageInfo ImageInfo, err error) {
	dynamoComponentRepositoryName, _, dynamoComponentVersion := xstrings.Partition(opt.DynamoComponent.Spec.DynamoComponent, ":")
	dockerRegistry, err := r.getDockerRegistry(ctx, opt.DynamoComponent)
783
784
785
786
	if err != nil {
		err = errors.Wrap(err, "get docker registry")
		return
	}
787
788
	imageInfo.DockerRegistry = *dockerRegistry
	imageInfo.ImageName = getDynamoComponentImageName(opt.DynamoComponent, *dockerRegistry, dynamoComponentRepositoryName, dynamoComponentVersion)
789

790
	imageInfo.DockerConfigJSONSecretName = dockerRegistry.SecretName
791

792
	imageInfo.DockerRegistryInsecure = opt.DynamoComponent.Annotations[commonconsts.KubeAnnotationDynamoDockerRegistryInsecure] == "true"
793
794
795
	return
}

796
func (r *DynamoComponentReconciler) getImageBuilderJobName() string {
797
	guid := xid.New()
798
	return fmt.Sprintf("dynamo-image-builder-%s", guid.String())
799
800
}

801
func (r *DynamoComponentReconciler) getImageBuilderJobLabels(DynamoComponent *nvidiacomv1alpha1.DynamoComponent) map[string]string {
802
	return map[string]string{
803
804
		commonconsts.KubeLabelDynamoComponent:      DynamoComponent.Name,
		commonconsts.KubeLabelIsDynamoImageBuilder: "true",
805
806
807
	}
}

808
func (r *DynamoComponentReconciler) getImageBuilderPodLabels(DynamoComponent *nvidiacomv1alpha1.DynamoComponent) map[string]string {
809
	return map[string]string{
810
811
		commonconsts.KubeLabelDynamoComponent:      DynamoComponent.Name,
		commonconsts.KubeLabelIsDynamoImageBuilder: "true",
812
813
814
815
816
817
818
819
820
821
	}
}

func hash(text string) string {
	// nolint: gosec
	hasher := md5.New()
	hasher.Write([]byte(text))
	return hex.EncodeToString(hasher.Sum(nil))
}

822
type GenerateImageBuilderJobOption struct {
823
824
	ImageInfo       ImageInfo
	DynamoComponent *nvidiacomv1alpha1.DynamoComponent
825
826
827
}

//nolint:nakedret
828
func (r *DynamoComponentReconciler) generateImageBuilderJob(ctx context.Context, opt GenerateImageBuilderJobOption) (job *batchv1.Job, err error) {
829
	// nolint: gosimple
830
	podTemplateSpec, err := r.generateImageBuilderPodTemplateSpec(ctx, GenerateImageBuilderPodTemplateSpecOption(opt))
831
	if err != nil {
832
		err = errors.Wrap(err, "generate image builder pod template spec")
833
834
835
		return
	}
	kubeAnnotations := make(map[string]string)
836
	hashStr, err := r.getHashStr(opt.DynamoComponent)
837
838
839
840
	if err != nil {
		err = errors.Wrap(err, "failed to get hash string")
		return
	}
841
	kubeAnnotations[consts.KubeAnnotationDynamoComponentHash] = hashStr
842
843
	job = &batchv1.Job{
		ObjectMeta: metav1.ObjectMeta{
844
			Name:        r.getImageBuilderJobName(),
845
846
			Namespace:   opt.DynamoComponent.Namespace,
			Labels:      r.getImageBuilderJobLabels(opt.DynamoComponent),
847
848
849
			Annotations: kubeAnnotations,
		},
		Spec: batchv1.JobSpec{
850
851
852
			TTLSecondsAfterFinished: ptr.To(int32(60 * 60 * 24)),
			Completions:             ptr.To(int32(1)),
			Parallelism:             ptr.To(int32(1)),
853
854
855
856
857
			PodFailurePolicy: &batchv1.PodFailurePolicy{
				Rules: []batchv1.PodFailurePolicyRule{
					{
						Action: batchv1.PodFailurePolicyActionFailJob,
						OnExitCodes: &batchv1.PodFailurePolicyOnExitCodesRequirement{
858
							ContainerName: ptr.To(BuilderContainerName),
859
							Operator:      batchv1.PodFailurePolicyOnExitCodesOpIn,
860
							Values:        []int32{BuilderJobFailedExitCode},
861
862
863
864
865
866
867
						},
					},
				},
			},
			Template: *podTemplateSpec,
		},
	}
868
	err = ctrl.SetControllerReference(opt.DynamoComponent, job, r.Scheme)
869
870
871
872
873
874
875
	if err != nil {
		err = errors.Wrapf(err, "set controller reference for job %s", job.Name)
		return
	}
	return
}

876
func injectPodAffinity(podSpec *corev1.PodSpec, DynamoComponent *nvidiacomv1alpha1.DynamoComponent) {
877
878
879
	if podSpec.Affinity == nil {
		podSpec.Affinity = &corev1.Affinity{}
	}
880
881
882
883
884
885
886
887
888
889

	if podSpec.Affinity.PodAffinity == nil {
		podSpec.Affinity.PodAffinity = &corev1.PodAffinity{}
	}

	podSpec.Affinity.PodAffinity.PreferredDuringSchedulingIgnoredDuringExecution = append(podSpec.Affinity.PodAffinity.PreferredDuringSchedulingIgnoredDuringExecution, corev1.WeightedPodAffinityTerm{
		Weight: 100,
		PodAffinityTerm: corev1.PodAffinityTerm{
			LabelSelector: &metav1.LabelSelector{
				MatchLabels: map[string]string{
890
					commonconsts.KubeLabelDynamoComponent: DynamoComponent.Name,
891
892
893
894
895
896
897
898
899
900
901
902
903
				},
			},
			TopologyKey: corev1.LabelHostname,
		},
	})
}

const BuilderContainerName = "builder"
const BuilderJobFailedExitCode = 42
const ModelSeederContainerName = "seeder"
const ModelSeederJobFailedExitCode = 42

type GenerateImageBuilderPodTemplateSpecOption struct {
904
905
	ImageInfo       ImageInfo
	DynamoComponent *nvidiacomv1alpha1.DynamoComponent
906
907
908
}

//nolint:gocyclo,nakedret
909
910
911
func (r *DynamoComponentReconciler) generateImageBuilderPodTemplateSpec(ctx context.Context, opt GenerateImageBuilderPodTemplateSpecOption) (pod *corev1.PodTemplateSpec, err error) {
	dynamoComponentRepositoryName, _, dynamoComponentVersion := xstrings.Partition(opt.DynamoComponent.Spec.DynamoComponent, ":")
	kubeLabels := r.getImageBuilderPodLabels(opt.DynamoComponent)
912

913
	imageName := opt.ImageInfo.ImageName
914
915
916
917
918
919
920

	dockerConfigJSONSecretName := opt.ImageInfo.DockerConfigJSONSecretName

	dockerRegistryInsecure := opt.ImageInfo.DockerRegistryInsecure

	volumes := []corev1.Volume{
		{
921
			Name: "dynamo",
922
923
924
925
926
927
928
929
930
931
932
933
934
935
			VolumeSource: corev1.VolumeSource{
				EmptyDir: &corev1.EmptyDirVolumeSource{},
			},
		},
		{
			Name: "workspace",
			VolumeSource: corev1.VolumeSource{
				EmptyDir: &corev1.EmptyDirVolumeSource{},
			},
		},
	}

	volumeMounts := []corev1.VolumeMount{
		{
936
937
			Name:      "dynamo",
			MountPath: "/dynamo",
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
		},
		{
			Name:      "workspace",
			MountPath: "/workspace",
		},
	}

	if dockerConfigJSONSecretName != "" {
		volumes = append(volumes, corev1.Volume{
			Name: dockerConfigJSONSecretName,
			VolumeSource: corev1.VolumeSource{
				Secret: &corev1.SecretVolumeSource{
					SecretName: dockerConfigJSONSecretName,
					Items: []corev1.KeyToPath{
						{
							Key:  ".dockerconfigjson",
							Path: "config.json",
						},
					},
				},
			},
		})
		volumeMounts = append(volumeMounts, corev1.VolumeMount{
			Name:      dockerConfigJSONSecretName,
			MountPath: "/kaniko/.docker/",
		})
	}

966
	var dynamoComponent *schemas.DynamoComponent
967
	dynamoComponentDownloadURL := opt.DynamoComponent.Spec.DownloadURL
968

969
970
971
	if dynamoComponentDownloadURL == "" {
		var apiStoreClient *apiStoreClient.ApiStoreClient
		var apiStoreConf *commonconfig.ApiStoreConfig
972

973
		apiStoreClient, apiStoreConf, err = r.getApiStoreClient(ctx)
974
		if err != nil {
975
			err = errors.Wrap(err, "get api store client")
976
977
978
			return
		}

979
980
		if apiStoreClient == nil || apiStoreConf == nil {
			err = errors.New("can't get api store client, please check api store configuration")
981
982
983
			return
		}

984
		r.Recorder.Eventf(opt.DynamoComponent, corev1.EventTypeNormal, "GenerateImageBuilderPod", "Getting dynamoComponent %s from api store service", opt.DynamoComponent.Spec.DynamoComponent)
985
		dynamoComponent, err = apiStoreClient.GetDynamoComponent(ctx, dynamoComponentRepositoryName, dynamoComponentVersion)
986
		if err != nil {
987
			err = errors.Wrap(err, "get dynamoComponent")
988
989
			return
		}
990
		r.Recorder.Eventf(opt.DynamoComponent, corev1.EventTypeNormal, "GenerateImageBuilderPod", "Got dynamoComponent %s from api store service", opt.DynamoComponent.Spec.DynamoComponent)
991

992
993
		if dynamoComponent.TransmissionStrategy != nil && *dynamoComponent.TransmissionStrategy == schemas.TransmissionStrategyPresignedURL {
			var dynamoComponent_ *schemas.DynamoComponent
994
			r.Recorder.Eventf(opt.DynamoComponent, corev1.EventTypeNormal, "GenerateImageBuilderPod", "Getting presigned url for dynamoComponent %s from api store service", opt.DynamoComponent.Spec.DynamoComponent)
995
			dynamoComponent_, err = apiStoreClient.PresignDynamoComponentDownloadURL(ctx, dynamoComponentRepositoryName, dynamoComponentVersion)
996
			if err != nil {
997
				err = errors.Wrap(err, "presign dynamoComponent download url")
998
999
				return
			}
1000
			r.Recorder.Eventf(opt.DynamoComponent, corev1.EventTypeNormal, "GenerateImageBuilderPod", "Got presigned url for dynamoComponent %s from api store service", opt.DynamoComponent.Spec.DynamoComponent)
1001
			dynamoComponentDownloadURL = dynamoComponent_.PresignedDownloadUrl
1002
		} else {
1003
			dynamoComponentDownloadURL = fmt.Sprintf("%s/api/v1/dynamo_nims/%s/versions/%s/download", apiStoreConf.Endpoint, dynamoComponentRepositoryName, dynamoComponentVersion)
1004
1005
1006
1007
1008
1009
		}

	}
	internalImages := commonconfig.GetInternalImages()
	logrus.Infof("Image builder is using the images %v", *internalImages)

1010
	buildEngine := getDynamoComponentImageBuildEngine()
1011

1012
	privileged := buildEngine != DynamoComponentImageBuildEngineBuildkitRootless
1013

1014
	dynamoComponentDownloadCommandTemplate, err := template.New("downloadCommand").Parse(`
1015
1016
1017
set -e

mkdir -p /workspace/buildcontext
1018
url="{{.DynamoComponentDownloadURL}}"
1019
echo "Downloading dynamoComponent {{.DynamoComponentRepositoryName}}:{{.DynamoComponentVersion}} to /tmp/downloaded.tar..."
1020
1021
1022
1023
1024
1025
1026
if [[ ${url} == s3://* ]]; then
	echo "Downloading from s3..."
	aws s3 cp ${url} /tmp/downloaded.tar
elif [[ ${url} == gs://* ]]; then
	echo "Downloading from GCS..."
	gsutil cp ${url} /tmp/downloaded.tar
else
1027
	curl --fail -L ${url} --output /tmp/downloaded.tar --progress-bar
1028
1029
fi
cd /workspace/buildcontext
1030
echo "Extracting dynamoComponent tar file..."
1031
tar -xvf /tmp/downloaded.tar
1032
echo "Removing dynamoComponent tar file..."
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
rm /tmp/downloaded.tar
{{if not .Privileged}}
echo "Changing directory permission..."
chown -R 1000:1000 /workspace
{{end}}
echo "Done"
	`)

	if err != nil {
		err = errors.Wrap(err, "failed to parse download command template")
		return
	}

1046
	var dynamoComponentDownloadCommandBuffer bytes.Buffer
1047

1048
	err = dynamoComponentDownloadCommandTemplate.Execute(&dynamoComponentDownloadCommandBuffer, map[string]interface{}{
1049
1050
1051
1052
		"DynamoComponentDownloadURL":    dynamoComponentDownloadURL,
		"DynamoComponentRepositoryName": dynamoComponentRepositoryName,
		"DynamoComponentVersion":        dynamoComponentVersion,
		"Privileged":                    privileged,
1053
1054
1055
1056
1057
1058
	})
	if err != nil {
		err = errors.Wrap(err, "failed to execute download command template")
		return
	}

1059
	dynamoComponentDownloadCommand := dynamoComponentDownloadCommandBuffer.String()
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071

	downloaderContainerResources := corev1.ResourceRequirements{
		Limits: corev1.ResourceList{
			corev1.ResourceCPU:    resource.MustParse("1000m"),
			corev1.ResourceMemory: resource.MustParse("3000Mi"),
		},
		Requests: corev1.ResourceList{
			corev1.ResourceCPU:    resource.MustParse("100m"),
			corev1.ResourceMemory: resource.MustParse("1000Mi"),
		},
	}

1072
	downloaderContainerEnvFrom := opt.DynamoComponent.Spec.DownloaderContainerEnvFrom
1073
1074
1075

	initContainers := []corev1.Container{
		{
1076
			Name:  "dynamocomponent-downloader",
1077
			Image: internalImages.DynamoComponentsDownloader,
1078
			Command: []string{
1079
				"sh",
1080
				"-c",
1081
				dynamoComponentDownloadCommand,
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
			},
			VolumeMounts: volumeMounts,
			Resources:    downloaderContainerResources,
			EnvFrom:      downloaderContainerEnvFrom,
			Env: []corev1.EnvVar{
				{
					Name:  "AWS_EC2_METADATA_DISABLED",
					Value: "true",
				},
			},
		},
	}

	containers := make([]corev1.Container, 0)

Neelay Shah's avatar
Neelay Shah committed
1097
1098
	var globalExtraPodMetadata *dynamoCommon.ExtraPodMetadata
	var globalExtraPodSpec *dynamoCommon.ExtraPodSpec
1099
1100
1101
1102
1103
	var globalExtraContainerEnv []corev1.EnvVar
	var globalDefaultImageBuilderContainerResources *corev1.ResourceRequirements
	var buildArgs []string
	var builderArgs []string

1104
	configNamespace, err := commonconfig.GetDynamoImageBuilderNamespace(ctx)
1105
	if err != nil {
1106
		err = errors.Wrap(err, "failed to get dynamo image builder namespace")
1107
1108
1109
		return
	}

1110
	configCmName := "dynamo-image-builder-config"
1111
	r.Recorder.Eventf(opt.DynamoComponent, corev1.EventTypeNormal, "GenerateImageBuilderPod", "Getting configmap %s from namespace %s", configCmName, configNamespace)
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
	configCm := &corev1.ConfigMap{}
	err = r.Get(ctx, types.NamespacedName{Name: configCmName, Namespace: configNamespace}, configCm)
	configCmIsNotFound := k8serrors.IsNotFound(err)
	if err != nil && !configCmIsNotFound {
		err = errors.Wrap(err, "failed to get configmap")
		return
	}
	err = nil // nolint: ineffassign

	if !configCmIsNotFound {
1122
		r.Recorder.Eventf(opt.DynamoComponent, corev1.EventTypeNormal, "GenerateImageBuilderPod", "Configmap %s is got from namespace %s", configCmName, configNamespace)
1123

Neelay Shah's avatar
Neelay Shah committed
1124
		globalExtraPodMetadata = &dynamoCommon.ExtraPodMetadata{}
1125
1126
1127
1128
1129
1130
1131
1132
1133

		if val, ok := configCm.Data["extra_pod_metadata"]; ok {
			err = yaml.Unmarshal([]byte(val), globalExtraPodMetadata)
			if err != nil {
				err = errors.Wrapf(err, "failed to yaml unmarshal extra_pod_metadata, please check the configmap %s in namespace %s", configCmName, configNamespace)
				return
			}
		}

Neelay Shah's avatar
Neelay Shah committed
1134
		globalExtraPodSpec = &dynamoCommon.ExtraPodSpec{}
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182

		if val, ok := configCm.Data["extra_pod_spec"]; ok {
			err = yaml.Unmarshal([]byte(val), globalExtraPodSpec)
			if err != nil {
				err = errors.Wrapf(err, "failed to yaml unmarshal extra_pod_spec, please check the configmap %s in namespace %s", configCmName, configNamespace)
				return
			}
		}

		globalExtraContainerEnv = []corev1.EnvVar{}

		if val, ok := configCm.Data["extra_container_env"]; ok {
			err = yaml.Unmarshal([]byte(val), &globalExtraContainerEnv)
			if err != nil {
				err = errors.Wrapf(err, "failed to yaml unmarshal extra_container_env, please check the configmap %s in namespace %s", configCmName, configNamespace)
				return
			}
		}

		if val, ok := configCm.Data["default_image_builder_container_resources"]; ok {
			globalDefaultImageBuilderContainerResources = &corev1.ResourceRequirements{}
			err = yaml.Unmarshal([]byte(val), globalDefaultImageBuilderContainerResources)
			if err != nil {
				err = errors.Wrapf(err, "failed to yaml unmarshal default_image_builder_container_resources, please check the configmap %s in namespace %s", configCmName, configNamespace)
				return
			}
		}

		buildArgs = []string{}

		if val, ok := configCm.Data["build_args"]; ok {
			err = yaml.Unmarshal([]byte(val), &buildArgs)
			if err != nil {
				err = errors.Wrapf(err, "failed to yaml unmarshal build_args, please check the configmap %s in namespace %s", configCmName, configNamespace)
				return
			}
		}

		builderArgs = []string{}
		if val, ok := configCm.Data["builder_args"]; ok {
			err = yaml.Unmarshal([]byte(val), &builderArgs)
			if err != nil {
				err = errors.Wrapf(err, "failed to yaml unmarshal builder_args, please check the configmap %s in namespace %s", configCmName, configNamespace)
				return
			}
		}
		logrus.Info("passed in builder args: ", builderArgs)
	} else {
1183
		r.Recorder.Eventf(opt.DynamoComponent, corev1.EventTypeNormal, "GenerateImageBuilderPod", "Configmap %s is not found in namespace %s", configCmName, configNamespace)
1184
1185
1186
1187
1188
1189
	}

	if buildArgs == nil {
		buildArgs = make([]string, 0)
	}

1190
1191
	if opt.DynamoComponent.Spec.BuildArgs != nil {
		buildArgs = append(buildArgs, opt.DynamoComponent.Spec.BuildArgs...)
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
	}

	dockerFilePath := "/workspace/buildcontext/env/docker/Dockerfile"

	builderContainerEnvFrom := make([]corev1.EnvFromSource, 0)
	builderContainerEnvs := []corev1.EnvVar{
		{
			Name:  "DOCKER_CONFIG",
			Value: "/kaniko/.docker/",
		},
		{
			Name:  "IFS",
			Value: "''",
		},
	}

	kanikoCacheRepo := os.Getenv("KANIKO_CACHE_REPO")
	if kanikoCacheRepo == "" {
1210
		kanikoCacheRepo = opt.ImageInfo.DockerRegistry.DynamoRepositoryURI
1211
1212
1213
	}

	kubeAnnotations := make(map[string]string)
1214
	kubeAnnotations[consts.KubeAnnotationDynamoComponentImageBuiderHash] = opt.DynamoComponent.Annotations[consts.KubeAnnotationDynamoComponentImageBuiderHash]
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229

	command := []string{
		"/kaniko/executor",
	}
	args := []string{
		"--context=/workspace/buildcontext",
		"--verbosity=info",
		"--image-fs-extract-retry=3",
		"--cache=false",
		fmt.Sprintf("--cache-repo=%s", kanikoCacheRepo),
		"--compressed-caching=false",
		"--compression=zstd",
		"--compression-level=-7",
		fmt.Sprintf("--dockerfile=%s", dockerFilePath),
		fmt.Sprintf("--insecure=%v", dockerRegistryInsecure),
1230
		fmt.Sprintf("--destination=%s", imageName),
1231
1232
1233
1234
1235
1236
1237
1238
1239
	}

	kanikoSnapshotMode := os.Getenv("KANIKO_SNAPSHOT_MODE")
	if kanikoSnapshotMode != "" {
		args = append(args, fmt.Sprintf("--snapshot-mode=%s", kanikoSnapshotMode))
	}

	var builderImage string
	switch buildEngine {
1240
	case DynamoComponentImageBuildEngineKaniko:
1241
1242
1243
1244
1245
1246
1247
		builderImage = internalImages.Kaniko
		if isEstargzEnabled() {
			builderContainerEnvs = append(builderContainerEnvs, corev1.EnvVar{
				Name:  "GGCR_EXPERIMENT_ESTARGZ",
				Value: "1",
			})
		}
1248
	case DynamoComponentImageBuildEngineBuildkit:
1249
		builderImage = internalImages.Buildkit
1250
	case DynamoComponentImageBuildEngineBuildkitRootless:
1251
1252
		builderImage = internalImages.BuildkitRootless
	default:
1253
		err = errors.Errorf("unknown dynamoComponent image build engine %s", buildEngine)
1254
1255
1256
		return
	}

1257
	isBuildkit := buildEngine == DynamoComponentImageBuildEngineBuildkit || buildEngine == DynamoComponentImageBuildEngineBuildkitRootless
1258
1259

	if isBuildkit {
1260
		output := fmt.Sprintf("type=image,name=%s,push=true,registry.insecure=%v", imageName, dockerRegistryInsecure)
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
		buildkitdFlags := []string{}
		if !privileged {
			buildkitdFlags = append(buildkitdFlags, "--oci-worker-no-process-sandbox")
		}
		if isEstargzEnabled() {
			buildkitdFlags = append(buildkitdFlags, "--oci-worker-snapshotter=stargz")
			output += ",oci-mediatypes=true,compression=estargz,force-compression=true"
		}
		if len(buildkitdFlags) > 0 {
			builderContainerEnvs = append(builderContainerEnvs, corev1.EnvVar{
				Name:  "BUILDKITD_FLAGS",
				Value: strings.Join(buildkitdFlags, " "),
			})
		}
1275
1276
1277
1278
1279
1280
1281
1282
		buildkitURL := os.Getenv("BUILDKIT_URL")
		if buildkitURL == "" {
			err = errors.New("BUILDKIT_URL is not set")
			return
		}
		command = []string{
			"buildctl",
		}
1283
		args = []string{
1284
1285
			"--addr",
			buildkitURL,
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
			"build",
			"--frontend",
			"dockerfile.v0",
			"--local",
			"context=/workspace/buildcontext",
			"--local",
			fmt.Sprintf("dockerfile=%s", filepath.Dir(dockerFilePath)),
			"--output",
			output,
		}
		cacheRepo := os.Getenv("BUILDKIT_CACHE_REPO")
1297
1298
1299
		if cacheRepo != "" {
			args = append(args, "--export-cache", fmt.Sprintf("type=registry,ref=%s:buildcache,mode=max,compression=zstd,ignore-error=true", cacheRepo))
			args = append(args, "--import-cache", fmt.Sprintf("type=registry,ref=%s:buildcache", cacheRepo))
1300
1301
1302
1303
1304
		}
	}

	var builderContainerSecurityContext *corev1.SecurityContext

1305
	if buildEngine == DynamoComponentImageBuildEngineBuildkit {
1306
1307
1308
		builderContainerSecurityContext = &corev1.SecurityContext{
			Privileged: ptr.To(true),
		}
1309
	} else if buildEngine == DynamoComponentImageBuildEngineBuildkitRootless {
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
		kubeAnnotations["container.apparmor.security.beta.kubernetes.io/builder"] = "unconfined"
		builderContainerSecurityContext = &corev1.SecurityContext{
			SeccompProfile: &corev1.SeccompProfile{
				Type: corev1.SeccompProfileTypeUnconfined,
			},
			RunAsUser:  ptr.To(int64(1000)),
			RunAsGroup: ptr.To(int64(1000)),
		}
	}

	// add build args to pass via --build-arg
	for _, buildArg := range buildArgs {
		quotedBuildArg := unix.SingleQuote.Quote(buildArg)
		if isBuildkit {
			args = append(args, "--opt", fmt.Sprintf("build-arg:%s", quotedBuildArg))
		} else {
			args = append(args, fmt.Sprintf("--build-arg=%s", quotedBuildArg))
		}
	}
	// add other arguments to builder
	args = append(args, builderArgs...)
1331
	logrus.Info("dynamo-image-builder args: ", args)
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355

	builderContainerArgs := []string{
		"-c",
		fmt.Sprintf("sleep 15; %s && exit 0 || exit %d", shquot.POSIXShell(append(command, args...)), BuilderJobFailedExitCode), // TODO: remove once functionality exists to wait for istio sidecar.
	}

	container := corev1.Container{
		Name:            BuilderContainerName,
		Image:           builderImage,
		ImagePullPolicy: corev1.PullAlways,
		Command:         []string{"sh"},
		Args:            builderContainerArgs,
		VolumeMounts:    volumeMounts,
		Env:             builderContainerEnvs,
		EnvFrom:         builderContainerEnvFrom,
		TTY:             true,
		Stdin:           true,
		SecurityContext: builderContainerSecurityContext,
	}

	if globalDefaultImageBuilderContainerResources != nil {
		container.Resources = *globalDefaultImageBuilderContainerResources
	}

1356
1357
	if opt.DynamoComponent.Spec.ImageBuilderContainerResources != nil {
		container.Resources = *opt.DynamoComponent.Spec.ImageBuilderContainerResources
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
	}

	containers = append(containers, container)

	pod = &corev1.PodTemplateSpec{
		ObjectMeta: metav1.ObjectMeta{
			Labels:      kubeLabels,
			Annotations: kubeAnnotations,
		},
		Spec: corev1.PodSpec{
			RestartPolicy:  corev1.RestartPolicyNever,
			Volumes:        volumes,
			InitContainers: initContainers,
			Containers:     containers,
		},
	}

	if globalExtraPodMetadata != nil {
		for k, v := range globalExtraPodMetadata.Annotations {
			pod.Annotations[k] = v
		}

		for k, v := range globalExtraPodMetadata.Labels {
			pod.Labels[k] = v
		}
	}

1385
1386
	if opt.DynamoComponent.Spec.ImageBuilderExtraPodMetadata != nil {
		for k, v := range opt.DynamoComponent.Spec.ImageBuilderExtraPodMetadata.Annotations {
1387
1388
1389
			pod.Annotations[k] = v
		}

1390
		for k, v := range opt.DynamoComponent.Spec.ImageBuilderExtraPodMetadata.Labels {
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
			pod.Labels[k] = v
		}
	}

	if globalExtraPodSpec != nil {
		pod.Spec.PriorityClassName = globalExtraPodSpec.PriorityClassName
		pod.Spec.SchedulerName = globalExtraPodSpec.SchedulerName
		pod.Spec.NodeSelector = globalExtraPodSpec.NodeSelector
		pod.Spec.Affinity = globalExtraPodSpec.Affinity
		pod.Spec.Tolerations = globalExtraPodSpec.Tolerations
		pod.Spec.TopologySpreadConstraints = globalExtraPodSpec.TopologySpreadConstraints
		pod.Spec.ServiceAccountName = globalExtraPodSpec.ServiceAccountName
	}

1405
1406
1407
	if opt.DynamoComponent.Spec.ImageBuilderExtraPodSpec != nil {
		if opt.DynamoComponent.Spec.ImageBuilderExtraPodSpec.PriorityClassName != "" {
			pod.Spec.PriorityClassName = opt.DynamoComponent.Spec.ImageBuilderExtraPodSpec.PriorityClassName
1408
1409
		}

1410
1411
		if opt.DynamoComponent.Spec.ImageBuilderExtraPodSpec.SchedulerName != "" {
			pod.Spec.SchedulerName = opt.DynamoComponent.Spec.ImageBuilderExtraPodSpec.SchedulerName
1412
1413
		}

1414
1415
		if opt.DynamoComponent.Spec.ImageBuilderExtraPodSpec.NodeSelector != nil {
			pod.Spec.NodeSelector = opt.DynamoComponent.Spec.ImageBuilderExtraPodSpec.NodeSelector
1416
1417
		}

1418
1419
		if opt.DynamoComponent.Spec.ImageBuilderExtraPodSpec.Affinity != nil {
			pod.Spec.Affinity = opt.DynamoComponent.Spec.ImageBuilderExtraPodSpec.Affinity
1420
1421
		}

1422
1423
		if opt.DynamoComponent.Spec.ImageBuilderExtraPodSpec.Tolerations != nil {
			pod.Spec.Tolerations = opt.DynamoComponent.Spec.ImageBuilderExtraPodSpec.Tolerations
1424
1425
		}

1426
1427
		if opt.DynamoComponent.Spec.ImageBuilderExtraPodSpec.TopologySpreadConstraints != nil {
			pod.Spec.TopologySpreadConstraints = opt.DynamoComponent.Spec.ImageBuilderExtraPodSpec.TopologySpreadConstraints
1428
1429
		}

1430
1431
		if opt.DynamoComponent.Spec.ImageBuilderExtraPodSpec.ServiceAccountName != "" {
			pod.Spec.ServiceAccountName = opt.DynamoComponent.Spec.ImageBuilderExtraPodSpec.ServiceAccountName
1432
1433
1434
		}
	}

1435
	injectPodAffinity(&pod.Spec, opt.DynamoComponent)
1436
1437
1438

	if pod.Spec.ServiceAccountName == "" {
		serviceAccounts := &corev1.ServiceAccountList{}
1439
		err = r.List(ctx, serviceAccounts, client.InNamespace(opt.DynamoComponent.Namespace), client.MatchingLabels{
1440
			commonconsts.KubeLabelDynamoImageBuilderPod: commonconsts.KubeLabelValueTrue,
1441
1442
		})
		if err != nil {
1443
			err = errors.Wrapf(err, "failed to list service accounts in namespace %s", opt.DynamoComponent.Namespace)
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
			return
		}
		if len(serviceAccounts.Items) > 0 {
			pod.Spec.ServiceAccountName = serviceAccounts.Items[0].Name
		} else {
			pod.Spec.ServiceAccountName = "default"
		}
	}

	for i, c := range pod.Spec.InitContainers {
		env := c.Env
		if globalExtraContainerEnv != nil {
			env = append(env, globalExtraContainerEnv...)
		}
1458
		env = append(env, opt.DynamoComponent.Spec.ImageBuilderExtraContainerEnv...)
1459
1460
1461
1462
1463
1464
1465
		pod.Spec.InitContainers[i].Env = env
	}
	for i, c := range pod.Spec.Containers {
		env := c.Env
		if globalExtraContainerEnv != nil {
			env = append(env, globalExtraContainerEnv...)
		}
1466
		env = append(env, opt.DynamoComponent.Spec.ImageBuilderExtraContainerEnv...)
1467
1468
1469
1470
1471
1472
		pod.Spec.Containers[i].Env = env
	}

	return
}

1473
func (r *DynamoComponentReconciler) getHashStr(DynamoComponent *nvidiacomv1alpha1.DynamoComponent) (string, error) {
1474
1475
	var hash uint64
	hash, err := hashstructure.Hash(struct {
1476
		Spec        nvidiacomv1alpha1.DynamoComponentSpec
1477
1478
1479
		Labels      map[string]string
		Annotations map[string]string
	}{
1480
1481
1482
		Spec:        DynamoComponent.Spec,
		Labels:      DynamoComponent.Labels,
		Annotations: DynamoComponent.Annotations,
1483
1484
	}, hashstructure.FormatV2, nil)
	if err != nil {
1485
		err = errors.Wrap(err, "get DynamoComponent CR spec hash")
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
		return "", err
	}
	hashStr := strconv.FormatUint(hash, 10)
	return hashStr, nil
}

const (
	trueStr = "true"
)

// SetupWithManager sets up the controller with the Manager.
1497
func (r *DynamoComponentReconciler) SetupWithManager(mgr ctrl.Manager) error {
1498
1499

	err := ctrl.NewControllerManagedBy(mgr).
1500
		For(&nvidiacomv1alpha1.DynamoComponent{}, builder.WithPredicates(predicate.GenerationChangedPredicate{})).
1501
		Owns(&nvidiacomv1alpha1.DynamoComponent{}).
1502
1503
1504
		Owns(&batchv1.Job{}).
		WithEventFilter(controller_common.EphemeralDeploymentEventFilter(r.Config)).
		Complete(r)
1505
	return errors.Wrap(err, "failed to setup DynamoComponent controller")
1506
}