Skip to content

Commit

Permalink
fix: gracefully shutdown
Browse files Browse the repository at this point in the history
  • Loading branch information
ernado committed Jan 25, 2025
1 parent 261b9af commit b011709
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 4 deletions.
16 changes: 14 additions & 2 deletions cmd/otelbot/healthcheck.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,9 @@ import (
"context"
"net/http"
"time"

"github.com/go-faster/errors"
"github.com/go-faster/sdk/zctx"
)

func (a *App) setupHealthCheck() {
Expand All @@ -19,9 +22,18 @@ func (a *App) setupHealthCheck() {
a.services["healthcheck"] = func(ctx context.Context) error {
go func() {
<-ctx.Done()
_ = srv.Shutdown(context.Background())
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()
_ = srv.Shutdown(ctx)
}()
return srv.ListenAndServe()
if err := srv.ListenAndServe(); err != nil {
if errors.Is(err, http.ErrServerClosed) && ctx.Err() != nil {
zctx.From(ctx).Info("Healthcheck HTTP server closed gracefully")
return nil
}
return errors.Wrap(err, "healthcheck http server")
}
return nil
}
}

Expand Down
21 changes: 19 additions & 2 deletions cmd/oteldb/app.go
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ type App struct {
cfg Config

services map[string]func(context.Context) error
shutdown func()
otelStorage

lg *zap.Logger
Expand Down Expand Up @@ -271,9 +272,18 @@ func (app *App) setupHealthCheck() {
app.services["healthcheck"] = func(ctx context.Context) error {
go func() {
<-ctx.Done()
_ = srv.Shutdown(context.Background())
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()
_ = srv.Shutdown(ctx)
}()
return srv.ListenAndServe()
if err := srv.ListenAndServe(); err != nil {
if errors.Is(err, http.ErrServerClosed) && ctx.Err() != nil {
zctx.From(ctx).Info("Healthcheck HTTP server closed gracefully")
return nil
}
return errors.Wrap(err, "healthcheck http server")
}
return nil
}
}

Expand Down Expand Up @@ -317,13 +327,20 @@ func (app *App) setupCollector() error {
}

app.services["otelcol"] = func(ctx context.Context) error {
// Collector is listening for os.Interrupt, syscall.SIGTERM itself,
// and will return nil error on shutdown. See Collector.Run.
//
// So, we should shut down other services.
defer app.shutdown()

return col.Run(ctx)
}
return nil
}

// Run runs application.
func (app *App) Run(ctx context.Context) error {
ctx, app.shutdown = context.WithCancel(ctx)
g, ctx := errgroup.WithContext(ctx)

runningServices := make(map[string]struct{})
Expand Down

0 comments on commit b011709

Please sign in to comment.