Skip to content

Instantly share code, notes, and snippets.

@astoycos
Created April 18, 2023 15:36
Show Gist options
  • Save astoycos/2c42882f70a29c42f6729ca7e1bf04c3 to your computer and use it in GitHub Desktop.
Save astoycos/2c42882f70a29c42f6729ca7e1bf04c3 to your computer and use it in GitHub Desktop.
Quick example of a Prometheus probe in a golang application
// You can edit this code!
// Click here and start typing.
package main
import (
"context"
"fmt"
"time"
"net/http"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
utilruntime "k8s.io/apimachinery/pkg/util/runtime"
utilwait "k8s.io/apimachinery/pkg/util/wait"
"k8s.io/klog/v2"
)
var fake_metric = prometheus.NewCounter(prometheus.CounterOpts{
Name: "fake_metric",
Help: "every-tick",
})
// StartMetricsServer runs the prometheus listener so that KPNG metrics can be collected
// TODO add TLS Auth if configured
func StartMetricsServer(bindAddress string,
stopChan <-chan struct{}) {
mux := http.NewServeMux()
mux.Handle("/metrics", promhttp.Handler())
klog.Infof("Starting metrics server at %s", bindAddress)
go func() {
var server *http.Server
go utilwait.Until(func() {
var err error
server = &http.Server{
Addr: bindAddress,
Handler: mux,
}
err = server.ListenAndServe()
if err != nil && err != http.ErrServerClosed {
utilruntime.HandleError(fmt.Errorf("starting metrics server failed: %v", err))
}
}, 5*time.Second, stopChan)
<-stopChan
klog.Infof("Stopping metrics server %s", server.Addr)
shutdownCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
if err := server.Shutdown(shutdownCtx); err != nil {
klog.Errorf("Error stopping metrics server: %v", err)
}
}()
}
func main() {
fmt.Println("Prometheus demo")
prometheus.MustRegister(fake_metric)
ctx := context.Background()
StartMetricsServer("127.0.0.1:8080", ctx.Done())
// Create a ticker that ticks every second
ticker := time.NewTicker(time.Second)
// Run a Goroutine increment fake counter ever second
go func() {
for {
select {
case <-ticker.C:
fake_metric.Inc()
}
}
}()
// Keep the main Goroutine running indefinitely
select {}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment