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

davsclaus pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/camel.git


The following commit(s) were added to refs/heads/main by this push:
     new 6608ced0096d CAMEL-22104: camel-jbang-kubernetes - prometheus trait 
(#30845)
6608ced0096d is described below

commit 6608ced0096dd9ac3feaf274b5e88b9d9c029952
Author: Claus Ibsen <[email protected]>
AuthorDate: Thu Nov 26 08:57:20 2026 +0100

    CAMEL-22104: camel-jbang-kubernetes - prometheus trait (#30845)
    
    The prometheus trait names the container port that serves the metrics
    of camel-observability-services (the management port 9876, or the
    application port of a WAR) and creates a PodMonitor of the Prometheus
    Operator that selects the pods of the Deployment. Options: enabled,
    pod-monitor, pod-monitor-labels, container-port, container-port-name
    and path.
    
    The docs of the Jolokia trait show kubectl port-forward to reach Jolokia
    from outside the cluster (CAMEL-22105: no Route or Ingress for it).
    
    Co-Authored-By: Claude Opus 5.5 <[email protected]>
---
 .../pages/camel-jbang-kubernetes-advanced.adoc     |  62 ++++++++-
 .../modules/ROOT/pages/camel-jbang-kubernetes.adoc |   6 +-
 .../core/commands/kubernetes/KubernetesExport.java |  23 ++++
 .../kubernetes/traits/PrometheusTrait.java         | 142 +++++++++++++++++++++
 .../commands/kubernetes/traits/TraitCatalog.java   |   1 +
 .../kubernetes/traits/model/Prometheus.java        | 113 ++++++++++++++++
 .../commands/kubernetes/traits/model/Traits.java   |  15 ++-
 .../commands/kubernetes/KubernetesExportTest.java  |  89 +++++++++++++
 8 files changed, 448 insertions(+), 3 deletions(-)

diff --git 
a/docs/user-manual/modules/ROOT/pages/camel-jbang-kubernetes-advanced.adoc 
b/docs/user-manual/modules/ROOT/pages/camel-jbang-kubernetes-advanced.adoc
index f13c5aced045..6bd6e7b72a53 100644
--- a/docs/user-manual/modules/ROOT/pages/camel-jbang-kubernetes-advanced.adoc
+++ b/docs/user-manual/modules/ROOT/pages/camel-jbang-kubernetes-advanced.adoc
@@ -2,7 +2,7 @@
 
 The xref:camel-jbang-kubernetes.adoc[Kubernetes Plugin] page covers what most 
applications need.
 This page lists the less common settings: the trait options the plugin 
inherited from Camel K,
-running as a CronJob, Knative, and the Jolokia port.
+running as a CronJob, Knative, the Jolokia port and Prometheus metrics.
 
 == Trait options
 
@@ -300,6 +300,66 @@ Example:
 camel kubernetes export Sample.java --trait jolokia.enabled=true --trait 
jolokia.expose=true
 ----
 
+Jolokia gives full JMX access to the application, so it is not exposed outside 
the cluster by a Route or an Ingress.
+To reach it from your machine, forward the port of the pod (or of the Service 
with `jolokia.expose=true`):
+
+[source,bash]
+----
+kubectl port-forward deployment/sample 8778:8778
+----
+
+Then Jolokia answers on `http://localhost:8778/jolokia`.
+
+=== Prometheus trait
+
+Let Prometheus scrape the metrics of the application. The application includes 
`camel-observability-services`, which
+serves the metrics at `/observe/metrics` on the management port (`9876`). The 
trait names that port of the container,
+and creates a `PodMonitor` that selects the pods of the Deployment. The 
`PodMonitor` is a resource of the
+https://prometheus-operator.dev/[Prometheus Operator], which must be installed 
in the cluster.
+
+[cols="2m,1m,5a"]
+|===
+|Property | Type | Description
+
+| prometheus.enabled
+| bool
+| Can be used to enable or disable a trait. All traits share this common 
property. (default `false`).
+
+| prometheus.pod-monitor
+| bool
+| Whether a `PodMonitor` is created (default `true`). Without it, only the 
container port is named, for a Prometheus
+that finds its targets in another way.
+
+| prometheus.pod-monitor-labels
+| []string
+| The labels of the `PodMonitor`, as `key=value`, such as 
`release=prometheus`, so the `podMonitorSelector` of the
+Prometheus resource selects it.
+
+| prometheus.container-port
+| int
+| The port of the container that serves the metrics (default the management 
port, `9876`; for a WAR, the port of the
+application, which serves the management endpoints).
+
+| prometheus.container-port-name
+| string
+| The name of the container port (default `management`). A port that the 
container already has for the same number,
+such as `http`, keeps its name.
+
+| prometheus.path
+| string
+| The path of the metrics (default `/observe/metrics`).
+
+|===
+
+The trait applies to a Deployment: a CronJob ends before it is scraped, and a 
Knative service has one port only.
+
+Example:
+
+[source,bash]
+----
+camel kubernetes run * --trait prometheus.enabled=true --trait 
prometheus.pod-monitor-labels=release=prometheus
+----
+
 
 === Mount trait
 
diff --git a/docs/user-manual/modules/ROOT/pages/camel-jbang-kubernetes.adoc 
b/docs/user-manual/modules/ROOT/pages/camel-jbang-kubernetes.adoc
index e5241b56885b..f65e65e0e15d 100644
--- a/docs/user-manual/modules/ROOT/pages/camel-jbang-kubernetes.adoc
+++ b/docs/user-manual/modules/ROOT/pages/camel-jbang-kubernetes.adoc
@@ -241,6 +241,10 @@ The application includes `camel-observability-services`, 
and the Deployment gets
 - Spring Boot: `/observe/health/liveness`, `/observe/health/readiness`
 - Quarkus: `/observe/health/live`, `/observe/health/ready`, 
`/observe/health/started`
 
+The metrics are at `/observe/metrics`. With the Prometheus Operator in the 
cluster, `--trait prometheus.enabled=true`
+creates a `PodMonitor` for them (see
+xref:camel-jbang-kubernetes-advanced.adoc#_prometheus_trait[Kubernetes Plugin 
Advanced Options]).
+
 == Exposing HTTP endpoints
 
 When your routes consume HTTP (such as `platform-http` or the REST DSL), a 
Service is generated for the container port (`8080`)
@@ -346,4 +350,4 @@ with `--cluster-type=minikube`, `run` prints a hint when it 
is not.
 
 xref:camel-jbang-kubernetes-advanced.adoc[Kubernetes Plugin Advanced Options] 
covers the trait options inherited from Camel K:
 the full container, Service, Ingress and OpenShift Route settings, running as 
a CronJob, Knative serving and eventing,
-the Jolokia port, mounts, and OpenAPI specs from ConfigMaps.
+the Jolokia port, Prometheus metrics, mounts, and OpenAPI specs from 
ConfigMaps.
diff --git 
a/dsl/camel-jbang/camel-jbang-plugin-kubernetes/src/main/java/org/apache/camel/dsl/jbang/core/commands/kubernetes/KubernetesExport.java
 
b/dsl/camel-jbang/camel-jbang-plugin-kubernetes/src/main/java/org/apache/camel/dsl/jbang/core/commands/kubernetes/KubernetesExport.java
index 65228c2db48a..d649d0ab0418 100644
--- 
a/dsl/camel-jbang/camel-jbang-plugin-kubernetes/src/main/java/org/apache/camel/dsl/jbang/core/commands/kubernetes/KubernetesExport.java
+++ 
b/dsl/camel-jbang/camel-jbang-plugin-kubernetes/src/main/java/org/apache/camel/dsl/jbang/core/commands/kubernetes/KubernetesExport.java
@@ -40,9 +40,13 @@ import 
org.apache.camel.dsl.jbang.core.commands.MavenResolverMixin;
 import org.apache.camel.dsl.jbang.core.commands.QuarkusPlatformMixin;
 import org.apache.camel.dsl.jbang.core.commands.Run;
 import org.apache.camel.dsl.jbang.core.commands.RunHelper;
+import 
org.apache.camel.dsl.jbang.core.commands.kubernetes.traits.ContainerTrait;
+import 
org.apache.camel.dsl.jbang.core.commands.kubernetes.traits.PrometheusTrait;
 import org.apache.camel.dsl.jbang.core.commands.kubernetes.traits.TraitCatalog;
 import org.apache.camel.dsl.jbang.core.commands.kubernetes.traits.TraitContext;
 import org.apache.camel.dsl.jbang.core.commands.kubernetes.traits.TraitHelper;
+import 
org.apache.camel.dsl.jbang.core.commands.kubernetes.traits.model.Container;
+import 
org.apache.camel.dsl.jbang.core.commands.kubernetes.traits.model.Prometheus;
 import org.apache.camel.dsl.jbang.core.commands.kubernetes.traits.model.Traits;
 import org.apache.camel.dsl.jbang.core.common.CommandLineHelper;
 import org.apache.camel.dsl.jbang.run.RunPipeline;
@@ -406,6 +410,7 @@ public class KubernetesExport extends Export {
         } else {
             setContainerHealthPaths(managementPort);
         }
+        setMetricsPort(traitsSpec, managementPort);
 
         // Run export
         int exit = super.doExport();
@@ -539,6 +544,24 @@ public class KubernetesExport extends Export {
         return "war".equalsIgnoreCase(packaging);
     }
 
+    /**
+     * The port the prometheus trait scrapes, when not given: the management 
port of camel-observability-services, or
+     * the port of the application for a WAR, which serves the management 
endpoints on it.
+     */
+    private void setMetricsPort(Traits traitsSpec, int managementPort) {
+        Prometheus prometheus = traitsSpec.getPrometheus();
+        if (prometheus == null || prometheus.getContainerPort() != null) {
+            return;
+        }
+        long port = managementPort > 0 ? managementPort : 
PrometheusTrait.DEFAULT_METRICS_PORT;
+        if (RuntimeType.springBoot == runtime && isWarPackaging()) {
+            port = Optional.ofNullable(traitsSpec.getContainer())
+                    .map(Container::getPort)
+                    .orElse((long) ContainerTrait.DEFAULT_CONTAINER_PORT);
+        }
+        prometheus.setContainerPort(port);
+    }
+
     private void setContainerHealthPaths(int port) {
         // the camel-observability-services artifact is added as dependency if 
observe=true in run command
         // it renames the container health base path to /observe, so this has 
to be in the container health probes http path
diff --git 
a/dsl/camel-jbang/camel-jbang-plugin-kubernetes/src/main/java/org/apache/camel/dsl/jbang/core/commands/kubernetes/traits/PrometheusTrait.java
 
b/dsl/camel-jbang/camel-jbang-plugin-kubernetes/src/main/java/org/apache/camel/dsl/jbang/core/commands/kubernetes/traits/PrometheusTrait.java
new file mode 100644
index 000000000000..d35f09a11f03
--- /dev/null
+++ 
b/dsl/camel-jbang/camel-jbang-plugin-kubernetes/src/main/java/org/apache/camel/dsl/jbang/core/commands/kubernetes/traits/PrometheusTrait.java
@@ -0,0 +1,142 @@
+/*
+ * 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 org.apache.camel.dsl.jbang.core.commands.kubernetes.traits;
+
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Optional;
+
+import io.fabric8.kubernetes.api.model.ContainerPort;
+import io.fabric8.kubernetes.api.model.GenericKubernetesResourceBuilder;
+import 
org.apache.camel.dsl.jbang.core.commands.kubernetes.traits.model.Prometheus;
+import org.apache.camel.dsl.jbang.core.commands.kubernetes.traits.model.Traits;
+import org.apache.camel.dsl.jbang.core.common.CliException;
+
+/**
+ * Lets Prometheus scrape the metrics of the integration, which 
camel-observability-services serves on the management
+ * port: names the container port of the metrics, and creates a PodMonitor of 
the Prometheus Operator for the pods of
+ * the Deployment.
+ */
+public class PrometheusTrait extends BaseTrait {
+
+    public static final int PROMETHEUS_TRAIT_ORDER = 1900;
+
+    public static final int DEFAULT_METRICS_PORT = 9876;
+    public static final String DEFAULT_METRICS_PORT_NAME = "management";
+    public static final String DEFAULT_METRICS_PATH = "/observe/metrics";
+
+    public static final String POD_MONITOR_API_VERSION = 
"monitoring.coreos.com/v1";
+    public static final String POD_MONITOR_KIND = "PodMonitor";
+
+    public PrometheusTrait() {
+        super("prometheus", PROMETHEUS_TRAIT_ORDER);
+    }
+
+    @Override
+    public boolean configure(Traits traitConfig, TraitContext context) {
+        // must be explicitly enabled
+        if (traitConfig.getPrometheus() == null
+                || 
!Optional.ofNullable(traitConfig.getPrometheus().getEnabled()).orElse(false)) {
+            return false;
+        }
+        // a mistake in the labels fails the export, before the manifest is 
built
+        labels(traitConfig.getPrometheus().getPodMonitorLabels());
+        if (context.getDeployment().isEmpty()) {
+            // a CronJob ends before it is scraped, and a Knative service has 
one port only
+            context.printer().println("The prometheus trait applies to a 
Deployment only, and is skipped");
+            return false;
+        }
+        return true;
+    }
+
+    @Override
+    public void apply(Traits traitConfig, TraitContext context) {
+        Prometheus prometheus = 
Optional.ofNullable(traitConfig.getPrometheus()).orElseGet(Prometheus::new);
+        int port = 
Optional.ofNullable(prometheus.getContainerPort()).map(Long::intValue).orElse(DEFAULT_METRICS_PORT);
+
+        // the port may be declared already, such as the http port of a WAR, 
which serves the management endpoints
+        Optional<ContainerPort> existing = context.getDeployment()
+                .map(d -> d.buildSpec())
+                .map(s -> s.getTemplate())
+                .map(t -> t.getSpec())
+                .map(s -> s.getContainers())
+                .filter(c -> !c.isEmpty())
+                .map(c -> c.get(0).getPorts())
+                .flatMap(ports -> ports.stream().filter(p -> 
Objects.equals(p.getContainerPort(), port)).findFirst());
+        String portName = existing.map(ContainerPort::getName)
+                .orElseGet(() -> 
Optional.ofNullable(prometheus.getContainerPortName()).orElse(DEFAULT_METRICS_PORT_NAME));
+        if (existing.isEmpty()) {
+            context.doWithDeployments(
+                    d -> d.editSpec()
+                            .editOrNewTemplate()
+                            .editOrNewSpec()
+                            .editFirstContainer()
+                            .addNewPort()
+                            .withName(portName)
+                            .withContainerPort(port)
+                            .withProtocol("TCP")
+                            .endPort()
+                            .endContainer()
+                            .endSpec()
+                            .endTemplate()
+                            .endSpec());
+        }
+
+        if (Optional.ofNullable(prometheus.getPodMonitor()).orElse(true)) {
+            context.add(podMonitor(context.getName(), portName,
+                    
Optional.ofNullable(prometheus.getPath()).orElse(DEFAULT_METRICS_PATH),
+                    labels(prometheus.getPodMonitorLabels())));
+        }
+    }
+
+    private static GenericKubernetesResourceBuilder podMonitor(
+            String name, String portName, String path, Map<String, String> 
labels) {
+        Map<String, Object> endpoint = new LinkedHashMap<>();
+        endpoint.put("port", portName);
+        endpoint.put("path", path);
+        Map<String, Object> spec = new LinkedHashMap<>();
+        spec.put("selector", Map.of("matchLabels", 
Map.of(KUBERNETES_LABEL_NAME, name)));
+        spec.put("podMetricsEndpoints", List.of(endpoint));
+
+        GenericKubernetesResourceBuilder builder = new 
GenericKubernetesResourceBuilder()
+                .withApiVersion(POD_MONITOR_API_VERSION)
+                .withKind(POD_MONITOR_KIND)
+                .withNewMetadata()
+                .withName(name)
+                .endMetadata()
+                .addToAdditionalProperties("spec", spec);
+        if (!labels.isEmpty()) {
+            builder.editMetadata().withLabels(labels).endMetadata();
+        }
+        return builder;
+    }
+
+    private static Map<String, String> labels(List<String> keyValues) {
+        Map<String, String> answer = new LinkedHashMap<>();
+        for (String keyValue : 
Optional.ofNullable(keyValues).orElseGet(List::of)) {
+            String[] parts = keyValue.split("=", 2);
+            if (parts.length != 2 || parts[0].isBlank()) {
+                throw CliException.usage(
+                        "The prometheus trait takes pod-monitor-labels as 
key=value, not: " + keyValue);
+            }
+            answer.put(parts[0].trim(), parts[1].trim());
+        }
+        return answer;
+    }
+}
diff --git 
a/dsl/camel-jbang/camel-jbang-plugin-kubernetes/src/main/java/org/apache/camel/dsl/jbang/core/commands/kubernetes/traits/TraitCatalog.java
 
b/dsl/camel-jbang/camel-jbang-plugin-kubernetes/src/main/java/org/apache/camel/dsl/jbang/core/commands/kubernetes/traits/TraitCatalog.java
index b8642e08c64f..40571cbf8d51 100644
--- 
a/dsl/camel-jbang/camel-jbang-plugin-kubernetes/src/main/java/org/apache/camel/dsl/jbang/core/commands/kubernetes/traits/TraitCatalog.java
+++ 
b/dsl/camel-jbang/camel-jbang-plugin-kubernetes/src/main/java/org/apache/camel/dsl/jbang/core/commands/kubernetes/traits/TraitCatalog.java
@@ -53,6 +53,7 @@ public class TraitCatalog {
         register(new AnnotationTrait());
         register(new CamelTrait());
         register(new JolokiaTrait());
+        register(new PrometheusTrait());
     }
 
     public List<Trait> allTraits() {
diff --git 
a/dsl/camel-jbang/camel-jbang-plugin-kubernetes/src/main/java/org/apache/camel/dsl/jbang/core/commands/kubernetes/traits/model/Prometheus.java
 
b/dsl/camel-jbang/camel-jbang-plugin-kubernetes/src/main/java/org/apache/camel/dsl/jbang/core/commands/kubernetes/traits/model/Prometheus.java
new file mode 100644
index 000000000000..87dde802df0d
--- /dev/null
+++ 
b/dsl/camel-jbang/camel-jbang-plugin-kubernetes/src/main/java/org/apache/camel/dsl/jbang/core/commands/kubernetes/traits/model/Prometheus.java
@@ -0,0 +1,113 @@
+/*
+ * 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 org.apache.camel.dsl.jbang.core.commands.kubernetes.traits.model;
+
+import java.util.List;
+
+import com.fasterxml.jackson.annotation.JsonInclude;
+import com.fasterxml.jackson.annotation.JsonProperty;
+import com.fasterxml.jackson.annotation.JsonPropertyDescription;
+import com.fasterxml.jackson.annotation.JsonPropertyOrder;
+import com.fasterxml.jackson.annotation.JsonSetter;
+import com.fasterxml.jackson.annotation.Nulls;
+
+@JsonInclude(JsonInclude.Include.NON_NULL)
+@JsonPropertyOrder({
+        "enabled", "podMonitor", "podMonitorLabels", "containerPort", 
"containerPortName", "path" })
+public class Prometheus {
+
+    @JsonProperty("enabled")
+    @JsonPropertyDescription("Can be used to enable or disable a trait.")
+    @JsonSetter(nulls = Nulls.SKIP)
+    private Boolean enabled;
+
+    @JsonProperty("podMonitor")
+    @JsonPropertyDescription("Whether a PodMonitor resource is created 
(default `true`). The PodMonitor needs the Prometheus Operator in the cluster.")
+    @JsonSetter(nulls = Nulls.SKIP)
+    private Boolean podMonitor;
+
+    @JsonProperty("podMonitorLabels")
+    @JsonPropertyDescription("The labels of the PodMonitor, such as 
`release=prometheus`, so the Prometheus Operator selects it.")
+    @JsonSetter(nulls = Nulls.SKIP)
+    private List<String> podMonitorLabels;
+
+    @JsonProperty("containerPort")
+    @JsonPropertyDescription("The port of the container that serves the 
metrics (default the management port, `9876`).")
+    @JsonSetter(nulls = Nulls.SKIP)
+    private Long containerPort;
+
+    @JsonProperty("containerPortName")
+    @JsonPropertyDescription("The name of the container port that serves the 
metrics (default `management`). A port the container already has for the same 
number keeps its name.")
+    @JsonSetter(nulls = Nulls.SKIP)
+    private String containerPortName;
+
+    @JsonProperty("path")
+    @JsonPropertyDescription("The path of the metrics (default 
`/observe/metrics`).")
+    @JsonSetter(nulls = Nulls.SKIP)
+    private String path;
+
+    public Prometheus() {
+    }
+
+    public Boolean getEnabled() {
+        return enabled;
+    }
+
+    public void setEnabled(Boolean enabled) {
+        this.enabled = enabled;
+    }
+
+    public Boolean getPodMonitor() {
+        return podMonitor;
+    }
+
+    public void setPodMonitor(Boolean podMonitor) {
+        this.podMonitor = podMonitor;
+    }
+
+    public List<String> getPodMonitorLabels() {
+        return podMonitorLabels;
+    }
+
+    public void setPodMonitorLabels(List<String> podMonitorLabels) {
+        this.podMonitorLabels = podMonitorLabels;
+    }
+
+    public Long getContainerPort() {
+        return containerPort;
+    }
+
+    public void setContainerPort(Long containerPort) {
+        this.containerPort = containerPort;
+    }
+
+    public String getContainerPortName() {
+        return containerPortName;
+    }
+
+    public void setContainerPortName(String containerPortName) {
+        this.containerPortName = containerPortName;
+    }
+
+    public String getPath() {
+        return path;
+    }
+
+    public void setPath(String path) {
+        this.path = path;
+    }
+}
diff --git 
a/dsl/camel-jbang/camel-jbang-plugin-kubernetes/src/main/java/org/apache/camel/dsl/jbang/core/commands/kubernetes/traits/model/Traits.java
 
b/dsl/camel-jbang/camel-jbang-plugin-kubernetes/src/main/java/org/apache/camel/dsl/jbang/core/commands/kubernetes/traits/model/Traits.java
index 496663f9c61b..09814d178e89 100644
--- 
a/dsl/camel-jbang/camel-jbang-plugin-kubernetes/src/main/java/org/apache/camel/dsl/jbang/core/commands/kubernetes/traits/model/Traits.java
+++ 
b/dsl/camel-jbang/camel-jbang-plugin-kubernetes/src/main/java/org/apache/camel/dsl/jbang/core/commands/kubernetes/traits/model/Traits.java
@@ -30,7 +30,7 @@ import com.fasterxml.jackson.annotation.Nulls;
 @JsonPropertyOrder({
         "camel", "container", "cronjob", "environment", "ingress", "knative", 
"knative-service", "mount", "openapi", "pod",
         "route",
-        "service", "service-binding", "jolokia" })
+        "service", "service-binding", "jolokia", "prometheus" })
 public class Traits {
 
     @JsonProperty("addons")
@@ -103,6 +103,11 @@ public class Traits {
     @JsonSetter(nulls = Nulls.SKIP)
     private Jolokia jolokia;
 
+    @JsonProperty("prometheus")
+    @JsonPropertyDescription("The configuration of Prometheus trait")
+    @JsonSetter(nulls = Nulls.SKIP)
+    private Prometheus prometheus;
+
     public Map<String, Addons> getAddons() {
         return this.addons;
     }
@@ -199,6 +204,14 @@ public class Traits {
         this.jolokia = jolokia;
     }
 
+    public Prometheus getPrometheus() {
+        return prometheus;
+    }
+
+    public void setPrometheus(Prometheus prometheus) {
+        this.prometheus = prometheus;
+    }
+
     public Service getService() {
         return service;
     }
diff --git 
a/dsl/camel-jbang/camel-jbang-plugin-kubernetes/src/test/java/org/apache/camel/dsl/jbang/core/commands/kubernetes/KubernetesExportTest.java
 
b/dsl/camel-jbang/camel-jbang-plugin-kubernetes/src/test/java/org/apache/camel/dsl/jbang/core/commands/kubernetes/KubernetesExportTest.java
index 7763ba168624..5fc0389b0a0e 100644
--- 
a/dsl/camel-jbang/camel-jbang-plugin-kubernetes/src/test/java/org/apache/camel/dsl/jbang/core/commands/kubernetes/KubernetesExportTest.java
+++ 
b/dsl/camel-jbang/camel-jbang-plugin-kubernetes/src/test/java/org/apache/camel/dsl/jbang/core/commands/kubernetes/KubernetesExportTest.java
@@ -16,15 +16,21 @@
  */
 package org.apache.camel.dsl.jbang.core.commands.kubernetes;
 
+import java.io.File;
 import java.io.FileInputStream;
+import java.io.IOException;
 import java.io.InputStream;
 import java.nio.file.Files;
 import java.nio.file.Path;
 import java.util.List;
+import java.util.Map;
 import java.util.Properties;
 import java.util.stream.Stream;
 
 import io.fabric8.kubernetes.api.model.Container;
+import io.fabric8.kubernetes.api.model.ContainerPort;
+import io.fabric8.kubernetes.api.model.GenericKubernetesResource;
+import io.fabric8.kubernetes.api.model.HasMetadata;
 import io.fabric8.kubernetes.api.model.Service;
 import io.fabric8.kubernetes.api.model.ServicePort;
 import io.fabric8.kubernetes.api.model.Volume;
@@ -969,6 +975,89 @@ class KubernetesExportTest extends 
KubernetesExportBaseTestSupport {
         Assertions.assertEquals("quay.io/camel/demo-app:1.0", 
props.get("jkube.container-image.name"));
     }
 
+    @ParameterizedTest
+    @SuppressWarnings("unchecked")
+    @MethodSource("runtimeProvider")
+    public void shouldAddPrometheusPodMonitor(RuntimeType rt) throws Exception 
{
+        // CAMEL-22104
+        KubernetesExport command = createCommand(new String[] { 
"classpath:route-service.yaml" },
+                "--trait", "prometheus.enabled=true",
+                "--trait", 
"prometheus.pod-monitor-labels=release=prometheus,team=orders",
+                "--runtime=" + rt.runtime());
+        Assertions.assertEquals(0, command.doCall());
+
+        Container container = 
getDeployment(rt).getSpec().getTemplate().getSpec().getContainers().get(0);
+        ContainerPort metrics = container.getPorts().stream()
+                .filter(p -> "management".equals(p.getName())).findFirst()
+                .orElseThrow(() -> new RuntimeCamelException("No management 
port: " + container.getPorts()));
+        Assertions.assertEquals(9876, metrics.getContainerPort());
+
+        GenericKubernetesResource podMonitor = getPodMonitor();
+        Assertions.assertEquals("monitoring.coreos.com/v1", 
podMonitor.getApiVersion());
+        Assertions.assertEquals("route-service", 
podMonitor.getMetadata().getName());
+        Assertions.assertEquals(Map.of("release", "prometheus", "team", 
"orders"), podMonitor.getMetadata().getLabels());
+        Map<String, Object> spec = (Map<String, Object>) 
podMonitor.getAdditionalProperties().get("spec");
+        Assertions.assertEquals(Map.of("matchLabels", 
Map.of(BaseTrait.KUBERNETES_LABEL_NAME, "route-service")),
+                spec.get("selector"));
+        Assertions.assertEquals(List.of(Map.of("port", "management", "path", 
"/observe/metrics")),
+                spec.get("podMetricsEndpoints"));
+    }
+
+    @Test
+    public void shouldAddPrometheusPortWithoutPodMonitor() throws Exception {
+        KubernetesExport command = createCommand(new String[] { 
"classpath:route-service.yaml" },
+                "--trait", "prometheus.enabled=true",
+                "--trait", "prometheus.pod-monitor=false",
+                "--trait", "prometheus.container-port=9100",
+                "--trait", "prometheus.container-port-name=metrics",
+                "--runtime=" + RuntimeType.main.runtime());
+        Assertions.assertEquals(0, command.doCall());
+
+        Container container = 
getDeployment(RuntimeType.main).getSpec().getTemplate().getSpec().getContainers().get(0);
+        Assertions.assertTrue(container.getPorts().stream()
+                .anyMatch(p -> "metrics".equals(p.getName()) && 
p.getContainerPort() == 9100), container.getPorts().toString());
+        
Assertions.assertFalse(workingDir.toPath().resolve("src/main/jkube/podmonitor.yml").toFile().exists());
+    }
+
+    @SuppressWarnings("unchecked")
+    @Test
+    public void shouldScrapeTheHttpPortThatServesTheMetrics() throws Exception 
{
+        // the port of the metrics is the http port of the container: its name 
is kept, and no port is added
+        KubernetesExport command = createCommand(new String[] { 
"classpath:route-service.yaml" },
+                "--trait", "prometheus.enabled=true",
+                "--trait", "prometheus.container-port=8080",
+                "--runtime=" + RuntimeType.main.runtime());
+        Assertions.assertEquals(0, command.doCall());
+
+        Container container = 
getDeployment(RuntimeType.main).getSpec().getTemplate().getSpec().getContainers().get(0);
+        Assertions.assertEquals(1, container.getPorts().stream().filter(p -> 
p.getContainerPort() == 8080).count(),
+                container.getPorts().toString());
+        Map<String, Object> spec = (Map<String, Object>) 
getPodMonitor().getAdditionalProperties().get("spec");
+        Assertions.assertEquals(List.of(Map.of("port", "http", "path", 
"/observe/metrics")),
+                spec.get("podMetricsEndpoints"));
+    }
+
+    @Test
+    public void shouldRejectAPodMonitorLabelWithoutValue() throws Exception {
+        KubernetesExport command = createCommand(new String[] { 
"classpath:route-service.yaml" },
+                "--trait", "prometheus.enabled=true",
+                "--trait", "prometheus.pod-monitor-labels=release",
+                "--runtime=" + RuntimeType.main.runtime());
+        CliException e = Assertions.assertThrows(CliException.class, 
command::doCall);
+        Assertions.assertEquals(CliExitCode.USAGE, e.getExitCode());
+        Assertions.assertTrue(e.getMessage().contains("pod-monitor-labels as 
key=value"), e.getMessage());
+    }
+
+    private GenericKubernetesResource getPodMonitor() throws IOException {
+        File file = 
workingDir.toPath().resolve("src/main/jkube/podmonitor.yml").toFile();
+        Assertions.assertTrue(file.isFile(), "No PodMonitor: " + file);
+        try (FileInputStream fis = new FileInputStream(file)) {
+            HasMetadata resource = kubernetesClient.load(fis).items().get(0);
+            Assertions.assertEquals("PodMonitor", resource.getKind());
+            return (GenericKubernetesResource) resource;
+        }
+    }
+
     @ParameterizedTest
     @MethodSource("runtimeProvider")
     public void shouldAddJolokiaSpec(RuntimeType rt) throws Exception {

Reply via email to