dynamocomponent_controller.go 50.7 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
667
668

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

	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
682
683
684
685
686
687
688
689
690
	}

	return
}

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

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

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

716
	tag = fmt.Sprintf("dynamo.%s%s", getDynamoComponentImagePrefix(DynamoComponent), tail)
717
718
719

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

728
729
func checkImageExists(DynamoComponent *nvidiacomv1alpha1.DynamoComponent, dockerRegistry schemas.DockerRegistrySchema, imageName string) (bool, error) {
	if DynamoComponent.Annotations["nvidia.com/force-build-image"] == commonconsts.KubeLabelValueTrue {
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
		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 {
766
	DockerRegistry             schemas.DockerRegistrySchema
767
768
769
770
771
772
	DockerConfigJSONSecretName string
	ImageName                  string
	DockerRegistryInsecure     bool
}

type GetImageInfoOption struct {
773
	DynamoComponent *nvidiacomv1alpha1.DynamoComponent
774
775
776
}

//nolint:nakedret
777
778
779
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)
780
781
782
783
	if err != nil {
		err = errors.Wrap(err, "get docker registry")
		return
	}
784
785
	imageInfo.DockerRegistry = *dockerRegistry
	imageInfo.ImageName = getDynamoComponentImageName(opt.DynamoComponent, *dockerRegistry, dynamoComponentRepositoryName, dynamoComponentVersion)
786

787
	imageInfo.DockerConfigJSONSecretName = dockerRegistry.SecretName
788

789
	imageInfo.DockerRegistryInsecure = opt.DynamoComponent.Annotations[commonconsts.KubeAnnotationDynamoDockerRegistryInsecure] == "true"
790
791
792
	return
}

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

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

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

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

819
type GenerateImageBuilderJobOption struct {
820
821
	ImageInfo       ImageInfo
	DynamoComponent *nvidiacomv1alpha1.DynamoComponent
822
823
824
}

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

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

	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{
887
					commonconsts.KubeLabelDynamoComponent: DynamoComponent.Name,
888
889
890
891
892
893
894
895
896
897
898
899
900
				},
			},
			TopologyKey: corev1.LabelHostname,
		},
	})
}

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

type GenerateImageBuilderPodTemplateSpecOption struct {
901
902
	ImageInfo       ImageInfo
	DynamoComponent *nvidiacomv1alpha1.DynamoComponent
903
904
905
}

//nolint:gocyclo,nakedret
906
907
908
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)
909

910
	imageName := opt.ImageInfo.ImageName
911
912
913
914
915
916
917

	dockerConfigJSONSecretName := opt.ImageInfo.DockerConfigJSONSecretName

	dockerRegistryInsecure := opt.ImageInfo.DockerRegistryInsecure

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

	volumeMounts := []corev1.VolumeMount{
		{
933
934
			Name:      "dynamo",
			MountPath: "/dynamo",
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
		},
		{
			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/",
		})
	}

963
	var dynamoComponent *schemas.DynamoComponent
964
	dynamoComponentDownloadURL := opt.DynamoComponent.Spec.DownloadURL
965

