You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

server.go 7.0 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269
  1. // +build !windows
  2. // Copyright 2019 The Gitea Authors. All rights reserved.
  3. // Use of this source code is governed by a MIT-style
  4. // license that can be found in the LICENSE file.
  5. // This code is highly inspired by endless go
  6. package graceful
  7. import (
  8. "crypto/tls"
  9. "net"
  10. "os"
  11. "strings"
  12. "sync"
  13. "syscall"
  14. "time"
  15. "code.gitea.io/gitea/modules/log"
  16. )
  17. type state uint8
  18. const (
  19. stateInit state = iota
  20. stateRunning
  21. stateShuttingDown
  22. stateTerminate
  23. )
  24. var (
  25. // RWMutex for when adding servers or shutting down
  26. runningServerReg sync.RWMutex
  27. // ensure we only fork once
  28. runningServersForked bool
  29. // DefaultReadTimeOut default read timeout
  30. DefaultReadTimeOut time.Duration
  31. // DefaultWriteTimeOut default write timeout
  32. DefaultWriteTimeOut time.Duration
  33. // DefaultMaxHeaderBytes default max header bytes
  34. DefaultMaxHeaderBytes int
  35. // IsChild reports if we are a fork iff LISTEN_FDS is set and our parent PID is not 1
  36. IsChild = len(os.Getenv(listenFDs)) > 0 && os.Getppid() > 1
  37. )
  38. func init() {
  39. runningServerReg = sync.RWMutex{}
  40. DefaultMaxHeaderBytes = 0 // use http.DefaultMaxHeaderBytes - which currently is 1 << 20 (1MB)
  41. }
  42. // ServeFunction represents a listen.Accept loop
  43. type ServeFunction = func(net.Listener) error
  44. // Server represents our graceful server
  45. type Server struct {
  46. network string
  47. address string
  48. listener net.Listener
  49. PreSignalHooks map[os.Signal][]func()
  50. PostSignalHooks map[os.Signal][]func()
  51. wg sync.WaitGroup
  52. sigChan chan os.Signal
  53. state state
  54. lock *sync.RWMutex
  55. BeforeBegin func(network, address string)
  56. OnShutdown func()
  57. }
  58. // NewServer creates a server on network at provided address
  59. func NewServer(network, address string) *Server {
  60. runningServerReg.Lock()
  61. defer runningServerReg.Unlock()
  62. if IsChild {
  63. log.Info("Restarting new server: %s:%s on PID: %d", network, address, os.Getpid())
  64. } else {
  65. log.Info("Starting new server: %s:%s on PID: %d", network, address, os.Getpid())
  66. }
  67. srv := &Server{
  68. wg: sync.WaitGroup{},
  69. sigChan: make(chan os.Signal),
  70. PreSignalHooks: map[os.Signal][]func(){},
  71. PostSignalHooks: map[os.Signal][]func(){},
  72. state: stateInit,
  73. lock: &sync.RWMutex{},
  74. network: network,
  75. address: address,
  76. }
  77. srv.BeforeBegin = func(network, addr string) {
  78. log.Debug("Starting server on %s:%s (PID: %d)", network, addr, syscall.Getpid())
  79. }
  80. return srv
  81. }
  82. // ListenAndServe listens on the provided network address and then calls Serve
  83. // to handle requests on incoming connections.
  84. func (srv *Server) ListenAndServe(serve ServeFunction) error {
  85. go srv.handleSignals()
  86. l, err := GetListener(srv.network, srv.address)
  87. if err != nil {
  88. log.Error("Unable to GetListener: %v", err)
  89. return err
  90. }
  91. srv.listener = newWrappedListener(l, srv)
  92. if IsChild {
  93. _ = syscall.Kill(syscall.Getppid(), syscall.SIGTERM)
  94. }
  95. srv.BeforeBegin(srv.network, srv.address)
  96. return srv.Serve(serve)
  97. }
  98. // ListenAndServeTLS listens on the provided network address and then calls
  99. // Serve to handle requests on incoming TLS connections.
  100. //
  101. // Filenames containing a certificate and matching private key for the server must
  102. // be provided. If the certificate is signed by a certificate authority, the
  103. // certFile should be the concatenation of the server's certificate followed by the
  104. // CA's certificate.
  105. func (srv *Server) ListenAndServeTLS(certFile, keyFile string, serve ServeFunction) error {
  106. config := &tls.Config{}
  107. if config.NextProtos == nil {
  108. config.NextProtos = []string{"http/1.1"}
  109. }
  110. config.Certificates = make([]tls.Certificate, 1)
  111. var err error
  112. config.Certificates[0], err = tls.LoadX509KeyPair(certFile, keyFile)
  113. if err != nil {
  114. log.Error("Failed to load https cert file %s for %s:%s: %v", certFile, srv.network, srv.address, err)
  115. return err
  116. }
  117. return srv.ListenAndServeTLSConfig(config, serve)
  118. }
  119. // ListenAndServeTLSConfig listens on the provided network address and then calls
  120. // Serve to handle requests on incoming TLS connections.
  121. func (srv *Server) ListenAndServeTLSConfig(tlsConfig *tls.Config, serve ServeFunction) error {
  122. go srv.handleSignals()
  123. l, err := GetListener(srv.network, srv.address)
  124. if err != nil {
  125. log.Error("Unable to get Listener: %v", err)
  126. return err
  127. }
  128. wl := newWrappedListener(l, srv)
  129. srv.listener = tls.NewListener(wl, tlsConfig)
  130. if IsChild {
  131. _ = syscall.Kill(syscall.Getppid(), syscall.SIGTERM)
  132. }
  133. srv.BeforeBegin(srv.network, srv.address)
  134. return srv.Serve(serve)
  135. }
  136. // Serve accepts incoming HTTP connections on the wrapped listener l, creating a new
  137. // service goroutine for each. The service goroutines read requests and then call
  138. // handler to reply to them. Handler is typically nil, in which case the
  139. // DefaultServeMux is used.
  140. //
  141. // In addition to the standard Serve behaviour each connection is added to a
  142. // sync.Waitgroup so that all outstanding connections can be served before shutting
  143. // down the server.
  144. func (srv *Server) Serve(serve ServeFunction) error {
  145. defer log.Debug("Serve() returning... (PID: %d)", syscall.Getpid())
  146. srv.setState(stateRunning)
  147. err := serve(srv.listener)
  148. log.Debug("Waiting for connections to finish... (PID: %d)", syscall.Getpid())
  149. srv.wg.Wait()
  150. srv.setState(stateTerminate)
  151. // use of closed means that the listeners are closed - i.e. we should be shutting down - return nil
  152. if err != nil && strings.Contains(err.Error(), "use of closed") {
  153. return nil
  154. }
  155. return err
  156. }
  157. func (srv *Server) getState() state {
  158. srv.lock.RLock()
  159. defer srv.lock.RUnlock()
  160. return srv.state
  161. }
  162. func (srv *Server) setState(st state) {
  163. srv.lock.Lock()
  164. defer srv.lock.Unlock()
  165. srv.state = st
  166. }
  167. type wrappedListener struct {
  168. net.Listener
  169. stopped bool
  170. server *Server
  171. }
  172. func newWrappedListener(l net.Listener, srv *Server) *wrappedListener {
  173. return &wrappedListener{
  174. Listener: l,
  175. server: srv,
  176. }
  177. }
  178. func (wl *wrappedListener) Accept() (net.Conn, error) {
  179. var c net.Conn
  180. // Set keepalive on TCPListeners connections.
  181. if tcl, ok := wl.Listener.(*net.TCPListener); ok {
  182. tc, err := tcl.AcceptTCP()
  183. if err != nil {
  184. return nil, err
  185. }
  186. _ = tc.SetKeepAlive(true) // see http.tcpKeepAliveListener
  187. _ = tc.SetKeepAlivePeriod(3 * time.Minute) // see http.tcpKeepAliveListener
  188. c = tc
  189. } else {
  190. var err error
  191. c, err = wl.Listener.Accept()
  192. if err != nil {
  193. return nil, err
  194. }
  195. }
  196. c = wrappedConn{
  197. Conn: c,
  198. server: wl.server,
  199. }
  200. wl.server.wg.Add(1)
  201. return c, nil
  202. }
  203. func (wl *wrappedListener) Close() error {
  204. if wl.stopped {
  205. return syscall.EINVAL
  206. }
  207. wl.stopped = true
  208. return wl.Listener.Close()
  209. }
  210. func (wl *wrappedListener) File() (*os.File, error) {
  211. // returns a dup(2) - FD_CLOEXEC flag *not* set so the listening socket can be passed to child processes
  212. return wl.Listener.(filer).File()
  213. }
  214. type wrappedConn struct {
  215. net.Conn
  216. server *Server
  217. }
  218. func (w wrappedConn) Close() error {
  219. err := w.Conn.Close()
  220. if err == nil {
  221. w.server.wg.Done()
  222. }
  223. return err
  224. }