From fd8436cb972221de14561670f1c0575c58530f90 Mon Sep 17 00:00:00 2001
From: geoffrey1330 <israelgeoffrey13@gmail.com>
Date: Fri, 22 Sep 2023 11:08:02 +0100
Subject: [PATCH] Add prepopulated keptn_ metrics to localhost:2222/metrics
 endpoint Signed-off-by: geoffrey1330 <israelgeoffrey13@gmail.com>

---
 lifecycle-operator/main.go                         | 12 ++++++++++++
 ...04-teststep-retrieve-metrics-via-localhost.yaml |  9 +++++++++
 test/testmetrics/metrics/retrieve-metrics2.sh      | 14 ++++++++++++++
 3 files changed, 35 insertions(+)
 create mode 100644 test/testmetrics/metrics/04-teststep-retrieve-metrics-via-localhost.yaml
 create mode 100644 test/testmetrics/metrics/retrieve-metrics2.sh

diff --git a/lifecycle-operator/main.go b/lifecycle-operator/main.go
index 2696070a62..2faeff5bec 100644
--- a/lifecycle-operator/main.go
+++ b/lifecycle-operator/main.go
@@ -17,6 +17,7 @@ limitations under the License.
 package main
 
 import (
+	"context"
 	"flag"
 	"fmt"
 	"log"
@@ -119,6 +120,14 @@ func main() {
 	}
 	provider := metric.NewMeterProvider(metric.WithReader(exporter))
 	meter := provider.Meter("keptn/task")
+
+	keptnLifecycleActive, err := meter.Int64Counter("keptn_lifecycle_active")
+
+	if err != nil {
+		setupLog.Error(err, "unable to create metric keptn_lifecycle_active")
+		os.Exit(1)
+	}
+
 	keptnMeters := telemetry.SetUpKeptnTaskMeters(meter)
 
 	// Start the prometheus HTTP server and pass the exporter Collector to it
@@ -347,6 +356,9 @@ func main() {
 		setupLog.Error(err, "unable to set up ready check")
 		os.Exit(1)
 	}
+
+	// Set the metric value as soon as the operator starts
+	keptnLifecycleActive.Add(context.Background(), 1)
 	if !disableWebhook {
 		webhookBuilder = webhookBuilder.SetCertificateWatcher(
 			certificates.NewCertificateWatcher(
diff --git a/test/testmetrics/metrics/04-teststep-retrieve-metrics-via-localhost.yaml b/test/testmetrics/metrics/04-teststep-retrieve-metrics-via-localhost.yaml
new file mode 100644
index 0000000000..242fde78ba
--- /dev/null
+++ b/test/testmetrics/metrics/04-teststep-retrieve-metrics-via-localhost.yaml
@@ -0,0 +1,9 @@
+apiVersion: kuttl.dev/v1
+kind: TestStep
+commands:
+  - script: ./retrieve-metrics2.sh "keptn_lifecycle_active"
+    validate:
+      assert:
+        - contains:
+            - "keptn_lifecycle_active"
+            
\ No newline at end of file
diff --git a/test/testmetrics/metrics/retrieve-metrics2.sh b/test/testmetrics/metrics/retrieve-metrics2.sh
new file mode 100644
index 0000000000..3fbef1fda9
--- /dev/null
+++ b/test/testmetrics/metrics/retrieve-metrics2.sh
@@ -0,0 +1,14 @@
+#!/bin/bash
+
+# Usage: ./retrieve-metrics.sh <component_name>
+
+component_name=$1
+
+# Replace with the actual URL where the metrics are exposed
+metrics_url="http://localhost:2222/metrics"
+
+# Fetch metrics for the specified component
+metrics=$(curl -s $metrics_url | grep "${component_name}_active")
+
+echo "Metrics for $component_name:"
+echo "$metrics"