change init job logic

[ZITADOPER-10]
This commit is contained in:
Haim Kortovich
2025-04-03 11:30:39 -05:00
parent 6c884db44c
commit b374e79755

View File

@@ -279,7 +279,7 @@ func (r *ZitadelClusterReconciler) reconcileInitJob(ctx context.Context, zitadel
key := client.ObjectKeyFromObject(zitadel) key := client.ObjectKeyFromObject(zitadel)
key.Name = "init-job-" + key.Name key.Name = "init-job-" + key.Name
// Build the desired InitJob // Build the desired job
desiredInitJob, err := r.Builder.BuildInitJob(zitadel, key) desiredInitJob, err := r.Builder.BuildInitJob(zitadel, key)
if err != nil { if err != nil {
return ctrl.Result{}, fmt.Errorf("error building InitJob: %v", err) return ctrl.Result{}, fmt.Errorf("error building InitJob: %v", err)
@@ -291,12 +291,50 @@ func (r *ZitadelClusterReconciler) reconcileInitJob(ctx context.Context, zitadel
if !errors.IsNotFound(err) { if !errors.IsNotFound(err) {
return ctrl.Result{}, fmt.Errorf("error getting InitJob: %v", err) return ctrl.Result{}, fmt.Errorf("error getting InitJob: %v", err)
} }
// If job not found, create the InitJob // If job is not found, create the job
if err := r.Create(ctx, desiredInitJob); err != nil { if err := r.Create(ctx, desiredInitJob); err != nil {
return ctrl.Result{}, fmt.Errorf("error creating InitJob: %v", err) return ctrl.Result{}, fmt.Errorf("error creating InitJob: %v", err)
} }
return ctrl.Result{}, nil return ctrl.Result{}, nil
} }
// Compare the image in the existing job with the desired image
existingImage := existingJob.Spec.Template.Spec.Containers[0].Image
desiredImage := desiredInitJob.Spec.Template.Spec.Containers[0].Image
// If the images don't match, delete the existing job and wait for deletion
if existingImage != desiredImage {
if err := r.Delete(ctx, &existingJob); err != nil {
return ctrl.Result{}, fmt.Errorf("error deleting existing InitJob: %v", err)
}
// Wait for the job to be fully deleted before creating a new one
for {
err := r.Get(ctx, key, &existingJob)
if errors.IsNotFound(err) {
break // Job has been deleted, we can proceed
}
if err != nil {
return ctrl.Result{}, fmt.Errorf("error checking if InitJob is deleted: %v", err)
}
// Sleep for a short interval to avoid tight loop
time.Sleep(1 * time.Second)
}
// Now create the new job
if err := r.Create(ctx, desiredInitJob); err != nil {
return ctrl.Result{}, fmt.Errorf("error creating new InitJob: %v", err)
}
}
if err := r.Get(ctx, key, &existingJob); err != nil {
return ctrl.Result{}, fmt.Errorf("error fetching existing InitJob status: %v", err)
}
if existingJob.Status.Succeeded != 1 { // Replace with actual success condition
return ctrl.Result{}, fmt.Errorf("InitJob is not successful, current status: %v", existingJob.Status)
}
// If the job exists and the image matches, no action is needed
return ctrl.Result{}, nil return ctrl.Result{}, nil
} }