2015-10-26 08:45:55 +08:00
|
|
|
package server
|
|
|
|
|
|
|
|
import (
|
|
|
|
"net"
|
|
|
|
"sync"
|
|
|
|
"syscall"
|
|
|
|
)
|
|
|
|
|
|
|
|
// newGracefulListener returns a gracefulListener that wraps l and
|
|
|
|
// uses wg (stored in the host server) to count connections.
|
|
|
|
func newGracefulListener(l ListenerFile, wg *sync.WaitGroup) *gracefulListener {
|
|
|
|
gl := &gracefulListener{ListenerFile: l, stop: make(chan error), httpWg: wg}
|
|
|
|
go func() {
|
|
|
|
<-gl.stop
|
2015-11-15 09:00:18 +08:00
|
|
|
gl.Lock()
|
2015-10-26 08:45:55 +08:00
|
|
|
gl.stopped = true
|
2015-11-15 09:00:18 +08:00
|
|
|
gl.Unlock()
|
2015-10-26 08:45:55 +08:00
|
|
|
gl.stop <- gl.ListenerFile.Close()
|
|
|
|
}()
|
|
|
|
return gl
|
|
|
|
}
|
|
|
|
|
|
|
|
// gracefuListener is a net.Listener which can
|
|
|
|
// count the number of connections on it. Its
|
|
|
|
// methods mainly wrap net.Listener to be graceful.
|
|
|
|
type gracefulListener struct {
|
|
|
|
ListenerFile
|
2015-11-15 09:00:18 +08:00
|
|
|
stop chan error
|
|
|
|
stopped bool
|
|
|
|
sync.Mutex // protects the stopped flag
|
|
|
|
httpWg *sync.WaitGroup // pointer to the host's wg used for counting connections
|
2015-10-26 08:45:55 +08:00
|
|
|
}
|
|
|
|
|
2015-11-15 09:00:18 +08:00
|
|
|
// Accept accepts a connection.
|
2015-10-26 08:45:55 +08:00
|
|
|
func (gl *gracefulListener) Accept() (c net.Conn, err error) {
|
|
|
|
c, err = gl.ListenerFile.Accept()
|
|
|
|
if err != nil {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
c = gracefulConn{Conn: c, httpWg: gl.httpWg}
|
|
|
|
gl.httpWg.Add(1)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
// Close immediately closes the listener.
|
|
|
|
func (gl *gracefulListener) Close() error {
|
2015-11-15 09:00:18 +08:00
|
|
|
gl.Lock()
|
2015-10-26 08:45:55 +08:00
|
|
|
if gl.stopped {
|
2015-11-15 09:00:18 +08:00
|
|
|
gl.Unlock()
|
2015-10-26 08:45:55 +08:00
|
|
|
return syscall.EINVAL
|
|
|
|
}
|
2015-11-15 09:00:18 +08:00
|
|
|
gl.Unlock()
|
2015-10-26 08:45:55 +08:00
|
|
|
gl.stop <- nil
|
|
|
|
return <-gl.stop
|
|
|
|
}
|
|
|
|
|
|
|
|
// gracefulConn represents a connection on a
|
|
|
|
// gracefulListener so that we can keep track
|
|
|
|
// of the number of connections, thus facilitating
|
|
|
|
// a graceful shutdown.
|
|
|
|
type gracefulConn struct {
|
|
|
|
net.Conn
|
|
|
|
httpWg *sync.WaitGroup // pointer to the host server's connection waitgroup
|
|
|
|
}
|
|
|
|
|
|
|
|
// Close closes c's underlying connection while updating the wg count.
|
|
|
|
func (c gracefulConn) Close() error {
|
2015-10-27 03:34:31 +08:00
|
|
|
err := c.Conn.Close()
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
// close can fail on http2 connections (as of Oct. 2015, before http2 in std lib)
|
|
|
|
// so don't decrement count unless close succeeds
|
2015-10-26 08:45:55 +08:00
|
|
|
c.httpWg.Done()
|
2015-10-27 03:34:31 +08:00
|
|
|
return nil
|
2015-10-26 08:45:55 +08:00
|
|
|
}
|