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

janhoy 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 e1befb09 Resubmit collection backups that Solr has lost track of (#910)
e1befb09 is described below

commit e1befb09c3bbab52d24af693ef90363e80ebc0a2
Author: Houston Putman <[email protected]>
AuthorDate: Fri Nov 20 04:54:23 2026 -0800

    Resubmit collection backups that Solr has lost track of (#910)
---
 controllers/events_test.go                     |  34 ++-
 controllers/solrbackup_async_recovery_test.go  |  12 +-
 controllers/solrbackup_controller.go           | 143 ++++++----
 controllers/solrbackup_controller_unit_test.go | 355 +++++++++++++++++++++++++
 helm/solr-operator/Chart.yaml                  |   7 +
 5 files changed, 492 insertions(+), 59 deletions(-)

diff --git a/controllers/events_test.go b/controllers/events_test.go
index d2a5d1ec..1f8a420b 100644
--- a/controllers/events_test.go
+++ b/controllers/events_test.go
@@ -33,8 +33,10 @@ import (
        metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
        "k8s.io/apimachinery/pkg/runtime"
        "k8s.io/apimachinery/pkg/runtime/schema"
+       "k8s.io/apimachinery/pkg/types"
        clientgoscheme "k8s.io/client-go/kubernetes/scheme"
        "k8s.io/client-go/tools/record"
+       ctrl "sigs.k8s.io/controller-runtime"
        "sigs.k8s.io/controller-runtime/pkg/client"
        "sigs.k8s.io/controller-runtime/pkg/client/fake"
        "sigs.k8s.io/controller-runtime/pkg/client/interceptor"
@@ -336,9 +338,12 @@ func TestDeletePodForUpdateReportsRealDeleteError(t 
*testing.T) {
        requireEvent(t, rec, corev1.EventTypeWarning, "PodUpdateError")
 }
 
-// emitted when a backup is attempted against a repository that the SolrCloud 
has not yet marked
-// available. A GCS repository is used so that EnsureDirectoryForBackup is a 
no-op (no pod exec).
-func TestReconcileSolrCloudBackupEmitsCloudNotReadyEvent(t *testing.T) {
+// TestSolrBackupReconcileEmitsOneEventWhenCloudNotReady checks that a backup 
attempted against a
+// repository that the SolrCloud has not yet marked available records exactly 
one warning event.
+// reconcileSolrCloudBackup only returns its errors, and Reconcile records 
them, so an error must
+// not also be recorded where it happens. A GCS repository is used so that 
EnsureDirectoryForBackup
+// is a no-op (no pod exec).
+func TestSolrBackupReconcileEmitsOneEventWhenCloudNotReady(t *testing.T) {
        scheme := runtime.NewScheme()
        if err := clientgoscheme.AddToScheme(scheme); err != nil {
                t.Fatalf("could not add client-go types to scheme: %v", err)
@@ -369,12 +374,27 @@ func 
TestReconcileSolrCloudBackupEmitsCloudNotReadyEvent(t *testing.T) {
 
        rec := record.NewFakeRecorder(8)
        r := &SolrBackupReconciler{
-               Client:   
fake.NewClientBuilder().WithScheme(scheme).WithObjects(solrCloud).Build(),
+               Client: fake.NewClientBuilder().WithScheme(scheme).
+                       WithObjects(solrCloud, backup).
+                       WithStatusSubresource(&solrv1beta1.SolrBackup{}).
+                       Build(),
                Recorder: rec,
        }
 
-       if _, _, err := r.reconcileSolrCloudBackup(context.Background(), 
backup, &backup.Status.IndividualSolrBackupStatus, logr.Discard()); err == nil {
-               t.Error("expected a 'cloud not ready' error, got nil")
+       // The first reconcile may only fill in the backup's defaults, and 
requeue.
+       req := ctrl.Request{NamespacedName: types.NamespacedName{Namespace: 
backup.Namespace, Name: backup.Name}}
+       for i := 0; i < 2; i++ {
+               result, err := r.Reconcile(context.Background(), req)
+               if err != nil {
+                       t.Fatalf("expected the reconcile to succeed and 
requeue, got: %v", err)
+               }
+               if !result.Requeue {
+                       if result.RequeueAfter == 0 {
+                               t.Error("expected the backup to be requeued 
while the cloud is not ready")
+                       }
+                       break
+               }
        }
-       requireEvent(t, rec, corev1.EventTypeWarning, "BackupCloudNotReady")
+       requireEvent(t, rec, corev1.EventTypeWarning, "BackupError")
+       requireNoEvent(t, rec)
 }
diff --git a/controllers/solrbackup_async_recovery_test.go 
b/controllers/solrbackup_async_recovery_test.go
index ea48e557..0499bbb2 100644
--- a/controllers/solrbackup_async_recovery_test.go
+++ b/controllers/solrbackup_async_recovery_test.go
@@ -106,12 +106,13 @@ func 
TestCollectionBackupAdoptsRequestSolrAlreadyAccepted(t *testing.T) {
        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())
+       asyncFinished, err := 
reconcileSolrCollectionBackup(context.Background(), backup, status, cloud, 
repo, "books", logr.Discard())
        require.NoError(t, err)
-       assert.True(t, finished)
+       assert.True(t, asyncFinished, "the finished async request should be 
reported, so it is deleted once the status is saved")
+       assert.True(t, status.CollectionBackupStatuses[0].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")
+       assert.NotContains(t, solr.actions, "DELETESTATUS", "the async request 
is only deleted once the backup status is saved")
 }
 
 // A finished request may be left over from a previous recurrence, so it must 
not count as this backup.
@@ -138,7 +139,10 @@ func TestCollectionBackupRejectsUnknownAsyncState(t 
*testing.T) {
 
        _, err := reconcileSolrCollectionBackup(context.Background(), backup, 
status, cloud, repo, "books", logr.Discard())
        assert.Error(t, err)
-       assert.Empty(t, status.CollectionBackupStatuses)
+       // The collection's status is still recorded, as not started, so the 
SolrBackup cannot finish without it.
+       require.Len(t, status.CollectionBackupStatuses, 1)
+       assert.False(t, status.CollectionBackupStatuses[0].InProgress)
+       assert.Nil(t, status.CollectionBackupStatuses[0].StartTime)
        assert.NotContains(t, solr.actions, "BACKUP")
 }
 
diff --git a/controllers/solrbackup_controller.go 
b/controllers/solrbackup_controller.go
index bc7b2e3a..26df01fc 100644
--- a/controllers/solrbackup_controller.go
+++ b/controllers/solrbackup_controller.go
@@ -20,12 +20,14 @@ package controllers
 import (
        "context"
        "fmt"
-       "k8s.io/apimachinery/pkg/fields"
        "reflect"
+       "time"
+
+       "k8s.io/apimachinery/pkg/fields"
+       utilerrors "k8s.io/apimachinery/pkg/util/errors"
        "sigs.k8s.io/controller-runtime/pkg/builder"
        "sigs.k8s.io/controller-runtime/pkg/handler"
        "sigs.k8s.io/controller-runtime/pkg/predicate"
-       "time"
 
        "github.com/apache/solr-operator/controllers/util"
        "github.com/go-logr/logr"
@@ -126,9 +128,21 @@ func (r *SolrBackupReconciler) Reconcile(ctx 
context.Context, req ctrl.Request)
                }
        }
 
+       // The SolrCloud being backed up, and a context carrying any auth 
needed to call its Solr API.
+       // They are only set when backup work is done.
+       var solrCloud *solrv1beta1.SolrCloud
+       var solrCtx context.Context
+       // Collections whose async backup requests finished during this 
reconcile. Solr's async statuses for them may only
+       // be deleted once the status recording their results has been saved.
+       var asyncFinishedCollections []string
+
        // Do backup work if a backup is in-progress or needs to be started
        if doBackupWork {
-               solrCloud, _, err1 := r.reconcileSolrCloudBackup(ctx, backup, 
&backup.Status.IndividualSolrBackupStatus, logger)
+               var err1 error
+               solrCloud, solrCtx, err1 = r.getSolrCloudForBackup(ctx, backup, 
logger)
+               if err1 == nil {
+                       asyncFinishedCollections, err1 = 
r.reconcileSolrCloudBackup(solrCtx, backup, solrCloud, 
&backup.Status.IndividualSolrBackupStatus, logger)
+               }
                if err1 != nil {
                        // TODO Should we be failing the backup for some 
sub-set of errors here?
                        logger.Error(err1, "Error while taking SolrCloud 
backup")
@@ -149,7 +163,7 @@ func (r *SolrBackupReconciler) Reconcile(ctx 
context.Context, req ctrl.Request)
                                r.Recorder.Eventf(backup, 
corev1.EventTypeWarning, "BackupFailed",
                                        "The backup of SolrCloud %q finished 
but was not successful", backup.Spec.SolrCloud)
                        }
-               } else if solrCloud != nil {
+               } else {
                        // When working with the collection backups, 
auto-requeue after 5 seconds
                        // to check on the status of the async solr backup calls
                        updateRequeueAfter(&requeueOrNot, time.Second*5)
@@ -180,44 +194,63 @@ func (r *SolrBackupReconciler) Reconcile(ctx 
context.Context, req ctrl.Request)
                err = r.Status().Patch(ctx, backup, 
client.MergeFrom(unmodifiedBackupResource))
        }
 
+       // Only delete the async statuses once their results are saved. If they 
were deleted first, and the status could
+       // not be saved, the next reconcile would find the backups still in 
progress, but Solr would report them as
+       // "notfound", so they would be taken again.
+       if err == nil {
+               for _, collection := range asyncFinishedCollections {
+                       // A failure is only logged. The status is already 
saved, so the backup result is not lost.
+                       _ = util.DeleteAsyncInfoForBackup(solrCtx, solrCloud, 
collection, backup.Name, logger)
+               }
+       }
+
        return requeueOrNot, err
 }
 
-func (r *SolrBackupReconciler) reconcileSolrCloudBackup(ctx context.Context, 
backup *solrv1beta1.SolrBackup, currentBackupStatus 
*solrv1beta1.IndividualSolrBackupStatus, logger logr.Logger) (solrCloud 
*solrv1beta1.SolrCloud, actionTaken bool, err error) {
-       // Get the solrCloud that this backup is for.
+// getSolrCloudForBackup fetches the SolrCloud that the backup is for, and 
returns a context carrying any auth needed
+// to call its Solr API.
+func (r *SolrBackupReconciler) getSolrCloudForBackup(ctx context.Context, 
backup *solrv1beta1.SolrBackup, logger logr.Logger) (solrCloud 
*solrv1beta1.SolrCloud, solrCtx context.Context, err error) {
        solrCloud = &solrv1beta1.SolrCloud{}
-
        err = r.Get(ctx, types.NamespacedName{Namespace: backup.Namespace, 
Name: backup.Spec.SolrCloud}, solrCloud)
-       if err != nil && errors.IsNotFound(err) {
-               logger.Error(err, "Could not find cloud to backup", 
"solrCloud", backup.Spec.SolrCloud)
-               return nil, actionTaken, err
-       } else if err != nil {
-               return nil, actionTaken, err
+       if err != nil {
+               if errors.IsNotFound(err) {
+                       logger.Error(err, "Could not find cloud to backup", 
"solrCloud", backup.Spec.SolrCloud)
+               }
+               return nil, ctx, err
        }
 
        // Add any additional values needed to Authn to Solr to the Context 
used when invoking the API
+       solrCtx = ctx
        if solrCloud.Spec.SolrSecurity != nil {
-               ctx, err = util.AddAuthToContext(ctx, &r.Client, solrCloud)
-               if err != nil {
-                       return nil, actionTaken, err
+               if solrCtx, err = util.AddAuthToContext(ctx, &r.Client, 
solrCloud); err != nil {
+                       return nil, ctx, err
                }
        }
+       return solrCloud, solrCtx, nil
+}
 
+// reconcileSolrCloudBackup starts, or checks on, the backup of each 
collection. ctx must carry any auth needed to call
+// the SolrCloud's Solr API, see getSolrCloudForBackup.
+//
+// Errors are only returned, never recorded as events here, since the caller 
records an event for them.
+//
+// asyncFinishedCollections lists the collections whose async backup requests 
finished during this call. Their async
+// statuses in Solr must be deleted, but only once the backup status, which 
records their results, has been saved.
+func (r *SolrBackupReconciler) reconcileSolrCloudBackup(ctx context.Context, 
backup *solrv1beta1.SolrBackup, solrCloud *solrv1beta1.SolrCloud, 
currentBackupStatus *solrv1beta1.IndividualSolrBackupStatus, logger 
logr.Logger) (asyncFinishedCollections []string, err error) {
        // First check if the collection backups have been completed
        collectionBackupsFinished := 
util.UpdateStatusOfCollectionBackups(currentBackupStatus)
 
        // If the collectionBackups are complete, then nothing else has to be 
done here
        if collectionBackupsFinished {
-               return solrCloud, actionTaken, nil
+               return nil, nil
        }
 
-       actionTaken = true
        backupRepository := 
util.GetBackupRepositoryByName(solrCloud.Spec.BackupRepositories, 
backup.Spec.RepositoryName)
        if backupRepository == nil {
                err = fmt.Errorf("Unable to find backup repository to use for 
backup [%s] (which specified the repository"+
                        " [%s]).  solrcloud must define a repository matching 
that name (or have only 1 repository defined).",
                        backup.Name, backup.Spec.RepositoryName)
-               return solrCloud, actionTaken, err
+               return nil, err
        }
 
        // This should only occur before the backup processes have been started
@@ -225,15 +258,13 @@ func (r *SolrBackupReconciler) 
reconcileSolrCloudBackup(ctx context.Context, bac
                // Prep the backup directory in the persistentVolume
                err = util.EnsureDirectoryForBackup(solrCloud, 
backupRepository, backup, r.Config)
                if err != nil {
-                       return solrCloud, actionTaken, err
+                       return nil, err
                }
 
                // Make sure that all solr living Solr pods have the backupRepo 
configured
                if 
!solrCloud.Status.BackupRepositoriesAvailable[backupRepository.Name] {
                        logger.Info("Cloud not ready for backup", "solrCloud", 
solrCloud.Name, "repository", backupRepository.Name)
-                       r.Recorder.Eventf(backup, corev1.EventTypeWarning, 
"BackupCloudNotReady",
-                               "SolrCloud %q is not yet ready for backups in 
the %q repository", solrCloud.Name, backupRepository.Name)
-                       return solrCloud, actionTaken, 
errors.NewServiceUnavailable(fmt.Sprintf("Cloud is not ready for backups in the 
%s repository", backupRepository.Name))
+                       return nil, 
errors.NewServiceUnavailable(fmt.Sprintf("Cloud is not ready for backups in the 
%s repository", backupRepository.Name))
                }
 
                // Only set the solr version at the start of the backup. This 
shouldn't change throughout the backup.
@@ -245,31 +276,39 @@ func (r *SolrBackupReconciler) 
reconcileSolrCloudBackup(ctx context.Context, bac
 
        collectionsToBackup := backup.Spec.Collections
 
-       // If there are no collections specified, we need to list through 
collections available in Solr
+       // If there are no collections specified, we need to list through 
collections available in Solr.
+       // Without the list there is nothing to back up, so this ends the 
reconcile. The caller logs the error and requeues.
        if len(collectionsToBackup) == 0 {
-               collectionsToBackup, err = util.ListAllSolrCollections(ctx, 
solrCloud, logger)
-               if err != nil {
-                       logger.Error(err, "Error listing collections", 
"solrCloud", solrCloud.Name)
-                       r.Recorder.Eventf(backup, corev1.EventTypeWarning, 
"BackupCollectionListError",
-                               "Error listing the collections to back up for 
SolrCloud %q: %v", solrCloud.Name, err)
+               if collectionsToBackup, err = util.ListAllSolrCollections(ctx, 
solrCloud, logger); err != nil {
+                       return nil, fmt.Errorf("could not list the collections 
to back up in SolrCloud %q: %w", solrCloud.Name, err)
                }
        }
 
+       var errs []error
        // Go through each collection specified and reconcile the backup.
+       // A failure for one collection does not hold up the others, the errors 
are returned together.
        for _, collection := range collectionsToBackup {
                // This will in-place update the CollectionBackupStatus in the 
backup object
-               if _, err = reconcileSolrCollectionBackup(ctx, backup, 
currentBackupStatus, solrCloud, backupRepository, collection, logger); err != 
nil {
-                       break
+               asyncFinished, collectionErr := 
reconcileSolrCollectionBackup(ctx, backup, currentBackupStatus, solrCloud, 
backupRepository, collection, logger)
+               if collectionErr != nil {
+                       errs = append(errs, fmt.Errorf("collection %q: %w", 
collection, collectionErr))
+               }
+               if asyncFinished {
+                       asyncFinishedCollections = 
append(asyncFinishedCollections, collection)
                }
        }
 
        // First check if the collection backups have been completed
        util.UpdateStatusOfCollectionBackups(currentBackupStatus)
 
-       return solrCloud, actionTaken, err
+       return asyncFinishedCollections, utilerrors.NewAggregate(errs)
 }
 
-func reconcileSolrCollectionBackup(ctx context.Context, backup 
*solrv1beta1.SolrBackup, currentBackupStatus 
*solrv1beta1.IndividualSolrBackupStatus, solrCloud *solrv1beta1.SolrCloud, 
backupRepository *solrv1beta1.SolrBackupRepository, collection string, logger 
logr.Logger) (finished bool, err error) {
+// reconcileSolrCollectionBackup starts, or checks on, the backup of a single 
collection, updating its status in place.
+//
+// asyncFinished is true when Solr reported the collection's async backup 
request as finished during this call. Its
+// async status must then be deleted, but only once the updated backup status 
has been saved.
+func reconcileSolrCollectionBackup(ctx context.Context, backup 
*solrv1beta1.SolrBackup, currentBackupStatus 
*solrv1beta1.IndividualSolrBackupStatus, solrCloud *solrv1beta1.SolrCloud, 
backupRepository *solrv1beta1.SolrBackupRepository, collection string, logger 
logr.Logger) (asyncFinished bool, err error) {
        now := metav1.Now()
        collectionBackupStatus := solrv1beta1.CollectionBackupStatus{}
        collectionBackupStatus.Collection = collection
@@ -284,32 +323,36 @@ func reconcileSolrCollectionBackup(ctx context.Context, 
backup *solrv1beta1.Solr
 
        // If the collection backup hasn't started, start it
        if collectionBackupStatus.Finished {
-               return true, nil
+               return false, nil
        } else if !collectionBackupStatus.InProgress {
-               // Start the backup by calling solr, unless Solr already has it
+               // Start the backup by calling solr, unless Solr already has it.
+               // The collection's status is recorded even if the backup could 
not be started, and the error is returned below.
+               // The SolrBackup can then not finish until this collection's 
backup has, even if all others finish first.
                var started bool
-               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
+               if started, err = util.PrepareBackupForCollection(ctx, 
solrCloud, collection, backup.Name, logger); err == nil {
+                       if !started {
+                               started, err = 
util.StartBackupForCollection(ctx, solrCloud, backupRepository, backup, 
collection, logger)
+                               // Reset on every submission, including when a 
backup that Solr lost track of is resubmitted. The 5 second grace
+                               // before resubmitting a "notfound" backup is 
measured from this, so it also applies to the resubmitted backup.
+                               if started {
+                                       collectionBackupStatus.StartTime = &now
+                               }
+                       } else if collectionBackupStatus.StartTime == nil {
+                               // We did not submit a new backup, but found 
one already running in Solr. Without a start time, use now.
+                               collectionBackupStatus.StartTime = &now
                        }
                }
                collectionBackupStatus.InProgress = started
-               if started && collectionBackupStatus.StartTime == nil {
-                       collectionBackupStatus.StartTime = &now
-               }
                collectionBackupStatus.BackupName = 
util.FullCollectionBackupName(collection, backup.Name)
        } else if collectionBackupStatus.InProgress {
-               var successful bool
+               var finished, successful bool
                var asyncStatus string
                // Check the state of the backup, when it is in progress, and 
update the state accordingly
                finished, successful, asyncStatus, err = 
util.CheckBackupForCollection(ctx, solrCloud, collection, backup.Name, logger)
                if err != nil {
                        return false, err
                }
+               asyncFinished = finished
                collectionBackupStatus.Finished = finished
                if finished {
                        collectionBackupStatus.InProgress = false
@@ -320,10 +363,14 @@ func reconcileSolrCollectionBackup(ctx context.Context, 
backup *solrv1beta1.Solr
                        if collectionBackupStatus.FinishTime == nil {
                                collectionBackupStatus.FinishTime = &now
                        }
-
-                       err = util.DeleteAsyncInfoForBackup(ctx, solrCloud, 
collection, backup.Name, logger)
+                       // The async status is deleted by the caller, once this 
result has been saved
                } else {
                        collectionBackupStatus.AsyncBackupStatus = asyncStatus
+                       // If we have waited over 5 seconds, and the backup is 
still not found, submit it again
+                       if asyncStatus == "notfound" &&
+                               (collectionBackupStatus.StartTime != nil && 
time.Since(collectionBackupStatus.StartTime.Time) > time.Second*5) {
+                               collectionBackupStatus.InProgress = false
+                       }
                }
        }
 
@@ -333,7 +380,7 @@ func reconcileSolrCollectionBackup(ctx context.Context, 
backup *solrv1beta1.Solr
                currentBackupStatus.CollectionBackupStatuses[backupIndex] = 
collectionBackupStatus
        }
 
-       return collectionBackupStatus.Finished, err
+       return asyncFinished, err
 }
 
 // SetupWithManager sets up the controller with the Manager.
diff --git a/controllers/solrbackup_controller_unit_test.go 
b/controllers/solrbackup_controller_unit_test.go
new file mode 100644
index 00000000..c436dbf7
--- /dev/null
+++ b/controllers/solrbackup_controller_unit_test.go
@@ -0,0 +1,355 @@
+/*
+ * 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"
+       "crypto/tls"
+       "errors"
+       "fmt"
+       "io"
+       "net/http"
+       "strings"
+       "testing"
+       "time"
+
+       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"
+       "k8s.io/apimachinery/pkg/runtime"
+       "k8s.io/apimachinery/pkg/types"
+       clientgoscheme "k8s.io/client-go/kubernetes/scheme"
+       "k8s.io/client-go/tools/record"
+       ctrl "sigs.k8s.io/controller-runtime"
+       "sigs.k8s.io/controller-runtime/pkg/client"
+       fakeclient "sigs.k8s.io/controller-runtime/pkg/client/fake"
+       "sigs.k8s.io/controller-runtime/pkg/client/interceptor"
+)
+
+type roundTripFunc func(*http.Request) (*http.Response, error)
+
+func (f roundTripFunc) RoundTrip(request *http.Request) (*http.Response, 
error) {
+       return f(request)
+}
+
+// fakeSolrCollectionsApi stands in for the Solr Collections API. 
REQUESTSTATUS answers with the
+// next async state queued for the request id, or "notfound" when none is 
queued. BACKUP and
+// DELETESTATUS always succeed, and every call is recorded.
+type fakeSolrCollectionsApi struct {
+       t *testing.T
+       // Queued async states, by request id
+       asyncStates map[string][]string
+       // BACKUP calls for these collections fail.
+       failBackupFor map[string]bool
+       calls         []string
+       backupParams  []map[string]string
+}
+
+func (f *fakeSolrCollectionsApi) roundTrip(request *http.Request) 
(*http.Response, error) {
+       query := request.URL.Query()
+       action := query.Get("action")
+       f.calls = append(f.calls, action)
+
+       var body string
+       switch action {
+       case "REQUESTSTATUS":
+               state := "notfound"
+               if queued := f.asyncStates[query.Get("requestid")]; len(queued) 
> 0 {
+                       state = queued[0]
+                       f.asyncStates[query.Get("requestid")] = queued[1:]
+               }
+               body = 
fmt.Sprintf(`{"responseHeader":{"status":0},"status":{"state":%q}}`, state)
+       case "BACKUP":
+               if f.failBackupFor[query.Get("collection")] {
+                       return &http.Response{
+                               StatusCode: http.StatusServiceUnavailable,
+                               Header:     make(http.Header),
+                               Body:       
io.NopCloser(strings.NewReader("unavailable")),
+                       }, nil
+               }
+               f.backupParams = append(f.backupParams, map[string]string{
+                       "collection": query.Get("collection"),
+                       "name":       query.Get("name"),
+                       "async":      query.Get("async"),
+               })
+               body = `{"responseHeader":{"status":0}}`
+       case "DELETESTATUS":
+               body = `{"responseHeader":{"status":0},"status":"successfully 
removed stored response"}`
+       case "LIST":
+               // Only used to test a failure to list the collections.
+               return &http.Response{
+                       StatusCode: http.StatusServiceUnavailable,
+                       Header:     make(http.Header),
+                       Body:       
io.NopCloser(strings.NewReader("unavailable")),
+               }, nil
+       default:
+               f.t.Fatalf("Unexpected Collections API action %q", action)
+       }
+       return &http.Response{
+               StatusCode: http.StatusOK,
+               Header:     make(http.Header),
+               Body:       io.NopCloser(strings.NewReader(body)),
+       }, nil
+}
+
+// useFakeSolr routes all Solr API calls to the fake for the duration of the 
test. The async states
+// are queued for the backup of "collection" by the "backup" SolrBackup, see 
notFoundTestFixtures.
+func useFakeSolr(t *testing.T, asyncStates ...string) *fakeSolrCollectionsApi {
+       fake := &fakeSolrCollectionsApi{t: t, asyncStates: map[string][]string{
+               util.AsyncIdForCollectionBackup("collection", "backup"): 
asyncStates,
+       }}
+       solr_api.SetNoVerifyTLSHttpClient(&http.Client{Transport: 
roundTripFunc(fake.roundTrip)})
+       t.Cleanup(func() {
+               // Restore the client that solr_api's init() sets up.
+               transport := http.DefaultTransport.(*http.Transport).Clone()
+               transport.TLSClientConfig = &tls.Config{InsecureSkipVerify: 
true}
+               solr_api.SetNoVerifyTLSHttpClient(&http.Client{Transport: 
transport})
+       })
+       return fake
+}
+
+func notFoundTestFixtures(startedAgo time.Duration) (*solrv1beta1.SolrBackup, 
*solrv1beta1.IndividualSolrBackupStatus, *solrv1beta1.SolrCloud, 
*solrv1beta1.SolrBackupRepository) {
+       backup := &solrv1beta1.SolrBackup{ObjectMeta: metav1.ObjectMeta{Name: 
"backup", Namespace: "ns"}}
+       cloud := &solrv1beta1.SolrCloud{ObjectMeta: metav1.ObjectMeta{Name: 
"cloud", Namespace: "ns"}}
+       repo := &solrv1beta1.SolrBackupRepository{Name: "repo", GCS: 
&solrv1beta1.GcsRepository{Bucket: "bucket"}}
+       startTime := metav1.NewTime(time.Now().Add(-startedAgo))
+       status := &solrv1beta1.IndividualSolrBackupStatus{
+               CollectionBackupStatuses: []solrv1beta1.CollectionBackupStatus{{
+                       Collection: "collection",
+                       BackupName: util.FullCollectionBackupName("collection", 
backup.Name),
+                       InProgress: true,
+                       StartTime:  &startTime,
+               }},
+       }
+       return backup, status, cloud, repo
+}
+
+// Solr can lose track of an accepted backup, e.g. when its async status is 
deleted while the
+// operator is down, and then REQUESTSTATUS answers "notfound" forever. The 
operator must submit
+// the backup again, rather than wait on it indefinitely, and must then see it 
through to the end.
+func TestCollectionBackupIsResubmittedWhenSolrLosesTrackOfIt(t *testing.T) {
+       // The second "notfound" is the check, before resubmitting, that Solr 
holds no request for the backup.
+       fake := useFakeSolr(t, "notfound", "notfound", "completed")
+       backup, status, cloud, repo := notFoundTestFixtures(time.Minute)
+       originalStart := status.CollectionBackupStatuses[0].StartTime.DeepCopy()
+       ctx := context.Background()
+
+       // 1. Solr no longer knows about the backup: it is no longer considered 
in progress.
+       asyncFinished, err := reconcileSolrCollectionBackup(ctx, backup, 
status, cloud, repo, "collection", logr.Discard())
+       require.NoError(t, err)
+       collectionStatus := status.CollectionBackupStatuses[0]
+       assert.False(t, asyncFinished, "There is no async status to delete for 
a backup Solr lost track of")
+       assert.False(t, collectionStatus.InProgress, "A backup Solr lost track 
of must not stay in progress")
+       assert.False(t, collectionStatus.Finished)
+       assert.Nil(t, collectionStatus.Successful)
+       assert.Equal(t, "notfound", collectionStatus.AsyncBackupStatus, "The 
status should say why the backup was resubmitted")
+       assert.False(t, util.UpdateStatusOfCollectionBackups(status), "The 
overall backup must not be finished")
+
+       // 2. The next reconcile submits the backup again, with the same name 
and async id.
+       asyncFinished, err = reconcileSolrCollectionBackup(ctx, backup, status, 
cloud, repo, "collection", logr.Discard())
+       require.NoError(t, err)
+       collectionStatus = status.CollectionBackupStatuses[0]
+       assert.False(t, asyncFinished)
+       assert.True(t, collectionStatus.InProgress, "The resubmitted backup 
should be in progress")
+       require.Len(t, fake.backupParams, 1, "The backup should have been 
submitted again")
+       assert.Equal(t, map[string]string{
+               "collection": "collection",
+               "name":       util.FullCollectionBackupName("collection", 
backup.Name),
+               "async":      util.AsyncIdForCollectionBackup("collection", 
backup.Name),
+       }, fake.backupParams[0])
+       require.NotNil(t, collectionStatus.StartTime)
+       assert.True(t, collectionStatus.StartTime.After(originalStart.Time), 
"Resubmitting must reset the start time")
+
+       // 3. The resubmitted backup completes, and the collection backup 
finishes successfully.
+       // Its async status is left for the caller to delete, once this result 
has been saved.
+       asyncFinished, err = reconcileSolrCollectionBackup(ctx, backup, status, 
cloud, repo, "collection", logr.Discard())
+       require.NoError(t, err)
+       collectionStatus = status.CollectionBackupStatuses[0]
+       assert.True(t, asyncFinished, "The finished backup's async status 
should be reported for deletion")
+       assert.True(t, collectionStatus.Finished)
+       assert.False(t, collectionStatus.InProgress)
+       require.NotNil(t, collectionStatus.Successful)
+       assert.True(t, *collectionStatus.Successful)
+       assert.Empty(t, collectionStatus.AsyncBackupStatus)
+       assert.NotNil(t, collectionStatus.FinishTime)
+
+       assert.True(t, util.UpdateStatusOfCollectionBackups(status), "The 
overall backup should now be finished")
+       require.NotNil(t, status.Successful)
+       assert.True(t, *status.Successful)
+
+       assert.Equal(t, []string{"REQUESTSTATUS", "REQUESTSTATUS", "BACKUP", 
"REQUESTSTATUS"}, fake.calls, "The async status must not be deleted before the 
result is saved")
+       assert.Empty(t, 
fake.asyncStates[util.AsyncIdForCollectionBackup("collection", backup.Name)], 
"Every queued async state should have been used")
+}
+
+// Right after a backup is submitted, a "notfound" must not trigger a 
resubmission straight away.
+func TestCollectionBackupIsNotResubmittedRightAfterStarting(t *testing.T) {
+       fake := useFakeSolr(t, "notfound")
+       backup, status, cloud, repo := notFoundTestFixtures(time.Second)
+
+       asyncFinished, err := 
reconcileSolrCollectionBackup(context.Background(), backup, status, cloud, 
repo, "collection", logr.Discard())
+       require.NoError(t, err)
+       collectionStatus := status.CollectionBackupStatuses[0]
+       assert.False(t, asyncFinished)
+       assert.True(t, collectionStatus.InProgress, "The backup should still be 
waited on")
+       assert.Equal(t, "notfound", collectionStatus.AsyncBackupStatus)
+       assert.Equal(t, []string{"REQUESTSTATUS"}, fake.calls)
+}
+
+// newInProgressBackupReconciler sets up a SolrBackup whose single collection 
backup is in progress,
+// against a SolrCloud whose repository is ready. Status patches are recorded 
in fake.calls as
+// "PATCH STATUS", so their order relative to the Solr calls can be checked. 
If failStatusPatch is
+// set, saving the status fails.
+func newInProgressBackupReconciler(t *testing.T, fake *fakeSolrCollectionsApi, 
failStatusPatch bool) (*SolrBackupReconciler, ctrl.Request) {
+       scheme := runtime.NewScheme()
+       require.NoError(t, clientgoscheme.AddToScheme(scheme))
+       require.NoError(t, solrv1beta1.AddToScheme(scheme))
+
+       cloud := &solrv1beta1.SolrCloud{
+               ObjectMeta: metav1.ObjectMeta{Name: "cloud", Namespace: "ns"},
+               Spec: solrv1beta1.SolrCloudSpec{
+                       BackupRepositories: 
[]solrv1beta1.SolrBackupRepository{{Name: "repo", GCS: 
&solrv1beta1.GcsRepository{Bucket: "bucket"}}},
+               },
+               Status: 
solrv1beta1.SolrCloudStatus{BackupRepositoriesAvailable: 
map[string]bool{"repo": true}},
+       }
+       backup, status, _, _ := notFoundTestFixtures(time.Minute)
+       backup.Spec = solrv1beta1.SolrBackupSpec{SolrCloud: "cloud", 
RepositoryName: "repo", Collections: []string{"collection"}}
+       backup.WithDefaults()
+       status.StartTime = metav1.Now()
+       backup.Status.IndividualSolrBackupStatus = *status
+
+       statusClient := fakeclient.NewClientBuilder().WithScheme(scheme).
+               WithObjects(cloud, backup).
+               WithStatusSubresource(&solrv1beta1.SolrBackup{}).
+               WithInterceptorFuncs(interceptor.Funcs{
+                       SubResourcePatch: func(ctx context.Context, c 
client.Client, subResourceName string, obj client.Object, patch client.Patch, 
opts ...client.SubResourcePatchOption) error {
+                               fake.calls = append(fake.calls, "PATCH STATUS")
+                               if failStatusPatch {
+                                       return errors.New("forced status patch 
failure")
+                               }
+                               return 
c.SubResource(subResourceName).Patch(ctx, obj, patch, opts...)
+                       },
+               }).
+               Build()
+
+       r := &SolrBackupReconciler{Client: statusClient, Recorder: 
record.NewFakeRecorder(16)}
+       return r, ctrl.Request{NamespacedName: types.NamespacedName{Namespace: 
backup.Namespace, Name: backup.Name}}
+}
+
+// Solr's async status for a finished collection backup must only be deleted 
once the backup's
+// status, recording the result, has been saved. Otherwise a failed save would 
leave the backup
+// in progress, with Solr reporting it as "notfound", and it would be taken 
again.
+func TestSolrBackupAsyncStatusIsDeletedOnlyAfterTheStatusIsSaved(t *testing.T) 
{
+       fake := useFakeSolr(t, "completed")
+       r, req := newInProgressBackupReconciler(t, fake, false)
+
+       _, err := r.Reconcile(context.Background(), req)
+       require.NoError(t, err)
+       assert.Equal(t, []string{"REQUESTSTATUS", "PATCH STATUS", 
"DELETESTATUS"}, fake.calls)
+
+       saved := &solrv1beta1.SolrBackup{}
+       require.NoError(t, r.Get(context.Background(), req.NamespacedName, 
saved))
+       require.Len(t, saved.Status.CollectionBackupStatuses, 1)
+       assert.True(t, saved.Status.CollectionBackupStatuses[0].Finished, "The 
collection backup result should be saved")
+       assert.True(t, saved.Status.Finished, "The backup should be saved as 
finished")
+}
+
+func TestSolrBackupAsyncStatusIsKeptWhenTheStatusCannotBeSaved(t *testing.T) {
+       fake := useFakeSolr(t, "completed")
+       r, req := newInProgressBackupReconciler(t, fake, true)
+
+       _, err := r.Reconcile(context.Background(), req)
+       require.Error(t, err, "The failed status save should be returned, so 
the reconcile is retried")
+       assert.Equal(t, []string{"REQUESTSTATUS", "PATCH STATUS"}, fake.calls,
+               "The async status must be kept, so the next reconcile can still 
find the backup's result")
+}
+
+// When the collections to back up have to be listed, and listing them fails, 
nothing can be backed
+// up, so the error must end the reconcile of the SolrCloud backup.
+func TestSolrCloudBackupStopsWhenCollectionsCannotBeListed(t *testing.T) {
+       fake := useFakeSolr(t)
+       backup, _, cloud, repo := notFoundTestFixtures(time.Minute)
+       cloud.Spec.BackupRepositories = 
[]solrv1beta1.SolrBackupRepository{*repo}
+       status := &solrv1beta1.IndividualSolrBackupStatus{StartTime: 
metav1.Now()}
+
+       r := &SolrBackupReconciler{Recorder: record.NewFakeRecorder(4)}
+       asyncFinished, err := r.reconcileSolrCloudBackup(context.Background(), 
backup, cloud, status, logr.Discard())
+       require.Error(t, err)
+       assert.Contains(t, err.Error(), "could not list the collections to back 
up")
+       assert.Empty(t, asyncFinished)
+       assert.Empty(t, status.CollectionBackupStatuses)
+       assert.Equal(t, []string{"LIST"}, fake.calls, "No collection backups 
should be attempted")
+}
+
+// A collection whose backup cannot be started must still hold up the 
SolrBackup. Otherwise, once
+// the other collections finish, the SolrBackup would be finished, and 
successful, without it.
+func TestSolrBackupDoesNotFinishWithoutACollectionThatFailedToStart(t 
*testing.T) {
+       fake := useFakeSolr(t)
+       fake.failBackupFor = map[string]bool{"a": true}
+       // b is checked before it is submitted, and then once in progress.
+       fake.asyncStates[util.AsyncIdForCollectionBackup("b", "backup")] = 
[]string{"notfound", "completed"}
+       backup, _, cloud, repo := notFoundTestFixtures(time.Minute)
+       backup.Spec.Collections = []string{"a", "b"}
+       status := &solrv1beta1.IndividualSolrBackupStatus{StartTime: 
metav1.Now()}
+       r := &SolrBackupReconciler{Recorder: record.NewFakeRecorder(4)}
+       cloud.Spec.BackupRepositories = 
[]solrv1beta1.SolrBackupRepository{*repo}
+
+       // 1. a fails to start, b starts.
+       _, err := r.reconcileSolrCloudBackup(context.Background(), backup, 
cloud, status, logr.Discard())
+       require.Error(t, err)
+       assert.Contains(t, err.Error(), `collection "a"`)
+       require.Len(t, status.CollectionBackupStatuses, 2, "Both collections 
should have a status, even the one that failed to start")
+       assert.Equal(t, "a", status.CollectionBackupStatuses[0].Collection)
+       assert.False(t, status.CollectionBackupStatuses[0].InProgress)
+       assert.Nil(t, status.CollectionBackupStatuses[0].StartTime)
+       assert.True(t, status.CollectionBackupStatuses[1].InProgress)
+
+       // 2. a fails to start again, b completes. The SolrBackup must not 
finish without a.
+       asyncFinished, err := r.reconcileSolrCloudBackup(context.Background(), 
backup, cloud, status, logr.Discard())
+       require.Error(t, err)
+       assert.Equal(t, []string{"b"}, asyncFinished)
+       assert.True(t, status.CollectionBackupStatuses[1].Finished)
+       assert.False(t, status.CollectionBackupStatuses[0].Finished)
+       assert.False(t, status.Finished, "The SolrBackup must not finish while 
a collection has not been backed up")
+       assert.Nil(t, status.Successful)
+}
+
+// The grace before resubmitting a "notfound" backup must also apply to a 
resubmitted backup, so a
+// "notfound" straight after resubmitting does not resubmit it yet again.
+func TestResubmittedCollectionBackupGetsTheSameGraceBeforeAnotherResubmit(t 
*testing.T) {
+       fake := useFakeSolr(t, "notfound", "notfound")
+       backup, status, cloud, repo := notFoundTestFixtures(time.Minute)
+       ctx := context.Background()
+
+       // 1. Solr no longer knows about the backup, and 2. it is resubmitted.
+       for i := 0; i < 2; i++ {
+               _, err := reconcileSolrCollectionBackup(ctx, backup, status, 
cloud, repo, "collection", logr.Discard())
+               require.NoError(t, err)
+       }
+       require.Len(t, fake.backupParams, 1)
+
+       // 3. Solr reports "notfound" right after the resubmission: it is not 
resubmitted again yet.
+       _, err := reconcileSolrCollectionBackup(ctx, backup, status, cloud, 
repo, "collection", logr.Discard())
+       require.NoError(t, err)
+       assert.True(t, status.CollectionBackupStatuses[0].InProgress, "The 
resubmitted backup should still be waited on")
+       // The second REQUESTSTATUS is the check, before resubmitting, that 
Solr holds no request for the backup.
+       assert.Equal(t, []string{"REQUESTSTATUS", "REQUESTSTATUS", "BACKUP", 
"REQUESTSTATUS"}, fake.calls)
+}
diff --git a/helm/solr-operator/Chart.yaml b/helm/solr-operator/Chart.yaml
index 8c5e475a..82c14b6c 100644
--- a/helm/solr-operator/Chart.yaml
+++ b/helm/solr-operator/Chart.yaml
@@ -248,6 +248,13 @@ annotations:
           url: https://github.com/apache/solr-operator/issues/813
         - name: Github PR
           url: https://github.com/apache/solr-operator/pull/900
+    - kind: fixed
+      description: A collection backup that Solr has lost track of, whose 
async status is reported as `notfound`, is now submitted again instead of being 
waited on forever. Previously this left the SolrBackup in progress 
indefinitely, and stopped recurring backups from ever being scheduled again. 
The operator also no longer deletes a backup's async status in Solr until the 
backup's result has been saved, which is one way this could happen, and a 
failing collection no longer stops the oth [...]
+      links:
+        - name: Github Issue
+          url: https://github.com/apache/solr-operator/issues/824
+        - name: Github PR
+          url: https://github.com/apache/solr-operator/pull/910
     - kind: fixed
       description: A SolrCloud that is being deleted no longer gets stuck when 
its providedConfigMap has already been removed, e.g. by Helm in the same 
uninstall
       links:

Reply via email to