Skip to content

Commit

Permalink
feat(RHTAPWATCH-570): Update exporters code with actual metrics
Browse files Browse the repository at this point in the history
Update the dsexporter code and related unit tests with
actual metrics.

Signed-off-by: Homaja Marisetty <[email protected]>
  • Loading branch information
hmariset committed Jan 30, 2024
1 parent c1b5f5e commit ca50e57
Show file tree
Hide file tree
Showing 2 changed files with 68 additions and 16 deletions.
45 changes: 38 additions & 7 deletions exporters/dsexporter/dsexporter.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,31 +9,57 @@ import (
)

type CustomCollector struct {
requestCounter prometheus.Counter
konfluxProbeSuccess *prometheus.GaugeVec
}

// Creating a new instance of CustomCollector.
func NewCustomCollector() *CustomCollector {
return &CustomCollector{
requestCounter: prometheus.NewCounter(prometheus.CounterOpts{
Name: "request_count",
Help: "Number of requests handled by the handler",
}),
konfluxProbeSuccess: prometheus.NewGaugeVec(prometheus.GaugeOpts{
Name: "konflux_probe_success",
Help: "Availability of konflux service/component",
},
[]string{"service", "check"}),
}
}

// Describe method sends descriptions of the metrics to Prometheus.
// When Prometheus scrapes the /metrics endpoint of the exporter,
// it first calls the Describe method to get a description of all the metrics.
func (e *CustomCollector) Describe(ch chan<- *prometheus.Desc) {
e.requestCounter.Describe(ch)
e.konfluxProbeSuccess.Describe(ch)
}

// Collect method sends the current values of the metrics to Prometheus.
// After Prometheus understands what metrics are available (using the `Describe` method),
// it then calls the `Collect` method to actually get the values of those metrics.
func (e *CustomCollector) Collect(ch chan<- prometheus.Metric) {
e.requestCounter.Collect(ch)
e.konfluxProbeSuccess.Collect(ch)
}

func availabilityHandler(response http.ResponseWriter, req *http.Request, exporter *CustomCollector) {
service := req.URL.Query().Get("service")
check := req.URL.Query().Get("check")
availability := checkIfServiceUp(service)

exporter.konfluxProbeSuccess.WithLabelValues("service", "check").Set(availability)
fmt.Fprintf(response, "Service: %s, Check Name: %s, Availability: %f", service, check, availability)
}

func checkIfServiceUp(service string) float64 {
serviceUrl := "https://" + service

resp, err := http.Get(serviceUrl)
if err != nil {
return 0
}

defer resp.Body.Close()
if resp.StatusCode == http.StatusOK {
return 1
} else {
return 0
}
}

// Using a separate pedantic registry ensures that only your custom metric is exposed on the "/metrics" endpoint,
Expand All @@ -43,13 +69,18 @@ func main() {
exporter := NewCustomCollector()
reg.MustRegister(exporter)

http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
availabilityHandler(w, r, exporter)
})

http.Handle("/metrics", promhttp.HandlerFor(
reg,
promhttp.HandlerOpts{
EnableOpenMetrics: true,
Registry: reg,
},
))

fmt.Println("Server is listening on http://localhost:8090/metrics")
http.ListenAndServe(":8090", nil)
}
39 changes: 30 additions & 9 deletions exporters/dsexporter/dsexporter_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ package main

import (
"testing"
"net/http"
"net/http/httptest"

"github.com/prometheus/client_golang/prometheus"
"github.com/stretchr/testify/assert"
Expand All @@ -16,31 +18,50 @@ func TestCustomCollector(t *testing.T) {
metricFamilies, err := metrics.Gather()
assert.NoError(t, err)

var RequestCountValue float64
var konfluxProbeSuccessValue float64
for _, mf := range metricFamilies {
if mf.GetName() == "request_count" {
RequestCountValue = mf.GetMetric()[0].GetCounter().GetValue()
if mf.GetName() == "konflux_probe_success" {
konfluxProbeSuccessValue = mf.GetMetric()[0].GetCounter().GetValue()
break
}
}

// Check whether the exported metric value is initially 0.
assert.Equal(t, float64(0), RequestCountValue)
assert.Equal(t, float64(0), konfluxProbeSuccessValue)

// Increment the requestCounter by calling the Inc method.
exporter.requestCounter.Inc()
// Increment the konfluxProbeSuccess by calling the Inc method.
exporter.konfluxProbeSuccess.With(prometheus.Labels{"service":"test_service", "check":"github"}).Inc()

// Collecting metrics again
metricFamilies, err = metrics.Gather()
assert.NoError(t, err)

for _, mf := range metricFamilies {
if mf.GetName() == "request_count" {
RequestCountValue = mf.GetMetric()[0].GetCounter().GetValue()
if mf.GetName() == "konflux_probe_success" {
konfluxProbeSuccessValue = mf.GetMetric()[0].GetCounter().GetValue()
break
}
}

// Check whether the exported metric value is now 1 after incrementing.
assert.Equal(t, float64(1), RequestCountValue)
assert.Equal(t, float64(1), konfluxProbeSuccessValue)
}

func TestcheckIfServiceUp(t *testing.T) {
exporter := NewCustomCollector()
mockHandler := http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {

Check failure on line 52 in exporters/dsexporter/dsexporter_test.go

View check run for this annotation

Red Hat Konflux / Red Hat Trusted App Pipeline / o11y-on-pull-request

exporters/dsexporter/dsexporter_test.go#L52

http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {…}) (no value) used as value
w.WriteHeader(http.StatusOK)
availabilityHandler(w, r, exporter)
})

mockServer :=httptest.NewServer(mockHandler)
defer mockServer.Close()

serviceUrl := mockServer.URL

available := checkIfServiceUp(serviceUrl)

if available == 0 {
t.Error("Service not accessible")
}
}

0 comments on commit ca50e57

Please sign in to comment.