Skip to content

Commit

Permalink
api/prometheus: add prometheus metrics to API routes
Browse files Browse the repository at this point in the history
  • Loading branch information
jzelinskie committed Feb 24, 2016
1 parent f8b4a52 commit 83b19b6
Show file tree
Hide file tree
Showing 4 changed files with 239 additions and 131 deletions.
29 changes: 23 additions & 6 deletions api/context/context.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,28 +15,45 @@
package context

import (
"fmt"
"net/http"
"strconv"
"time"

"github.com/coreos/pkg/capnslog"
"github.com/julienschmidt/httprouter"
"github.com/prometheus/client_golang/prometheus"

"github.com/coreos/clair/database"
"github.com/coreos/clair/utils"
)

var log = capnslog.NewPackageLogger("github.com/coreos/clair", "api")
var (
log = capnslog.NewPackageLogger("github.com/coreos/clair", "api")

type Handler func(http.ResponseWriter, *http.Request, httprouter.Params, *RouteContext) int
promResponseDurationMilliseconds = prometheus.NewHistogramVec(prometheus.HistogramOpts{
Name: "clair_api_response_duration_milliseconds",
Help: "The duration of time it takes to receieve and write a response to an API request",
Buckets: prometheus.ExponentialBuckets(9.375, 2, 10),
}, []string{"route", "code"})
)

func init() {
prometheus.MustRegister(promResponseDurationMilliseconds)
}

type Handler func(http.ResponseWriter, *http.Request, httprouter.Params, *RouteContext) (route string, status int)

func HTTPHandler(handler Handler, ctx *RouteContext) httprouter.Handle {
return func(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
status := handler(w, r, p, ctx)
statusStr := fmt.Sprintf("%d", status)
start := time.Now()
route, status := handler(w, r, p, ctx)
statusStr := strconv.Itoa(status)
if status == 0 {
statusStr = "???"
}
utils.PrometheusObserveTimeMilliseconds(promResponseDurationMilliseconds.WithLabelValues(route, statusStr), start)

log.Infof("%s %s %s %s", statusStr, r.Method, r.RequestURI, r.RemoteAddr)
log.Infof("%s \"%s %s\" %s", r.RemoteAddr, r.Method, r.RequestURI, statusStr)
}
}

Expand Down
7 changes: 5 additions & 2 deletions api/router.go
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,9 @@ func newHealthHandler(ctx *context.RouteContext) http.Handler {
return router
}

func getHealth(w http.ResponseWriter, r *http.Request, p httprouter.Params, ctx *context.RouteContext) int {
return 0
func getHealth(w http.ResponseWriter, r *http.Request, p httprouter.Params, ctx *context.RouteContext) (string, int) {
if ctx.Store.Ping() {
return "health", http.StatusOK
}
return "health", http.StatusInternalServerError
}
Loading

0 comments on commit 83b19b6

Please sign in to comment.