Skip to content

Commit

Permalink
feat: add graceful shutdown for proxy server (#776)
Browse files Browse the repository at this point in the history
Signed-off-by: Anish Ramasekar <anish.ramasekar@gmail.com>
  • Loading branch information
aramase committed Mar 6, 2023
1 parent 278a6b5 commit e5e3b2a
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 4 deletions.
24 changes: 23 additions & 1 deletion cmd/proxy/main.go
Original file line number Diff line number Diff line change
@@ -1,8 +1,12 @@
package main

import (
"context"
"flag"
"fmt"
"os"
"os/signal"
"syscall"

"monis.app/mlog"
"sigs.k8s.io/controller-runtime/pkg/manager/signals"
Expand Down Expand Up @@ -48,13 +52,31 @@ func mainErr() error {
return nil
}

ctx := withShutdownSignal(context.Background())

p, err := proxy.NewProxy(proxyPort, mlog.New().WithName("proxy"))
if err != nil {
return fmt.Errorf("setup: failed to create proxy: %w", err)
}
if err := p.Run(); err != nil {
if err := p.Run(ctx); err != nil {
return fmt.Errorf("setup: failed to run proxy: %w", err)
}

return nil
}

// withShutdownSignal returns a copy of the parent context that will close if
// the process receives termination signals.
func withShutdownSignal(ctx context.Context) context.Context {
signalChan := make(chan os.Signal, 1)
signal.Notify(signalChan, syscall.SIGTERM, syscall.SIGINT, os.Interrupt)

nctx, cancel := context.WithCancel(ctx)

go func() {
<-signalChan
mlog.Info("received shutdown signal")
cancel()
}()
return nctx
}
19 changes: 16 additions & 3 deletions pkg/proxy/proxy.go
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ var (
)

type Proxy interface {
Run() error
Run(ctx context.Context) error
}

type proxy struct {
Expand Down Expand Up @@ -88,7 +88,7 @@ func NewProxy(port int, logger mlog.Logger) (Proxy, error) {
}

// Run runs the proxy server
func (p *proxy) Run() error {
func (p *proxy) Run(ctx context.Context) error {
rtr := mux.NewRouter()
rtr.PathPrefix(tokenPathPrefix).HandlerFunc(p.msiHandler)
rtr.PathPrefix(readyzPathPrefix).HandlerFunc(p.readyzHandler)
Expand All @@ -100,7 +100,20 @@ func (p *proxy) Run() error {
ReadHeaderTimeout: 5 * time.Second,
Handler: rtr,
}
return server.ListenAndServe()

go func() {
if err := server.ListenAndServe(); err != nil && err != http.ErrServerClosed {
panic(err)
}
}()

<-ctx.Done()

p.logger.Info("shutting down the proxy server")
// shutdown the server gracefully with a 5 second timeout
shutdownCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
return server.Shutdown(shutdownCtx)
}

func (p *proxy) msiHandler(w http.ResponseWriter, r *http.Request) {
Expand Down

0 comments on commit e5e3b2a

Please sign in to comment.