server.go 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175
  1. package server
  2. import (
  3. "context"
  4. "crypto/tls"
  5. "log"
  6. "net"
  7. "net/http"
  8. "os"
  9. "time"
  10. "github.com/pkg/errors"
  11. )
  12. // ServerShutdownTimeout is the default time to wait before closing
  13. // connections on shutdown.
  14. const ServerShutdownTimeout = 60 * time.Second
  15. // Server is a incomplete component that implements a basic HTTP/HTTPS
  16. // server.
  17. type Server struct {
  18. *http.Server
  19. listener *net.TCPListener
  20. reloadCh chan net.Listener
  21. shutdownCh chan struct{}
  22. }
  23. // New creates a new HTTP/HTTPS server configured with the passed
  24. // address, http.Handler and tls.Config.
  25. func New(addr string, handler http.Handler, tlsConfig *tls.Config) *Server {
  26. return &Server{
  27. reloadCh: make(chan net.Listener),
  28. shutdownCh: make(chan struct{}),
  29. Server: newHTTPServer(addr, handler, tlsConfig),
  30. }
  31. }
  32. // newHTTPServer creates a new http.Server with the TCP address, handler and
  33. // tls.Config.
  34. func newHTTPServer(addr string, handler http.Handler, tlsConfig *tls.Config) *http.Server {
  35. return &http.Server{
  36. Addr: addr,
  37. Handler: handler,
  38. TLSConfig: tlsConfig,
  39. WriteTimeout: 15 * time.Second,
  40. ReadTimeout: 15 * time.Second,
  41. IdleTimeout: 15 * time.Second,
  42. ErrorLog: log.New(os.Stderr, "", log.Ldate|log.Ltime|log.Llongfile),
  43. }
  44. }
  45. // ListenAndServe listens on the TCP network address srv.Addr and then calls
  46. // Serve to handle requests on incoming connections.
  47. func (srv *Server) ListenAndServe() error {
  48. ln, err := net.Listen("tcp", srv.Addr)
  49. if err != nil {
  50. return err
  51. }
  52. return srv.Serve(ln)
  53. }
  54. // Serve runs Serve or ServeTLS on the underlying http.Server and listen to
  55. // channels to reload or shutdown the server.
  56. func (srv *Server) Serve(ln net.Listener) error {
  57. var err error
  58. // Store the current listener.
  59. // In reloads we'll create a copy of the underlying os.File so the close of the server one does not affect the copy.
  60. srv.listener = ln.(*net.TCPListener)
  61. for {
  62. // Start server
  63. if srv.TLSConfig == nil || (len(srv.TLSConfig.Certificates) == 0 && srv.TLSConfig.GetCertificate == nil) {
  64. log.Printf("Serving HTTP on %s ...", srv.Addr)
  65. err = srv.Server.Serve(tcpKeepAliveListener{ln.(*net.TCPListener)})
  66. } else {
  67. log.Printf("Serving HTTPS on %s ...", srv.Addr)
  68. err = srv.Server.ServeTLS(tcpKeepAliveListener{ln.(*net.TCPListener)}, "", "")
  69. }
  70. // log unexpected errors
  71. if err != http.ErrServerClosed {
  72. log.Println(errors.Wrap(err, "unexpected error"))
  73. }
  74. select {
  75. case ln = <-srv.reloadCh:
  76. srv.listener = ln.(*net.TCPListener)
  77. case <-srv.shutdownCh:
  78. return http.ErrServerClosed
  79. }
  80. }
  81. }
  82. // Shutdown gracefully shuts down the server without interrupting any active
  83. // connections.
  84. func (srv *Server) Shutdown() error {
  85. ctx, cancel := context.WithTimeout(context.Background(), ServerShutdownTimeout)
  86. defer cancel() // release resources if Shutdown ends before the timeout
  87. defer close(srv.shutdownCh) // close shutdown channel
  88. return srv.Server.Shutdown(ctx)
  89. }
  90. func (srv *Server) reloadShutdown() error {
  91. ctx, cancel := context.WithTimeout(context.Background(), ServerShutdownTimeout)
  92. defer cancel() // release resources if Shutdown ends before the timeout
  93. return srv.Server.Shutdown(ctx)
  94. }
  95. // Reload reloads the current server with the configuration of the passed
  96. // server.
  97. func (srv *Server) Reload(ns *Server) error {
  98. var err error
  99. var ln net.Listener
  100. if srv.Addr != ns.Addr {
  101. // Open new address
  102. ln, err = net.Listen("tcp", ns.Addr)
  103. if err != nil {
  104. return errors.WithStack(err)
  105. }
  106. } else {
  107. // Get a copy of the underlying os.File
  108. fd, err := srv.listener.File()
  109. if err != nil {
  110. return errors.WithStack(err)
  111. }
  112. // Make sure to close the copy
  113. defer fd.Close()
  114. // Creates a new listener copying fd
  115. ln, err = net.FileListener(fd)
  116. if err != nil {
  117. return errors.WithStack(err)
  118. }
  119. }
  120. // Close old server without sending a signal
  121. if err := srv.reloadShutdown(); err != nil {
  122. return err
  123. }
  124. // Update old server
  125. srv.Server = ns.Server
  126. srv.reloadCh <- ln
  127. return nil
  128. }
  129. // Forbidden writes on the http.ResponseWriter a text/plain forbidden
  130. // response.
  131. func (srv *Server) Forbidden(w http.ResponseWriter) {
  132. header := w.Header()
  133. header.Set("Content-Type", "text/plain; charset=utf-8")
  134. header.Set("Content-Length", "11")
  135. w.WriteHeader(http.StatusForbidden)
  136. w.Write([]byte("Forbidden.\n"))
  137. }
  138. // tcpKeepAliveListener sets TCP keep-alive timeouts on accepted
  139. // connections. It's used by ListenAndServe and ListenAndServeTLS so
  140. // dead TCP connections (e.g. closing laptop mid-download) eventually
  141. // go away.
  142. type tcpKeepAliveListener struct {
  143. *net.TCPListener
  144. }
  145. func (ln tcpKeepAliveListener) Accept() (c net.Conn, err error) {
  146. tc, err := ln.AcceptTCP()
  147. if err != nil {
  148. return
  149. }
  150. tc.SetKeepAlive(true)
  151. tc.SetKeepAlivePeriod(3 * time.Minute)
  152. return tc, nil
  153. }