feat(api): add varz endpoint with metrics

This commit is contained in:
Nicolas Carlier 2019-01-06 20:46:49 +00:00
parent 438e49b020
commit 35a2321f80
4 changed files with 69 additions and 0 deletions

View File

@ -30,4 +30,9 @@ var routes = Routes{
"/healtz", "/healtz",
healthz, healthz,
}, },
Route{
"GET",
"/varz",
varz,
},
} }

25
pkg/api/varz.go Normal file
View File

@ -0,0 +1,25 @@
package api
import (
"expvar"
"fmt"
"net/http"
"github.com/ncarlier/webhookd/pkg/config"
)
func varz(conf *config.Config) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
fmt.Fprintf(w, "{\n")
first := true
expvar.Do(func(kv expvar.KeyValue) {
if !first {
fmt.Fprintf(w, ",\n")
}
first = false
fmt.Fprintf(w, "%q: %s", kv.Key, kv.Value)
})
fmt.Fprintf(w, "\n}\n")
})
}

35
pkg/metric/metric.go Normal file
View File

@ -0,0 +1,35 @@
package metric
import (
"expvar"
"runtime"
"time"
)
var startTime = time.Now().UTC()
func goroutines() interface{} {
return runtime.NumGoroutine()
}
// uptime is an expvar.Func compliant wrapper for uptime info.
func uptime() interface{} {
uptime := time.Since(startTime)
return int64(uptime)
}
var stats = expvar.NewMap("hookstats")
var (
// Requests count the number of request
Requests expvar.Int
// RequestsFailed count the number of failed request
RequestsFailed expvar.Int
)
func init() {
stats.Set("requests", &Requests)
stats.Set("requests_failed", &RequestsFailed)
expvar.Publish("goroutines", expvar.Func(goroutines))
expvar.Publish("uptime", expvar.Func(uptime))
}

View File

@ -3,6 +3,8 @@ package worker
import ( import (
"fmt" "fmt"
"github.com/ncarlier/webhookd/pkg/metric"
"github.com/ncarlier/webhookd/pkg/logger" "github.com/ncarlier/webhookd/pkg/logger"
"github.com/ncarlier/webhookd/pkg/model" "github.com/ncarlier/webhookd/pkg/model"
"github.com/ncarlier/webhookd/pkg/notification" "github.com/ncarlier/webhookd/pkg/notification"
@ -42,8 +44,10 @@ func (w Worker) Start() {
case work := <-w.Work: case work := <-w.Work:
// Receive a work request. // Receive a work request.
logger.Debug.Printf("Worker #%d received work request: %s#%d\n", w.ID, work.Name, work.ID) logger.Debug.Printf("Worker #%d received work request: %s#%d\n", w.ID, work.Name, work.ID)
metric.Requests.Add(1)
err := run(&work) err := run(&work)
if err != nil { if err != nil {
metric.RequestsFailed.Add(1)
work.MessageChan <- []byte(fmt.Sprintf("error: %s", err.Error())) work.MessageChan <- []byte(fmt.Sprintf("error: %s", err.Error()))
} else { } else {
work.MessageChan <- []byte("done") work.MessageChan <- []byte("done")