Shutdown metrics server when listener exits (#3445)

This commit is contained in:
Nikola Jokic
2024-04-16 21:29:03 +02:00
committed by GitHub
parent 4ee49fee14
commit f965dfef73
4 changed files with 14 additions and 7 deletions

View File

@@ -117,15 +117,19 @@ func (app *App) Run(ctx context.Context) error {
} }
g, ctx := errgroup.WithContext(ctx) g, ctx := errgroup.WithContext(ctx)
metricsCtx, cancelMetrics := context.WithCancelCause(ctx)
g.Go(func() error { g.Go(func() error {
app.logger.Info("Starting listener") app.logger.Info("Starting listener")
return app.listener.Listen(ctx, app.worker) listnerErr := app.listener.Listen(ctx, app.worker)
cancelMetrics(fmt.Errorf("Listener exited: %w", listnerErr))
return listnerErr
}) })
if app.metrics != nil { if app.metrics != nil {
g.Go(func() error { g.Go(func() error {
app.logger.Info("Starting metrics server") app.logger.Info("Starting metrics server")
return app.metrics.ListenAndServe(ctx) return app.metrics.ListenAndServe(metricsCtx)
}) })
} }

View File

@@ -174,8 +174,8 @@ func (l *Listener) Listen(ctx context.Context, handler Handler) error {
continue continue
} }
// New context is created to avoid cancelation during message handling. // Remove cancellation from the context to avoid cancelling the message handling.
if err := l.handleMessage(context.Background(), handler, msg); err != nil { if err := l.handleMessage(context.WithoutCancel(ctx), handler, msg); err != nil {
return fmt.Errorf("failed to handle message: %w", err) return fmt.Errorf("failed to handle message: %w", err)
} }
} }

View File

@@ -484,8 +484,8 @@ func TestListener_Listen(t *testing.T) {
). ).
Once() Once()
// Ensure delete message is called with background context // Ensure delete message is called without cancel
client.On("DeleteMessage", context.Background(), mock.Anything, mock.Anything, mock.Anything).Return(nil).Once() client.On("DeleteMessage", context.WithoutCancel(ctx), mock.Anything, mock.Anything, mock.Anything).Return(nil).Once()
config.Client = client config.Client = client

View File

@@ -4,6 +4,7 @@ import (
"context" "context"
"net/http" "net/http"
"strconv" "strconv"
"time"
"github.com/actions/actions-runner-controller/github/actions" "github.com/actions/actions-runner-controller/github/actions"
"github.com/go-logr/logr" "github.com/go-logr/logr"
@@ -338,7 +339,9 @@ func (e *exporter) ListenAndServe(ctx context.Context) error {
e.logger.Info("starting metrics server", "addr", e.srv.Addr) e.logger.Info("starting metrics server", "addr", e.srv.Addr)
go func() { go func() {
<-ctx.Done() <-ctx.Done()
e.logger.Info("stopping metrics server") e.logger.Info("stopping metrics server", "err", ctx.Err())
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
e.srv.Shutdown(ctx) e.srv.Shutdown(ctx)
}() }()
return e.srv.ListenAndServe() return e.srv.ListenAndServe()