OpenRAG is a comprehensive, single package Retrieval-Augmented Generation platform built on Langflow, Docling, and Opensearch.
Python
fix: restart deployment if env changes (#1665)
mingad2a1363d7d3
diff --git a/kubernetes/operator/internal/controller/openrag_controller.go b/kubernetes/operator/internal/controller/openrag_controller.goindex be6381029..1e4113174 100644--- a/kubernetes/operator/internal/controller/openrag_controller.go+++ b/kubernetes/operator/internal/controller/openrag_controller.go@@ -119,7 +119,9 @@ func (r *OpenRAGReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctif err := r.reconcileServiceAccounts(ctx, instance, targetNS); err != nil {return r.updateStatusError(ctx, instance, "service accounts", err)}- if err := r.reconcileEnvSecrets(ctx, instance, targetNS); err != nil {+ // Reconcile .env secrets and get their hashes to trigger pod restarts when secrets change+ backendEnvHash, langflowEnvHash, err := r.reconcileEnvSecrets(ctx, instance, targetNS)+ if err != nil {return r.updateStatusError(ctx, instance, "env secrets", err)}if err := r.reconcilePVCs(ctx, instance, targetNS); err != nil {@@ -128,7 +130,7 @@ func (r *OpenRAGReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctif err := r.reconcileServices(ctx, instance, targetNS); err != nil {return r.updateStatusError(ctx, instance, "services", err)}- if err := r.reconcileDeployments(ctx, instance, targetNS); err != nil {+ if err := r.reconcileDeployments(ctx, instance, targetNS, backendEnvHash, langflowEnvHash); err != nil {return r.updateStatusError(ctx, instance, "deployments", err)}if err := r.reconcileDoclingComponents(ctx, instance, targetNS); err != nil {@@ -207,19 +209,24 @@ func parseEnvValue(envContent, key string) string {// reconcileEnvSecrets creates / updates the backend and Langflow .env Secrets// from CR fields and fixed runtime defaults.// All sensitive values (whether user-provided or generated) are consolidated into .env files.-func (r *OpenRAGReconciler) reconcileEnvSecrets(ctx context.Context, o *openragv1alpha1.OpenRAG, targetNS string) error {+// Returns SHA256 hashes of the backend and langflow .env content to use as pod annotations.+func (r *OpenRAGReconciler) reconcileEnvSecrets(ctx context.Context, o *openragv1alpha1.OpenRAG, targetNS string) (backendHash, langflowHash string, err error) {// Build backend .env content with all secrets consolidatedbackendEnvContent, err := r.buildBackendEnv(ctx, o, targetNS)if err != nil {- return fmt.Errorf("failed to build backend env: %w", err)+ return "", "", fmt.Errorf("failed to build backend env: %w", err)}// Build langflow .env content with all secrets consolidatedlangflowEnvContent, err := r.buildLangflowEnv(ctx, o, targetNS)if err != nil {- return fmt.Errorf("failed to build langflow env: %w", err)+ return "", "", fmt.Errorf("failed to build langflow env: %w", err)}+ // Calculate SHA256 hashes of .env content for pod restart triggering+ backendHash = calculateHash(backendEnvContent)+ langflowHash = calculateHash(langflowEnvContent)+type envDef struct {name stringcontent string@@ -242,13 +249,13 @@ func (r *OpenRAGReconciler) reconcileEnvSecrets(ctx context.Context, o *openragvStringData: map[string]string{".env": d.content},}if err := r.setOwnerOrLabel(o, secret, targetNS); err != nil {- return err+ return "", "", err}if err := r.createOrUpdate(ctx, secret); err != nil {- return err+ return "", "", err}}- return nil+ return backendHash, langflowHash, nil}func (r *OpenRAGReconciler) buildBackendEnv(ctx context.Context, o *openragv1alpha1.OpenRAG, targetNS string) (string, error) {@@ -610,11 +617,11 @@ func (r *OpenRAGReconciler) reconcileServices(ctx context.Context, o *openragv1areturn nil}-func (r *OpenRAGReconciler) reconcileDeployments(ctx context.Context, o *openragv1alpha1.OpenRAG, targetNS string) error {+func (r *OpenRAGReconciler) reconcileDeployments(ctx context.Context, o *openragv1alpha1.OpenRAG, targetNS string, backendEnvHash, langflowEnvHash string) error {deploys := []client.Object{r.frontendDeployment(o, targetNS),- r.backendDeployment(o, targetNS),- r.langflowDeployment(o, targetNS),+ r.backendDeployment(o, targetNS, backendEnvHash),+ r.langflowDeployment(o, targetNS, langflowEnvHash),}for _, d := range deploys {if err := r.setOwnerOrLabel(o, d, targetNS); err != nil {@@ -679,7 +686,7 @@ func (r *OpenRAGReconciler) frontendDeployment(o *openragv1alpha1.OpenRAG, targe}}-func (r *OpenRAGReconciler) backendDeployment(o *openragv1alpha1.OpenRAG, targetNS string) *appsv1.Deployment {+func (r *OpenRAGReconciler) backendDeployment(o *openragv1alpha1.OpenRAG, targetNS string, envHash string) *appsv1.Deployment {spec := o.Spec.Backendreplicas := replicasOrDefault(spec.Replicas)@@ -723,6 +730,8 @@ func (r *OpenRAGReconciler) backendDeployment(o *openragv1alpha1.OpenRAG, targetdeploymentAnnotations := mergeDeploymentAnnotations(spec.Annotations)podLabels := mergePodLabels(baseLabels, spec.PodLabels)podAnnotations := mergePodAnnotations(spec.PodAnnotations)+ // Add .env secret hash to trigger pod restart when secret changes+ podAnnotations["openr.ag/backend-env-hash"] = envHashreturn &appsv1.Deployment{ObjectMeta: metav1.ObjectMeta{Name: resourceName("be"),@@ -767,7 +776,7 @@ func (r *OpenRAGReconciler) backendDeployment(o *openragv1alpha1.OpenRAG, target}}-func (r *OpenRAGReconciler) langflowDeployment(o *openragv1alpha1.OpenRAG, targetNS string) *appsv1.Deployment {+func (r *OpenRAGReconciler) langflowDeployment(o *openragv1alpha1.OpenRAG, targetNS string, envHash string) *appsv1.Deployment {spec := o.Spec.Langflowreplicas := replicasOrDefault(spec.Replicas)@@ -843,6 +852,8 @@ func (r *OpenRAGReconciler) langflowDeployment(o *openragv1alpha1.OpenRAG, targedeploymentAnnotations := mergeDeploymentAnnotations(spec.Annotations)podLabels := mergePodLabels(baseLabels, spec.PodLabels)podAnnotations := mergePodAnnotations(spec.PodAnnotations)+ // Add .env secret hash to trigger pod restart when secret changes+ podAnnotations["openr.ag/langflow-env-hash"] = envHashreturn &appsv1.Deployment{ObjectMeta: metav1.ObjectMeta{Name: resourceName("lf"),@@ -2632,3 +2643,10 @@ func (r *OpenRAGReconciler) getOrGenerateSecret(ctx context.Context, o *openragvreturn newSecret, nil}++// calculateHash calculates the SHA256 hash of a string and returns the hex-encoded result.+// This is used to create annotations on pod templates that trigger rolling restarts when secrets change.+func calculateHash(content string) string {+ hash := sha256.Sum256([]byte(content))+ return hex.EncodeToString(hash[:])+}diff --git a/kubernetes/operator/internal/controller/openrag_controller_test.go b/kubernetes/operator/internal/controller/openrag_controller_test.goindex 54ccc25c3..746617656 100644--- a/kubernetes/operator/internal/controller/openrag_controller_test.go+++ b/kubernetes/operator/internal/controller/openrag_controller_test.go@@ -1273,3 +1273,189 @@ func TestReconcile_AllComponentsWithCustomNames_OperatorCreates(t *testing.T) {assert.True(t, errors.IsNotFound(err), "Default Service for %s should not be created", role)}}++// ---------------------------------------------------------------------------+// .env Secret Hash and Pod Restart Tests+// ---------------------------------------------------------------------------++func TestCalculateHash_Deterministic(t *testing.T) {+ // Same content should always produce the same hash+ content := "VAR1=value1\nVAR2=value2\nVAR3=value3\n"++ hash1 := calculateHash(content)+ hash2 := calculateHash(content)++ assert.Equal(t, hash1, hash2, "Same content should produce same hash")+ assert.NotEmpty(t, hash1, "Hash should not be empty")+ assert.Len(t, hash1, 64, "SHA256 hash should be 64 hex characters")+}++func TestCalculateHash_DifferentContent(t *testing.T) {+ // Different content should produce different hashes+ content1 := "VAR1=value1\nVAR2=value2\n"+ content2 := "VAR1=value1\nVAR2=different\n"++ hash1 := calculateHash(content1)+ hash2 := calculateHash(content2)++ assert.NotEqual(t, hash1, hash2, "Different content should produce different hash")+}++func TestEnvHash_StableAcrossReconciles(t *testing.T) {+ // Test that identical env produces identical hash even across multiple reconcile loops+ s := newScheme(t)+ cr := minimalCR("test-openrag", "test-ns")+ cr.Spec.Backend.Env = []corev1.EnvVar{+ {Name: "CUSTOM_VAR", Value: "custom_value"},+ }++ r, _ := reconciler(s, cr)++ // Reconcile multiple times+ var hashes []string+ for i := 0; i < 5; i++ {+ backendEnvContent, err := r.buildBackendEnv(context.Background(), cr, "test-ns")+ require.NoError(t, err)+ hash := calculateHash(backendEnvContent)+ hashes = append(hashes, hash)+ }++ // All hashes should be identical+ for i := 1; i < len(hashes); i++ {+ assert.Equal(t, hashes[0], hashes[i], "Hash should be stable across reconciles (iteration %d)", i)+ }+}++func TestEnvHash_ChangesWhenEnvChanges(t *testing.T) {+ // Test that changing env vars produces different hash+ s := newScheme(t)+ cr := minimalCR("test-openrag", "test-ns")+ cr.Spec.Backend.Env = []corev1.EnvVar{+ {Name: "CUSTOM_VAR", Value: "original_value"},+ }++ r, _ := reconciler(s, cr)++ // Get hash with original env+ backendEnvContent1, err := r.buildBackendEnv(context.Background(), cr, "test-ns")+ require.NoError(t, err)+ hash1 := calculateHash(backendEnvContent1)++ // Change env var value+ cr.Spec.Backend.Env = []corev1.EnvVar{+ {Name: "CUSTOM_VAR", Value: "changed_value"},+ }++ // Get hash with changed env+ backendEnvContent2, err := r.buildBackendEnv(context.Background(), cr, "test-ns")+ require.NoError(t, err)+ hash2 := calculateHash(backendEnvContent2)++ assert.NotEqual(t, hash1, hash2, "Hash should change when env vars change")+}++func TestDeployment_ContainsEnvHashAnnotation(t *testing.T) {+ // Test that backend deployment has env hash annotation+ s := newScheme(t)+ cr := minimalCR("test-openrag", "test-ns")+ r, c := reconciler(s, cr)++ reconcileOnce(t, r, cr)++ // Get backend deployment+ backendDeploy := &appsv1.Deployment{}+ require.NoError(t, c.Get(context.Background(),+ types.NamespacedName{Name: resourceName("be"), Namespace: "test-ns"}, backendDeploy))++ // Check for hash annotation+ annotations := backendDeploy.Spec.Template.Annotations+ require.NotNil(t, annotations, "Pod template should have annotations")+ assert.Contains(t, annotations, "openr.ag/backend-env-hash", "Backend pod should have env hash annotation")+ assert.NotEmpty(t, annotations["openr.ag/backend-env-hash"], "Hash annotation should not be empty")+ assert.Len(t, annotations["openr.ag/backend-env-hash"], 64, "Hash should be 64 hex characters")++ // Get langflow deployment+ langflowDeploy := &appsv1.Deployment{}+ require.NoError(t, c.Get(context.Background(),+ types.NamespacedName{Name: resourceName("lf"), Namespace: "test-ns"}, langflowDeploy))++ // Check for hash annotation+ lfAnnotations := langflowDeploy.Spec.Template.Annotations+ require.NotNil(t, lfAnnotations, "Langflow pod template should have annotations")+ assert.Contains(t, lfAnnotations, "openr.ag/langflow-env-hash", "Langflow pod should have env hash annotation")+ assert.NotEmpty(t, lfAnnotations["openr.ag/langflow-env-hash"], "Hash annotation should not be empty")+ assert.Len(t, lfAnnotations["openr.ag/langflow-env-hash"], 64, "Hash should be 64 hex characters")+}++func TestDeployment_HashChangeTriggersUpdate(t *testing.T) {+ // Test that changing env causes hash annotation to change, triggering pod restart+ s := newScheme(t)+ cr := minimalCR("test-openrag", "test-ns")+ cr.Spec.Backend.Env = []corev1.EnvVar{+ {Name: "CUSTOM_VAR", Value: "original"},+ }+ r, c := reconciler(s, cr)++ // Initial reconcile+ reconcileOnce(t, r, cr)++ // Get initial hash+ backendDeploy1 := &appsv1.Deployment{}+ require.NoError(t, c.Get(context.Background(),+ types.NamespacedName{Name: resourceName("be"), Namespace: "test-ns"}, backendDeploy1))+ hash1 := backendDeploy1.Spec.Template.Annotations["openr.ag/backend-env-hash"]+ require.NotEmpty(t, hash1, "Initial hash should exist")++ // Update CR with different env value+ updatedCR := &openragv1alpha1.OpenRAG{}+ require.NoError(t, c.Get(context.Background(),+ types.NamespacedName{Name: "test-openrag", Namespace: "test-ns"}, updatedCR))+ updatedCR.Spec.Backend.Env = []corev1.EnvVar{+ {Name: "CUSTOM_VAR", Value: "changed"},+ }+ require.NoError(t, c.Update(context.Background(), updatedCR))++ // Reconcile again with updated CR+ reconcileOnce(t, r, updatedCR)++ // Get updated hash+ backendDeploy2 := &appsv1.Deployment{}+ require.NoError(t, c.Get(context.Background(),+ types.NamespacedName{Name: resourceName("be"), Namespace: "test-ns"}, backendDeploy2))+ hash2 := backendDeploy2.Spec.Template.Annotations["openr.ag/backend-env-hash"]+ require.NotEmpty(t, hash2, "Updated hash should exist")++ // Hash should have changed+ assert.NotEqual(t, hash1, hash2, "Hash should change when env changes, triggering pod restart")+}++func TestDeployment_NoHashChangeWhenEnvUnchanged(t *testing.T) {+ // Test that reconciling without env changes keeps the same hash+ s := newScheme(t)+ cr := minimalCR("test-openrag", "test-ns")+ cr.Spec.Backend.Env = []corev1.EnvVar{+ {Name: "CUSTOM_VAR", Value: "constant"},+ }+ r, c := reconciler(s, cr)++ // Initial reconcile+ reconcileOnce(t, r, cr)++ // Get initial hash+ backendDeploy1 := &appsv1.Deployment{}+ require.NoError(t, c.Get(context.Background(),+ types.NamespacedName{Name: resourceName("be"), Namespace: "test-ns"}, backendDeploy1))+ hash1 := backendDeploy1.Spec.Template.Annotations["openr.ag/backend-env-hash"]++ // Reconcile again without changing env+ reconcileOnce(t, r, cr)++ // Get hash after second reconcile+ backendDeploy2 := &appsv1.Deployment{}+ require.NoError(t, c.Get(context.Background(),+ types.NamespacedName{Name: resourceName("be"), Namespace: "test-ns"}, backendDeploy2))+ hash2 := backendDeploy2.Spec.Template.Annotations["openr.ag/backend-env-hash"]++ // Hash should be identical (no unnecessary pod restart)+ assert.Equal(t, hash1, hash2, "Hash should remain same when env unchanged (avoids unnecessary restarts)")+}