966
967
968
	if dynamoComponentDownloadURL == "" {
		var apiStoreClient *apiStoreClient.ApiStoreClient
		var apiStoreConf *commonconfig.ApiStoreConfig
969

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

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

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

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

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

1007
	buildEngine := getDynamoComponentImageBuildEngine()
1008

1009
	privileged := buildEngine != DynamoComponentImageBuildEngineBuildkitRootless
1010

1011
	dynamoComponentDownloadCommandTemplate, err := template.New("downloadCommand").Parse(`
1012
1013
1014
set -e

mkdir -p /workspace/buildcontext
1015
url="{{.DynamoComponentDownloadURL}}"
1016
echo "Downloading dynamoComponent {{.DynamoComponentRepositoryName}}:{{.DynamoComponentVersion}} to /tmp/downloaded.tar..."
1017
1018
1019
1020
1021
1022
1023
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
1024
	curl --fail -L ${url} --output /tmp/downloaded.tar --progress-bar
1025
1026
fi
cd /workspace/buildcontext
1027
echo "Extracting dynamoComponent tar file..."
1028
tar -xvf /tmp/downloaded.tar
1029
echo "Removing dynamoComponent tar file..."
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
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
	}

1043
	var dynamoComponentDownloadCommandBuffer bytes.Buffer
1044

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

1056
	dynamoComponentDownloadCommand := dynamoComponentDownloadCommandBuffer.String()
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068

	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"),
		},
	}

1069
	downloaderContainerEnvFrom := opt.DynamoComponent.Spec.DownloaderContainerEnvFrom
1070
1071
1072

	initContainers := []corev1.Container{
		{
1073
			Name:  "dynamocomponent-downloader",
1074
			Image: internalImages.DynamoComponentsDownloader,
1075
			Command: []string{
1076
				"sh",
1077
				"-c",
1078
				dynamoComponentDownloadCommand,
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
			},
			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
1094
1095
	var globalExtraPodMetadata *dynamoCommon.ExtraPodMetadata
	var globalExtraPodSpec *dynamoCommon.ExtraPodSpec
1096
1097
1098
1099
1100
	var globalExtraContainerEnv []corev1.EnvVar
	var globalDefaultImageBuilderContainerResources *corev1.ResourceRequirements
	var buildArgs []string
	var builderArgs []string

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

1107
	configCmName := "dynamo-image-builder-config"
1108
	r.Recorder.Eventf(opt.DynamoComponent, corev1.EventTypeNormal, "GenerateImageBuilderPod", "Getting configmap %s from namespace %s", configCmName, configNamespace)
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
	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 {
1119
		r.Recorder.Eventf(opt.DynamoComponent, corev1.EventTypeNormal, "GenerateImageBuilderPod", "Configmap %s is got from namespace %s", configCmName, configNamespace)
1120

Neelay Shah's avatar
Neelay Shah committed
1121
		globalExtraPodMetadata = &dynamoCommon.ExtraPodMetadata{}
1122
1123
1124
1125
1126
1127
1128
1129
1130

		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
1131
		globalExtraPodSpec = &dynamoCommon.ExtraPodSpec{}
1132
1133
1134
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

		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 {
1180
		r.Recorder.Eventf(opt.DynamoComponent, corev1.EventTypeNormal, "GenerateImageBuilderPod", "Configmap %s is not found in namespace %s", configCmName, configNamespace)
1181
1182
1183
1184
1185
1186
	}

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

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

	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 == "" {
1207
		kanikoCacheRepo = opt.ImageInfo.DockerRegistry.DynamoRepositoryURI
1208
1209
1210
	}

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

	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),
1227
		fmt.Sprintf("--destination=%s", imageName),
1228
1229
1230
1231
1232
1233
1234
1235
1236
	}

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

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

1254
	isBuildkit := buildEngine == DynamoComponentImageBuildEngineBuildkit || buildEngine == DynamoComponentImageBuildEngineBuildkitRootless
1255
1256

	if isBuildkit {
1257
		output := fmt.Sprintf("type=image,name=%s,push=true,registry.insecure=%v", imageName, dockerRegistryInsecure)
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
		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, " "),
			})
		}
1272
1273
1274
1275
1276
1277
1278
1279
		buildkitURL := os.Getenv("BUILDKIT_URL")
		if buildkitURL == "" {
			err = errors.New("BUILDKIT_URL is not set")
			return
		}
		command = []string{
			"buildctl",
		}
1280
		args = []string{
1281
1282
			"--addr",
			buildkitURL,
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
			"build",
			"--frontend",
			"dockerfile.v0",
			"--local",
			"context=/workspace/buildcontext",
			"--local",
			fmt.Sprintf("dockerfile=%s", filepath.Dir(dockerFilePath)),
			"--output",
			output,
		}
		cacheRepo := os.Getenv("BUILDKIT_CACHE_REPO")
1294
1295
1296
		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))
1297
1298
1299
1300
1301
		}
	}

	var builderContainerSecurityContext *corev1.SecurityContext

1302
	if buildEngine == DynamoComponentImageBuildEngineBuildkit {
1303
1304
1305
		builderContainerSecurityContext = &corev1.SecurityContext{
			Privileged: ptr.To(true),
		}
1306
	} else if buildEngine == DynamoComponentImageBuildEngineBuildkitRootless {
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
		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...)
1328
	logrus.Info("dynamo-image-builder args: ", args)
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352

	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
	}

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

	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
		}
	}

1382
1383
	if opt.DynamoComponent.Spec.ImageBuilderExtraPodMetadata != nil {
		for k, v := range opt.DynamoComponent.Spec.ImageBuilderExtraPodMetadata.Annotations {
1384
1385
1386
			pod.Annotations[k] = v
		}

1387
		for k, v := range opt.DynamoComponent.Spec.ImageBuilderExtraPodMetadata.Labels {
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
			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
	}

1402
1403
1404
	if opt.DynamoComponent.Spec.ImageBuilderExtraPodSpec != nil {
		if opt.DynamoComponent.Spec.ImageBuilderExtraPodSpec.PriorityClassName != "" {
			pod.Spec.PriorityClassName = opt.DynamoComponent.Spec.ImageBuilderExtraPodSpec.PriorityClassName
1405
1406
		}

1407
1408
		if opt.DynamoComponent.Spec.ImageBuilderExtraPodSpec.SchedulerName != "" {
			pod.Spec.SchedulerName = opt.DynamoComponent.Spec.ImageBuilderExtraPodSpec.SchedulerName
1409
1410
		}

1411
1412
		if opt.DynamoComponent.Spec.ImageBuilderExtraPodSpec.NodeSelector != nil {
			pod.Spec.NodeSelector = opt.DynamoComponent.Spec.ImageBuilderExtraPodSpec.NodeSelector
1413
1414
		}

1415
1416
		if opt.DynamoComponent.Spec.ImageBuilderExtraPodSpec.Affinity != nil {
			pod.Spec.Affinity = opt.DynamoComponent.Spec.ImageBuilderExtraPodSpec.Affinity
1417
1418
		}

1419
1420
		if opt.DynamoComponent.Spec.ImageBuilderExtraPodSpec.Tolerations != nil {
			pod.Spec.Tolerations = opt.DynamoComponent.Spec.ImageBuilderExtraPodSpec.Tolerations
1421
1422
		}

1423
1424
		if opt.DynamoComponent.Spec.ImageBuilderExtraPodSpec.TopologySpreadConstraints != nil {
			pod.Spec.TopologySpreadConstraints = opt.DynamoComponent.Spec.ImageBuilderExtraPodSpec.TopologySpreadConstraints
1425
1426
		}

1427
1428
		if opt.DynamoComponent.Spec.ImageBuilderExtraPodSpec.ServiceAccountName != "" {
			pod.Spec.ServiceAccountName = opt.DynamoComponent.Spec.ImageBuilderExtraPodSpec.ServiceAccountName
1429
1430
1431
		}
	}

1432
	injectPodAffinity(&pod.Spec, opt.DynamoComponent)
1433
1434
1435

	if pod.Spec.ServiceAccountName == "" {
		serviceAccounts := &corev1.ServiceAccountList{}
1436
		err = r.List(ctx, serviceAccounts, client.InNamespace(opt.DynamoComponent.Namespace), client.MatchingLabels{
1437
			commonconsts.KubeLabelDynamoImageBuilderPod: commonconsts.KubeLabelValueTrue,
1438
1439
		})
		if err != nil {
1440
			err = errors.Wrapf(err, "failed to list service accounts in namespace %s", opt.DynamoComponent.Namespace)
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
			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...)
		}
1455
		env = append(env, opt.DynamoComponent.Spec.ImageBuilderExtraContainerEnv...)
1456
1457
1458
1459
1460
1461
1462
		pod.Spec.InitContainers[i].Env = env
	}
	for i, c := range pod.Spec.Containers {
		env := c.Env
		if globalExtraContainerEnv != nil {
			env = append(env, globalExtraContainerEnv...)
		}
1463
		env = append(env, opt.DynamoComponent.Spec.ImageBuilderExtraContainerEnv...)
1464
1465
1466
1467
1468
1469
		pod.Spec.Containers[i].Env = env
	}

	return
}

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

const (
	trueStr = "true"
)

// SetupWithManager sets up the controller with the Manager.
1494
func (r *DynamoComponentReconciler) SetupWithManager(mgr ctrl.Manager) error {
1495
1496

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