server.go 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214
  1. package server
  2. import (
  3. "context"
  4. "crypto/tls"
  5. "log"
  6. "net"
  7. "net/http"
  8. "os"
  9. "strings"
  10. "time"
  11. "github.com/pkg/errors"
  12. )
  13. // ServerShutdownTimeout is the default time to wait before closing
  14. // connections on shutdown.
  15. const ServerShutdownTimeout = 60 * time.Second
  16. // Server is a incomplete component that implements a basic HTTP/HTTPS
  17. // server.
  18. type Server struct {
  19. *http.Server
  20. listener *net.TCPListener
  21. reloadCh chan net.Listener
  22. shutdownCh chan struct{}
  23. }
  24. // New creates a new HTTP/HTTPS server configured with the passed
  25. // address, http.Handler and tls.Config.
  26. func New(addr string, handler http.Handler, tlsConfig *tls.Config) *Server {
  27. return &Server{
  28. reloadCh: make(chan net.Listener),
  29. shutdownCh: make(chan struct{}),
  30. Server: newHTTPServer(addr, handler, tlsConfig),
  31. }
  32. }
  33. // newHTTPServer creates a new http.Server with the TCP address, handler and
  34. // tls.Config.
  35. func newHTTPServer(addr string, handler http.Handler, tlsConfig *tls.Config) *http.Server {
  36. return &http.Server{
  37. Addr: addr,
  38. Handler: handler,
  39. TLSConfig: tlsConfig,
  40. WriteTimeout: 15 * time.Second,
  41. ReadTimeout: 15 * time.Second,
  42. ReadHeaderTimeout: 15 * time.Second,
  43. IdleTimeout: 15 * time.Second,
  44. ErrorLog: log.New(os.Stderr, "", log.Ldate|log.Ltime|log.Llongfile),
  45. }
  46. }
  47. // ListenAndServe listens on the TCP network address srv.Addr and then calls
  48. // Serve to handle requests on incoming connections.
  49. func (srv *Server) ListenAndServe() error {
  50. ln, err := net.Listen("tcp", srv.Addr)
  51. if err != nil {
  52. return err
  53. }
  54. return srv.Serve(ln)
  55. }
  56. // Serve runs Serve or ServeTLS on the underlying http.Server and listen to
  57. // channels to reload or shutdown the server.
  58. func (srv *Server) Serve(ln net.Listener) error {
  59. var (
  60. listener = ln
  61. err error
  62. )
  63. // Attempt to unwrap the listener if it's a [Listener].
  64. wl, isWrapped := listener.(*Listener)
  65. if isWrapped {
  66. listener = wl.listener.Unwrap()
  67. }
  68. // Store the current listener. When the server is reloaded a copy of the
  69. // underlying os.File is created, so when the server is closed, it does
  70. // not affect the copy.
  71. if ll, ok := listener.(*net.TCPListener); ok {
  72. srv.listener = ll
  73. }
  74. for {
  75. switch {
  76. case srv.TLSConfig == nil || (len(srv.TLSConfig.Certificates) == 0 && srv.TLSConfig.GetCertificate == nil):
  77. log.Printf("Serving HTTP on %s ...", srv.Addr)
  78. err = srv.Server.Serve(ln)
  79. case isWrapped:
  80. log.Printf("Serving %s on %s ...", wl.proto, wl.Addr())
  81. err = srv.Server.Serve(wl)
  82. default:
  83. log.Printf("Serving HTTPS on %s ...", srv.Addr)
  84. err = srv.Server.ServeTLS(ln, "", "")
  85. }
  86. // log unexpected errors
  87. if err != http.ErrServerClosed {
  88. log.Println(errors.Wrap(err, "unexpected error"))
  89. }
  90. select {
  91. case ln = <-srv.reloadCh:
  92. srv.listener = ln.(*net.TCPListener)
  93. case <-srv.shutdownCh:
  94. return http.ErrServerClosed
  95. }
  96. }
  97. }
  98. // UnwrappableListener indicates a [net.Listener] that can
  99. // be unwrapped to obtain the underlying [net.Listener]. It
  100. // is used by the [Server] to obtain a [*net.TCPListener]
  101. // implementing the [net.Listener] interface.
  102. type UnwrappableListener interface {
  103. net.Listener
  104. Unwrap() net.Listener
  105. }
  106. // NewListener wraps the inner [net.Listener].
  107. func NewListener(listener UnwrappableListener, proto string) *Listener {
  108. return &Listener{
  109. listener: listener,
  110. proto: strings.ToUpper(proto),
  111. }
  112. }
  113. // Listener wraps a [net.Listener].
  114. type Listener struct {
  115. listener UnwrappableListener
  116. proto string
  117. }
  118. // Accept waits for and returns the next connection to the listener.
  119. func (w *Listener) Accept() (net.Conn, error) {
  120. return w.listener.Accept()
  121. }
  122. // Close closes the listener.
  123. // Any blocked Accept operations will be unblocked and return errors.
  124. func (w *Listener) Close() error {
  125. return w.listener.Close()
  126. }
  127. // Addr returns the listener's network address.
  128. func (w *Listener) Addr() net.Addr {
  129. return w.listener.Addr()
  130. }
  131. // Shutdown gracefully shuts down the server without interrupting any active
  132. // connections.
  133. func (srv *Server) Shutdown() error {
  134. ctx, cancel := context.WithTimeout(context.Background(), ServerShutdownTimeout)
  135. defer cancel() // release resources if Shutdown ends before the timeout
  136. defer close(srv.shutdownCh) // close shutdown channel
  137. return srv.Server.Shutdown(ctx)
  138. }
  139. func (srv *Server) reloadShutdown() error {
  140. ctx, cancel := context.WithTimeout(context.Background(), ServerShutdownTimeout)
  141. defer cancel() // release resources if Shutdown ends before the timeout
  142. return srv.Server.Shutdown(ctx)
  143. }
  144. // Reload reloads the current server with the configuration of the passed
  145. // server.
  146. func (srv *Server) Reload(ns *Server) error {
  147. var err error
  148. var ln net.Listener
  149. if srv.Addr != ns.Addr {
  150. // Open new address
  151. ln, err = net.Listen("tcp", ns.Addr)
  152. if err != nil {
  153. return errors.WithStack(err)
  154. }
  155. } else {
  156. // Get a copy of the underlying os.File
  157. fd, err := srv.listener.File()
  158. if err != nil {
  159. return errors.WithStack(err)
  160. }
  161. // Make sure to close the copy
  162. defer fd.Close()
  163. // Creates a new listener copying fd
  164. ln, err = net.FileListener(fd)
  165. if err != nil {
  166. return errors.WithStack(err)
  167. }
  168. }
  169. // Close old server without sending a signal
  170. if err := srv.reloadShutdown(); err != nil {
  171. return err
  172. }
  173. // Update old server
  174. srv.Server = ns.Server
  175. srv.reloadCh <- ln
  176. return nil
  177. }
  178. // Forbidden writes on the http.ResponseWriter a text/plain forbidden
  179. // response.
  180. func (srv *Server) Forbidden(w http.ResponseWriter) {
  181. header := w.Header()
  182. header.Set("Content-Type", "text/plain; charset=utf-8")
  183. header.Set("Content-Length", "11")
  184. w.WriteHeader(http.StatusForbidden)
  185. w.Write([]byte("Forbidden.\n"))
  186. }