Skip to content

Instantly share code, notes, and snippets.

@jamesmcdonald
Created December 5, 2017 09:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jamesmcdonald/aa6864a07c04b2b995f08e832417c5a7 to your computer and use it in GitHub Desktop.
Save jamesmcdonald/aa6864a07c04b2b995f08e832417c5a7 to your computer and use it in GitHub Desktop.
Metricer
// Overcomplicated "healthy" metric generator
package main
import (
"fmt"
"math/rand"
"net/http"
"os"
"strconv"
"time"
)
type metric struct {
name string
value int
}
var getmetrics func(chan<- metric)
func envmetrics(channel chan<- metric) {
healthy, err := strconv.Atoi(os.Getenv("HEALTHY"))
if err != nil {
healthy = 0
}
channel <- metric{name: "healthy", value: healthy}
close(channel)
}
func randmetrics(failpct int) func(chan<- metric) {
seed := rand.NewSource(time.Now().UnixNano())
rs := rand.New(seed)
return func(channel chan<- metric) {
val := rs.Intn(100)
if val < failpct {
val = 0
} else {
val = 1
}
channel <- metric{name: "healthy", value: val}
close(channel)
}
}
func timedmetrics(frequency int, failpct int) func(chan<- metric) {
// Start at a random offset in the frequency
seed := rand.NewSource(time.Now().UnixNano())
rs := rand.New(seed)
offset := rs.Intn(frequency)
start := time.Now().Add(-time.Duration(offset) * time.Second)
return func(channel chan<- metric) {
elapsedsecs := int(time.Since(start).Seconds())
cyclepos := elapsedsecs % frequency
var val int
if (float64(cyclepos)/float64(frequency))*100.0 < float64(failpct) {
val = 0
} else {
val = 1
}
channel <- metric{name: "healthy", value: val}
close(channel)
}
}
func metricHandler(w http.ResponseWriter, r *http.Request) {
channel := make(chan metric)
go getmetrics(channel)
for m := range channel {
fmt.Fprintf(w, "%s %d\r\n", m.name, m.value)
}
}
func main() {
switch len(os.Args) {
case 3:
frequency, err := strconv.Atoi(os.Args[1])
if err != nil {
panic(err)
}
failpct, err := strconv.Atoi(os.Args[2])
if err != nil {
panic(err)
}
getmetrics = timedmetrics(frequency, failpct)
fmt.Printf("Timed mode, loop every %d seconds, failure rate at %d%%\n", frequency, failpct)
case 2:
failpct, err := strconv.Atoi(os.Args[1])
if err != nil {
panic(err)
}
getmetrics = randmetrics(failpct)
fmt.Printf("Random mode, failure rate at %d%%\n", failpct)
default:
getmetrics = envmetrics
fmt.Println("Reporting based on HEALTHY from environment")
}
http.HandleFunc("/metrics", metricHandler)
http.ListenAndServe(":8080", nil)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment