From f20e6a0ae4ed63db328aea16c20c49f8dd8a5750 Mon Sep 17 00:00:00 2001 From: beorn7 Date: Fri, 6 Oct 2017 17:20:20 +0200 Subject: [PATCH] Only respond to API requests once the server is ready --- web/api/v1/api.go | 17 +++++++++++++---- web/api/v1/api_test.go | 3 ++- web/web.go | 1 + 3 files changed, 16 insertions(+), 5 deletions(-) diff --git a/web/api/v1/api.go b/web/api/v1/api.go index a42da28b4..131ed70ea 100644 --- a/web/api/v1/api.go +++ b/web/api/v1/api.go @@ -107,10 +107,18 @@ type API struct { now func() model.Time config func() config.Config + ready func(http.HandlerFunc) http.HandlerFunc } // NewAPI returns an initialized API type. -func NewAPI(qe *promql.Engine, st local.Storage, tr targetRetriever, ar alertmanagerRetriever, configFunc func() config.Config) *API { +func NewAPI( + qe *promql.Engine, + st local.Storage, + tr targetRetriever, + ar alertmanagerRetriever, + configFunc func() config.Config, + readyFunc func(http.HandlerFunc) http.HandlerFunc, +) *API { return &API{ QueryEngine: qe, Storage: st, @@ -118,6 +126,7 @@ func NewAPI(qe *promql.Engine, st local.Storage, tr targetRetriever, ar alertman alertmanagerRetriever: ar, now: model.Now, config: configFunc, + ready: readyFunc, } } @@ -134,9 +143,9 @@ func (api *API) Register(r *route.Router) { w.WriteHeader(http.StatusNoContent) } }) - return prometheus.InstrumentHandler(name, httputil.CompressionHandler{ + return api.ready(prometheus.InstrumentHandler(name, httputil.CompressionHandler{ Handler: hf, - }) + })) } r.Options("/*path", instr("options", api.options)) @@ -153,7 +162,7 @@ func (api *API) Register(r *route.Router) { r.Get("/alertmanagers", instr("alertmanagers", api.alertmanagers)) r.Get("/status/config", instr("config", api.serveConfig)) - r.Post("/read", prometheus.InstrumentHandler("read", http.HandlerFunc(api.remoteRead))) + r.Post("/read", api.ready(prometheus.InstrumentHandler("read", http.HandlerFunc(api.remoteRead)))) } type queryData struct { diff --git a/web/api/v1/api_test.go b/web/api/v1/api_test.go index 370795d26..463fb1d40 100644 --- a/web/api/v1/api_test.go +++ b/web/api/v1/api_test.go @@ -104,6 +104,7 @@ func TestEndpoints(t *testing.T) { config: func() config.Config { return samplePrometheusCfg }, + ready: func(f http.HandlerFunc) http.HandlerFunc { return f }, } start := model.Time(0) @@ -723,7 +724,7 @@ func TestParseDuration(t *testing.T) { func TestOptionsMethod(t *testing.T) { r := route.New() - api := &API{} + api := &API{ready: func(f http.HandlerFunc) http.HandlerFunc { return f }} api.Register(r) s := httptest.NewServer(r) diff --git a/web/web.go b/web/web.go index 0f87f6b94..396853d02 100644 --- a/web/web.go +++ b/web/web.go @@ -172,6 +172,7 @@ func New(o *Options) *Handler { defer h.mtx.RUnlock() return *h.config }, + h.testReady, ) if o.RoutePrefix != "/" {