This is an automated email from the ASF dual-hosted git repository.

HoustonPutman pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/solr-operator.git


The following commit(s) were added to refs/heads/main by this push:
     new 30efc387 Recover a SolrBackup whose InProgress status update was lost 
(#907)
30efc387 is described below

commit 30efc387e193dd15e598d80f8222175a737e5faa
Author: Jan Høydahl <[email protected]>
AuthorDate: Thu Nov 19 20:49:53 2026 +0100

    Recover a SolrBackup whose InProgress status update was lost (#907)
    
    * Recover a SolrBackup whose InProgress status update was lost
    
    If Solr accepted a collection backup but the operator failed to persist
    InProgress=true (e.g. it restarted in between), every later reconcile
    resubmitted the same async ID, Solr rejected it as a duplicate, and the
    backup was stuck forever.
    
    Check Solr for the async ID before submitting. A submitted or running
    request is adopted and polled. A completed or failed one may be left over
    from a previous recurrence, which reuses the async ID, so it is deleted and
    the backup resubmitted rather than counted as this run's result.
    
    Fixes #848
    
    Co-Authored-By: Claude Opus 5.5 <[email protected]>
    
    * Only adopt submitted or running backup requests, link the PR in the 
changelog
    
    Co-Authored-By: Claude Opus 5.5 <[email protected]>
    
    ---------
    
    Co-authored-by: Claude Opus 5.5 <[email protected]>
---
 controllers/solrbackup_async_recovery_test.go | 153 ++++++++++++++++++++++++++
 controllers/solrbackup_controller.go          |  13 ++-
 controllers/util/backup_util.go               |  25 +++++
 helm/solr-operator/Chart.yaml                 |   7 ++
 4 files changed, 194 insertions(+), 4 deletions(-)

diff --git a/controllers/solrbackup_async_recovery_test.go 
b/controllers/solrbackup_async_recovery_test.go
new file mode 100644
index 00000000..ea48e557
--- /dev/null
+++ b/controllers/solrbackup_async_recovery_test.go
@@ -0,0 +1,153 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package controllers
+
+import (
+       "context"
+       "encoding/json"
+       "io"
+       "net/http"
+       "strings"
+       "testing"
+
+       solrv1beta1 "github.com/apache/solr-operator/api/v1beta1"
+       "github.com/apache/solr-operator/controllers/util"
+       "github.com/apache/solr-operator/controllers/util/solr_api"
+       "github.com/go-logr/logr"
+       "github.com/stretchr/testify/assert"
+       "github.com/stretchr/testify/require"
+       metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
+)
+
+// fakeSolrAsync tracks async request states by ID and, like Solr, rejects a 
BACKUP whose async ID is already tracked.
+type fakeSolrAsync struct {
+       states  map[string]string
+       actions []string
+}
+
+func (f *fakeSolrAsync) RoundTrip(request *http.Request) (*http.Response, 
error) {
+       query := request.URL.Query()
+       action := query.Get("action")
+       f.actions = append(f.actions, action)
+
+       status := http.StatusOK
+       var body interface{}
+       switch action {
+       case "BACKUP":
+               asyncId := query.Get("async")
+               if _, exists := f.states[asyncId]; exists {
+                       status = http.StatusBadRequest
+                       body = map[string]interface{}{"responseHeader": 
map[string]int{"status": 400}}
+               } else {
+                       f.states[asyncId] = "submitted"
+                       body = map[string]interface{}{"responseHeader": 
map[string]int{"status": 0}, "requestid": asyncId}
+               }
+       case "REQUESTSTATUS":
+               state, exists := f.states[query.Get("requestid")]
+               if !exists {
+                       state = "notfound"
+               }
+               body = map[string]interface{}{"responseHeader": 
map[string]int{"status": 0}, "status": map[string]string{"state": state}}
+       case "DELETESTATUS":
+               delete(f.states, query.Get("requestid"))
+               body = map[string]interface{}{"responseHeader": 
map[string]int{"status": 0}, "status": "successfully removed"}
+       }
+
+       encoded, err := json.Marshal(body)
+       if err != nil {
+               return nil, err
+       }
+       return &http.Response{StatusCode: status, Header: make(http.Header), 
Body: io.NopCloser(strings.NewReader(string(encoded)))}, nil
+}
+
+func backupAsyncFixture(t *testing.T, existingState string) (*fakeSolrAsync, 
*solrv1beta1.SolrBackup, *solrv1beta1.SolrCloud, 
*solrv1beta1.SolrBackupRepository) {
+       t.Helper()
+       backup := &solrv1beta1.SolrBackup{ObjectMeta: metav1.ObjectMeta{Name: 
"nightly", Namespace: "default"}}
+       solr := &fakeSolrAsync{states: map[string]string{}}
+       if existingState != "" {
+               solr.states[util.AsyncIdForCollectionBackup("books", 
backup.Name)] = existingState
+       }
+       // Only main.go fills the mTLS slot, which the Solr API calls prefer, 
so resetting it to nil restores it.
+       solr_api.SetMTLSHttpClient(&http.Client{Transport: solr})
+       t.Cleanup(func() {
+               solr_api.SetMTLSHttpClient(nil)
+       })
+
+       cloud := &solrv1beta1.SolrCloud{ObjectMeta: metav1.ObjectMeta{Name: 
"cloud", Namespace: "default"}}
+       repo := &solrv1beta1.SolrBackupRepository{Name: "gcs", GCS: 
&solrv1beta1.GcsRepository{Bucket: "bucket"}}
+       return solr, backup, cloud, repo
+}
+
+// A backup Solr accepted, but whose InProgress status never reached the 
apiserver, must be tracked rather than resubmitted.
+func TestCollectionBackupAdoptsRequestSolrAlreadyAccepted(t *testing.T) {
+       solr, backup, cloud, repo := backupAsyncFixture(t, "running")
+       status := &solrv1beta1.IndividualSolrBackupStatus{}
+
+       _, err := reconcileSolrCollectionBackup(context.Background(), backup, 
status, cloud, repo, "books", logr.Discard())
+       require.NoError(t, err)
+       require.Len(t, status.CollectionBackupStatuses, 1)
+       assert.True(t, status.CollectionBackupStatuses[0].InProgress)
+       assert.NotNil(t, status.CollectionBackupStatuses[0].StartTime)
+       assert.NotContains(t, solr.actions, "BACKUP")
+
+       solr.states[util.AsyncIdForCollectionBackup("books", backup.Name)] = 
"completed"
+       finished, err := reconcileSolrCollectionBackup(context.Background(), 
backup, status, cloud, repo, "books", logr.Discard())
+       require.NoError(t, err)
+       assert.True(t, finished)
+       require.NotNil(t, status.CollectionBackupStatuses[0].Successful)
+       assert.True(t, *status.CollectionBackupStatuses[0].Successful)
+       assert.Empty(t, solr.states, "the async request should be deleted once 
the backup finishes")
+}
+
+// A finished request may be left over from a previous recurrence, so it must 
not count as this backup.
+func TestCollectionBackupResubmitsOverFinishedRequest(t *testing.T) {
+       for _, state := range []string{"completed", "failed"} {
+               t.Run(state, func(t *testing.T) {
+                       solr, backup, cloud, repo := backupAsyncFixture(t, 
state)
+                       status := &solrv1beta1.IndividualSolrBackupStatus{}
+
+                       finished, err := 
reconcileSolrCollectionBackup(context.Background(), backup, status, cloud, 
repo, "books", logr.Discard())
+                       require.NoError(t, err)
+                       assert.False(t, finished)
+                       assert.True(t, 
status.CollectionBackupStatuses[0].InProgress)
+                       assert.Equal(t, []string{"REQUESTSTATUS", 
"DELETESTATUS", "BACKUP"}, solr.actions)
+                       assert.Equal(t, "submitted", 
solr.states[util.AsyncIdForCollectionBackup("books", backup.Name)])
+               })
+       }
+}
+
+func TestCollectionBackupRejectsUnknownAsyncState(t *testing.T) {
+       solr, backup, cloud, repo := backupAsyncFixture(t, "")
+       solr.states[util.AsyncIdForCollectionBackup("books", backup.Name)] = ""
+       status := &solrv1beta1.IndividualSolrBackupStatus{}
+
+       _, err := reconcileSolrCollectionBackup(context.Background(), backup, 
status, cloud, repo, "books", logr.Discard())
+       assert.Error(t, err)
+       assert.Empty(t, status.CollectionBackupStatuses)
+       assert.NotContains(t, solr.actions, "BACKUP")
+}
+
+func TestCollectionBackupSubmitsWhenSolrHasNoRequest(t *testing.T) {
+       solr, backup, cloud, repo := backupAsyncFixture(t, "")
+       status := &solrv1beta1.IndividualSolrBackupStatus{}
+
+       _, err := reconcileSolrCollectionBackup(context.Background(), backup, 
status, cloud, repo, "books", logr.Discard())
+       require.NoError(t, err)
+       assert.True(t, status.CollectionBackupStatuses[0].InProgress)
+       assert.Equal(t, []string{"REQUESTSTATUS", "BACKUP"}, solr.actions)
+}
diff --git a/controllers/solrbackup_controller.go 
b/controllers/solrbackup_controller.go
index 7d9c2444..bc7b2e3a 100644
--- a/controllers/solrbackup_controller.go
+++ b/controllers/solrbackup_controller.go
@@ -286,11 +286,16 @@ func reconcileSolrCollectionBackup(ctx context.Context, 
backup *solrv1beta1.Solr
        if collectionBackupStatus.Finished {
                return true, nil
        } else if !collectionBackupStatus.InProgress {
-               // Start the backup by calling solr
+               // Start the backup by calling solr, unless Solr already has it
                var started bool
-               started, err = util.StartBackupForCollection(ctx, solrCloud, 
backupRepository, backup, collection, logger)
-               if err != nil {
-                       return true, err
+               if started, err = util.PrepareBackupForCollection(ctx, 
solrCloud, collection, backup.Name, logger); err != nil {
+                       return false, err
+               }
+               if !started {
+                       started, err = util.StartBackupForCollection(ctx, 
solrCloud, backupRepository, backup, collection, logger)
+                       if err != nil {
+                               return true, err
+                       }
                }
                collectionBackupStatus.InProgress = started
                if started && collectionBackupStatus.StartTime == nil {
diff --git a/controllers/util/backup_util.go b/controllers/util/backup_util.go
index ca4056e1..317112be 100644
--- a/controllers/util/backup_util.go
+++ b/controllers/util/backup_util.go
@@ -109,6 +109,31 @@ func StartBackupForCollection(ctx context.Context, cloud 
*solr.SolrCloud, backup
        return success, err
 }
 
+// PrepareBackupForCollection checks Solr for an async request left behind 
under the backup's async ID,
+// e.g. when the status update recording an accepted backup was lost. A 
request still submitted or running
+// is adopted. A finished one may be from a previous recurrence, so it is 
deleted to let the backup be resubmitted.
+func PrepareBackupForCollection(ctx context.Context, cloud *solr.SolrCloud, 
collection string, backupName string, logger logr.Logger) (alreadyStarted bool, 
err error) {
+       asyncId := AsyncIdForCollectionBackup(collection, backupName)
+       asyncState, message, err := solr_api.CheckAsyncRequest(ctx, cloud, 
asyncId)
+       if err != nil {
+               logger.Error(err, "Error checking for an existing collection 
backup", "solrCloud", cloud.Name, "collection", collection, "message", message)
+               return false, err
+       }
+
+       switch asyncState {
+       case "notfound":
+               return false, nil
+       case "completed", "failed":
+               logger.Info("Deleting a finished async request left over from 
an earlier collection backup", "solrCloud", cloud.Name, "collection", 
collection, "asyncState", asyncState)
+               return false, DeleteAsyncInfoForBackup(ctx, cloud, collection, 
backupName, logger)
+       case "submitted", "running":
+               logger.Info("Found a collection backup already started in Solr, 
tracking it", "solrCloud", cloud.Name, "collection", collection, "asyncState", 
asyncState)
+               return true, nil
+       default:
+               return false, fmt.Errorf("unexpected async state %q for 
collection backup %q", asyncState, asyncId)
+       }
+}
+
 func CheckBackupForCollection(ctx context.Context, cloud *solr.SolrCloud, 
collection string, backupName string, logger logr.Logger) (finished bool, 
success bool, asyncStatus string, err error) {
        logger.Info("Calling to check on collection backup", "solrCloud", 
cloud.Name, "collection", collection)
 
diff --git a/helm/solr-operator/Chart.yaml b/helm/solr-operator/Chart.yaml
index d620dac5..aab5d663 100644
--- a/helm/solr-operator/Chart.yaml
+++ b/helm/solr-operator/Chart.yaml
@@ -91,6 +91,13 @@ annotations:
           url: https://github.com/apache/solr-operator/issues/778
         - name: Github PR
           url: https://github.com/apache/solr-operator/pull/779
+    - kind: fixed
+      description: A SolrBackup no longer gets stuck when the operator loses 
the status update recording that Solr accepted the backup, such as when the 
operator restarts at that moment
+      links:
+        - name: Github Issue
+          url: https://github.com/apache/solr-operator/issues/848
+        - name: Github PR
+          url: https://github.com/apache/solr-operator/pull/907
     - kind: fixed
       description: Fixed initContainer script that imports security.json
       links:

Reply via email to