This is an automated email from the ASF dual-hosted git repository. squakez pushed a commit to branch v3 in repository https://gitbox.apache.org/repos/asf/camel-k.git
commit 819865538eb1306d40a41c876c76423ff417611d Author: Sanjeev Kumar <[email protected]> AuthorDate: Fri Nov 27 19:57:58 2026 +0530 feat(keda): add IBM MQ auto scaler mapping (#6922) * feat(keda): add IBM MQ auto scaler mapping * fix(keda): use ibmmq metadata as scaler selection * test(keda): cover IBM MQ metadata selection and REST host * fix(keda): remove redundant IBM MQ queue type hint * test(keda): align JMS discovery with IBM MQ metadata selection * docs(keda): explain IBM MQ selection and REST host source * style(keda): format IBM MQ property test * test(keda): remove obsolete IBM MQ discriminator assertion * docs(keda): describe metadata-aware mapper extension * docs(keda): clarify explicit IBM MQ opt-in * docs(keda): update metadata-aware mapper flow * test(keda): fix metadata table reference * style(keda): format IBM MQ scaler tests * test(keda): add ephemeral IBM MQ broker for scaler e2e * test(keda): add IBM MQ auto-discovery integration fixture * test(keda): verify IBM MQ auto-discovery against live broker * test(keda): use Camel Integration ready condition * test(keda): expose secret-backed scaler credentials in pod template * test(keda): pin released IBM MQ developer image * test(keda): align IBM MQ client with broker release * test(keda): enable authenticated IBM MQ consumer route * test(keda): add IBM MQ message producer for autoscaling * test(keda): exercise IBM MQ autoscaling end to end * test(keda): configure IBM MQ scaler credentials from env * test(keda): assert IBM MQ env credential references * docs(keda): clarify IBM MQ scaler env authentication * test(keda): use explicit IBM MQ admin env names * test(keda): assert explicit admin env references * docs(keda): show IBM MQ env-backed authentication * test(keda): use dynamic namespace for IBM MQ e2e * docs(keda): correct IBM MQ auto-discovery selection * test(keda): assert IBM MQ autoscaling behavior only * test(keda): configure IBM MQ credentials with environment trait * test(keda): configure producer credentials with environment trait * test(e2e): skip IBM MQ test on unsupported architectures * test(keda): allow longer Spring RabbitMQ startup Co-authored-by: Copilot <[email protected]> * test(keda): disable unused MQ service account token mount * ci: rerun KEDA tests * test(keda): fix IBM MQ autoscaling E2E test * test(keda): allow IBM MQ image pull in CI * test(keda): let KEDA resolve IBM MQ admin credentials --------- Co-authored-by: Copilot <[email protected]> --- .../ROOT/pages/contributing/keda-scaler.adoc | 49 ++++++- docs/modules/traits/pages/keda.adoc | 1 + e2e/keda/files/ibmmq-ephemeral.yaml | 126 ++++++++++++++++++ e2e/keda/files/keda-it-ibmmq-to-log-auto.yaml | 79 +++++++++++ e2e/keda/files/timer-to-ibmmq.yaml | 49 +++++++ e2e/keda/keda_ibmmq_test.go | 96 ++++++++++++++ e2e/keda/keda_spring_rabbitmq_test.go | 5 +- e2e/keda/setup/setup.sh | 2 +- pkg/trait/keda.go | 2 +- pkg/trait/keda/mapper.go | 25 +++- pkg/trait/keda/scalers/ibmmq.go | 106 +++++++++++++++ pkg/trait/keda/scalers/ibmmq_test.go | 144 +++++++++++++++++++++ pkg/trait/keda_test.go | 51 ++++++++ 13 files changed, 729 insertions(+), 6 deletions(-) diff --git a/docs/modules/ROOT/pages/contributing/keda-scaler.adoc b/docs/modules/ROOT/pages/contributing/keda-scaler.adoc index ea7e206f0..222a3675a 100644 --- a/docs/modules/ROOT/pages/contributing/keda-scaler.adoc +++ b/docs/modules/ROOT/pages/contributing/keda-scaler.adoc @@ -13,7 +13,7 @@ When the KEDA trait is enabled, `kedaTrait.Configure` runs automatic discovery u Discovery follows this flow: . `metadata.ExtractAll` inspects all Integration sources and extracts their Camel `from` URIs. -. Each URI is passed to `MapToKedaTrigger`, together with the Integration properties. +. Each URI is passed to `MapToKedaTriggerWithAutoMetadata`, together with the Integration properties and the `keda.autoMetadata` map. The existing `MapToKedaTrigger` entry point remains available for callers that do not need to supply auto-metadata. . `ParseComponentURI` separates the URI into its component name, path value, and query parameters. . The component name is used to look up a `ScaleMapper` in the registry. . If a mapper is registered, it converts the path and parameters into a KEDA scaler type and metadata, which become a `KedaTrigger`. @@ -38,6 +38,11 @@ type ScaleMapper interface { `Component` returns the Camel component name used as the registry key. `Map` receives the path part of the Camel URI, its decoded query parameters, and the Integration properties, and returns the corresponding KEDA scaler type and metadata. +A mapper that needs an explicit opt-in from KEDA configuration can additionally implement the optional `AutoMetadataScaleMapper` interface. +The dispatcher then calls `MapWithAutoMetadata` with the same URI inputs, Integration properties, and the `keda.autoMetadata` map. +Mappers that implement only `ScaleMapper` continue to use `Map` unchanged. +The JMS/IBM MQ mapping uses this extension because the generic `jms` scheme is shared by different providers and the presence of the `ibmmq` metadata entry is the explicit scaler selection. + Each implementation registers itself by calling `keda.Register` from an `init` function. The blank import of `pkg/trait/keda/scalers` in `pkg/trait/keda.go` ensures that these registration functions run when the trait package is loaded. @@ -66,6 +71,48 @@ metadata: Other KEDA Kafka metadata, such as `lagThreshold`, can be supplied through `keda.autoMetadata` when it is not derived from the Camel URI. +== IBM MQ over JMS + +IBM MQ commonly uses Camel's generic `jms` component, so the endpoint scheme alone cannot distinguish it from ActiveMQ or another JMS provider. +The IBM MQ mapper is selected when `keda.autoMetadata` contains an `ibmmq` entry. +That entry already identifies the IBM MQ scaler, so a separate queue-type discriminator is unnecessary. +It only maps JMS queue destinations; topics and temporary destinations are ignored. + +For example, this source endpoint: + +[source,text] +---- +jms:queue:ORDERS +---- + +can be opted into IBM MQ discovery with: + +[source,yaml] +---- +traits: + keda: + enabled: true + autoMetadata: + ibmmq: + host: https://mq.example.com/ibmmq/rest/v2/admin/action/qmgr/QM1/mqsc + queueDepth: "25" + usernameFromEnv: MQ_ADMIN_USERNAME + passwordFromEnv: MQ_ADMIN_PASSWORD +---- + +The mapper creates an `ibmmq` trigger and derives `queueName` from the JMS destination. +The `host` value is the IBM MQ Queue Manager Admin REST endpoint required by KEDA. +It is not the JMS broker's host/port: Camel JMS is configured through a provider-specific `ConnectionFactory`, whose `hostName`, `port`, `channel`, and `queueManager` describe the messaging connection rather than the mqweb Admin REST URL. +That REST endpoint can use a different host, port, and path, so it cannot be inferred safely from generic JMS properties or an opaque bean reference. +Supply it explicitly through `keda.autoMetadata.ibmmq.host`. +Other entries under `keda.autoMetadata.ibmmq` are passed through as KEDA scaler metadata. For `usernameFromEnv` and `passwordFromEnv`, provide the names of environment variables on the scaled Integration pod, and populate those variables from Kubernetes Secrets. + +This mapping does not inspect the JMS `ConnectionFactory` bean or copy its credentials. +Configure authentication using KEDA's supported IBM MQ options, such as `usernameFromEnv` and `passwordFromEnv`. These metadata values name environment variables that KEDA reads from the scale target, which is the Integration resource and not its Deployment. +Declare them in `spec.template.spec.containers` of the Integration, for the container named `integration`, using Kubernetes Secret references. +Variables set only through the `environment` trait are not visible to KEDA. +See the https://keda.sh/docs/latest/scalers/ibm-mq/[KEDA IBM MQ scaler] documentation for the complete trigger and authentication options. + == Complete mapping example The following example uses fictional component and scaler names to show the complete mapping process. diff --git a/docs/modules/traits/pages/keda.adoc b/docs/modules/traits/pages/keda.adoc index 1d933bc6c..e44257fd9 100644 --- a/docs/modules/traits/pages/keda.adoc +++ b/docs/modules/traits/pages/keda.adoc @@ -80,5 +80,6 @@ Automatic discovery currently supports the following Camel components: * `spring-rabbitmq`: creates a RabbitMQ trigger whose `queueName` is the `queues` value of the endpoint URI, when it names a single queue. The broker address is not part of the URI: a `host` endpoint parameter, when present, is used as the trigger `host` as is; otherwise set `host`, together with `mode` and `value`, with `keda.autoMetadata`. See the https://keda.sh/docs/latest/scalers/rabbitmq-queue/[KEDA RabbitMQ Queue scaler] documentation for the available trigger metadata. * `azure-servicebus`: creates an Azure Service Bus trigger from the queue or topic name in the endpoint URI. `serviceBusType=topic` maps the path to `topicName` and requires `subscriptionName`; otherwise the path maps to `queueName`. The `serviceBusType`, `subscriptionName`, and `fullyQualifiedNamespace` options fall back to the corresponding `camel.component.azure-servicebus.*` properties. A public-cloud fully qualified namespace is reduced to the KEDA `namespace` metadata. For other Az [...] * `nats`: creates a NATS JetStream trigger for a JetStream consumer with a durable name (`jetstreamEnabled=true`, `jetstreamName` and `durableName`, as endpoint options or `camel.component.nats.*` properties). The stream is `jetstreamName`, the consumer is `<durableName>-durable` (the name Camel gives the durable consumer) and the account is `$G`, the default account of a NATS server without configured accounts. When `servers` is set, `natsServerMonitoringEndpoint` is set to `<host>:8222 [...] +* `jms` with an explicit IBM MQ selection: creates an IBM MQ trigger for queue destinations only when `keda.autoMetadata` contains an `ibmmq` entry and the required IBM MQ Admin REST `host` is supplied. This is an explicit opt-in, not provider detection; use it only when the configured JMS `ConnectionFactory` connects to IBM MQ. A generic JMS endpoint without this opt-in does not create an IBM MQ trigger, and topic or temporary destinations are not mapped. See the https://keda.sh/docs/la [...] Unsupported Camel components do not produce an automatically discovered trigger. You can still configure their KEDA triggers explicitly with `keda.triggers`. \ No newline at end of file diff --git a/e2e/keda/files/ibmmq-ephemeral.yaml b/e2e/keda/files/ibmmq-ephemeral.yaml new file mode 100644 index 000000000..becd894fc --- /dev/null +++ b/e2e/keda/files/ibmmq-ephemeral.yaml @@ -0,0 +1,126 @@ +# --------------------------------------------------------------------------- +# 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. +# --------------------------------------------------------------------------- + +# These credentials are only for the disposable IBM MQ developer broker used +# by the KEDA integration test. The image reads the password keys from +# /run/secrets; they are not passed to the MQ container as environment values. +apiVersion: v1 +kind: Secret +metadata: + name: ibmmq-auth +stringData: + mqAdminUsername: admin + mqAdminPassword: admin-passw0rd + mqAppUsername: app + mqAppPassword: app-passw0rd +--- +apiVersion: apps/v1 +kind: Deployment +metadata: + name: ibmmq +spec: + replicas: 1 + selector: + matchLabels: + app: ibmmq + template: + metadata: + labels: + app: ibmmq + spec: + # The broker does not call the Kubernetes API. Avoid mounting the + # service-account token under /var/run/secrets, which overlaps the + # read-only IBM MQ password Secret mounted at /run/secrets. + automountServiceAccountToken: false + terminationGracePeriodSeconds: 60 + containers: + - name: ibmmq + image: icr.io/ibm-messaging/mq:9.4.0.26-r2 + imagePullPolicy: IfNotPresent + env: + - name: LICENSE + value: accept + - name: MQ_QMGR_NAME + value: QM1 + - name: MQ_CONNAUTH_USE_HTP + value: "true" + ports: + - name: mq + containerPort: 1414 + protocol: TCP + - name: mqweb + containerPort: 9443 + protocol: TCP + startupProbe: + exec: + command: + - chkmqstarted + failureThreshold: 60 + periodSeconds: 5 + timeoutSeconds: 5 + readinessProbe: + exec: + command: + - chkmqready + failureThreshold: 1 + periodSeconds: 5 + timeoutSeconds: 5 + livenessProbe: + exec: + command: + - chkmqhealthy + failureThreshold: 3 + periodSeconds: 10 + timeoutSeconds: 5 + resources: + requests: + cpu: "1" + memory: 1Gi + limits: + cpu: "2" + memory: 2Gi + volumeMounts: + - name: mq-passwords + mountPath: /run/secrets + readOnly: true + volumes: + - name: mq-passwords + secret: + secretName: ibmmq-auth + defaultMode: 0444 + items: + - key: mqAdminPassword + path: mqAdminPassword + - key: mqAppPassword + path: mqAppPassword +--- +apiVersion: v1 +kind: Service +metadata: + name: ibmmq +spec: + selector: + app: ibmmq + ports: + - name: mq + port: 1414 + targetPort: mq + protocol: TCP + - name: mqweb + port: 9443 + targetPort: mqweb + protocol: TCP diff --git a/e2e/keda/files/keda-it-ibmmq-to-log-auto.yaml b/e2e/keda/files/keda-it-ibmmq-to-log-auto.yaml new file mode 100644 index 000000000..f5975408e --- /dev/null +++ b/e2e/keda/files/keda-it-ibmmq-to-log-auto.yaml @@ -0,0 +1,79 @@ +# --------------------------------------------------------------------------- +# 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. +# --------------------------------------------------------------------------- + +apiVersion: camel.apache.org/v1 +kind: Integration +metadata: + name: keda-it-ibmmq-to-log-auto +spec: + # KEDA resolves usernameFromEnv and passwordFromEnv from the pod template of the + # scale target. The target is this Integration (not its Deployment), so the admin + # credentials must be declared here. The pod trait copies them to the Deployment. + template: + spec: + containers: + - name: integration + env: + - name: MQ_ADMIN_USERNAME + valueFrom: + secretKeyRef: + name: ibmmq-auth + key: mqAdminUsername + - name: MQ_ADMIN_PASSWORD + valueFrom: + secretKeyRef: + name: ibmmq-auth + key: mqAdminPassword + dependencies: + - camel:jms + - mvn:com.ibm.mq:com.ibm.mq.jakarta.client:9.4.0.26 + flows: + - route: + from: + uri: jms:queue:DEV.QUEUE.1 + steps: + - to: log:ibmmq + traits: + environment: + vars: + - MQ_APP_USERNAME=secret:ibmmq-auth/mqAppUsername + - MQ_APP_PASSWORD=secret:ibmmq-auth/mqAppPassword + camel: + properties: + - camel.beans.mqCF=#class:com.ibm.mq.jakarta.jms.MQConnectionFactory + - camel.beans.mqCF.hostName=ibmmq.%%%.svc + - camel.beans.mqCF.port=1414 + - camel.beans.mqCF.channel=DEV.APP.SVRCONN + - camel.beans.mqCF.queueManager=QM1 + - camel.beans.mqCF.transportType=1 + - camel.component.jms.connection-factory=#bean:mqCF + - camel.component.jms.username={{env:MQ_APP_USERNAME}} + - camel.component.jms.password={{env:MQ_APP_PASSWORD}} + keda: + enabled: true + auto: true + minReplicaCount: 0 + maxReplicaCount: 1 + cooldownPeriod: 30 + pollingInterval: 5 + autoMetadata: + ibmmq: + host: https://ibmmq.%%%.svc:9443/ibmmq/rest/v2/admin/action/qmgr/QM1/mqsc + queueDepth: "1" + usernameFromEnv: MQ_ADMIN_USERNAME + passwordFromEnv: MQ_ADMIN_PASSWORD + unsafeSsl: "true" diff --git a/e2e/keda/files/timer-to-ibmmq.yaml b/e2e/keda/files/timer-to-ibmmq.yaml new file mode 100644 index 000000000..5b825cea9 --- /dev/null +++ b/e2e/keda/files/timer-to-ibmmq.yaml @@ -0,0 +1,49 @@ +# --------------------------------------------------------------------------- +# 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. +# --------------------------------------------------------------------------- + +apiVersion: camel.apache.org/v1 +kind: Integration +metadata: + name: timer-to-ibmmq +spec: + dependencies: + - camel:jms + - mvn:com.ibm.mq:com.ibm.mq.jakarta.client:9.4.0.26 + flows: + - route: + from: + uri: timer:foo?period=1000 + steps: + - setBody: + constant: "IBM MQ scaler E2E message" + - to: jms:queue:DEV.QUEUE.1 + traits: + environment: + vars: + - MQ_APP_USERNAME=secret:ibmmq-auth/mqAppUsername + - MQ_APP_PASSWORD=secret:ibmmq-auth/mqAppPassword + camel: + properties: + - camel.beans.mqCF=#class:com.ibm.mq.jakarta.jms.MQConnectionFactory + - camel.beans.mqCF.hostName=ibmmq.%%%.svc + - camel.beans.mqCF.port=1414 + - camel.beans.mqCF.channel=DEV.APP.SVRCONN + - camel.beans.mqCF.queueManager=QM1 + - camel.beans.mqCF.transportType=1 + - camel.component.jms.connection-factory=#bean:mqCF + - camel.component.jms.username={{env:MQ_APP_USERNAME}} + - camel.component.jms.password={{env:MQ_APP_PASSWORD}} diff --git a/e2e/keda/keda_ibmmq_test.go b/e2e/keda/keda_ibmmq_test.go new file mode 100644 index 000000000..1e82419cd --- /dev/null +++ b/e2e/keda/keda_ibmmq_test.go @@ -0,0 +1,96 @@ +//go:build integration +// +build integration + +/* +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 keda + +import ( + "context" + "runtime" + "testing" + + . "github.com/onsi/gomega" + . "github.com/onsi/gomega/gstruct" + corev1 "k8s.io/api/core/v1" + + . "github.com/apache/camel-k/v2/e2e/support" + v1 "github.com/apache/camel-k/v2/pkg/apis/camel/v1" +) + +func TestIBMMQKedaAutoDiscoveryAndAutoscale(t *testing.T) { + // The IBM MQ developer container image is published only for amd64, + // s390x, and ppc64le. Skip rather than failing image pulls on unsupported + // architectures such as arm64. + switch runtime.GOARCH { + case "amd64", "s390x", "ppc64le": + default: + t.Skipf("IBM MQ developer image does not support %s (supported: amd64, s390x, ppc64le)", runtime.GOARCH) + } + + WithNewTestNamespace(t, func(ctx context.Context, g *WithT, ns string) { + consumerName := "keda-it-ibmmq-to-log-auto" + producerName := "timer-to-ibmmq" + + ExpectExecSucceed(t, g, Kubectl("apply", "-f", "files/ibmmq-ephemeral.yaml", "-n", ns)) + // The IBM MQ developer image is large and has to be pulled into the + // ephemeral CI cluster. ExpectExecSucceed uses the suite's one-minute + // default command timeout, which can expire while the pod is still in + // ContainerCreating even though kubectl is allowed to wait five minutes. + ExpectExecSucceedWithTimeout(t, g, + Kubectl("rollout", "status", "deployment/ibmmq", "-n", ns, "--timeout=300s"), + "5m", + ) + + ExpectExecSucceed(t, g, Kubectl( + "apply", "-f", + cloneAndReplaceNamespace(t, "files/keda-it-ibmmq-to-log-auto.yaml", ns), + "-n", ns, + )) + + g.Eventually( + IntegrationConditionStatus(t, ctx, ns, consumerName, v1.IntegrationConditionReady), + TestTimeoutLong, + ).Should(Equal(corev1.ConditionTrue)) + + // The queue is empty, so KEDA can scale the consumer to zero as soon as the + // ScaledObject is active: do not expect to observe one replica before that. + g.Eventually(IntegrationStatusReplicas(t, ctx, ns, consumerName), TestTimeoutLong). + Should(PointTo(BeNumerically("==", 0))) + + ExpectExecSucceed(t, g, Kubectl( + "apply", "-f", + cloneAndReplaceNamespace(t, "files/timer-to-ibmmq.yaml", ns), + "-n", ns, + )) + + g.Eventually( + IntegrationConditionStatus(t, ctx, ns, producerName, v1.IntegrationConditionReady), + TestTimeoutLong, + ).Should(Equal(corev1.ConditionTrue)) + + g.Eventually(IntegrationStatusReplicas(t, ctx, ns, consumerName), TestTimeoutMedium). + Should(PointTo(BeNumerically("==", 1))) + g.Eventually(IntegrationLogs(t, ctx, ns, consumerName), TestTimeoutMedium). + Should(ContainSubstring("IBM MQ scaler E2E message")) + + ExpectExecSucceed(t, g, Kubectl("delete", "it", producerName, "-n", ns)) + g.Eventually(IntegrationStatusReplicas(t, ctx, ns, consumerName), TestTimeoutMedium). + Should(PointTo(BeNumerically("==", 0))) + }) +} diff --git a/e2e/keda/keda_spring_rabbitmq_test.go b/e2e/keda/keda_spring_rabbitmq_test.go index 569da5ab4..077d7247f 100644 --- a/e2e/keda/keda_spring_rabbitmq_test.go +++ b/e2e/keda/keda_spring_rabbitmq_test.go @@ -45,7 +45,10 @@ func TestSpringRabbitMQKedaAutoscale(t *testing.T) { ExpectExecSucceed(t, g, Kubectl("apply", "-f", consumerFile, "-n", ns)) // Trigger is auto-discovered from the consumer URI - g.Eventually(ScaledObject(t, ctx, ns, consumerName), TestTimeoutMedium). + // The ScaledObject is created after the integration reaches a running phase. + // Spring RabbitMQ requires an additional dependency build, so allow the + // longer integration startup timeout here. + g.Eventually(ScaledObject(t, ctx, ns, consumerName), TestTimeoutLong). ShouldNot(BeNil()) scaledObj := ScaledObject(t, ctx, ns, consumerName)() g.Expect(scaledObj).NotTo(BeNil()) diff --git a/e2e/keda/setup/setup.sh b/e2e/keda/setup/setup.sh index 636b779cd..f1badc527 100755 --- a/e2e/keda/setup/setup.sh +++ b/e2e/keda/setup/setup.sh @@ -19,5 +19,5 @@ #### Setup KEDA Operator # Installs KEDA operator into 'keda' namespace -kubectl apply --server-side -f https://github.com/kedacore/keda/releases/download/v2.17.2/keda-2.17.2.yaml +kubectl apply --server-side -f https://github.com/kedacore/keda/releases/download/v2.19.0/keda-2.19.0.yaml kubectl rollout status deployment keda-operator -n keda --timeout=180s diff --git a/pkg/trait/keda.go b/pkg/trait/keda.go index ea7d89923..75bb3d9d9 100644 --- a/pkg/trait/keda.go +++ b/pkg/trait/keda.go @@ -166,7 +166,7 @@ func (t *kedaTrait) autoDiscoverTriggers(e *Environment) error { props := integrationProperties(e) for _, fromURI := range meta.FromURIs { - trigger, err := kedamapper.MapToKedaTrigger(fromURI, props) + trigger, err := kedamapper.MapToKedaTriggerWithAutoMetadata(fromURI, props, t.AutoMetadata) if err != nil { return err } diff --git a/pkg/trait/keda/mapper.go b/pkg/trait/keda/mapper.go index ceeca765b..37c8f2853 100644 --- a/pkg/trait/keda/mapper.go +++ b/pkg/trait/keda/mapper.go @@ -28,6 +28,14 @@ type ScaleMapper interface { Map(pathValue string, params map[string]string, props map[string]string) (kedaType string, metadata map[string]string) } +// AutoMetadataScaleMapper is an optional extension for mappers that need +// KEDA autoMetadata to decide whether a generic Camel component can be mapped. +// Existing ScaleMapper implementations do not need to implement this interface. +type AutoMetadataScaleMapper interface { + ScaleMapper + MapWithAutoMetadata(pathValue string, params map[string]string, props map[string]string, autoMetadata map[string]map[string]string) (kedaType string, metadata map[string]string) +} + var registry = map[string]ScaleMapper{} func Register(m ScaleMapper) { @@ -41,6 +49,12 @@ func GetMapper(component string) (ScaleMapper, bool) { } func MapToKedaTrigger(rawURI string, props map[string]string) (*traitv1.KedaTrigger, error) { + return MapToKedaTriggerWithAutoMetadata(rawURI, props, nil) +} + +// MapToKedaTriggerWithAutoMetadata maps a Camel consumer URI to a KEDA trigger. +// autoMetadata is passed only to mappers implementing AutoMetadataScaleMapper. +func MapToKedaTriggerWithAutoMetadata(rawURI string, props map[string]string, autoMetadata map[string]map[string]string) (*traitv1.KedaTrigger, error) { scheme, pathValue, params, err := ParseComponentURI(rawURI) if err != nil { return nil, err @@ -52,9 +66,16 @@ func MapToKedaTrigger(rawURI string, props map[string]string) (*traitv1.KedaTrig if !found { return nil, nil } - kedaType, metadata := mapper.Map(pathValue, params, props) + var kedaType string + var metadata map[string]string + if metadataMapper, ok := mapper.(AutoMetadataScaleMapper); ok { + kedaType, metadata = metadataMapper.MapWithAutoMetadata(pathValue, params, props, autoMetadata) + } else { + kedaType, metadata = mapper.Map(pathValue, params, props) + } + // An empty type means that the mapper deliberately declined discovery + // (for example, because an explicit provider discriminator was absent). if kedaType == "" { - // The mapper found nothing to scale on for this endpoint. return nil, nil } diff --git a/pkg/trait/keda/scalers/ibmmq.go b/pkg/trait/keda/scalers/ibmmq.go new file mode 100644 index 000000000..691bb4fd7 --- /dev/null +++ b/pkg/trait/keda/scalers/ibmmq.go @@ -0,0 +1,106 @@ +/* +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 scalers + +import ( + "strings" + + keda "github.com/apache/camel-k/v2/pkg/trait/keda" +) + +const ( + ibmmqScalerType = "ibmmq" + ibmmqAdminHostKey = "host" +) + +// IBMMQScaler maps explicitly selected JMS queue endpoints to the KEDA IBM MQ scaler. +type IBMMQScaler struct{} + +func init() { + keda.Register(&IBMMQScaler{}) +} + +func (i *IBMMQScaler) Component() string { + return "jms" +} + +// Map intentionally declines discovery without autoMetadata. IBM MQ and other +// JMS providers share the same Camel component, so the provider cannot be +// inferred safely from the endpoint URI. +func (i *IBMMQScaler) Map(pathValue string, params map[string]string, props map[string]string) (string, map[string]string) { + return "", nil +} + +// MapWithAutoMetadata maps JMS queue consumers only when the Integration +// explicitly opts in to IBM MQ and provides KEDA's required admin REST host. +func (i *IBMMQScaler) MapWithAutoMetadata(pathValue string, params map[string]string, props map[string]string, autoMetadata map[string]map[string]string) (string, map[string]string) { + ibmmqMetadata, ok := autoMetadata[ibmmqScalerType] + if !ok { + return "", nil + } + if strings.TrimSpace(ibmmqMetadata[ibmmqAdminHostKey]) == "" { + // The KEDA IBM MQ scaler requires the Queue Manager Admin REST endpoint. + // Generic JMS ConnectionFactory properties describe the messaging + // connection; they do not reliably identify the separate mqweb REST URL. + return "", nil + } + + queueName, ok := jmsQueueName(pathValue, params) + if !ok { + return "", nil + } + + return ibmmqScalerType, map[string]string{ + "queueName": queueName, + } +} + +// jmsQueueName returns the destination name only for queue endpoints. Camel +// JMS treats an unqualified destination as a queue; topic and temporary +// destinations are not supported by the KEDA IBM MQ queue scaler. +func jmsQueueName(pathValue string, params map[string]string) (string, bool) { + pathValue = strings.TrimSpace(pathValue) + if pathValue == "" { + return "", false + } + + destinationType := "queue" + destinationName := pathValue + + if prefix, name, found := strings.Cut(pathValue, ":"); found { + switch strings.ToLower(prefix) { + case "queue": + destinationName = name + case "topic", "temp-queue", "temp-topic": + return "", false + default: + // Do not guess when the destination syntax is not recognized. + return "", false + } + } + + if configuredType := strings.TrimSpace(params["destinationType"]); configuredType != "" { + destinationType = strings.ToLower(configuredType) + } + destinationName = strings.TrimSpace(destinationName) + if destinationType != "queue" || destinationName == "" { + return "", false + } + + return destinationName, true +} diff --git a/pkg/trait/keda/scalers/ibmmq_test.go b/pkg/trait/keda/scalers/ibmmq_test.go new file mode 100644 index 000000000..77a5d6a4a --- /dev/null +++ b/pkg/trait/keda/scalers/ibmmq_test.go @@ -0,0 +1,144 @@ +/* +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 scalers + +import ( + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + keda "github.com/apache/camel-k/v2/pkg/trait/keda" +) + +func TestIBMMQScalerRegistered(t *testing.T) { + mapper, found := keda.GetMapper("jms") + require.True(t, found, "IBM MQ mapper should be registered for jms") + assert.Equal(t, "jms", mapper.Component()) +} + +func TestIBMMQScalerMapWithAutoMetadata(t *testing.T) { + scaler := &IBMMQScaler{} + validMetadata := map[string]map[string]string{ + "ibmmq": { + "host": "https://mq.example.com/ibmmq/rest/v2/admin/action/qmgr/QM1/mqsc", + }, + } + + tests := []struct { + name string + pathValue string + params map[string]string + props map[string]string + autoMetadata map[string]map[string]string + expectedType string + expectedMeta map[string]string + }{ + { + name: "queue with prefix", + pathValue: "queue:ORDERS", + autoMetadata: validMetadata, + expectedType: "ibmmq", + expectedMeta: map[string]string{"queueName": "ORDERS"}, + }, + { + name: "queue without prefix defaults to queue", + pathValue: "ORDERS", + autoMetadata: validMetadata, + expectedType: "ibmmq", + expectedMeta: map[string]string{"queueName": "ORDERS"}, + }, + { + name: "topic is not mapped", + pathValue: "topic:ORDERS", + autoMetadata: validMetadata, + }, + { + name: "temporary queue is not mapped", + pathValue: "temp-queue:ORDERS", + autoMetadata: validMetadata, + }, + { + name: "topic destination type is not mapped", + pathValue: "ORDERS", + params: map[string]string{"destinationType": "topic"}, + autoMetadata: validMetadata, + }, + { + name: "IBM MQ scaler is not selected", + pathValue: "queue:ORDERS", + autoMetadata: map[string]map[string]string{ + "activemq": {"host": "tcp://mq.example.com:1414"}, + }, + }, + { + name: "JMS connection properties do not identify the Admin REST host", + pathValue: "queue:ORDERS", + props: map[string]string{ + "camel.component.jms.connection-factory": "#bean:ibmMqConnectionFactory", + "camel.beans.ibmMqConnectionFactory.hostName": "mq.example.com", + "camel.beans.ibmMqConnectionFactory.port": "1414", + "camel.beans.ibmMqConnectionFactory.queueManager": "QM1", + "camel.beans.ibmMqConnectionFactory.channel": "DEV.APP.SVRCONN", + }, + autoMetadata: map[string]map[string]string{ + "ibmmq": {"queueDepth": "25"}, + }, + }, + { + name: "missing admin REST host is not mapped", + pathValue: "queue:ORDERS", + autoMetadata: map[string]map[string]string{ + "ibmmq": {"queueDepth": "25"}, + }, + }, + { + name: "empty queue name is not mapped", + pathValue: "queue:", + autoMetadata: validMetadata, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + kedaType, metadata := scaler.MapWithAutoMetadata(tt.pathValue, tt.params, tt.props, tt.autoMetadata) + assert.Equal(t, tt.expectedType, kedaType) + assert.Equal(t, tt.expectedMeta, metadata) + }) + } +} + +func TestMapToKedaTriggerIBMMQ(t *testing.T) { + autoMetadata := map[string]map[string]string{ + "ibmmq": { + "host": "https://mq.example.com/ibmmq/rest/v2/admin/action/qmgr/QM1/mqsc", + }, + } + + trigger, err := keda.MapToKedaTriggerWithAutoMetadata("jms:queue:ORDERS", nil, autoMetadata) + require.NoError(t, err) + require.NotNil(t, trigger) + assert.Equal(t, "ibmmq", trigger.Type) + assert.Equal(t, map[string]string{"queueName": "ORDERS"}, trigger.Metadata) +} + +func TestMapToKedaTriggerIBMMQRequiresScalerSelection(t *testing.T) { + trigger, err := keda.MapToKedaTrigger("jms:queue:ORDERS", nil) + require.NoError(t, err) + assert.Nil(t, trigger) +} diff --git a/pkg/trait/keda_test.go b/pkg/trait/keda_test.go index bb0b08080..b3d6dd4b9 100644 --- a/pkg/trait/keda_test.go +++ b/pkg/trait/keda_test.go @@ -143,6 +143,23 @@ func TestKedaAutoDiscovery(t *testing.T) { }, expectedCount: 1, }, + { + name: "ibmmq over jms queue", + source: `from("jms:queue:ORDERS").log("${body}");`, + expectedType: "ibmmq", + expectedParams: map[string]string{ + "queueName": "ORDERS", + "host": "https://mq.example.com/ibmmq/rest/v2/admin/action/qmgr/QM1/mqsc", + "queueDepth": "25", + }, + autoMetadata: map[string]map[string]string{ + "ibmmq": { + "host": "https://mq.example.com/ibmmq/rest/v2/admin/action/qmgr/QM1/mqsc", + "queueDepth": "25", + }, + }, + expectedCount: 1, + }, } for _, tt := range tests { @@ -175,6 +192,40 @@ func TestKedaAutoDiscovery(t *testing.T) { } } +func TestKedaAutoDiscoveryJMSRequiresIBMMetadataAndAdminHost(t *testing.T) { + tests := []struct { + name string + autoMetadata map[string]map[string]string + }{ + { + name: "IBM MQ scaler is not selected", + autoMetadata: map[string]map[string]string{ + "activemq": {"host": "tcp://mq.example.com:1414"}, + }, + }, + { + name: "missing required admin REST host", + autoMetadata: map[string]map[string]string{ + "ibmmq": {"queueDepth": "25"}, + }, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + environment := autoDiscoveryEnvWithSource( + t, + `from("jms:queue:ORDERS").log("${body}");`, + nil, + tt.autoMetadata, + ) + _, _, err := environment.Catalog.apply(&environment) + require.NoError(t, err) + assert.Nil(t, getKedaScaledObject(environment.Resources), "JMS must not be auto-mapped without an ibmmq autoMetadata entry and admin REST host") + }) + } +} + func TestKedaAuthentication(t *testing.T) { environment := nominalEnv(t) environment.Integration.Spec.Traits.Keda.Triggers[0].Secrets = []*traitv1.KedaSecret{
