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 a1621b89 Add Solr 10 compatibility support (#827)
a1621b89 is described below
commit a1621b89b49a061a5a26c9ba9f388a0a48f089af
Author: Daniel Meint <[email protected]>
AuthorDate: Thu Nov 19 16:10:08 2026 +0100
Add Solr 10 compatibility support (#827)
Co-Authored-By: Claude Opus 4.7 <[email protected]>
Co-authored-by: Jan Høydahl <[email protected]>
---
.github/workflows/e2e-tests.yaml | 8 +-
api/v1beta1/common_types.go | 7 +
api/v1beta1/solrcloud_types.go | 86 +++++
controllers/reconcile_events_test.go | 111 ++++++
controllers/solrcloud_controller.go | 51 ++-
.../solrcloud_controller_basic_auth_test.go | 4 +-
controllers/solrcloud_controller_test.go | 6 +-
controllers/solrcloud_controller_tls_test.go | 8 +-
controllers/solrcloud_controller_version_test.go | 163 +++++++++
controllers/solrprometheusexporter_controller.go | 49 ++-
.../solrprometheusexporter_controller_test.go | 6 +-
controllers/solrprometheusexporter_version_test.go | 56 +++
controllers/util/prometheus_exporter_util.go | 5 +-
controllers/util/solr_security_util.go | 21 +-
controllers/util/solr_tls_util.go | 13 +-
controllers/util/solr_util.go | 109 +++++-
controllers/util/solr_util_test.go | 407 ++++++++++++++++++++-
controllers/util/zk_util.go | 17 +-
controllers/util/zk_util_test.go | 33 ++
.../solr-cloud/pages/custom-solr-config.adoc | 4 +
docs/modules/solr-cloud/pages/index.adoc | 13 +
.../solr-prometheus-exporter/pages/index.adoc | 3 +
.../modules/upgrade-notes/pages/upgrade-notes.adoc | 70 +++-
helm/solr-operator/Chart.yaml | 19 +
helm/solr/Chart.yaml | 5 +
helm/solr/README.md | 2 +-
tests/e2e/prometheus_exporter_test.go | 2 +
tests/e2e/prometheus_exporter_tls_test.go | 2 +
tests/e2e/solrcloud_security_json_test.go | 18 +
tests/e2e/test_utils_test.go | 55 ++-
30 files changed, 1267 insertions(+), 86 deletions(-)
diff --git a/.github/workflows/e2e-tests.yaml b/.github/workflows/e2e-tests.yaml
index 635b4f3c..b3a7e19b 100644
--- a/.github/workflows/e2e-tests.yaml
+++ b/.github/workflows/e2e-tests.yaml
@@ -50,7 +50,7 @@ on:
type: string
default: 'pr'
solr-version:
- description: 'Solr image tag to test with (SOLR_IMAGE=solr:<tag>)'
+ description: 'Single Solr image tag to test with
(SOLR_IMAGE=solr:<tag>). Leave empty to test every version a pull request
tests.'
type: string
default: '9.11.0'
kube-version:
@@ -74,10 +74,14 @@ jobs:
timeout-minutes: 90
strategy:
+ # Both Solr versions are reported, a failure on one does not cancel the
other.
+ fail-fast: false
matrix:
go-version: [ '1.27' ]
kube-version: [ "${{ inputs.kube-version || 'v1.33.7' }}" ]
- solr-version: [ "${{ inputs.solr-version || '9.11.0' }}" ]
+ # Pull requests run the reduced profile against every supported Solr
major version, so that
+ # Solr 10 compatibility is covered. A manual run tests only the
version given by the input.
+ solr-version: ${{ fromJSON(inputs.solr-version && format('["{0}"]',
inputs.solr-version) || '["9.11.0", "10.1.0"]') }}
steps:
# Setup
diff --git a/api/v1beta1/common_types.go b/api/v1beta1/common_types.go
index 32a13d69..a5c43208 100644
--- a/api/v1beta1/common_types.go
+++ b/api/v1beta1/common_types.go
@@ -282,7 +282,14 @@ func (c *ContainerImage) ToImageName() (name string) {
return c.Repository + ":" + c.Tag
}
+// Version returns the version part of the image's tag, without a digest, e.g.
"10.0.0" for "10.0.0@sha256:...".
+func (c *ContainerImage) Version() string {
+ return ImageVersion(c.ToImageName())
+}
+
func ImageVersion(image string) (version string) {
+ // Ignore a digest, e.g. "solr:10.0.0@sha256:..."
+ image, _, _ = strings.Cut(image, "@")
split := strings.Split(image, ":")
if len(split) < 2 {
return ""
diff --git a/api/v1beta1/solrcloud_types.go b/api/v1beta1/solrcloud_types.go
index 493d304e..c5154da3 100644
--- a/api/v1beta1/solrcloud_types.go
+++ b/api/v1beta1/solrcloud_types.go
@@ -22,10 +22,12 @@ import (
"github.com/go-logr/logr"
zkApi "github.com/pravega/zookeeper-operator/api/v1beta1"
"math/rand"
+ "regexp"
"strconv"
"strings"
"k8s.io/apimachinery/pkg/util/intstr"
+ "k8s.io/apimachinery/pkg/util/version"
corev1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/api/resource"
@@ -1327,6 +1329,90 @@ func (zkInfo ZookeeperConnectionInfo)
ZkConnectionString() string {
return zkInfo.InternalConnectionString + zkInfo.ChRoot
}
+// solrImageTagVersionRegex matches Solr image tags, which must start with the
Solr version, "<major>[.<minor>[.<patch>...]]".
+// Anything after the version must start with neither a digit nor a dot,
+// e.g. "10.0.0", "10.1.0-SNAPSHOT", "10.0.0.1", "10.0.0@sha256:...",
"9.10-slim" or "8.11".
+// Short versions are accepted because released Solr Operator versions
defaulted to tags such as "8.11",
+// and they cannot change their major version.
+var solrImageTagVersionRegex =
regexp.MustCompile(`^(?P<version>\d+(?:\.\d+)*)(?:[^\d.].*)?$`)
+
+const (
+ // The range of Solr major versions that the Solr Operator supports.
+ MinSupportedSolrMajorVersion = 8
+ MaxSupportedSolrMajorVersion = 10
+)
+
+// SolrVersion returns the version of Solr that this SolrCloud runs, parsed
from spec.solrImage.tag.
+// An error is returned if the tag does not start with the Solr version,
+// or if the major version is not supported by the Solr Operator.
+func (sc *SolrCloud) SolrVersion() (*version.Version, error) {
+ tag := ""
+ if sc.Spec.SolrImage != nil {
+ tag = sc.Spec.SolrImage.Tag
+ }
+ return SolrVersionFromTag(tag)
+}
+
+// SolrVersionFromTag returns the Solr version that a Solr image tag starts
with.
+// An error is returned if the tag does not start with the Solr version,
+// or if the major version is not supported by the Solr Operator.
+func SolrVersionFromTag(tag string) (*version.Version, error) {
+ v, ok := ParseSolrVersion(tag)
+ if !ok {
+ return nil, fmt.Errorf("cannot determine the Solr version from
image tag %q: "+
+ "the tag must start with the Solr version, e.g.
\"10.0.0\" or \"10.0.0-my-build\"", tag)
+ }
+ if v.Major() < MinSupportedSolrMajorVersion || v.Major() >
MaxSupportedSolrMajorVersion {
+ return nil, fmt.Errorf("image tag %q is not a supported Solr
version: the Solr Operator supports Solr %d to %d, "+
+ "and the tag must start with the Solr version, e.g.
\"10.0.0\" or \"10.0.0-my-build\"",
+ tag, MinSupportedSolrMajorVersion,
MaxSupportedSolrMajorVersion)
+ }
+ return v, nil
+}
+
+// ParseSolrVersion returns the version that a Solr image tag starts with,
without checking
+// whether the Solr Operator supports it. A tag without a minor version, e.g.
"9", is version 9.0.
+// ok is false if the tag does not start with a version.
+func ParseSolrVersion(tag string) (v *version.Version, ok bool) {
+ match := solrImageTagVersionRegex.FindStringSubmatch(tag)
+ if match == nil {
+ return nil, false
+ }
+ versionString := match[solrImageTagVersionRegex.SubexpIndex("version")]
+ if !strings.Contains(versionString, ".") {
+ versionString += ".0"
+ }
+ v, err := version.ParseGeneric(versionString)
+ return v, err == nil
+}
+
+// mustParseSolrVersion parses a version that the Solr Operator compares Solr
versions against, e.g. "9.7" or "10".
+func mustParseSolrVersion(v string) *version.Version {
+ parsed, ok := ParseSolrVersion(v)
+ if !ok {
+ panic(fmt.Sprintf("invalid Solr version %q", v))
+ }
+ return parsed
+}
+
+// SolrVersionAtLeast returns true if this SolrCloud runs the given Solr
version or later,
+// e.g. SolrVersionAtLeast("10") for Solr 10+.
+// An undeterminable or unsupported version returns false, so it gets the same
code path as the oldest Solr versions.
+// That is safe because the SolrCloud controller does not reconcile such a
cloud.
+func (sc *SolrCloud) SolrVersionAtLeast(v string) bool {
+ current, err := sc.SolrVersion()
+ return err == nil && current.AtLeast(mustParseSolrVersion(v))
+}
+
+// SolrVersionBelow returns true if this SolrCloud runs a Solr version older
than the given one,
+// e.g. SolrVersionBelow("9") for Solr 8, or SolrVersionBelow("9.7") for Solr
9.6 and older.
+// An undeterminable or unsupported version returns true, so it gets the same
code path as the oldest Solr versions.
+// That is safe because the SolrCloud controller does not reconcile such a
cloud.
+func (sc *SolrCloud) SolrVersionBelow(v string) bool {
+ current, err := sc.SolrVersion()
+ return err != nil || current.LessThan(mustParseSolrVersion(v))
+}
+
// UsesHeadlessService returns whether the given solrCloud requires a headless
service to be created for it.
// solrCloud: SolrCloud instance
func (sc *SolrCloud) UsesHeadlessService() bool {
diff --git a/controllers/reconcile_events_test.go
b/controllers/reconcile_events_test.go
index 8655e8e1..12b07680 100644
--- a/controllers/reconcile_events_test.go
+++ b/controllers/reconcile_events_test.go
@@ -24,6 +24,7 @@ import (
solrv1beta1 "github.com/apache/solr-operator/api/v1beta1"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
+ appsv1 "k8s.io/api/apps/v1"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"sigs.k8s.io/controller-runtime/pkg/client"
@@ -165,6 +166,40 @@ var _ = FDescribe("SolrCloud controller - Events", func() {
expectEvent(ctx, solrCloud, corev1.EventTypeWarning,
"InvalidConfigMap")
})
})
+ FContext("on Solr 10 with a provided solr.xml that contains
hostContext", func() {
+ var providedConfigMap *corev1.ConfigMap
+
+ BeforeEach(func() {
+ providedConfigMap = &corev1.ConfigMap{
+ ObjectMeta: metav1.ObjectMeta{
+ Name: "solr9-solrxml-config",
+ Namespace: solrCloud.Namespace,
+ },
+ Data: map[string]string{"solr.xml":
`<solr><solrcloud><str name="hostContext">${hostContext:solr}</str>` +
+ `<int
name="hostPort">${solr.port.advertise:80}</int></solrcloud></solr>`},
+ }
+ solrCloud.Spec.SolrImage =
&solrv1beta1.ContainerImage{Tag: "10.0.0"}
+ solrCloud.Spec.CustomSolrKubeOptions =
solrv1beta1.CustomSolrKubeOptions{
+ ConfigMapOptions: &solrv1beta1.ConfigMapOptions{
+ ProvidedConfigMap:
providedConfigMap.Name,
+ },
+ }
+ })
+
+ FIt("records an InvalidConfigMap event but still reconciles the
SolrCloud", func(ctx context.Context) {
+ By("creating the ConfigMap")
+ Expect(k8sClient.Create(ctx,
providedConfigMap)).To(Succeed())
+
+ By("creating the SolrCloud")
+ Expect(k8sClient.Create(ctx, solrCloud)).To(Succeed())
+
+ By("checking that an InvalidConfigMap event was
recorded")
+ expectEvent(ctx, solrCloud, corev1.EventTypeWarning,
"InvalidConfigMap")
+
+ By("checking that the StatefulSet was still created")
+ expectStatefulSet(ctx, solrCloud,
solrCloud.StatefulSetName())
+ })
+ })
})
var _ = FDescribe("SolrPrometheusExporter controller - Events", func() {
@@ -238,4 +273,80 @@ var _ = FDescribe("SolrPrometheusExporter controller -
Events", func() {
expectEvent(ctx, solrPrometheusExporter,
corev1.EventTypeWarning, "InvalidConfigMap")
})
})
+
+ FContext("with a Solr 10 image", func() {
+ BeforeEach(func() {
+ solrPrometheusExporter.Spec.Image =
&solrv1beta1.ContainerImage{Tag: "10.0.0"}
+ })
+
+ FIt("records an UnsupportedSolrVersion event and creates no
Deployment", func(ctx context.Context) {
+ By("creating the SolrPrometheusExporter")
+ Expect(k8sClient.Create(ctx,
solrPrometheusExporter)).To(Succeed())
+
+ By("checking that an UnsupportedSolrVersion event was
recorded")
+ expectEvent(ctx, solrPrometheusExporter,
corev1.EventTypeWarning, "UnsupportedSolrVersion")
+
+ By("checking that no Deployment or Service was created")
+ expectNoDeployment(ctx, solrPrometheusExporter,
solrPrometheusExporter.MetricsDeploymentName())
+ expectNoService(ctx, solrPrometheusExporter,
solrPrometheusExporter.MetricsServiceName(), "Metrics Service should not exist
for a Solr 10 exporter")
+ })
+ })
+
+ FContext("referencing a SolrCloud that is upgraded to Solr 10", func() {
+ var solrCloud *solrv1beta1.SolrCloud
+
+ BeforeEach(func(ctx context.Context) {
+ solrCloud = &solrv1beta1.SolrCloud{
+ ObjectMeta: metav1.ObjectMeta{Name:
"events-cloud", Namespace: solrPrometheusExporter.Namespace},
+ Spec: solrv1beta1.SolrCloudSpec{
+ SolrImage:
&solrv1beta1.ContainerImage{Tag: "9.10.0"},
+ ZookeeperRef: &solrv1beta1.ZookeeperRef{
+ ConnectionInfo:
&solrv1beta1.ZookeeperConnectionInfo{InternalConnectionString: "host:2181"},
+ },
+ },
+ }
+ Expect(k8sClient.Create(ctx, solrCloud)).To(Succeed())
+ solrPrometheusExporter.Spec.SolrReference =
solrv1beta1.SolrReference{
+ Cloud: &solrv1beta1.SolrCloudReference{Name:
solrCloud.Name},
+ }
+ })
+
+ FIt("keeps the existing Deployment unchanged, marks the
exporter not ready and records an UnsupportedSolrVersion event", func(ctx
context.Context) {
+ By("creating the SolrPrometheusExporter")
+ Expect(k8sClient.Create(ctx,
solrPrometheusExporter)).To(Succeed())
+
+ By("waiting for the Solr 9 Deployment and marking it
ready")
+ deploymentName :=
solrPrometheusExporter.MetricsDeploymentName()
+ // Earlier specs use the same exporter name, so make
sure to update this exporter's Deployment
+ Eventually(func(g Gomega) {
+ deployment := &appsv1.Deployment{}
+ g.Expect(k8sClient.Get(ctx,
resourceKey(solrPrometheusExporter, deploymentName), deployment)).To(Succeed())
+
g.Expect(deployment.OwnerReferences).To(ContainElement(HaveField("UID",
solrPrometheusExporter.UID)))
+
g.Expect(deployment.Spec.Template.Spec.Containers[0].Image).To(HaveSuffix(":9.10.0"))
+ deployment.Status.Replicas = 1
+ deployment.Status.ReadyReplicas = 1
+ g.Expect(k8sClient.Status().Update(ctx,
deployment)).To(Succeed())
+ }).Should(Succeed())
+ expectSolrPrometheusExporterWithChecks(ctx,
solrPrometheusExporter, func(g Gomega, found
*solrv1beta1.SolrPrometheusExporter) {
+ g.Expect(found.Status.Ready).To(BeTrue(), "The
exporter should be ready while its Deployment is ready")
+ })
+
+ By("upgrading the SolrCloud to Solr 10")
+ Eventually(func(g Gomega) {
+ found := &solrv1beta1.SolrCloud{}
+ g.Expect(k8sClient.Get(ctx,
resourceKey(solrCloud, solrCloud.Name), found)).To(Succeed())
+ found.Spec.SolrImage.Tag = "10.0.0"
+ g.Expect(k8sClient.Update(ctx,
found)).To(Succeed())
+ }).Should(Succeed())
+
+ By("checking the event, the exporter status and the
unchanged Deployment")
+ expectEvent(ctx, solrPrometheusExporter,
corev1.EventTypeWarning, "UnsupportedSolrVersion")
+ expectSolrPrometheusExporterWithChecks(ctx,
solrPrometheusExporter, func(g Gomega, found
*solrv1beta1.SolrPrometheusExporter) {
+ g.Expect(found.Status.Ready).To(BeFalse(), "The
exporter should not be ready once its SolrCloud runs Solr 10")
+ })
+ expectDeploymentWithConsistentChecks(ctx,
solrPrometheusExporter, deploymentName, func(g Gomega, found
*appsv1.Deployment) {
+
g.Expect(found.Spec.Template.Spec.Containers[0].Image).To(HaveSuffix(":9.10.0"),
"The existing Deployment should not be updated")
+ })
+ })
+ })
})
diff --git a/controllers/solrcloud_controller.go
b/controllers/solrcloud_controller.go
index 203d6e10..d3b09d02 100644
--- a/controllers/solrcloud_controller.go
+++ b/controllers/solrcloud_controller.go
@@ -117,6 +117,19 @@ func (r *SolrCloudReconciler) Reconcile(ctx
context.Context, req ctrl.Request) (
return reconcile.Result{Requeue: true}, nil
}
+ // Version-specific resources cannot be generated without a supported
Solr major version.
+ // Wait for the user to fix the image tag, which triggers a new
reconcile.
+ if _, versionErr := instance.SolrVersion(); versionErr != nil {
+ if !instance.DeletionTimestamp.IsZero() {
+ // Don't block the deletion of the SolrCloud on its
storage finalizer
+ return r.reconcileStorageFinalizerForDeletion(ctx,
instance, logger)
+ }
+ logger.Error(versionErr, "Not reconciling SolrCloud, its Solr
version is not supported")
+ r.Recorder.Eventf(instance, corev1.EventTypeWarning,
"UnsupportedSolrVersion",
+ "Not reconciling SolrCloud: %s", versionErr.Error())
+ return reconcile.Result{}, nil
+ }
+
// When working with the clouds, some actions outside of kube may need
to be retried after a few seconds
requeueOrNot := reconcile.Result{}
@@ -247,6 +260,15 @@ func (r *SolrCloudReconciler) Reconcile(ctx
context.Context, req ctrl.Request) (
fmt.Errorf("custom solr.xml in
ConfigMap %s must contain a placeholder for either 'solr.port.advertise', or
its deprecated alternative 'hostPort', e.g. <int
name=\"hostPort\">${solr.port.advertise:80}</int>",
providedConfigMapName)
}
+ // Solr 10 refuses to start with some settings
that Solr 9 needs, so warn before the rolling restart reaches them.
+ // This only warns, as a match can be a false
positive, e.g. in an XML comment.
+ if instance.SolrVersionAtLeast("10") {
+ if settings :=
util.SettingsUnsupportedBySolr10(solrXml); len(settings) > 0 {
+ r.Recorder.Eventf(instance,
corev1.EventTypeWarning, "InvalidConfigMap",
+ "Custom solr.xml in
ConfigMap %s contains settings that Solr 10 refuses to start with: %s. "+
+ "Remove them,
see the Solr Operator upgrade notes", providedConfigMapName,
strings.Join(settings, ", "))
+ }
+ }
// stored in the pod spec annotations on the
statefulset so that we get a restart when solr.xml changes
reconcileConfigInfo[util.SolrXmlMd5Annotation]
= fmt.Sprintf("%x", md5.Sum([]byte(solrXml)))
reconcileConfigInfo[util.SolrXmlFile] =
foundConfigMap.Name
@@ -880,7 +902,7 @@ func createCloudStatus(solrCloud *solrv1beta1.SolrCloud,
if len(p.Status.ContainerStatuses) > 0 {
// The first container should always be running solr
nodeStatus.Version =
solrv1beta1.ImageVersion(p.Spec.Containers[0].Image)
- if nodeStatus.Version != solrCloud.Spec.SolrImage.Tag {
+ if nodeStatus.Version !=
solrCloud.Spec.SolrImage.Version() {
otherVersions = append(otherVersions,
nodeStatus.Version)
}
}
@@ -964,11 +986,11 @@ func createCloudStatus(solrCloud *solrv1beta1.SolrCloud,
// If there are multiple versions of solr running, use the first
otherVersion as the current running solr version of the cloud
if len(otherVersions) > 0 {
- newStatus.TargetVersion = solrCloud.Spec.SolrImage.Tag
+ newStatus.TargetVersion = solrCloud.Spec.SolrImage.Version()
newStatus.Version = otherVersions[0]
} else {
newStatus.TargetVersion = ""
- newStatus.Version = solrCloud.Spec.SolrImage.Tag
+ newStatus.Version = solrCloud.Spec.SolrImage.Version()
}
newStatus.InternalCommonAddress = solrCloud.UrlScheme(false) + "://" +
solrCloud.InternalCommonUrl(true)
@@ -1252,6 +1274,29 @@ func (r *SolrCloudReconciler)
reconcileStorageFinalizer(ctx context.Context, clo
return nil
}
+// reconcileStorageFinalizerForDeletion handles the storage finalizer of a
SolrCloud that is being deleted,
+// without reconciling anything else. It is used when the rest of the
SolrCloud cannot be reconciled.
+func (r *SolrCloudReconciler) reconcileStorageFinalizerForDeletion(ctx
context.Context, cloud *solrv1beta1.SolrCloud, logger logr.Logger)
(reconcile.Result, error) {
+ statefulSet := &appsv1.StatefulSet{}
+ if err := r.Get(ctx, types.NamespacedName{Namespace: cloud.Namespace,
Name: cloud.StatefulSetName()}, statefulSet); err != nil {
+ if !errors.IsNotFound(err) {
+ return reconcile.Result{}, err
+ }
+ // The StatefulSet can already be gone, e.g. with foreground
cascading deletion.
+ // Its PVCs still carry the StatefulSet's selector labels, so
use those.
+ statefulSet.Spec.Selector = &metav1.LabelSelector{MatchLabels:
util.SolrCloudSelectorLabels(cloud)}
+ }
+ // Same as in the main reconcile: without the PVC labels, all PVCs
could be deleted
+ if len(statefulSet.Spec.Selector.MatchLabels) == 0 {
+ return reconcile.Result{}, nil
+ }
+ if err := r.reconcileStorageFinalizer(ctx, cloud, statefulSet, logger);
err != nil {
+ logger.Error(err, "Cannot delete PVCs while garbage collecting
after deletion.")
+ return reconcile.Result{RequeueAfter: time.Second * 15}, nil
+ }
+ return reconcile.Result{}, nil
+}
+
func (r *SolrCloudReconciler) getPVCCount(ctx context.Context, cloud
*solrv1beta1.SolrCloud, pvcLabelSelector map[string]string) (int, error) {
pvcList, err := r.getPVCList(ctx, cloud, pvcLabelSelector)
if err != nil {
diff --git a/controllers/solrcloud_controller_basic_auth_test.go
b/controllers/solrcloud_controller_basic_auth_test.go
index 4b049069..c5d337ae 100644
--- a/controllers/solrcloud_controller_basic_auth_test.go
+++ b/controllers/solrcloud_controller_basic_auth_test.go
@@ -290,10 +290,10 @@ func expectBasicAuthConfigOnPodTemplateWithGomega(g
Gomega, solrCloud *solrv1bet
g.Expect(basicAuthSecretVolMount.MountPath).To(Equal("/etc/secrets/"+secretName),
"Wrong path used to mount Basic Auth volume")
expLivenessProbeCmd :=
fmt.Sprintf("JAVA_TOOL_OPTIONS=\"-Dbasicauth=$(cat
/etc/secrets/%s-solrcloud-basic-auth/username):$(cat
/etc/secrets/%s-solrcloud-basic-auth/password)
-Dsolr.httpclient.builder.factory=org.apache.solr.client.solrj.impl.PreemptiveBasicAuthClientBuilderFactory\"
"+
- "solr api -get \"http://${SOLR_HOST}:8983%s\" 2>&1 |
grep -v JAVA_TOOL_OPTIONS",
+ "solr api --solr-url \"http://${SOLR_HOST}:8983%s\"
2>&1 | grep -v JAVA_TOOL_OPTIONS",
solrCloud.Name, solrCloud.Name, expLivenessProbePath)
expReadinessProbeCmd :=
fmt.Sprintf("JAVA_TOOL_OPTIONS=\"-Dbasicauth=$(cat
/etc/secrets/%s-solrcloud-basic-auth/username):$(cat
/etc/secrets/%s-solrcloud-basic-auth/password)
-Dsolr.httpclient.builder.factory=org.apache.solr.client.solrj.impl.PreemptiveBasicAuthClientBuilderFactory\"
"+
- "solr api -get \"http://${SOLR_HOST}:8983%s\" 2>&1 |
grep -v JAVA_TOOL_OPTIONS",
+ "solr api --solr-url \"http://${SOLR_HOST}:8983%s\"
2>&1 | grep -v JAVA_TOOL_OPTIONS",
solrCloud.Name, solrCloud.Name, expReadinessProbePath)
g.Expect(mainContainer.LivenessProbe).To(Not(BeNil()), "main
container should have a liveness probe defined")
diff --git a/controllers/solrcloud_controller_test.go
b/controllers/solrcloud_controller_test.go
index 4177388c..da222376 100644
--- a/controllers/solrcloud_controller_test.go
+++ b/controllers/solrcloud_controller_test.go
@@ -268,7 +268,7 @@ var _ = FDescribe("SolrCloud controller - General", func() {
})
FIt("has the correct resources", func(ctx context.Context) {
By("testing the Solr ConfigMap")
- configMap := expectConfigMap(ctx, solrCloud,
solrCloud.ConfigMapName(), map[string]string{"solr.xml":
util.GenerateSolrXMLString("", []string{}, []string{})})
+ configMap := expectConfigMap(ctx, solrCloud,
solrCloud.ConfigMapName(), map[string]string{"solr.xml":
util.GenerateSolrXMLString("", []string{}, []string{}, false)})
Expect(configMap.Labels).To(Equal(util.MergeLabelsOrAnnotations(solrCloud.SharedLabelsWith(solrCloud.Labels),
testConfigMapLabels)), "Incorrect configMap labels")
Expect(configMap.Annotations).To(Equal(testConfigMapAnnotations), "Incorrect
configMap annotations")
@@ -748,14 +748,14 @@ var _ = FDescribe("SolrCloud controller - General",
func() {
g.Expect(logXmlVolMount).To(Not(BeNil()),
"Didn't find the log4j2-xml Volume mount")
g.Expect(logXmlVolMount.MountPath).To(Equal(expectedMountPath), "log4j2-xml
Volume mount has the wrong path")
-
g.Expect(found.Spec.Template.Annotations).To(HaveKeyWithValue(util.SolrXmlMd5Annotation,
fmt.Sprintf("%x", md5.Sum([]byte(util.GenerateSolrXMLString("", []string{},
[]string{}))))), "Custom solr.xml MD5 annotation should be set on the pod
template.")
+
g.Expect(found.Spec.Template.Annotations).To(HaveKeyWithValue(util.SolrXmlMd5Annotation,
fmt.Sprintf("%x", md5.Sum([]byte(util.GenerateSolrXMLString("", []string{},
[]string{}, false))))), "Custom solr.xml MD5 annotation should be set on the
pod template.")
g.Expect(found.Spec.Template.Annotations).To(HaveKeyWithValue(util.LogXmlMd5Annotation,
fmt.Sprintf("%x", md5.Sum([]byte(configMap.Data[util.LogXmlFile])))), "Custom
log4j2.xml MD5 annotation should be set on the pod template.")
expectedEnvVars :=
map[string]string{"LOG4J_PROPS": fmt.Sprintf("%s/%s", expectedMountPath,
util.LogXmlFile)}
testPodEnvVariablesWithGomega(g,
expectedEnvVars, found.Spec.Template.Spec.Containers[0].Env)
})
- expectConfigMap(ctx, solrCloud,
fmt.Sprintf("%s-solrcloud-configmap", solrCloud.GetName()),
map[string]string{util.SolrXmlFile: util.GenerateSolrXMLString("", []string{},
[]string{})})
+ expectConfigMap(ctx, solrCloud,
fmt.Sprintf("%s-solrcloud-configmap", solrCloud.GetName()),
map[string]string{util.SolrXmlFile: util.GenerateSolrXMLString("", []string{},
[]string{}, false)})
By("updating the user-provided log XML to trigger a pod
rolling restart")
configMap.Data[util.LogXmlFile] =
"<Configuration>Updated!</Configuration>"
diff --git a/controllers/solrcloud_controller_tls_test.go
b/controllers/solrcloud_controller_tls_test.go
index 374f28f7..6b5ce388 100644
--- a/controllers/solrcloud_controller_tls_test.go
+++ b/controllers/solrcloud_controller_tls_test.go
@@ -541,7 +541,7 @@ func expectTLSConfigOnPodTemplateWithGomega(g Gomega,
solrCloud *solrv1beta1.Sol
if solrCloud.Spec.CustomSolrKubeOptions.PodOptions != nil &&
solrCloud.Spec.CustomSolrKubeOptions.PodOptions.LivenessProbe != nil {
path =
solrCloud.Spec.CustomSolrKubeOptions.PodOptions.LivenessProbe.HTTPGet.Path
}
-
g.Expect(mainContainer.LivenessProbe.Exec.Command[2]).To(ContainSubstring(fmt.Sprintf("solr
api -get \"%s://${SOLR_HOST}:%d%s\"", solrCloud.UrlScheme(false),
solrCloud.Spec.SolrAddressability.PodPort, path)), "liveness probe should
invoke solr api -get to contact Solr securely")
+
g.Expect(mainContainer.LivenessProbe.Exec.Command[2]).To(ContainSubstring(fmt.Sprintf("solr
api --solr-url \"%s://${SOLR_HOST}:%d%s\"", solrCloud.UrlScheme(false),
solrCloud.Spec.SolrAddressability.PodPort, path)), "liveness probe should
invoke solr api --solr-url to contact Solr securely")
g.Expect(mainContainer.ReadinessProbe).To(Not(BeNil()), "main
container should have a readiness probe defined")
g.Expect(mainContainer.ReadinessProbe.Exec).To(Not(BeNil()),
"readiness probe should have an exec when mTLS is enabled")
g.Expect(mainContainer.ReadinessProbe.Exec.Command).To(HaveLen(3), "readiness
probe command has wrong number of args")
@@ -549,7 +549,7 @@ func expectTLSConfigOnPodTemplateWithGomega(g Gomega,
solrCloud *solrv1beta1.Sol
if solrCloud.Spec.CustomSolrKubeOptions.PodOptions != nil &&
solrCloud.Spec.CustomSolrKubeOptions.PodOptions.ReadinessProbe != nil {
path =
solrCloud.Spec.CustomSolrKubeOptions.PodOptions.ReadinessProbe.HTTPGet.Path
}
-
g.Expect(mainContainer.ReadinessProbe.Exec.Command[2]).To(ContainSubstring(fmt.Sprintf("solr
api -get \"%s://${SOLR_HOST}:%d%s\"", solrCloud.UrlScheme(false),
solrCloud.Spec.SolrAddressability.PodPort, path)), "readiness probe should
invoke solr api -get to contact Solr securely")
+
g.Expect(mainContainer.ReadinessProbe.Exec.Command[2]).To(ContainSubstring(fmt.Sprintf("solr
api --solr-url \"%s://${SOLR_HOST}:%d%s\"", solrCloud.UrlScheme(false),
solrCloud.Spec.SolrAddressability.PodPort, path)), "readiness probe should
invoke solr api --solr-url to contact Solr securely")
if solrCloud.Spec.CustomSolrKubeOptions.PodOptions != nil &&
solrCloud.Spec.CustomSolrKubeOptions.PodOptions.StartupProbe != nil {
g.Expect(mainContainer.StartupProbe).To(Not(BeNil()),
"main container should have a startup probe defined")
g.Expect(mainContainer.StartupProbe.Exec).To(Not(BeNil()), "startup probe
should have an exec when auth is enabled")
@@ -558,7 +558,7 @@ func expectTLSConfigOnPodTemplateWithGomega(g Gomega,
solrCloud *solrv1beta1.Sol
if solrCloud.Spec.CustomSolrKubeOptions.PodOptions !=
nil && solrCloud.Spec.CustomSolrKubeOptions.PodOptions.StartupProbe != nil {
path =
solrCloud.Spec.CustomSolrKubeOptions.PodOptions.StartupProbe.HTTPGet.Path
}
-
g.Expect(mainContainer.StartupProbe.Exec.Command[2]).To(ContainSubstring(fmt.Sprintf("solr
api -get \"%s://${SOLR_HOST}:%d%s\"", solrCloud.UrlScheme(false),
solrCloud.Spec.SolrAddressability.PodPort, path)), "startup probe should invoke
solr api -get to contact Solr securely")
+
g.Expect(mainContainer.StartupProbe.Exec.Command[2]).To(ContainSubstring(fmt.Sprintf("solr
api --solr-url \"%s://${SOLR_HOST}:%d%s\"", solrCloud.UrlScheme(false),
solrCloud.Spec.SolrAddressability.PodPort, path)), "startup probe should invoke
solr api --solr-url to contact Solr securely")
}
} else if solrCloud != nil {
g.Expect(mainContainer.LivenessProbe).To(Not(BeNil()), "main
container should have a liveness probe defined")
@@ -927,7 +927,7 @@ func expectZkSetupInitContainerForTLSWithGomega(g Gomega,
solrCloud *solrv1beta1
}
}
expChrootCmd := "solr zk ls ${ZK_CHROOT} -z ${ZK_SERVER} || solr zk
mkroot ${ZK_CHROOT} -z ${ZK_SERVER};"
- expCmd := "/opt/solr/server/scripts/cloud-scripts/zkcli.sh -zkhost
${ZK_HOST} -cmd clusterprop -name urlScheme -val https"
+ expCmd := "solr cluster --property urlScheme --value https -z
${ZK_HOST}"
if solrCloud.Spec.SolrTLS != nil {
g.Expect(zkSetupInitContainer).To(Not(BeNil()), "Didn't find
the zk-setup InitContainer in the sts!")
if zkSetupInitContainer != nil {
diff --git a/controllers/solrcloud_controller_version_test.go
b/controllers/solrcloud_controller_version_test.go
new file mode 100644
index 00000000..0c7b8d58
--- /dev/null
+++ b/controllers/solrcloud_controller_version_test.go
@@ -0,0 +1,163 @@
+/*
+ * 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"
+ "fmt"
+ "testing"
+
+ solrv1beta1 "github.com/apache/solr-operator/api/v1beta1"
+ "github.com/go-logr/logr"
+ appsv1 "k8s.io/api/apps/v1"
+ corev1 "k8s.io/api/core/v1"
+ apierrors "k8s.io/apimachinery/pkg/api/errors"
+ "k8s.io/apimachinery/pkg/api/resource"
+ 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"
+ "sigs.k8s.io/controller-runtime/pkg/client/fake"
+
+ "github.com/apache/solr-operator/controllers/util"
+)
+
+// TestReconcileSkipsSolrCloudWithUnknownSolrVersion verifies that a SolrCloud
whose Solr version cannot be
+// determined from its image tag gets an UnsupportedSolrVersion warning and no
child resources.
+func TestReconcileSkipsSolrCloudWithUnknownSolrVersion(t *testing.T) {
+ scheme := runtime.NewScheme()
+ if err := clientgoscheme.AddToScheme(scheme); err != nil {
+ t.Fatal(err)
+ }
+ if err := solrv1beta1.AddToScheme(scheme); err != nil {
+ t.Fatal(err)
+ }
+
+ solrCloud := &solrv1beta1.SolrCloud{
+ ObjectMeta: metav1.ObjectMeta{Name: "foo", Namespace:
"default"},
+ Spec: solrv1beta1.SolrCloudSpec{
+ SolrImage: &solrv1beta1.ContainerImage{Repository:
"my-registry/solr", Tag: "latest"},
+ },
+ }
+ // Store an already-defaulted SolrCloud, so that the reconcile gets
past the defaulting step
+ solrCloud.WithDefaults(logr.Discard())
+
+ fakeClient :=
fake.NewClientBuilder().WithScheme(scheme).WithObjects(solrCloud).Build()
+ rec := record.NewFakeRecorder(8)
+ r := &SolrCloudReconciler{Client: fakeClient, Scheme: scheme, Recorder:
rec}
+
+ result, err := r.Reconcile(context.Background(),
ctrl.Request{NamespacedName: types.NamespacedName{Name: "foo", Namespace:
"default"}})
+ if err != nil {
+ t.Fatalf("expected no error, got %v", err)
+ }
+ if result.Requeue || result.RequeueAfter != 0 {
+ t.Errorf("expected no requeue, got %+v", result)
+ }
+ requireEvent(t, rec, corev1.EventTypeWarning, "UnsupportedSolrVersion")
+ requireNoEvent(t, rec)
+
+ statefulSets := &appsv1.StatefulSetList{}
+ services := &corev1.ServiceList{}
+ configMaps := &corev1.ConfigMapList{}
+ for _, list := range []client.ObjectList{statefulSets, services,
configMaps} {
+ if err = fakeClient.List(context.Background(), list,
client.InNamespace("default")); err != nil {
+ t.Fatal(err)
+ }
+ }
+ if len(statefulSets.Items)+len(services.Items)+len(configMaps.Items) >
0 {
+ t.Errorf("expected no child resources, got %d StatefulSets, %d
Services and %d ConfigMaps",
+ len(statefulSets.Items), len(services.Items),
len(configMaps.Items))
+ }
+}
+
+// TestReconcileDeletesSolrCloudWithUnknownSolrVersion verifies that a
SolrCloud with an unknown Solr major version
+// can still be deleted: its storage finalizer deletes the PVCs and is
removed, instead of blocking the deletion.
+func TestReconcileDeletesSolrCloudWithUnknownSolrVersion(t *testing.T) {
+ // Without a StatefulSet, e.g. with foreground cascading deletion, the
PVCs must still be found and deleted
+ for _, withStatefulSet := range []bool{true, false} {
+ t.Run(fmt.Sprintf("withStatefulSet=%t", withStatefulSet),
func(t *testing.T) {
+ testReconcileDeletesSolrCloudWithUnknownSolrVersion(t,
withStatefulSet)
+ })
+ }
+}
+
+func testReconcileDeletesSolrCloudWithUnknownSolrVersion(t *testing.T,
withStatefulSet bool) {
+ scheme := runtime.NewScheme()
+ if err := clientgoscheme.AddToScheme(scheme); err != nil {
+ t.Fatal(err)
+ }
+ if err := solrv1beta1.AddToScheme(scheme); err != nil {
+ t.Fatal(err)
+ }
+
+ now := metav1.Now()
+ solrCloud := &solrv1beta1.SolrCloud{
+ ObjectMeta: metav1.ObjectMeta{
+ Name: "foo",
+ Namespace: "default",
+ DeletionTimestamp: &now,
+ Finalizers: []string{util.SolrStorageFinalizer},
+ },
+ Spec: solrv1beta1.SolrCloudSpec{
+ SolrImage: &solrv1beta1.ContainerImage{Repository:
"my-registry/solr", Tag: "latest"},
+ StorageOptions: solrv1beta1.SolrDataStorageOptions{
+ PersistentStorage:
&solrv1beta1.SolrPersistentDataStorageOptions{
+ VolumeReclaimPolicy:
solrv1beta1.VolumeReclaimPolicyDelete,
+ PersistentVolumeClaimTemplate:
solrv1beta1.PersistentVolumeClaimTemplate{
+ Spec:
corev1.PersistentVolumeClaimSpec{
+ Resources:
corev1.VolumeResourceRequirements{
+ Requests:
corev1.ResourceList{corev1.ResourceStorage: resource.MustParse("1Gi")},
+ },
+ },
+ },
+ },
+ },
+ },
+ }
+ solrCloud.WithDefaults(logr.Discard())
+
+ selector := util.SolrCloudSelectorLabels(solrCloud)
+ pvc := &corev1.PersistentVolumeClaim{
+ ObjectMeta: metav1.ObjectMeta{Name: "data-foo-solrcloud-0",
Namespace: "default", Labels: selector},
+ }
+ objects := []client.Object{solrCloud, pvc}
+ if withStatefulSet {
+ objects = append(objects, &appsv1.StatefulSet{
+ ObjectMeta: metav1.ObjectMeta{Name:
solrCloud.StatefulSetName(), Namespace: "default"},
+ Spec: appsv1.StatefulSetSpec{Selector:
&metav1.LabelSelector{MatchLabels: selector}},
+ })
+ }
+
+ fakeClient :=
fake.NewClientBuilder().WithScheme(scheme).WithObjects(objects...).Build()
+ rec := record.NewFakeRecorder(8)
+ r := &SolrCloudReconciler{Client: fakeClient, Scheme: scheme, Recorder:
rec}
+
+ if _, err := r.Reconcile(context.Background(),
ctrl.Request{NamespacedName: types.NamespacedName{Name: "foo", Namespace:
"default"}}); err != nil {
+ t.Fatalf("expected no error, got %v", err)
+ }
+ requireNoEvent(t, rec)
+
+ if err := fakeClient.Get(context.Background(),
client.ObjectKeyFromObject(pvc), &corev1.PersistentVolumeClaim{});
!apierrors.IsNotFound(err) {
+ t.Errorf("expected the PVC to be deleted, got %v", err)
+ }
+ if err := fakeClient.Get(context.Background(),
client.ObjectKeyFromObject(solrCloud), &solrv1beta1.SolrCloud{});
!apierrors.IsNotFound(err) {
+ t.Errorf("expected the SolrCloud to be deleted once its
finalizer is removed, got %v", err)
+ }
+}
diff --git a/controllers/solrprometheusexporter_controller.go
b/controllers/solrprometheusexporter_controller.go
index 8094c9ba..56a1b972 100644
--- a/controllers/solrprometheusexporter_controller.go
+++ b/controllers/solrprometheusexporter_controller.go
@@ -92,6 +92,27 @@ func (r *SolrPrometheusExporterReconciler) Reconcile(ctx
context.Context, req ct
requeueOrNot := ctrl.Result{}
+ // Get the ZkConnectionString to connect to
+ solrConnectionInfo := util.SolrConnectionInfo{}
+ var solrCloudImage *solrv1beta1.ContainerImage
+ if solrConnectionInfo, solrCloudImage, err = getSolrConnectionInfo(ctx,
r, prometheusExporter); err != nil {
+ return requeueOrNot, err
+ }
+
+ // Solr 10 removed the Prometheus exporter, and Solr 10's metrics API
only serves the Prometheus format,
+ // so neither a Solr 10+ exporter image nor a referenced Solr 10+
SolrCloud can work.
+ // Don't create or update any resources for such an exporter. An
existing Deployment is left alone, but marked not ready.
+ if msg := unsupportedExporterSolrVersion(prometheusExporter.Spec.Image,
solrCloudImage); msg != "" {
+ logger.Error(nil, msg)
+ r.Recorder.Event(prometheusExporter, corev1.EventTypeWarning,
"UnsupportedSolrVersion", msg)
+ if prometheusExporter.Status.Ready {
+ originalPrometheusExporter :=
prometheusExporter.DeepCopy()
+ prometheusExporter.Status.Ready = false
+ return reconcile.Result{}, r.Status().Patch(ctx,
prometheusExporter, client.MergeFrom(originalPrometheusExporter))
+ }
+ return reconcile.Result{}, nil
+ }
+
configMapKey := util.PrometheusExporterConfigMapKey
configXmlMd5 := ""
if prometheusExporter.Spec.Config == "" &&
prometheusExporter.Spec.CustomKubeOptions.ConfigMapOptions != nil &&
prometheusExporter.Spec.CustomKubeOptions.ConfigMapOptions.ProvidedConfigMap !=
"" {
@@ -180,13 +201,6 @@ func (r *SolrPrometheusExporterReconciler) Reconcile(ctx
context.Context, req ct
return requeueOrNot, err
}
- // Get the ZkConnectionString to connect to
- solrConnectionInfo := util.SolrConnectionInfo{}
- var solrCloudImage *solrv1beta1.ContainerImage
- if solrConnectionInfo, solrCloudImage, err = getSolrConnectionInfo(ctx,
r, prometheusExporter); err != nil {
- return requeueOrNot, err
- }
-
// Make sure the TLS config is in order
var tls *util.TLSCerts = nil
if prometheusExporter.Spec.SolrReference.SolrTLS != nil {
@@ -276,6 +290,27 @@ func (r *SolrPrometheusExporterReconciler) Reconcile(ctx
context.Context, req ct
return requeueOrNot, err
}
+// unsupportedExporterSolrVersion returns why the exporter cannot work with
Solr 10 or later, or "" if it can.
+// exporterImage is the exporter's own image, if set; solrCloudImage is the
image of the referenced SolrCloud, if any,
+// which is also the exporter's image when it doesn't set one.
+// Tags that don't start with a version are allowed, as custom exporter images
don't need to follow Solr's tags.
+func unsupportedExporterSolrVersion(exporterImage *solrv1beta1.ContainerImage,
solrCloudImage *solrv1beta1.ContainerImage) string {
+ const fix = "Delete this SolrPrometheusExporter and scrape the Solr
pods' /solr/admin/metrics endpoint directly instead"
+ if solrCloudImage != nil {
+ if v, ok := solrv1beta1.ParseSolrVersion(solrCloudImage.Tag);
ok && v.Major() >= 10 {
+ return fmt.Sprintf("Not reconciling
SolrPrometheusExporter: the referenced SolrCloud runs Solr %d, "+
+ "which the Prometheus exporter does not
support. %s", v.Major(), fix)
+ }
+ }
+ if exporterImage != nil {
+ if v, ok := solrv1beta1.ParseSolrVersion(exporterImage.Tag); ok
&& v.Major() >= 10 {
+ return fmt.Sprintf("Not reconciling
SolrPrometheusExporter: image %s is Solr %d, "+
+ "but the Prometheus exporter was removed in
Solr 10. %s", exporterImage.ToImageName(), v.Major(), fix)
+ }
+ }
+ return ""
+}
+
// referencedSolrCloud returns the name and namespace of the SolrCloud that
the given
// SolrPrometheusExporter references, or nil if it does not reference a
SolrCloud by name.
// The namespace of the reference is normally filled in by WithDefaults(), but
it is not guaranteed
diff --git a/controllers/solrprometheusexporter_controller_test.go
b/controllers/solrprometheusexporter_controller_test.go
index 25d4f006..71abe0ec 100644
--- a/controllers/solrprometheusexporter_controller_test.go
+++ b/controllers/solrprometheusexporter_controller_test.go
@@ -342,7 +342,7 @@ var _ = FDescribe("SolrPrometheusExporter controller -
General", func() {
},
Spec: solrv1beta1.SolrCloudSpec{
SolrImage: &solrv1beta1.ContainerImage{
- Tag:
"should-be-the-same",
+ Tag:
"9-should-be-the-same",
PullPolicy:
corev1.PullAlways,
ImagePullSecret:
testImagePullSecretName2,
},
@@ -371,7 +371,7 @@ var _ = FDescribe("SolrPrometheusExporter controller -
General", func() {
expectDeploymentWithChecks(ctx, solrPrometheusExporter,
solrPrometheusExporter.MetricsDeploymentName(), func(g Gomega, found
*appsv1.Deployment) {
g.Expect(found.Spec.Template.Spec.Containers[0].Command).To(Equal([]string{util.DefaultPrometheusExporterEntrypoint}),
"Incorrect command for the SolrPrometheusExporter container")
-
g.Expect(found.Spec.Template.Spec.Containers[0].Image).To(Equal(solrv1beta1.DefaultSolrRepo+":should-be-the-same"),
"Incorrect image, should be pulled from the SolrCloud")
+
g.Expect(found.Spec.Template.Spec.Containers[0].Image).To(Equal(solrv1beta1.DefaultSolrRepo+":9-should-be-the-same"),
"Incorrect image, should be pulled from the SolrCloud")
g.Expect(found.Spec.Template.Spec.Containers[0].ImagePullPolicy).To(Equal(corev1.PullAlways),
"Incorrect imagePullPolicy, should be pulled from the SolrCloud")
g.Expect(found.Spec.Template.Spec.ImagePullSecrets).To(ConsistOf(corev1.LocalObjectReference{Name:
testImagePullSecretName2}), "Incorrect imagePullSecrets, should be pulled from
the SolrCloud")
@@ -511,7 +511,7 @@ var _ = FDescribe("SolrPrometheusExporter controller -
General", func() {
},
Spec: solrv1beta1.SolrCloudSpec{
SolrImage: &solrv1beta1.ContainerImage{
- Tag:
"should-be-the-same",
+ Tag:
"9-should-be-the-same",
PullPolicy:
corev1.PullAlways,
ImagePullSecret:
testImagePullSecretName2,
},
diff --git a/controllers/solrprometheusexporter_version_test.go
b/controllers/solrprometheusexporter_version_test.go
new file mode 100644
index 00000000..5ae6c40d
--- /dev/null
+++ b/controllers/solrprometheusexporter_version_test.go
@@ -0,0 +1,56 @@
+/*
+ * 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 (
+ "testing"
+
+ solrv1beta1 "github.com/apache/solr-operator/api/v1beta1"
+)
+
+func TestUnsupportedExporterSolrVersion(t *testing.T) {
+ img := func(tag string) *solrv1beta1.ContainerImage {
+ return &solrv1beta1.ContainerImage{Repository: "solr", Tag: tag}
+ }
+ tests := []struct {
+ name string
+ exporterImage *solrv1beta1.ContainerImage
+ cloudImage *solrv1beta1.ContainerImage
+ wantBlocked bool
+ }{
+ {name: "no images", wantBlocked: false},
+ {name: "Solr 9 image", exporterImage: img("9.10.0"),
wantBlocked: false},
+ {name: "Solr 10 image", exporterImage: img("10.0.0"),
wantBlocked: true},
+ {name: "Solr 10 image with digest", exporterImage:
img("10.0.0@sha256:abc"), wantBlocked: true},
+ {name: "Solr 11 image", exporterImage: img("11.0.0"),
wantBlocked: true},
+ {name: "custom exporter image tag", exporterImage:
img("my-exporter-3"), wantBlocked: false},
+ {name: "inherited Solr 9 cloud image", cloudImage:
img("9.10.0"), wantBlocked: false},
+ {name: "inherited Solr 10 cloud image", cloudImage:
img("10.0.0"), wantBlocked: true},
+ {name: "Solr 9 exporter for a Solr 10 cloud", exporterImage:
img("9.10.0"), cloudImage: img("10.0.0"), wantBlocked: true},
+ {name: "custom exporter image for a Solr 10 cloud",
exporterImage: img("my-exporter-3"), cloudImage: img("10.0.0"), wantBlocked:
true},
+ {name: "Solr 9 exporter for a cloud with a custom tag",
exporterImage: img("9.10.0"), cloudImage: img("latest"), wantBlocked: false},
+ }
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ msg := unsupportedExporterSolrVersion(tt.exporterImage,
tt.cloudImage)
+ if got := msg != ""; got != tt.wantBlocked {
+ t.Errorf("blocked = %v (message %q), want %v",
got, msg, tt.wantBlocked)
+ }
+ })
+ }
+}
diff --git a/controllers/util/prometheus_exporter_util.go
b/controllers/util/prometheus_exporter_util.go
index 3094a761..b1101470 100644
--- a/controllers/util/prometheus_exporter_util.go
+++ b/controllers/util/prometheus_exporter_util.go
@@ -119,8 +119,9 @@ func
GenerateSolrPrometheusExporterDeployment(solrPrometheusExporter *solr.SolrP
if solrConnectionInfo.CloudZkConnnectionInfo != nil {
envVars = append(envVars, corev1.EnvVar{Name: "ZK_HOST", Value:
solrConnectionInfo.CloudZkConnnectionInfo.ZkConnectionString()})
- // Add ACL information, if given, through Env Vars
- if hasACLs, aclEnvs :=
AddACLsToEnv(solrConnectionInfo.CloudZkConnnectionInfo.AllACL,
solrConnectionInfo.CloudZkConnnectionInfo.ReadOnlyACL); hasACLs {
+ // Add ACL information, if given, through Env Vars.
+ // The exporter only runs on Solr 9 and older (Solr 10 removed
it), which still have the VMParams ACL classes.
+ if hasACLs, aclEnvs :=
AddACLsToEnv(solrConnectionInfo.CloudZkConnnectionInfo.AllACL,
solrConnectionInfo.CloudZkConnnectionInfo.ReadOnlyACL, false); hasACLs {
envVars = append(envVars, aclEnvs...)
// The $SOLR_ZK_CREDS_AND_ACLS parameter does not get
picked up when running the Prometheus Exporter, it must be added to the
JAVA_OPTS.
diff --git a/controllers/util/solr_security_util.go
b/controllers/util/solr_security_util.go
index 816d852e..a123253b 100644
--- a/controllers/util/solr_security_util.go
+++ b/controllers/util/solr_security_util.go
@@ -501,10 +501,17 @@ func useSecureProbe(solrCloud *solr.SolrCloud, probe
*corev1.Probe, mountPath st
if solrCloud.Spec.SolrSecurity != nil &&
solrCloud.Spec.SolrSecurity.ProbesRequireAuth &&
solrCloud.Spec.SolrSecurity.AuthenticationType == solr.Basic {
usernameFile := fmt.Sprintf("%s/%s", mountPath,
corev1.BasicAuthUsernameKey)
passwordFile := fmt.Sprintf("%s/%s", mountPath,
corev1.BasicAuthPasswordKey)
- javaToolOptions = append(javaToolOptions,
- fmt.Sprintf("-Dbasicauth=$(cat %s):$(cat %s)",
usernameFile, passwordFile),
-
"-Dsolr.httpclient.builder.factory=org.apache.solr.client.solrj.impl.PreemptiveBasicAuthClientBuilderFactory",
- )
+ if solrCloud.SolrVersionAtLeast("10") {
+ javaToolOptions = append(javaToolOptions,
+
fmt.Sprintf("-Dsolr.security.auth.basicauth.credentials=$(cat %s):$(cat %s)",
usernameFile, passwordFile),
+
"-Dsolr.solrj.http.jetty.customizer=org.apache.solr.client.solrj.jetty.PreemptiveBasicAuthClientCustomizer",
+ )
+ } else {
+ javaToolOptions = append(javaToolOptions,
+ fmt.Sprintf("-Dbasicauth=$(cat %s):$(cat %s)",
usernameFile, passwordFile),
+
"-Dsolr.httpclient.builder.factory=org.apache.solr.client.solrj.impl.PreemptiveBasicAuthClientBuilderFactory",
+ )
+ }
}
// construct the probe command to invoke the SolrCLI "api" action
@@ -520,7 +527,11 @@ func useSecureProbe(solrCloud *solr.SolrCloud, probe
*corev1.Probe, mountPath st
javaToolOptionsOutputFilter = ""
}
- probeCommand := fmt.Sprintf("%ssolr api -get
\"%s://${SOLR_HOST}:%d%s\"%s", javaToolOptionsStr, solrCloud.UrlScheme(false),
probe.HTTPGet.Port.IntVal, probe.HTTPGet.Path, javaToolOptionsOutputFilter)
+ apiUrlFlag := "--solr-url"
+ if solrCloud.SolrVersionBelow("9.7") {
+ apiUrlFlag = "-get"
+ }
+ probeCommand := fmt.Sprintf("%ssolr api %s
\"%s://${SOLR_HOST}:%d%s\"%s", javaToolOptionsStr, apiUrlFlag,
solrCloud.UrlScheme(false), probe.HTTPGet.Port.IntVal, probe.HTTPGet.Path,
javaToolOptionsOutputFilter)
probeCommand =
regexp.MustCompile(`\s+`).ReplaceAllString(strings.TrimSpace(probeCommand), " ")
// use an Exec instead of an HTTP GET
diff --git a/controllers/util/solr_tls_util.go
b/controllers/util/solr_tls_util.go
index 85287577..2109b81a 100644
--- a/controllers/util/solr_tls_util.go
+++ b/controllers/util/solr_tls_util.go
@@ -756,10 +756,15 @@ func mountedTLSPath(dir *solr.MountedTLSDirectory,
fileName string, defaultName
return fmt.Sprintf("%s/%s", dir.Path, fileName)
}
-// Command to set the urlScheme cluster prop to "https"
-func setUrlSchemeClusterPropCmd() string {
- return "/opt/solr/server/scripts/cloud-scripts/zkcli.sh -zkhost
${ZK_HOST} -cmd clusterprop -name urlScheme -val https" +
- "; /opt/solr/server/scripts/cloud-scripts/zkcli.sh -zkhost
${ZK_HOST} -cmd get /clusterprops.json;"
+// Command to set the urlScheme cluster prop to "https".
+// Solr 9.7 added the `solr cluster --property` CLI, and Solr 10 removed
zkcli.sh.
+func setUrlSchemeClusterPropCmd(isBeforeSolr97 bool) string {
+ if isBeforeSolr97 {
+ return "/opt/solr/server/scripts/cloud-scripts/zkcli.sh -zkhost
${ZK_HOST} -cmd clusterprop -name urlScheme -val https" +
+ "; /opt/solr/server/scripts/cloud-scripts/zkcli.sh
-zkhost ${ZK_HOST} -cmd get /clusterprops.json;"
+ }
+ return "solr cluster --property urlScheme --value https -z ${ZK_HOST}" +
+ "; solr zk cp zk:/clusterprops.json /dev/stdout -z ${ZK_HOST};"
}
// Appends additional Java system properties to the JAVA_OPTS environment
variable of the main container and ensures JAVA_OPTS is the last env var
diff --git a/controllers/util/solr_util.go b/controllers/util/solr_util.go
index 498dee2c..6a10308e 100644
--- a/controllers/util/solr_util.go
+++ b/controllers/util/solr_util.go
@@ -19,6 +19,8 @@ package util
import (
"fmt"
+ "regexp"
+ "slices"
"sort"
"strconv"
"strings"
@@ -71,6 +73,7 @@ const (
DistLibs = "/opt/solr/dist"
ContribLibs = "/opt/solr/contrib/%s/lib"
+ ModuleLibs = "/opt/solr/modules/%s/lib"
SysPropLibPlaceholder = "${solr.sharedLib:}"
)
@@ -81,6 +84,13 @@ var (
DefaultSolrZKPrepInitContainerCPU =
resource.NewMilliQuantity(400, resource.DecimalExponent)
)
+// SolrCloudSelectorLabels returns the labels that the SolrCloud's StatefulSet
selects its pods (and PVCs) by.
+func SolrCloudSelectorLabels(solrCloud *solr.SolrCloud) map[string]string {
+ selectorLabels := solrCloud.SharedLabels()
+ selectorLabels["technology"] = solr.SolrTechnologyLabel
+ return selectorLabels
+}
+
// GenerateStatefulSet returns a new appsv1.StatefulSet pointer generated for
the SolrCloud instance
// object: SolrCloud instance
// replicas: the number of replicas for the SolrCloud instance
@@ -104,10 +114,9 @@ func GenerateStatefulSet(solrCloud *solr.SolrCloud,
solrCloudStatus *solr.SolrCl
defaultReadinessProbe := createDefaultProbeHandlerForPath(probeScheme,
solrPodPort, DefaultReadinessProbePath)
labels := solrCloud.SharedLabelsWith(solrCloud.GetLabels())
- selectorLabels := solrCloud.SharedLabels()
+ selectorLabels := SolrCloudSelectorLabels(solrCloud)
labels["technology"] = solr.SolrTechnologyLabel
- selectorLabels["technology"] = solr.SolrTechnologyLabel
annotations := map[string]string{
SolrZKConnectionStringAnnotation:
solrCloudStatus.ZkConnectionString(),
@@ -153,6 +162,7 @@ func GenerateStatefulSet(solrCloud *solr.SolrCloud,
solrCloudStatus *solr.SolrCl
// Keep track of the SolrOpts that the Solr Operator needs to set
// These will be added to the SolrOpts given by the user.
+ // The hostPort sysprop is deprecated in favor of SOLR_PORT_ADVERTISE,
but custom solr.xml files may still use it.
// The "availability_zone" and "spread_domain" system properties are
used by Solr's AffinityPlacementFactory
// to spread replicas across zones, and across Kubernetes nodes within
a zone
allSolrOpts := []string{"-DhostPort=$(SOLR_NODE_PORT)",
"-Davailability_zone=$(SOLR_AVAILABILITY_ZONE)",
"-Dspread_domain=$(SOLR_SPREAD_DOMAIN)"}
@@ -421,6 +431,16 @@ func GenerateStatefulSet(solrCloud *solr.SolrCloud,
solrCloudStatus *solr.SolrCl
},
}
+ // Solr 10+ reads the listen port from SOLR_PORT_LISTEN instead of
SOLR_PORT,
+ // and uses SOLR_HOST_ADVERTISE in place of the deprecated 'host'
sysprop. Older Solr versions ignore them.
+ envVars = append(envVars, corev1.EnvVar{
+ Name: "SOLR_PORT_LISTEN",
+ Value: strconv.Itoa(solrPodPort),
+ }, corev1.EnvVar{
+ Name: "SOLR_HOST_ADVERTISE",
+ Value: solrHostName,
+ })
+
// Add all necessary information for connection to Zookeeper
zkEnvVars, zkSolrOpt, _ := createZkConnectionEnvVars(solrCloud,
solrCloudStatus)
if zkSolrOpt != "" {
@@ -871,6 +891,58 @@ const DefaultSolrXML = `<?xml version="1.0"
encoding="UTF-8" ?>
</solr>
`
+// DefaultSolrXMLForSolr10 is the solr.xml template for Solr 10+.
+// It mirrors Solr 10's stock server/solr/solr.xml, so the two can be diffed
directly. The operator only changes:
+// - sharedLib, which is generated (first placeholder) to add custom library
paths
+// - backup repositories, which are generated (second placeholder)
+//
+// Compared to DefaultSolrXML (Solr 9 and earlier), it drops settings that
Solr 10 rejects (hostContext,
+// genericCoreNodeNames) and the metrics element, which Solr 10's stock
solr.xml doesn't contain either.
+// Solr 10 still supports the metrics element, but leaving it out means
-DmetricsEnabled=false has no effect on Solr 10.
+// It reads the advertised host from "solr.host.advertise" instead of the
deprecated "host" sysprop,
+// and allowPaths from its Solr 10 sysprop "solr.security.allow.paths".
+const DefaultSolrXMLForSolr10 = `<?xml version="1.0" encoding="UTF-8" ?>
+<solr>
+ <int name="maxBooleanClauses">${solr.max.booleanClauses:1024}</int>
+ %s
+ <str name="modules">${solr.modules:}</str>
+ <str name="allowPaths">${solr.security.allow.paths:}</str>
+ <str name="allowUrls">${solr.security.allow.urls:}</str>
+ <str name="hideStackTrace">${solr.hideStackTrace:false}</str>
+ <int name="indexSearcherExecutorThreads">${solr.searchThreads:0}</int>
+ <solrcloud>
+ <str name="host">${solr.host.advertise:}</str>
+ <int name="hostPort">${solr.port.advertise:0}</int>
+ <int name="zkClientTimeout">${zkClientTimeout:30000}</int>
+ <int name="distribUpdateSoTimeout">${distribUpdateSoTimeout:600000}</int>
+ <int
name="distribUpdateConnTimeout">${distribUpdateConnTimeout:60000}</int>
+ <str
name="zkCredentialsProvider">${zkCredentialsProvider:org.apache.solr.common.cloud.DefaultZkCredentialsProvider}</str>
+ <str
name="zkACLProvider">${zkACLProvider:org.apache.solr.common.cloud.DefaultZkACLProvider}</str>
+ <str
name="zkCredentialsInjector">${zkCredentialsInjector:org.apache.solr.common.cloud.DefaultZkCredentialsInjector}</str>
+ <int
name="minStateByteLenForCompression">${minStateByteLenForCompression:-1}</int>
+ <str
name="stateCompressor">${stateCompressor:org.apache.solr.common.util.ZLibCompressor}</str>
+ </solrcloud>
+ <shardHandlerFactory name="shardHandlerFactory"
class="${defaultShardHandlerFactory:HttpShardHandlerFactory}">
+ <int name="socketTimeout">${socketTimeout:600000}</int>
+ <int name="connTimeout">${connTimeout:60000}</int>
+ </shardHandlerFactory>
+ %s
+</solr>
+`
+
+// solr10UnsupportedSolrXmlSettingRegex matches solr.xml settings that Solr 10
refuses to start with, e.g. <str name="hostContext">.
+var solr10UnsupportedSolrXmlSettingRegex =
regexp.MustCompile(`name\s*=\s*["'](hostContext|genericCoreNodeNames)["']`)
+
+// SettingsUnsupportedBySolr10 returns the names of the settings in the given
solr.xml that Solr 10 refuses to start with.
+func SettingsUnsupportedBySolr10(solrXml string) (settings []string) {
+ for _, match := range
solr10UnsupportedSolrXmlSettingRegex.FindAllStringSubmatch(solrXml, -1) {
+ if !slices.Contains(settings, match[1]) {
+ settings = append(settings, match[1])
+ }
+ }
+ return settings
+}
+
// GenerateConfigMap returns a new corev1.ConfigMap pointer generated for the
SolrCloud instance solr.xml
// solrCloud: SolrCloud instance
func GenerateConfigMap(solrCloud *solr.SolrCloud) *corev1.ConfigMap {
@@ -902,25 +974,36 @@ func GenerateSolrXMLStringForCloud(solrCloud
*solr.SolrCloud) string {
backupSection, solrModules, additionalLibs :=
GenerateBackupRepositoriesForSolrXml(solrCloud.Spec.BackupRepositories)
solrModules = append(solrModules, solrCloud.Spec.SolrModules...)
additionalLibs = append(additionalLibs,
solrCloud.Spec.AdditionalLibs...)
- return GenerateSolrXMLString(backupSection, solrModules, additionalLibs)
+ return GenerateSolrXMLString(backupSection, solrModules,
additionalLibs, solrCloud.SolrVersionAtLeast("10"))
}
-func GenerateSolrXMLString(backupSection string, solrModules []string,
additionalLibs []string) string {
- return fmt.Sprintf(DefaultSolrXML,
GenerateAdditionalLibXMLPart(solrModules, additionalLibs), backupSection)
+func GenerateSolrXMLString(backupSection string, solrModules []string,
additionalLibs []string, isSolr10 bool) string {
+ template := DefaultSolrXML
+ if isSolr10 {
+ template = DefaultSolrXMLForSolr10
+ }
+ return fmt.Sprintf(template, GenerateAdditionalLibXMLPart(solrModules,
additionalLibs, isSolr10), backupSection)
}
-func GenerateAdditionalLibXMLPart(solrModules []string, additionalLibs
[]string) string {
+func GenerateAdditionalLibXMLPart(solrModules []string, additionalLibs
[]string, isSolr10 bool) string {
libs := make(map[string]bool, 0)
// Placeholder for users to specify libs via sysprop
libs[SysPropLibPlaceholder] = true
// Add all module library locations
- if len(solrModules) > 0 {
- libs[DistLibs] = true
- }
- for _, module := range solrModules {
- libs[fmt.Sprintf(ContribLibs, module)] = true
+ if isSolr10 {
+ // The contrib and dist directories were removed in Solr 10,
modules only live in the modules directory
+ for _, module := range solrModules {
+ libs[fmt.Sprintf(ModuleLibs, module)] = true
+ }
+ } else {
+ if len(solrModules) > 0 {
+ libs[DistLibs] = true
+ }
+ for _, module := range solrModules {
+ libs[fmt.Sprintf(ContribLibs, module)] = true
+ }
}
// Add all custom library locations
@@ -1304,7 +1387,7 @@ func generateZKInteractionInitContainer(solrCloud
*solr.SolrCloud, solrCloudStat
}
if solrCloud.Spec.SolrTLS != nil {
- cmd += setUrlSchemeClusterPropCmd()
+ cmd +=
setUrlSchemeClusterPropCmd(solrCloud.SolrVersionBelow("9.7"))
}
if security != nil && security.SecurityJson != "" {
@@ -1366,7 +1449,7 @@ func createZkConnectionEnvVars(solrCloud *solr.SolrCloud,
solrCloudStatus *solr.
// Add ACL information, if given, through Env Vars
allACL, readOnlyACL := solrCloud.Spec.ZookeeperRef.GetACLs()
- if hasACLs, aclEnvs := AddACLsToEnv(allACL, readOnlyACL); hasACLs {
+ if hasACLs, aclEnvs := AddACLsToEnv(allACL, readOnlyACL,
solrCloud.SolrVersionAtLeast("10")); hasACLs {
envVars = append(envVars, aclEnvs...)
// The $SOLR_ZK_CREDS_AND_ACLS parameter does not get picked up
when running solr, it must be added to the SOLR_OPTS.
diff --git a/controllers/util/solr_util_test.go
b/controllers/util/solr_util_test.go
index b6d6bb43..1bb067a9 100644
--- a/controllers/util/solr_util_test.go
+++ b/controllers/util/solr_util_test.go
@@ -19,8 +19,12 @@ package util
import (
solr "github.com/apache/solr-operator/api/v1beta1"
+ "github.com/go-logr/logr"
"github.com/stretchr/testify/assert"
corev1 "k8s.io/api/core/v1"
+ "k8s.io/apimachinery/pkg/util/intstr"
+ "strconv"
+ "strings"
"testing"
)
@@ -117,27 +121,27 @@ func
TestGeneratedGcsRepositoryXmlSkipsCredentialIfUnset(t *testing.T) {
func TestGenerateAdditionalLibXMLPart(t *testing.T) {
// No specified libs
- xmlString := GenerateAdditionalLibXMLPart([]string{}, []string{})
+ xmlString := GenerateAdditionalLibXMLPart([]string{}, []string{}, false)
assert.EqualValuesf(t, xmlString, "<str
name=\"sharedLib\">${solr.sharedLib:}</str>", "Wrong sharedLib xml for no
specified libs")
// Just 1 repeated solr module
- xmlString = GenerateAdditionalLibXMLPart([]string{"gcs-repository",
"gcs-repository"}, []string{})
+ xmlString = GenerateAdditionalLibXMLPart([]string{"gcs-repository",
"gcs-repository"}, []string{}, false)
assert.EqualValuesf(t, xmlString, "<str
name=\"sharedLib\">${solr.sharedLib:},/opt/solr/contrib/gcs-repository/lib,/opt/solr/dist</str>",
"Wrong sharedLib xml for just 1 repeated solr module")
// Just 2 different solr modules
- xmlString = GenerateAdditionalLibXMLPart([]string{"gcs-repository",
"analytics"}, []string{})
+ xmlString = GenerateAdditionalLibXMLPart([]string{"gcs-repository",
"analytics"}, []string{}, false)
assert.EqualValuesf(t, xmlString, "<str
name=\"sharedLib\">${solr.sharedLib:},/opt/solr/contrib/analytics/lib,/opt/solr/contrib/gcs-repository/lib,/opt/solr/dist</str>",
"Wrong sharedLib xml for just 2 different solr modules")
// Just 2 repeated libs
- xmlString = GenerateAdditionalLibXMLPart([]string{},
[]string{"/ext/lib", "/ext/lib"})
+ xmlString = GenerateAdditionalLibXMLPart([]string{},
[]string{"/ext/lib", "/ext/lib"}, false)
assert.EqualValuesf(t, xmlString, "<str
name=\"sharedLib\">${solr.sharedLib:},/ext/lib</str>", "Wrong sharedLib xml for
just 1 repeated additional lib")
// Just 2 different libs
- xmlString = GenerateAdditionalLibXMLPart([]string{},
[]string{"/ext/lib2", "/ext/lib1"})
+ xmlString = GenerateAdditionalLibXMLPart([]string{},
[]string{"/ext/lib2", "/ext/lib1"}, false)
assert.EqualValuesf(t, xmlString, "<str
name=\"sharedLib\">${solr.sharedLib:},/ext/lib1,/ext/lib2</str>", "Wrong
sharedLib xml for just 2 different additional libs")
// Combination of everything
- xmlString = GenerateAdditionalLibXMLPart([]string{"gcs-repository",
"analytics", "analytics"}, []string{"/ext/lib2", "/ext/lib2", "/ext/lib1"})
+ xmlString = GenerateAdditionalLibXMLPart([]string{"gcs-repository",
"analytics", "analytics"}, []string{"/ext/lib2", "/ext/lib2", "/ext/lib1"},
false)
assert.EqualValuesf(t, xmlString, "<str
name=\"sharedLib\">${solr.sharedLib:},/ext/lib1,/ext/lib2,/opt/solr/contrib/analytics/lib,/opt/solr/contrib/gcs-repository/lib,/opt/solr/dist</str>",
"Wrong sharedLib xml for mix of additional libs and solr modules")
}
@@ -223,3 +227,394 @@ func TestGenerateSolrXMLStringForCloud(t *testing.T) {
}
assert.Containsf(t, GenerateSolrXMLStringForCloud(solrCloud), "<str
name=\"sharedLib\">${solr.sharedLib:},/ext/lib1,/ext/lib2</str>", "Wrong
sharedLib xml for a cloud with a just additionalLibs")
}
+
+func TestSolrVersion(t *testing.T) {
+ tests := []struct {
+ name string
+ image *solr.ContainerImage
+ want string
+ wantErr bool
+ }{
+ {name: "Solr 8 release", image: &solr.ContainerImage{Tag:
"8.11.4"}, want: "8.11.4"},
+ {name: "Solr 9 release", image: &solr.ContainerImage{Tag:
"9.10.0"}, want: "9.10.0"},
+ {name: "Solr 10 release", image: &solr.ContainerImage{Tag:
"10.0.0"}, want: "10.0.0"},
+ {name: "snapshot", image: &solr.ContainerImage{Tag:
"10.1.0-SNAPSHOT"}, want: "10.1.0"},
+ {name: "custom suffix", image: &solr.ContainerImage{Tag:
"10.2.0-my-company-custom-overlay-9.3"}, want: "10.2.0"},
+ {name: "more than three version parts", image:
&solr.ContainerImage{Tag: "10.0.0.1.2"}, want: "10.0.0.1.2"},
+ {name: "pinned digest", image: &solr.ContainerImage{Tag:
"10.0.0@sha256:0123456789abcdef"}, want: "10.0.0"},
+ {name: "slim variant", image: &solr.ContainerImage{Tag:
"9.10.0-slim"}, want: "9.10.0"},
+ {name: "major only", image: &solr.ContainerImage{Tag: "10"},
want: "10.0"},
+ {name: "major.minor", image: &solr.ContainerImage{Tag: "9.10"},
want: "9.10"},
+ {name: "default tag of operator v0.6 to v0.9", image:
&solr.ContainerImage{Tag: "8.11"}, want: "8.11"},
+ {name: "default tag of operator v0.5", image:
&solr.ContainerImage{Tag: "8.9"}, want: "8.9"},
+ {name: "major with variant", image: &solr.ContainerImage{Tag:
"9-slim"}, want: "9.0"},
+ {name: "trailing dot", image: &solr.ContainerImage{Tag: "10."},
wantErr: true},
+ {name: "dot without number", image: &solr.ContainerImage{Tag:
"10..0"}, wantErr: true},
+ {name: "v prefix", image: &solr.ContainerImage{Tag: "v10.0.0"},
wantErr: true},
+ {name: "latest", image: &solr.ContainerImage{Tag: "latest"},
wantErr: true},
+ {name: "slim", image: &solr.ContainerImage{Tag: "slim"},
wantErr: true},
+ {name: "non-version tag", image: &solr.ContainerImage{Tag:
"my-build-42"}, wantErr: true},
+ {name: "unsupported old major", image:
&solr.ContainerImage{Tag: "7.7.3"}, wantErr: true},
+ {name: "unsupported new major", image:
&solr.ContainerImage{Tag: "11.0.0"}, wantErr: true},
+ {name: "calendar-versioned tag", image:
&solr.ContainerImage{Tag: "2026.10.1"}, wantErr: true},
+ {name: "no tag", image: &solr.ContainerImage{}, wantErr: true},
+ {name: "no image", wantErr: true},
+ }
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ cloud := &solr.SolrCloud{Spec:
solr.SolrCloudSpec{SolrImage: tt.image}}
+ got, err := cloud.SolrVersion()
+ if tt.wantErr {
+ assert.Error(t, err)
+ assert.False(t,
cloud.SolrVersionAtLeast(strconv.Itoa(solr.MinSupportedSolrMajorVersion)), "an
unsupported version is never at least any version")
+ assert.True(t,
cloud.SolrVersionBelow(strconv.Itoa(solr.MinSupportedSolrMajorVersion)), "an
unsupported version is below every version")
+ return
+ }
+ assert.NoError(t, err)
+ assert.Equal(t, tt.want, got.String())
+ major := int(got.Major())
+ assert.Equal(t, major >= 10,
cloud.SolrVersionAtLeast("10"))
+ assert.True(t,
cloud.SolrVersionAtLeast(strconv.Itoa(major)))
+ assert.False(t,
cloud.SolrVersionAtLeast(strconv.Itoa(major+1)))
+ assert.False(t,
cloud.SolrVersionBelow(strconv.Itoa(major)))
+ assert.True(t,
cloud.SolrVersionBelow(strconv.Itoa(major+1)))
+ })
+ }
+}
+
+func TestSolrVersionBelow(t *testing.T) {
+ tests := []struct {
+ tag string
+ below9 bool
+ below9dot7 bool
+ }{
+ {tag: "8.11.4", below9: true, below9dot7: true},
+ {tag: "8.11", below9: true, below9dot7: true},
+ {tag: "9", below9: false, below9dot7: true},
+ {tag: "9-slim", below9: false, below9dot7: true},
+ {tag: "9.6.1", below9: false, below9dot7: true},
+ {tag: "9.7.0", below9: false, below9dot7: false},
+ {tag: "9.7", below9: false, below9dot7: false},
+ {tag: "9.10.0", below9: false, below9dot7: false},
+ {tag: "9.10-slim", below9: false, below9dot7: false},
+ {tag: "10.0.0", below9: false, below9dot7: false},
+ {tag: "10.2.0-my-company-custom-overlay-9.3", below9: false,
below9dot7: false},
+ {tag: "latest", below9: true, below9dot7: true},
+ }
+ for _, tt := range tests {
+ t.Run(tt.tag, func(t *testing.T) {
+ cloud := &solr.SolrCloud{Spec:
solr.SolrCloudSpec{SolrImage: &solr.ContainerImage{Tag: tt.tag}}}
+ assert.Equal(t, tt.below9, cloud.SolrVersionBelow("9"),
`SolrVersionBelow("9")`)
+ assert.Equal(t, tt.below9dot7,
cloud.SolrVersionBelow("9.7"), `SolrVersionBelow("9.7")`)
+ })
+ }
+}
+
+func TestSolrVersionFromDefaultImage(t *testing.T) {
+ cloud := &solr.SolrCloud{}
+ cloud.WithDefaults(logr.Discard())
+ got, err := cloud.SolrVersion()
+ assert.NoError(t, err, "the default Solr image tag must be supported")
+ assert.Equal(t, solr.DefaultSolrVersion, got.String())
+}
+
+func TestGenerateAdditionalLibXMLPartSolr10(t *testing.T) {
+ // Solr 10: modules are loaded from the modules directory, the contrib
and dist directories don't exist anymore
+ xmlString := GenerateAdditionalLibXMLPart([]string{"gcs-repository",
"analytics"}, []string{}, true)
+ assert.EqualValuesf(t, "<str
name=\"sharedLib\">${solr.sharedLib:},/opt/solr/modules/analytics/lib,/opt/solr/modules/gcs-repository/lib</str>",
xmlString, "Wrong sharedLib xml for Solr 10 modules")
+ assert.NotContains(t, xmlString, "/opt/solr/contrib/", "Solr 10 should
not reference the contrib directory")
+ assert.NotContains(t, xmlString, "/opt/solr/dist", "Solr 10 should not
reference the dist directory")
+
+ // Solr 10: custom additional libs should still be included
+ xmlString = GenerateAdditionalLibXMLPart([]string{},
[]string{"/ext/lib1", "/ext/lib2"}, true)
+ assert.EqualValuesf(t, "<str
name=\"sharedLib\">${solr.sharedLib:},/ext/lib1,/ext/lib2</str>", xmlString,
"Solr 10 should still include custom additional libs")
+
+ // Solr 10: combination of modules and custom libs, with a duplicate
module
+ xmlString = GenerateAdditionalLibXMLPart([]string{"ltr", "ltr"},
[]string{"/ext/lib1"}, true)
+ assert.EqualValuesf(t, "<str
name=\"sharedLib\">${solr.sharedLib:},/ext/lib1,/opt/solr/modules/ltr/lib</str>",
xmlString, "Wrong sharedLib xml for Solr 10 modules and custom libs")
+}
+
+func TestGenerateSolrXMLStringForCloudSolr10(t *testing.T) {
+ solrCloud := &solr.SolrCloud{
+ Spec: solr.SolrCloudSpec{
+ SolrImage: &solr.ContainerImage{
+ Repository: "library/solr",
+ Tag: "10.0.0",
+ },
+ SolrModules: []string{"ltr", "analytics"},
+ },
+ }
+ xmlString := GenerateSolrXMLStringForCloud(solrCloud)
+
+ // Should NOT contain Solr 9-specific settings
+ assert.NotContains(t, xmlString, "genericCoreNodeNames", "Solr 10 XML
should not contain genericCoreNodeNames")
+ assert.NotContains(t, xmlString, "hostContext", "Solr 10 XML should not
contain hostContext")
+ assert.Contains(t, xmlString, "${solr.security.allow.paths:}", "Solr 10
XML should read allowPaths from its Solr 10 sysprop")
+ assert.NotContains(t, xmlString, "${solr.allowPaths:}", "Solr 10 XML
should not use the Solr 9 allowPaths sysprop")
+ assert.NotContains(t, xmlString, "metricsEnabled", "Solr 10 XML should
not contain metricsEnabled")
+
+ // Should use the new system property name for host
+ assert.Contains(t, xmlString, "${solr.host.advertise:}", "Solr 10 XML
should use solr.host.advertise sysprop")
+ assert.NotContains(t, xmlString, "${host:}", "Solr 10 XML should not
use deprecated host sysprop")
+
+ // Should still contain valid Solr 10 settings
+ assert.Contains(t, xmlString, "hostPort", "Solr 10 XML should still
contain hostPort")
+ assert.Contains(t, xmlString, "zkClientTimeout", "Solr 10 XML should
still contain zkClientTimeout")
+ assert.Contains(t, xmlString, "zkCredentialsProvider", "Solr 10 XML
should still contain zkCredentialsProvider")
+
+ // Should load modules from the modules directory, not the removed
contrib directory
+ assert.Contains(t, xmlString, "/opt/solr/modules/ltr/lib", "Solr 10 XML
should load modules from the modules directory")
+ assert.NotContains(t, xmlString, "/opt/solr/contrib/", "Solr 10 XML
should not reference contrib directory")
+}
+
+// solr10StockSolrXml is the body of server/solr/solr.xml from the Solr 10.0.0
release (license header and comments removed).
+const solr10StockSolrXml = `<solr>
+ <int name="maxBooleanClauses">${solr.max.booleanClauses:1024}</int>
+ <str name="sharedLib">${solr.sharedLib:}</str>
+ <str name="modules">${solr.modules:}</str>
+ <str name="allowPaths">${solr.security.allow.paths:}</str>
+ <str name="allowUrls">${solr.security.allow.urls:}</str>
+ <str name="hideStackTrace">${solr.hideStackTrace:false}</str>
+ <int name="indexSearcherExecutorThreads">${solr.searchThreads:0}</int>
+ <solrcloud>
+ <str name="host">${solr.host.advertise:}</str>
+ <int name="hostPort">${solr.port.advertise:0}</int>
+ <int name="zkClientTimeout">${zkClientTimeout:30000}</int>
+ <int name="distribUpdateSoTimeout">${distribUpdateSoTimeout:600000}</int>
+ <int
name="distribUpdateConnTimeout">${distribUpdateConnTimeout:60000}</int>
+ <str
name="zkCredentialsProvider">${zkCredentialsProvider:org.apache.solr.common.cloud.DefaultZkCredentialsProvider}</str>
+ <str
name="zkACLProvider">${zkACLProvider:org.apache.solr.common.cloud.DefaultZkACLProvider}</str>
+ <str
name="zkCredentialsInjector">${zkCredentialsInjector:org.apache.solr.common.cloud.DefaultZkCredentialsInjector}</str>
+ <int
name="minStateByteLenForCompression">${minStateByteLenForCompression:-1}</int>
+ <str
name="stateCompressor">${stateCompressor:org.apache.solr.common.util.ZLibCompressor}</str>
+ </solrcloud>
+ <shardHandlerFactory name="shardHandlerFactory"
class="${defaultShardHandlerFactory:HttpShardHandlerFactory}">
+ <int name="socketTimeout">${socketTimeout:600000}</int>
+ <int name="connTimeout">${connTimeout:60000}</int>
+ </shardHandlerFactory>
+</solr>`
+
+// Without extra libraries or backup repositories, the generated Solr 10
solr.xml should be identical to Solr's stock one.
+func TestSolr10SolrXmlMatchesStock(t *testing.T) {
+ normalize := func(xml string) []string {
+ lines := make([]string, 0)
+ for _, line := range strings.Split(xml, "\n") {
+ if line = strings.TrimSpace(line); line != "" &&
!strings.HasPrefix(line, "<?xml") {
+ lines = append(lines, line)
+ }
+ }
+ return lines
+ }
+ generated := GenerateSolrXMLString("", []string{}, []string{}, true)
+ assert.Equal(t, normalize(solr10StockSolrXml), normalize(generated))
+}
+
+func TestGenerateSolrXMLStringForCloudSolr9(t *testing.T) {
+ solrCloud := &solr.SolrCloud{
+ Spec: solr.SolrCloudSpec{
+ SolrImage: &solr.ContainerImage{
+ Repository: "library/solr",
+ Tag: "9.10.0",
+ },
+ SolrModules: []string{"ltr"},
+ },
+ }
+ xmlString := GenerateSolrXMLStringForCloud(solrCloud)
+
+ // Should contain Solr 9-specific settings
+ assert.Contains(t, xmlString, "genericCoreNodeNames", "Solr 9 XML
should contain genericCoreNodeNames")
+ assert.Contains(t, xmlString, "hostContext", "Solr 9 XML should contain
hostContext")
+ assert.Contains(t, xmlString, "<str name=\"host\">", "Solr 9 XML should
contain host setting")
+ assert.Contains(t, xmlString, "allowPaths", "Solr 9 XML should contain
allowPaths")
+
+ // Should contain contrib paths for modules
+ assert.Contains(t, xmlString, "/opt/solr/contrib/ltr/lib", "Solr 9 XML
should reference contrib directory for modules")
+}
+
+func newProbeForTest() *corev1.Probe {
+ return &corev1.Probe{
+ ProbeHandler: corev1.ProbeHandler{
+ HTTPGet: &corev1.HTTPGetAction{
+ Path: "/solr/admin/info/system",
+ Port: intstr.FromInt32(8983),
+ },
+ },
+ }
+}
+
+func TestUseSecureProbeBeforeSolr97(t *testing.T) {
+ solrCloud := &solr.SolrCloud{
+ Spec: solr.SolrCloudSpec{
+ SolrImage: &solr.ContainerImage{Repository:
"library/solr", Tag: "9.6.1"},
+ },
+ }
+ probe := newProbeForTest()
+ useSecureProbe(solrCloud, probe, "/etc/secrets/foo")
+
+ assert.Nil(t, probe.HTTPGet, "HTTPGet should be replaced by Exec")
+ assert.NotNil(t, probe.Exec, "Exec command should be set")
+ cmd := probe.Exec.Command[2]
+ assert.Contains(t, cmd, "solr api -get", "Solr before 9.7 should use
'solr api -get' syntax")
+ assert.Contains(t, cmd, "${SOLR_HOST}", "probe should reference
SOLR_HOST env var")
+ assert.NotContains(t, cmd, "--solr-url", "Solr before 9.7 does not have
the --solr-url flag")
+}
+
+func TestUseSecureProbeFromSolr97(t *testing.T) {
+ for _, tag := range []string{"9.7.0", "9.10.0", "10.0.0"} {
+ solrCloud := &solr.SolrCloud{
+ Spec: solr.SolrCloudSpec{
+ SolrImage: &solr.ContainerImage{Repository:
"library/solr", Tag: tag},
+ },
+ }
+ probe := newProbeForTest()
+ useSecureProbe(solrCloud, probe, "/etc/secrets/foo")
+
+ assert.Nil(t, probe.HTTPGet, "HTTPGet should be replaced by
Exec")
+ assert.NotNil(t, probe.Exec, "Exec command should be set")
+ cmd := probe.Exec.Command[2]
+ assert.Contains(t, cmd, "solr api --solr-url", "Solr %s should
use 'solr api --solr-url' syntax", tag)
+ assert.NotContains(t, cmd, "-get ", "Solr %s should not use the
-get flag, which Solr 10 removed", tag)
+ }
+}
+
+func TestUseSecureProbeWithBasicAuth(t *testing.T) {
+ newCloud := func(tag string) *solr.SolrCloud {
+ return &solr.SolrCloud{
+ Spec: solr.SolrCloudSpec{
+ SolrImage: &solr.ContainerImage{Repository:
"library/solr", Tag: tag},
+ SolrSecurity: &solr.SolrSecurityOptions{
+ AuthenticationType: solr.Basic,
+ ProbesRequireAuth: true,
+ },
+ },
+ }
+ }
+
+ probe := newProbeForTest()
+ useSecureProbe(newCloud("9.10.0"), probe, "/etc/secrets/foo")
+ cmd := probe.Exec.Command[2]
+ assert.Contains(t, cmd, "-Dbasicauth=$(cat
/etc/secrets/foo/username):$(cat /etc/secrets/foo/password)", "Solr 9 should
pass credentials via JAVA_TOOL_OPTIONS")
+ assert.Contains(t, cmd, "PreemptiveBasicAuthClientBuilderFactory",
"Solr 9 should use the Solr 9 client builder factory")
+
+ probe = newProbeForTest()
+ useSecureProbe(newCloud("10.0.0"), probe, "/etc/secrets/foo")
+ cmd = probe.Exec.Command[2]
+ assert.Equal(t,
`JAVA_TOOL_OPTIONS="-Dsolr.security.auth.basicauth.credentials=$(cat
/etc/secrets/foo/username):$(cat /etc/secrets/foo/password) `+
+
`-Dsolr.solrj.http.jetty.customizer=org.apache.solr.client.solrj.jetty.PreemptiveBasicAuthClientCustomizer"
`+
+ `solr api --solr-url
"http://${SOLR_HOST}:8983/solr/admin/info/system" 2>&1 | grep -v
JAVA_TOOL_OPTIONS`, cmd, "Solr 10 should pass credentials via
JAVA_TOOL_OPTIONS")
+ assert.NotContains(t, cmd, "--credentials", "Solr 10 should not pass
credentials as a process argument")
+}
+
+func TestSetUrlSchemeClusterPropCmd(t *testing.T) {
+ // Solr before 9.7 uses zkcli.sh
+ solr96Cmd := setUrlSchemeClusterPropCmd(true)
+ assert.Contains(t, solr96Cmd, "zkcli.sh", "Solr before 9.7 should call
zkcli.sh")
+ assert.Contains(t, solr96Cmd, "clusterprop", "Solr before 9.7 should
use the clusterprop subcommand")
+
+ // Solr 9.7+ uses `solr cluster --property`
+ solr97Cmd := setUrlSchemeClusterPropCmd(false)
+ assert.NotContains(t, solr97Cmd, "zkcli.sh", "Solr 10 removed zkcli.sh")
+ assert.Contains(t, solr97Cmd, "solr cluster --property urlScheme
--value https", "Solr 9.7+ should set the cluster property via the `solr
cluster` CLI")
+}
+
+func newSolrCloudForTest(tag string, modules []string) *solr.SolrCloud {
+ cloud := &solr.SolrCloud{
+ Spec: solr.SolrCloudSpec{
+ SolrImage: &solr.ContainerImage{Repository:
"library/solr", Tag: tag},
+ SolrModules: modules,
+ },
+ }
+ cloud.WithDefaults(logr.Discard())
+ return cloud
+}
+
+func solrNodeContainerEnv(t *testing.T, cloud *solr.SolrCloud) []corev1.EnvVar
{
+ t.Helper()
+ status := &solr.SolrCloudStatus{
+ ZookeeperConnectionInfo: solr.ZookeeperConnectionInfo{
+ InternalConnectionString: "zk:2181",
+ ChRoot: "/solr",
+ },
+ }
+ ss := GenerateStatefulSet(cloud, status, map[string]string{},
map[string]string{}, nil, nil)
+ for _, c := range ss.Spec.Template.Spec.Containers {
+ if c.Name == SolrNodeContainer {
+ return c.Env
+ }
+ }
+ t.Fatalf("solr node container not found in generated StatefulSet")
+ return nil
+}
+
+func envValue(env []corev1.EnvVar, name string) (string, bool) {
+ for _, e := range env {
+ if e.Name == name {
+ return e.Value, true
+ }
+ }
+ return "", false
+}
+
+func TestGenerateStatefulSetSolr10EnvVars(t *testing.T) {
+ cloud := newSolrCloudForTest("10.0.0", []string{"ltr", "analytics"})
+ env := solrNodeContainerEnv(t, cloud)
+
+ advertise, ok := envValue(env, "SOLR_HOST_ADVERTISE")
+ assert.True(t, ok, "Solr 10 pod should have SOLR_HOST_ADVERTISE set")
+ assert.NotEmpty(t, advertise, "SOLR_HOST_ADVERTISE should not be empty")
+
+ _, ok = envValue(env, "SOLR_MODULES")
+ assert.False(t, ok, "SOLR_MODULES should not be set, modules are loaded
via sharedLib")
+
+ solrOpts, _ := envValue(env, "SOLR_OPTS")
+ assert.Contains(t, solrOpts, "-DhostPort=", "Solr 10 should still set
the hostPort sysprop for custom solr.xml files")
+}
+
+func TestGenerateStatefulSetListenPort(t *testing.T) {
+ for _, tag := range []string{"8.11.0", "9.10.0", "10.0.0"} {
+ cloud := newSolrCloudForTest(tag, nil)
+ cloud.Spec.SolrAddressability.PodPort = 8080
+ env := solrNodeContainerEnv(t, cloud)
+
+ port, _ := envValue(env, "SOLR_PORT")
+ assert.Equal(t, "8080", port, "SOLR_PORT should be the pod port
for Solr %s", tag)
+
+ listenPort, _ := envValue(env, "SOLR_PORT_LISTEN")
+ assert.Equal(t, "8080", listenPort, "SOLR_PORT_LISTEN should be
the pod port for Solr %s", tag)
+ }
+}
+
+func TestGenerateStatefulSetSolr9EnvVars(t *testing.T) {
+ cloud := newSolrCloudForTest("9.10.0", []string{"ltr"})
+ env := solrNodeContainerEnv(t, cloud)
+
+ advertise, ok := envValue(env, "SOLR_HOST_ADVERTISE")
+ assert.True(t, ok, "Solr 9 pod should have SOLR_HOST_ADVERTISE set")
+ assert.NotEmpty(t, advertise, "SOLR_HOST_ADVERTISE should not be empty")
+
+ _, ok = envValue(env, "SOLR_MODULES")
+ assert.False(t, ok, "SOLR_MODULES should not be set, modules are loaded
via sharedLib")
+
+ solrOpts, ok := envValue(env, "SOLR_OPTS")
+ assert.True(t, ok, "Solr 9 pod should have SOLR_OPTS set")
+ assert.True(t, strings.Contains(solrOpts, "-DhostPort="), "Solr 9
should set the hostPort sysprop")
+}
+
+func TestImageVersion(t *testing.T) {
+ assert.Equal(t, "10.0.0", solr.ImageVersion("library/solr:10.0.0"))
+ assert.Equal(t, "10.0.0",
solr.ImageVersion("library/solr:10.0.0@sha256:0123456789abcdef"), "a digest
should be ignored")
+ assert.Equal(t, "10.0.0",
solr.ImageVersion("my-registry:5000/solr:10.0.0"))
+ assert.Equal(t, "", solr.ImageVersion("library/solr"))
+
+ // The version of the SolrCloud's image must match the version of its
pods' images, also for pinned digests
+ image := &solr.ContainerImage{Repository: "library/solr", Tag:
"10.0.0@sha256:0123456789abcdef"}
+ assert.Equal(t, "10.0.0", image.Version())
+ assert.Equal(t, solr.ImageVersion(image.ToImageName()), image.Version())
+}
+
+func TestSettingsUnsupportedBySolr10(t *testing.T) {
+ assert.Empty(t, SettingsUnsupportedBySolr10(DefaultSolrXMLForSolr10),
"the operator's Solr 10 solr.xml must be accepted")
+ assert.Equal(t, []string{"hostContext", "genericCoreNodeNames"},
SettingsUnsupportedBySolr10(DefaultSolrXML),
+ "the operator's Solr 9 solr.xml contains both settings")
+ assert.Equal(t, []string{"hostContext"},
SettingsUnsupportedBySolr10(`<str name='hostContext'>solr</str><str name =
"hostContext">x</str>`))
+}
diff --git a/controllers/util/zk_util.go b/controllers/util/zk_util.go
index 0fcae5dc..7680ee21 100644
--- a/controllers/util/zk_util.go
+++ b/controllers/util/zk_util.go
@@ -399,7 +399,10 @@ func CopyZookeeperClusterFields(from, to
*zkApi.ZookeeperCluster, logger logr.Lo
// AddACLsToEnv creates the neccessary environment variables for using ZK
ACLs, and returns whether ACLs were provided.
// info: Zookeeper Connection Information
-func AddACLsToEnv(allACL *solrv1beta1.ZookeeperACL, readOnlyACL
*solrv1beta1.ZookeeperACL) (hasACLs bool, envVars []corev1.EnvVar) {
+// useCredentialsInjector selects DigestZkACLProvider,
DigestZkCredentialsProvider and VMParamsZkCredentialsInjector,
+// which read the same zkDigest* system properties. It must be set for Solr
10.1+, which removed
+// VMParamsAllAndReadonlyDigestZkACLProvider (SOLR-18122). The replacements
exist since Solr 9.1.
+func AddACLsToEnv(allACL *solrv1beta1.ZookeeperACL, readOnlyACL
*solrv1beta1.ZookeeperACL, useCredentialsInjector bool) (hasACLs bool, envVars
[]corev1.EnvVar) {
if allACL == nil && readOnlyACL == nil {
return false, envVars
}
@@ -465,8 +468,18 @@ func AddACLsToEnv(allACL *solrv1beta1.ZookeeperACL,
readOnlyACL *solrv1beta1.Zoo
envVars = append(envVars,
corev1.EnvVar{
Name: "SOLR_ZK_CREDS_AND_ACLS",
- Value:
"-DzkACLProvider=org.apache.solr.common.cloud.VMParamsAllAndReadonlyDigestZkACLProvider
-DzkCredentialsProvider=org.apache.solr.common.cloud.VMParamsSingleSetCredentialsDigestZkCredentialsProvider
" + strings.Join(zkDigests, " "),
+ Value: zkACLProviderOpts(useCredentialsInjector) + " "
+ strings.Join(zkDigests, " "),
})
return true, envVars
}
+
+func zkACLProviderOpts(useCredentialsInjector bool) string {
+ if useCredentialsInjector {
+ return
"-DzkACLProvider=org.apache.solr.common.cloud.DigestZkACLProvider" +
+ "
-DzkCredentialsProvider=org.apache.solr.common.cloud.DigestZkCredentialsProvider"
+
+ "
-DzkCredentialsInjector=org.apache.solr.common.cloud.VMParamsZkCredentialsInjector"
+ }
+ return
"-DzkACLProvider=org.apache.solr.common.cloud.VMParamsAllAndReadonlyDigestZkACLProvider"
+
+ "
-DzkCredentialsProvider=org.apache.solr.common.cloud.VMParamsSingleSetCredentialsDigestZkCredentialsProvider"
+}
diff --git a/controllers/util/zk_util_test.go b/controllers/util/zk_util_test.go
index 96876d15..4c7dd5f3 100644
--- a/controllers/util/zk_util_test.go
+++ b/controllers/util/zk_util_test.go
@@ -23,6 +23,7 @@ import (
"github.com/stretchr/testify/assert"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
+ "strings"
"testing"
)
@@ -58,3 +59,35 @@ func TestDefaultStorageOptions(t *testing.T) {
assert.Equal(t, "ephemeral", zkCluster.Spec.StorageType, "By default
when Solr is using ephemeral storage, zk should as well. Wrong storageType")
assert.Nil(t, zkCluster.Spec.Persistence, "By default when Solr is
using ephemeral storage, zk should as well. Therefore 'persistence' should be
nil")
}
+
+func TestZkACLProviderBySolrVersion(t *testing.T) {
+ acl := &solrv1beta1.ZookeeperACL{SecretRef: "acl-secret", UsernameKey:
"user", PasswordKey: "pass"}
+ tests := []struct {
+ tag string
+ wantPrefix string
+ }{
+ {tag: "9.11.0", wantPrefix:
"-DzkACLProvider=org.apache.solr.common.cloud.VMParamsAllAndReadonlyDigestZkACLProvider
-DzkCredentialsProvider=org.apache.solr.common.cloud.VMParamsSingleSetCredentialsDigestZkCredentialsProvider
-DzkDigestUsername="},
+ // Solr 10.1 removed VMParamsAllAndReadonlyDigestZkACLProvider
(SOLR-18122), and fails to start if zkACLProvider names a missing class
+ {tag: "10.0.0", wantPrefix:
"-DzkACLProvider=org.apache.solr.common.cloud.DigestZkACLProvider
-DzkCredentialsProvider=org.apache.solr.common.cloud.DigestZkCredentialsProvider
-DzkCredentialsInjector=org.apache.solr.common.cloud.VMParamsZkCredentialsInjector
-DzkDigestUsername="},
+ {tag: "10.1.0", wantPrefix:
"-DzkACLProvider=org.apache.solr.common.cloud.DigestZkACLProvider
-DzkCredentialsProvider=org.apache.solr.common.cloud.DigestZkCredentialsProvider
-DzkCredentialsInjector=org.apache.solr.common.cloud.VMParamsZkCredentialsInjector
-DzkDigestUsername="},
+ }
+ for _, tt := range tests {
+ t.Run(tt.tag, func(t *testing.T) {
+ solrCloud := &solrv1beta1.SolrCloud{Spec:
solrv1beta1.SolrCloudSpec{
+ SolrImage: &solrv1beta1.ContainerImage{Tag:
tt.tag},
+ ZookeeperRef:
&solrv1beta1.ZookeeperRef{ConnectionInfo:
&solrv1beta1.ZookeeperConnectionInfo{AllACL: acl, ReadOnlyACL: acl}},
+ }}
+ status :=
&solrv1beta1.SolrCloudStatus{ZookeeperConnectionInfo:
solrv1beta1.ZookeeperConnectionInfo{InternalConnectionString: "zk:2181",
ChRoot: "/"}}
+ envVars, solrOpts, _ :=
createZkConnectionEnvVars(solrCloud, status)
+ assert.Contains(t, solrOpts,
"$(SOLR_ZK_CREDS_AND_ACLS)")
+ var credsAndAcls string
+ for _, e := range envVars {
+ if e.Name == "SOLR_ZK_CREDS_AND_ACLS" {
+ credsAndAcls = e.Value
+ }
+ }
+ assert.True(t, strings.HasPrefix(credsAndAcls,
tt.wantPrefix), "Unexpected SOLR_ZK_CREDS_AND_ACLS for Solr %s: %s", tt.tag,
credsAndAcls)
+ assert.Contains(t, credsAndAcls,
"-DzkDigestReadonlyPassword=$(ZK_READ_ACL_PASSWORD)")
+ })
+ }
+}
diff --git a/docs/modules/solr-cloud/pages/custom-solr-config.adoc
b/docs/modules/solr-cloud/pages/custom-solr-config.adoc
index 9d3151c8..9fd6ffa0 100644
--- a/docs/modules/solr-cloud/pages/custom-solr-config.adoc
+++ b/docs/modules/solr-cloud/pages/custom-solr-config.adoc
@@ -106,6 +106,10 @@ spec:
NOTE: If you set `providedConfigMap`, then the ConfigMap must include the
`solr.xml` or `log4j2.xml` key, otherwise the SolrCloud will fail to reconcile.
+NOTE: The format of `solr.xml` differs between Solr major versions, e.g. Solr
9 requires `hostContext` and Solr 10 refuses to start with it.
+When upgrading a SolrCloud to a new Solr major version, create a new ConfigMap
with a `solr.xml` for that version, and change `spec.solrImage.tag` and
`providedConfigMap` in the same update.
+The `solr.xml` that ships with the new Solr version (`server/solr/solr.xml`)
is a good starting point.
+
[#solr-xml-managed-elements]
=== Elements the operator normally generates for you
diff --git a/docs/modules/solr-cloud/pages/index.adoc
b/docs/modules/solr-cloud/pages/index.adoc
index c36bf55c..4ec3737d 100644
--- a/docs/modules/solr-cloud/pages/index.adoc
+++ b/docs/modules/solr-cloud/pages/index.adoc
@@ -119,6 +119,19 @@ Also note that certain features available within the Solr
Operator are only supp
The version compatibility matrix shows the minimum Solr version supported for
*most* options.
Please refer to the Solr Reference guide to see what features are enabled for
the Solr version you are running.
+=== Solr Image Tags
+
+Some behavior of the Solr Operator depends on the Solr major version, e.g. the
`solr.xml` it generates and the `bin/solr` commands it runs.
+The operator reads the version from `spec.solrImage.tag`, so the tag must
start with the Solr version, e.g. `10.0.0`, `9.10`, `8.11` or `10`.
+Anything after the version must start with neither a digit nor a dot, e.g.
`9.10.0-slim`, `10.1.0-SNAPSHOT`, `10.0.0-my-custom-build` or
`10.0.0@sha256:...`.
+
+Tags without a version, such as `latest` or `slim`, are not accepted, because
the Solr version behind them can change without the SolrCloud changing.
+To pin an image by its digest, keep the version in the tag, e.g. `tag:
10.0.0@sha256:<digest>`.
+If you build your own images, tag them with the Solr version they are based
on, e.g. `10.0.0-2026.10.1` instead of `2026.10.1`.
+
+The operator does not reconcile a SolrCloud whose tag does not follow this
format, or whose Solr major version it does not support (see the
xref:upgrade-notes:upgrade-notes.adoc#solr-versions[Version Compatibility
Matrix]).
+It emits an `UnsupportedSolrVersion` Warning event instead.
+
=== Build Your Own Private Solr Images
The Solr Operator supports private Docker repo access for Solr images you may
want to store in a private Docker repo. It is recommended to source your image
from the official Solr images.
diff --git a/docs/modules/solr-prometheus-exporter/pages/index.adoc
b/docs/modules/solr-prometheus-exporter/pages/index.adoc
index d0690bc5..fa92ee25 100644
--- a/docs/modules/solr-prometheus-exporter/pages/index.adoc
+++ b/docs/modules/solr-prometheus-exporter/pages/index.adoc
@@ -17,6 +17,9 @@
// under the License.
Solr metrics can be collected from solr clouds/standalone solr both residing
within the kubernetes cluster and outside.
+
+NOTE: The Prometheus exporter was removed from Solr in Solr 10, so a
`SolrPrometheusExporter` only works with Solr 9 and earlier images.
+Solr 10 nodes expose their metrics in Prometheus format at
`/solr/admin/metrics`, which Prometheus can scrape directly.
To use the Prometheus exporter, the easiest thing to do is just provide a
reference to a Solr instance. That can be any of the following:
* The name and namespace of the Solr Cloud CRD
diff --git a/docs/modules/upgrade-notes/pages/upgrade-notes.adoc
b/docs/modules/upgrade-notes/pages/upgrade-notes.adoc
index 0a7bf3e6..0f1fa777 100644
--- a/docs/modules/upgrade-notes/pages/upgrade-notes.adoc
+++ b/docs/modules/upgrade-notes/pages/upgrade-notes.adoc
@@ -45,25 +45,26 @@ If you want to skip versions when upgrading, be sure to
check out the <<upgradin
=== Solr Versions
-[cols="^,^,^,^,^,^",options="header"]
+[cols="^,^,^,^,^,^,^",options="header"]
|===
-| Solr Operator Version | `7.7` | `8.0` - `8.10` | `8.11` | `9.0` - `9.3` |
`9.4`+
-
-| `v0.2.7` | YES | YES | YES | NO | NO
-| `v0.2.8` | YES | YES | YES | NO | NO
-| `v0.3.x` | YES | YES | YES | NO | NO
-| `v0.4.x` | YES | YES | YES | NO | NO
-| `v0.5.x` | YES | YES | YES | NO | NO
-| `v0.6.x` | YES | YES | YES | YES ^1^ | YES ^1^
-| `v0.7.x` | YES | YES | YES | YES ^1^ | YES ^1^
-| `v0.8.x` | NO | NO | YES | YES ^1^ | YES
-| `v0.9.x` | NO | NO | YES | YES ^1^ | YES
-| `v0.10.x` | NO | NO | YES | YES ^1^ | YES
+| Solr Operator Version | `7.7` | `8.0` - `8.10` | `8.11` | `9.0` - `9.3` |
`9.4`+ | `10.0`+
+
+| `v0.2.7` | YES | YES | YES | NO | NO | NO
+| `v0.2.8` | YES | YES | YES | NO | NO | NO
+| `v0.3.x` | YES | YES | YES | NO | NO | NO
+| `v0.4.x` | YES | YES | YES | NO | NO | NO
+| `v0.5.x` | YES | YES | YES | NO | NO | NO
+| `v0.6.x` | YES | YES | YES | YES ^1^ | YES ^1^ | NO
+| `v0.7.x` | YES | YES | YES | YES ^1^ | YES ^1^ | NO
+| `v0.8.x` | NO | NO | YES | YES ^1^ | YES | NO
+| `v0.9.x` | NO | NO | YES | YES ^1^ | YES | NO
+| `v0.10.x` | NO | NO | YES | YES ^1^ | YES | YES ^2^
|===
*Exceptions*
* ^1^ `SolrTLS` and `SolrClientTLS` are not supported
+* ^2^ The `SolrPrometheusExporter` is not supported, because `solr-exporter`
was removed in Solr 10
Please note that this represents basic compatibility with the Solr Operator.
There may be options and features that require newer versions of Solr.
@@ -136,6 +137,49 @@ _Note that the Helm chart version does not contain a `v`
prefix, which the downl
=== v0.10.0
+* *Solr 10 support, and Solr image tags must start with the Solr version*
++
+The Solr Operator now supports Solr 10.
+Solr 10 needs a different `solr.xml`, different env vars and different
`bin/solr` commands than Solr 9, so the operator reads the Solr version from
`spec.solrImage.tag`.
+The tag must therefore start with the Solr version, e.g. `9.10.0`, `10.0.0`,
`9.10`, `8.11`, `10`, `9.10.0-slim`, `10.0.0-my-custom-build` or
`10.0.0@sha256:<digest>`.
+Tags without a version, such as `latest` or `slim`, and custom tags that don't
start with the Solr version, are not accepted.
+The operator does not reconcile a SolrCloud with such a tag, or with an
unsupported Solr major version; it emits an `UnsupportedSolrVersion` Warning
event instead.
+*Before upgrading the operator*, check the image tags of your SolrClouds
(including the `image.tag` value of the `solr` Helm chart) and change them
where needed.
+SolrClouds that never set a tag got the operator's default tag at the time
they were created (e.g. `8.11`), which is accepted.
+Upgrading the operator restarts the pods of every SolrCloud, including the
ones that stay on Solr 8.11 or 9.x.
+The Solr 10 specific changes are gated on the Solr major version and do not
affect them, but other changes in this release do alter the pod template of
every SolrCloud: the new `solr.apache.org/storageMinimumSize` annotation, the
removal of the `postStart` lifecycle hook, and the new `SOLR_TOOL_OPTS`
environment variable on the ZooKeeper setup initContainer.
+This is a managed rolling restart that takes the cluster operation lock and
respects `maxPodsUnavailable`, so it behaves like any other rolling restart,
but plan for it.
+Changing a tag, e.g. from `latest` to `9.10.0`, changes the pod template and
therefore restarts all Solr pods, even if the new tag points to the same image.
+If you pass `-Dsolr.allowPaths=...` via `solrOpts`, use
`-Dsolr.security.allow.paths=...` when moving to Solr 10, which doesn't read
the old camelCase name anymore.
+Alternatively, set the paths via an environment variable in
`spec.customSolrKubeOptions.podOptions.envVars`: `SOLR_ALLOW_PATHS` on Solr
9.6+, and `SOLR_SECURITY_ALLOW_PATHS` on Solr 10.
+Solr 10 still reads `SOLR_ALLOW_PATHS`, but logs a deprecation warning for it.
+Solr 10 can't open indexes that were created with Solr 8, as Lucene only reads
indexes created by the previous major version, so check Solr's own upgrade
notes before upgrading a SolrCloud that started on Solr 8.
+
+* *Solr 10: custom `solr.xml` files need to be updated*
++
+If you provide your own `solr.xml` (via
`spec.customSolrKubeOptions.configMapOptions.providedConfigMap`), it needs to
change together with the Solr version.
+Solr 10 refuses to start with settings it no longer supports, such as
`hostContext` and `genericCoreNodeNames`, while Solr 9 requires `hostContext`,
so no single `solr.xml` works for both.
+Create a new ConfigMap with a Solr 10 `solr.xml`, and change
`spec.solrImage.tag` and `providedConfigMap` in the same update of the
SolrCloud.
+The operator emits an `InvalidConfigMap` Warning event if the custom
`solr.xml` of a Solr 10 SolrCloud still contains `hostContext` or
`genericCoreNodeNames`, but it doesn't stop the rolling restart.
+The easiest way is to start from the `solr.xml` that ships with Solr 10
(`server/solr/solr.xml`) and re-apply your changes; use
`${solr.host.advertise:}` for the `host` setting.
+
+* *Solr 10: custom `log4j2.xml` files need to be updated*
++
+Solr 10 renamed the `solr.log.dir` system property to `solr.logs.dir`.
+If you provide your own `log4j2.xml` (via
`spec.customSolrKubeOptions.configMapOptions.providedConfigMap`), any appender
referring to `${sys:solr.log.dir}` stops working on Solr 10.
+Log4j cannot resolve the old property, so every appender using it fails to
initialise and Solr starts with console logging only, writing no log files at
all.
+Solr still starts and still logs to stdout, which makes this easy to miss.
+Use `${sys:solr.logs.dir}`, or `${env:SOLR_LOGS_DIR}`, which the Solr
container image sets on both Solr 9 and Solr 10 and therefore needs no change
when upgrading.
+
+* *The `SolrPrometheusExporter` does not support Solr 10*
++
+`solr-exporter` was removed from the Solr distribution in Solr 10, so Solr 10
images don't contain `/opt/solr/prometheus-exporter` anymore.
+A `SolrPrometheusExporter` with a Solr 10 image cannot start, and one with an
older image cannot read the metrics of Solr 10, which only serves them in
Prometheus format.
+The operator does not create or update the resources of a
`SolrPrometheusExporter` that uses a Solr 10 image or refers to a Solr 10
SolrCloud; it emits an `UnsupportedSolrVersion` Warning event and sets its
status to not ready instead.
+An existing exporter Deployment keeps running when its SolrCloud is upgraded
to Solr 10, but it no longer reports Solr's metrics.
+Delete any `SolrPrometheusExporter` for a SolrCloud before upgrading that
SolrCloud to Solr 10.
+Instead, each Solr 10 node exposes its metrics in Prometheus format at
`/solr/admin/metrics`, so Prometheus can scrape the Solr pods directly (see
https://github.com/apache/solr-operator/issues/820[#820]).
+
* The default Solr version has been upgraded from `8.11` to `9.11.0`.
This only affects newly created resources, since the operator writes the
resolved Solr version into the resource's spec on the first reconcile, so an
operator upgrade never changes the Solr version of a running cluster.
Note that a Solr `>=9.10` node refuses to start if its `major.minor` version
is lower than the highest version already running in the same Solr cluster, so
a rolling downgrade of Solr requires setting the `SOLR_CLOUD_DOWNGRADE_ENABLED`
envVar to `true` on the pods.
diff --git a/helm/solr-operator/Chart.yaml b/helm/solr-operator/Chart.yaml
index abecbbe3..d620dac5 100644
--- a/helm/solr-operator/Chart.yaml
+++ b/helm/solr-operator/Chart.yaml
@@ -191,6 +191,25 @@ annotations:
url: https://github.com/apache/solr-operator/issues/556
- name: Github PR
url: https://github.com/apache/solr-operator/pull/892
+ - kind: added
+ description: Support for Solr 10. See the upgrade notes before upgrading
a SolrCloud to Solr 10.
+ links:
+ - name: Github Issue
+ url: https://github.com/apache/solr-operator/issues/821
+ - name: Github PR
+ url: https://github.com/apache/solr-operator/pull/827
+ - kind: changed
+ description: The operator no longer reconciles a SolrPrometheusExporter
that uses a Solr 10 image or refers to a Solr 10 SolrCloud, as Solr 10 removed
the Prometheus exporter. It emits an UnsupportedSolrVersion Warning event
instead.
+ links:
+ - name: Github Issue
+ url: https://github.com/apache/solr-operator/issues/820
+ - name: Github PR
+ url: https://github.com/apache/solr-operator/pull/827
+ - kind: changed
+ description: The SolrCloud image tag must start with the Solr version
(e.g. `10.0.0`, `9.10` or `8.11`). SolrClouds with other tags, such as
`latest`, are no longer reconciled; see the upgrade notes before upgrading the
operator.
+ links:
+ - name: Github PR
+ url: https://github.com/apache/solr-operator/pull/827
artifacthub.io/images: |
- name: solr-operator
image: apache/solr-operator:v0.10.0-prerelease
diff --git a/helm/solr/Chart.yaml b/helm/solr/Chart.yaml
index acd1d8f5..302e449e 100644
--- a/helm/solr/Chart.yaml
+++ b/helm/solr/Chart.yaml
@@ -75,6 +75,11 @@ annotations:
links:
- name: Solr Security News
url: https://solr.apache.org/security-news.html
+ - kind: changed
+ description: The `image.tag` value must start with the Solr version
(e.g. `10.0.0`, `9.10` or `8.11`). The Solr Operator does not reconcile
SolrClouds with other tags, such as `latest`; see the upgrade notes before
upgrading the operator.
+ links:
+ - name: Github PR
+ url: https://github.com/apache/solr-operator/pull/827
artifacthub.io/containsSecurityUpdates: "true"
artifacthub.io/recommendations: |
- url: https://artifacthub.io/packages/helm/apache-solr/solr-operator
diff --git a/helm/solr/README.md b/helm/solr/README.md
index 6b649d67..3c486f8f 100644
--- a/helm/solr/README.md
+++ b/helm/solr/README.md
@@ -82,7 +82,7 @@ Descriptions on how to use these options can be found in the
[SolrCloud document
| nameOverride | string | `""` | |
| replicas | int | `3` | The number of Solr pods to run in the Solr Cloud. If
you want to use autoScaling, do not set this field. |
| image.repository | string | `"solr"` | The repository of the Solr image |
-| image.tag | string | `"9.11.0"` | The tag/version of Solr to run |
+| image.tag | string | `"9.11.0"` | The tag/version of Solr to run. Must start
with the Solr version, e.g. `9`, `9.10` or `10.0.0-slim` |
| image.pullPolicy | string | | PullPolicy for the Solr image, defaults to the
empty Pod behavior |
| image.imagePullSecret | string | | PullSecret for the Solr image |
| busyBoxImage.repository | string | `"busybox"` | The repository of the
BusyBox image |
diff --git a/tests/e2e/prometheus_exporter_test.go
b/tests/e2e/prometheus_exporter_test.go
index f68e5f8d..a003d678 100644
--- a/tests/e2e/prometheus_exporter_test.go
+++ b/tests/e2e/prometheus_exporter_test.go
@@ -43,6 +43,8 @@ var _ = FDescribe("E2E - Prometheus Exporter", Ordered,
func() {
Create a single SolrCloud that all PrometheusExporter tests in
this "Describe" will use.
*/
BeforeAll(func(ctx context.Context) {
+ skipIfPrometheusExporterUnavailable()
+
solrCloud = generateBaseSolrCloud(2)
By("creating the SolrCloud")
diff --git a/tests/e2e/prometheus_exporter_tls_test.go
b/tests/e2e/prometheus_exporter_tls_test.go
index f6fa2299..ca964e53 100644
--- a/tests/e2e/prometheus_exporter_tls_test.go
+++ b/tests/e2e/prometheus_exporter_tls_test.go
@@ -44,6 +44,8 @@ var _ = FDescribe("E2E - Prometheus Exporter - TLS ",
Ordered, func() {
Create a single SolrCloud that all PrometheusExporter tests in
this "Describe" will use.
*/
BeforeAll(func(ctx context.Context) {
+ skipIfPrometheusExporterUnavailable()
+
installSolrIssuer(ctx, testNamespace())
solrCloud = generateBaseSolrCloudWithSecretTLS(ctx, 2, true,
true)
diff --git a/tests/e2e/solrcloud_security_json_test.go
b/tests/e2e/solrcloud_security_json_test.go
index f362a2a4..f377792a 100644
--- a/tests/e2e/solrcloud_security_json_test.go
+++ b/tests/e2e/solrcloud_security_json_test.go
@@ -111,4 +111,22 @@ var _ = FDescribe("E2E - SolrCloud - Security JSON",
func() {
// TODO: When balancing is in all Operator supported
Solr versions, add a test to make sure balancing occurred
})
})
+
+ FContext("Bootstrapped Security - Probes Require Auth", func() {
+
+ BeforeEach(func() {
+ solrCloud.Spec.SolrSecurity =
&solrv1beta1.SolrSecurityOptions{
+ AuthenticationType: "Basic",
+ ProbesRequireAuth: true,
+ }
+ })
+
+ // The pods only become ready if the authenticated exec probes
succeed, which is checked in "JustBeforeEach"
+ FIt("Starts correctly", func(ctx context.Context) {
+ expectStatefulSetWithChecks(ctx, solrCloud,
solrCloud.StatefulSetName(), func(g Gomega, found *appsv1.StatefulSet) {
+ readinessProbe :=
found.Spec.Template.Spec.Containers[0].ReadinessProbe
+ g.Expect(readinessProbe.Exec).ToNot(BeNil(),
"Probes that require auth should use an exec command")
+ })
+ })
+ })
})
diff --git a/tests/e2e/test_utils_test.go b/tests/e2e/test_utils_test.go
index 375c0401..77536c40 100644
--- a/tests/e2e/test_utils_test.go
+++ b/tests/e2e/test_utils_test.go
@@ -488,6 +488,14 @@ func callSolrApiInPod(ctx context.Context, solrCloud
*solrv1beta1.SolrCloud, htt
queryParamsString = "?" + queryParamsString
}
+ if solrCloud.SolrVersionAtLeast("10") {
+ // Solr 10's `solr api` only supports GET (--solr-url URL). The
legacy
+ // `-get/-post URL` flags were removed. Fail loudly if a
non-GET caller
+ // is added, instead of silently turning the request into a GET.
+ Expect(strings.ToLower(httpMethod)).To(Equal("get"),
"callSolrApiInPod against Solr 10 only supports GET")
+ }
+
+ credentials := ""
toolOpts := ""
if solrCloud.Spec.SolrSecurity != nil &&
solrCloud.Spec.SolrSecurity.AuthenticationType == solrv1beta1.Basic {
basicAuthSecretName := solrCloud.BasicAuthSecretName()
@@ -495,25 +503,32 @@ func callSolrApiInPod(ctx context.Context, solrCloud
*solrv1beta1.SolrCloud, htt
if err = k8sClient.Get(ctx, resourceKey(solrCloud,
basicAuthSecretName), basicAuthSecret); err != nil {
return "", err
}
- toolOpts =
- "JAVA_TOOL_OPTIONS=\"-Dbasicauth=" +
-
string(basicAuthSecret.Data[corev1.BasicAuthUsernameKey]) + ":" +
string(basicAuthSecret.Data[corev1.BasicAuthPasswordKey]) +
- "
-Dsolr.httpclient.builder.factory=org.apache.solr.client.solrj.impl.PreemptiveBasicAuthClientBuilderFactory\""
+ credentials =
string(basicAuthSecret.Data[corev1.BasicAuthUsernameKey]) + ":" +
string(basicAuthSecret.Data[corev1.BasicAuthPasswordKey])
+ if !solrCloud.SolrVersionAtLeast("10") {
+ toolOpts =
+ "JAVA_TOOL_OPTIONS=\"-Dbasicauth=" +
credentials +
+ "
-Dsolr.httpclient.builder.factory=org.apache.solr.client.solrj.impl.PreemptiveBasicAuthClientBuilderFactory\""
+ }
}
GinkgoLogr.Info(toolOpts)
- command := []string{
- "solr",
- "api",
- "-verbose",
- "-" + strings.ToLower(httpMethod),
- fmt.Sprintf(
- "\"%s://%s%s%s%s\"",
- solrCloud.UrlScheme(false),
- hostname,
- solrCloud.NodePortSuffix(false),
- apiPath,
- queryParamsString),
+ solrUrl := fmt.Sprintf(
+ "\"%s://%s%s%s%s\"",
+ solrCloud.UrlScheme(false),
+ hostname,
+ solrCloud.NodePortSuffix(false),
+ apiPath,
+ queryParamsString)
+
+ var command []string
+ if solrCloud.SolrVersionAtLeast("10") {
+ command = []string{"solr", "api", "--solr-url", solrUrl, "-v"}
+ if credentials != "" {
+ // The command is run via 'sh -c', and generated
passwords can contain shell characters such as '('
+ command = append(command, "--credentials",
"'"+strings.ReplaceAll(credentials, "'", `'\''`)+"'")
+ }
+ } else {
+ command = []string{"solr", "api", "-verbose", "-" +
strings.ToLower(httpMethod), solrUrl}
}
if toolOpts != "" {
commandString := fmt.Sprintf("%s %s", toolOpts,
strings.Join(command, " "))
@@ -661,6 +676,14 @@ func generateBaseSolrCloud(replicas int)
*solrv1beta1.SolrCloud {
}
}
+// skipIfPrometheusExporterUnavailable skips the current tests if the Solr
image under test is Solr 10 or later,
+// which no longer ships the Prometheus exporter.
+func skipIfPrometheusExporterUnavailable() {
+ if generateBaseSolrCloud(1).SolrVersionAtLeast("10") {
+ Skip("The Prometheus exporter was removed in Solr 10")
+ }
+}
+
// Uses default password from docs : SolrRocks
// The hash is generated as: base64(sha256(sha256(salt+password)))
base64(salt))
// See
https://solr.apache.org/guide/solr/latest/deployment-guide/basic-authentication-plugin.html