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 31, 2024
1 parent c1b5f5e commit 2ac8ebf
Show file tree
Hide file tree
Showing 2 changed files with 112 additions and 37 deletions.
52 changes: 45 additions & 7 deletions exporters/dsexporter/dsexporter.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,37 +3,70 @@ package main
import (
"fmt"
"net/http"
"time"

"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
)

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
timeout := 10 * time.Second

//http client with timeout
client := &http.Client{
Timeout: timeout,
}

resp, err := client.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 +76,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)
}
97 changes: 67 additions & 30 deletions exporters/dsexporter/dsexporter_test.go
Original file line number Diff line number Diff line change
@@ -1,46 +1,83 @@
package main

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

"github.com/prometheus/client_golang/prometheus"
"github.com/stretchr/testify/assert"
"github.com/prometheus/client_golang/prometheus/promhttp"
)

func TestCustomCollector(t *testing.T) {
exporter := NewCustomCollector()
prometheus.MustRegister(exporter)

// Simulate collecting metrics and check the exported metric value.
metrics := prometheus.DefaultGatherer
metricFamilies, err := metrics.Gather()
assert.NoError(t, err)

var RequestCountValue float64
for _, mf := range metricFamilies {
if mf.GetName() == "request_count" {
RequestCountValue = mf.GetMetric()[0].GetCounter().GetValue()
break
}
func TestAvailabilityHandler(t *testing.T) {
mockExporter := NewCustomCollector()

req, err := http.NewRequest("GET", "/?service=test.com&check=test", nil)
if err != nil {
t.Fatal(err)
}

// Check whether the exported metric value is initially 0.
assert.Equal(t, float64(0), RequestCountValue)
rec := httptest.NewRecorder()
availabilityHandler(rec, req, mockExporter)

// Increment the requestCounter by calling the Inc method.
exporter.requestCounter.Inc()
if status := rec.Code; status != http.StatusOK {
t.Errorf("Service unavailable")
}

// Collecting metrics again
metricFamilies, err = metrics.Gather()
assert.NoError(t, err)
expected := fmt.Sprintf("Service: test.com, Check Name: test, Availability:",)
assert.Contains(t, rec.Body.String(), expected)
}

for _, mf := range metricFamilies {
if mf.GetName() == "request_count" {
RequestCountValue = mf.GetMetric()[0].GetCounter().GetValue()
break
}
func TestcheckIfServiceUpPass(t *testing.T) {
mockServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
}))
defer mockServer.Close()

serviceUrl := mockServer.URL

available := checkIfServiceUp(serviceUrl)

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

func TestcheckIfServiceUpFail(t *testing.T) {
mockServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusNoContent)
}))
defer mockServer.Close()

serviceUrl := mockServer.URL

// Check whether the exported metric value is now 1 after incrementing.
assert.Equal(t, float64(1), RequestCountValue)
available := checkIfServiceUp(serviceUrl)

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

func TestCustomCollector(t *testing.T) {

mockServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {

if r.URL.Path == "/metrics" {
promhttp.Handler().ServeHTTP(w, r)
return
}

}))

defer mockServer.Close()

resp, err := http.Get(mockServer.URL + "/metrics")
if err != nil {
t.Fatal(err)
}

if resp.StatusCode != http.StatusOK {
t.Errorf("Service unavailable")
}
}

0 comments on commit 2ac8ebf

Please sign in to comment.