Skip to content

Commit

Permalink
Make TCP Keep Alive Timeout configurable
Browse files Browse the repository at this point in the history
  • Loading branch information
Oleksii Khliupin committed May 9, 2019
1 parent 2c58cba commit ace95f4
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 1 deletion.
7 changes: 7 additions & 0 deletions server/kit/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,10 @@ type Config struct {
// The string should be formatted like a time.Duration string.
IdleTimeout time.Duration `envconfig:"GIZMO_IDLE_TIMEOUT"`

// TCPKeepAliveTimeout can be used to override the default tcp timeout of 180s.
// The string should be formatted like a time.Duration string.
TCPKeepAliveTimeout time.Duration `envconfig:"GIZMO_TCP_KEEP_ALIVE_TIMEOUT"`

// ShutdownTimeout can be used to override the default http server shutdown timeout
// of 5m.
ShutdownTimeout time.Duration `envconfig:"GIZMO_SHUTDOWN_TIMEOUT"`
Expand Down Expand Up @@ -77,6 +81,9 @@ func loadConfig() Config {
if cfg.WriteTimeout.Nanoseconds() == 0 {
cfg.WriteTimeout = 10 * time.Second
}
if cfg.TCPKeepAliveTimeout.Nanoseconds() == 0 {
cfg.TCPKeepAliveTimeout = 3 * time.Minute
}
if cfg.GOMAXPROCS > 0 {
runtime.GOMAXPROCS(cfg.GOMAXPROCS)
}
Expand Down
27 changes: 26 additions & 1 deletion server/kit/kitserver.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import (
"net/http/pprof"
"runtime/debug"
"strings"
"time"

"cloud.google.com/go/errorreporting"
"cloud.google.com/go/profiler"
Expand Down Expand Up @@ -307,7 +308,16 @@ func basicDecoder(_ context.Context, r *http.Request) (interface{}, error) {

func (s *Server) start() error {
go func() {
err := s.svr.ListenAndServe()
ln, err := net.Listen("tcp", s.svr.Addr)
defer ln.Close()
if err != nil {
s.logger.Log(
"error", err,
"message", "HTTP server error - initiating shutting down")
s.stop()
return
}
err = s.svr.Serve(tcpKeepAliveListener{ln.(*net.TCPListener), s.cfg.TCPKeepAliveTimeout})
if err != nil && err != http.ErrServerClosed {
s.logger.Log(
"error", err,
Expand Down Expand Up @@ -399,3 +409,18 @@ func registerPprof(cfg Config, mx Router) {
mx.Handle(http.MethodGet, "/debug/pprof/threadcreate", pprof.Handler("threadcreate"))
mx.Handle(http.MethodGet, "/debug/pprof/block", pprof.Handler("block"))
}

type tcpKeepAliveListener struct {
*net.TCPListener
Timeout time.Duration
}

func (ln tcpKeepAliveListener) Accept() (net.Conn, error) {
tc, err := ln.AcceptTCP()
if err != nil {
return nil, err
}
tc.SetKeepAlive(true)
tc.SetKeepAlivePeriod(ln.Timeout)
return tc, nil
}

0 comments on commit ace95f4

Please sign in to comment.