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

server.go 8.3KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296
  1. // Copyright 2019 The Gitea Authors. All rights reserved.
  2. // SPDX-License-Identifier: MIT
  3. // This code is highly inspired by endless go
  4. package graceful
  5. import (
  6. "crypto/tls"
  7. "net"
  8. "os"
  9. "strings"
  10. "sync"
  11. "sync/atomic"
  12. "syscall"
  13. "time"
  14. "code.gitea.io/gitea/modules/log"
  15. "code.gitea.io/gitea/modules/proxyprotocol"
  16. "code.gitea.io/gitea/modules/setting"
  17. )
  18. var (
  19. // DefaultReadTimeOut default read timeout
  20. DefaultReadTimeOut time.Duration
  21. // DefaultWriteTimeOut default write timeout
  22. DefaultWriteTimeOut time.Duration
  23. // DefaultMaxHeaderBytes default max header bytes
  24. DefaultMaxHeaderBytes int
  25. // PerWriteWriteTimeout timeout for writes
  26. PerWriteWriteTimeout = 30 * time.Second
  27. // PerWriteWriteTimeoutKbTime is a timeout taking account of how much there is to be written
  28. PerWriteWriteTimeoutKbTime = 10 * time.Second
  29. )
  30. func init() {
  31. DefaultMaxHeaderBytes = 0 // use http.DefaultMaxHeaderBytes - which currently is 1 << 20 (1MB)
  32. }
  33. // ServeFunction represents a listen.Accept loop
  34. type ServeFunction = func(net.Listener) error
  35. // Server represents our graceful server
  36. type Server struct {
  37. network string
  38. address string
  39. listener net.Listener
  40. wg sync.WaitGroup
  41. state state
  42. lock *sync.RWMutex
  43. BeforeBegin func(network, address string)
  44. OnShutdown func()
  45. PerWriteTimeout time.Duration
  46. PerWritePerKbTimeout time.Duration
  47. }
  48. // NewServer creates a server on network at provided address
  49. func NewServer(network, address, name string) *Server {
  50. if GetManager().IsChild() {
  51. log.Info("Restarting new %s server: %s:%s on PID: %d", name, network, address, os.Getpid())
  52. } else {
  53. log.Info("Starting new %s server: %s:%s on PID: %d", name, network, address, os.Getpid())
  54. }
  55. srv := &Server{
  56. wg: sync.WaitGroup{},
  57. state: stateInit,
  58. lock: &sync.RWMutex{},
  59. network: network,
  60. address: address,
  61. PerWriteTimeout: setting.PerWriteTimeout,
  62. PerWritePerKbTimeout: setting.PerWritePerKbTimeout,
  63. }
  64. srv.BeforeBegin = func(network, addr string) {
  65. log.Debug("Starting server on %s:%s (PID: %d)", network, addr, syscall.Getpid())
  66. }
  67. return srv
  68. }
  69. // ListenAndServe listens on the provided network address and then calls Serve
  70. // to handle requests on incoming connections.
  71. func (srv *Server) ListenAndServe(serve ServeFunction, useProxyProtocol bool) error {
  72. go srv.awaitShutdown()
  73. listener, err := GetListener(srv.network, srv.address)
  74. if err != nil {
  75. log.Error("Unable to GetListener: %v", err)
  76. return err
  77. }
  78. // we need to wrap the listener to take account of our lifecycle
  79. listener = newWrappedListener(listener, srv)
  80. // Now we need to take account of ProxyProtocol settings...
  81. if useProxyProtocol {
  82. listener = &proxyprotocol.Listener{
  83. Listener: listener,
  84. ProxyHeaderTimeout: setting.ProxyProtocolHeaderTimeout,
  85. AcceptUnknown: setting.ProxyProtocolAcceptUnknown,
  86. }
  87. }
  88. srv.listener = listener
  89. srv.BeforeBegin(srv.network, srv.address)
  90. return srv.Serve(serve)
  91. }
  92. // ListenAndServeTLSConfig listens on the provided network address and then calls
  93. // Serve to handle requests on incoming TLS connections.
  94. func (srv *Server) ListenAndServeTLSConfig(tlsConfig *tls.Config, serve ServeFunction, useProxyProtocol, proxyProtocolTLSBridging bool) error {
  95. go srv.awaitShutdown()
  96. if tlsConfig.MinVersion == 0 {
  97. tlsConfig.MinVersion = tls.VersionTLS12
  98. }
  99. listener, err := GetListener(srv.network, srv.address)
  100. if err != nil {
  101. log.Error("Unable to get Listener: %v", err)
  102. return err
  103. }
  104. // we need to wrap the listener to take account of our lifecycle
  105. listener = newWrappedListener(listener, srv)
  106. // Now we need to take account of ProxyProtocol settings... If we're not bridging then we expect that the proxy will forward the connection to us
  107. if useProxyProtocol && !proxyProtocolTLSBridging {
  108. listener = &proxyprotocol.Listener{
  109. Listener: listener,
  110. ProxyHeaderTimeout: setting.ProxyProtocolHeaderTimeout,
  111. AcceptUnknown: setting.ProxyProtocolAcceptUnknown,
  112. }
  113. }
  114. // Now handle the tls protocol
  115. listener = tls.NewListener(listener, tlsConfig)
  116. // Now if we're bridging then we need the proxy to tell us who we're bridging for...
  117. if useProxyProtocol && proxyProtocolTLSBridging {
  118. listener = &proxyprotocol.Listener{
  119. Listener: listener,
  120. ProxyHeaderTimeout: setting.ProxyProtocolHeaderTimeout,
  121. AcceptUnknown: setting.ProxyProtocolAcceptUnknown,
  122. }
  123. }
  124. srv.listener = listener
  125. srv.BeforeBegin(srv.network, srv.address)
  126. return srv.Serve(serve)
  127. }
  128. // Serve accepts incoming HTTP connections on the wrapped listener l, creating a new
  129. // service goroutine for each. The service goroutines read requests and then call
  130. // handler to reply to them. Handler is typically nil, in which case the
  131. // DefaultServeMux is used.
  132. //
  133. // In addition to the standard Serve behaviour each connection is added to a
  134. // sync.Waitgroup so that all outstanding connections can be served before shutting
  135. // down the server.
  136. func (srv *Server) Serve(serve ServeFunction) error {
  137. defer log.Debug("Serve() returning... (PID: %d)", syscall.Getpid())
  138. srv.setState(stateRunning)
  139. GetManager().RegisterServer()
  140. err := serve(srv.listener)
  141. log.Debug("Waiting for connections to finish... (PID: %d)", syscall.Getpid())
  142. srv.wg.Wait()
  143. srv.setState(stateTerminate)
  144. GetManager().ServerDone()
  145. // use of closed means that the listeners are closed - i.e. we should be shutting down - return nil
  146. if err == nil || strings.Contains(err.Error(), "use of closed") || strings.Contains(err.Error(), "http: Server closed") {
  147. return nil
  148. }
  149. return err
  150. }
  151. func (srv *Server) getState() state {
  152. srv.lock.RLock()
  153. defer srv.lock.RUnlock()
  154. return srv.state
  155. }
  156. func (srv *Server) setState(st state) {
  157. srv.lock.Lock()
  158. defer srv.lock.Unlock()
  159. srv.state = st
  160. }
  161. type filer interface {
  162. File() (*os.File, error)
  163. }
  164. type wrappedListener struct {
  165. net.Listener
  166. stopped bool
  167. server *Server
  168. }
  169. func newWrappedListener(l net.Listener, srv *Server) *wrappedListener {
  170. return &wrappedListener{
  171. Listener: l,
  172. server: srv,
  173. }
  174. }
  175. func (wl *wrappedListener) Accept() (net.Conn, error) {
  176. var c net.Conn
  177. // Set keepalive on TCPListeners connections.
  178. if tcl, ok := wl.Listener.(*net.TCPListener); ok {
  179. tc, err := tcl.AcceptTCP()
  180. if err != nil {
  181. return nil, err
  182. }
  183. _ = tc.SetKeepAlive(true) // see http.tcpKeepAliveListener
  184. _ = tc.SetKeepAlivePeriod(3 * time.Minute) // see http.tcpKeepAliveListener
  185. c = tc
  186. } else {
  187. var err error
  188. c, err = wl.Listener.Accept()
  189. if err != nil {
  190. return nil, err
  191. }
  192. }
  193. closed := int32(0)
  194. c = &wrappedConn{
  195. Conn: c,
  196. server: wl.server,
  197. closed: &closed,
  198. perWriteTimeout: wl.server.PerWriteTimeout,
  199. perWritePerKbTimeout: wl.server.PerWritePerKbTimeout,
  200. }
  201. wl.server.wg.Add(1)
  202. return c, nil
  203. }
  204. func (wl *wrappedListener) Close() error {
  205. if wl.stopped {
  206. return syscall.EINVAL
  207. }
  208. wl.stopped = true
  209. return wl.Listener.Close()
  210. }
  211. func (wl *wrappedListener) File() (*os.File, error) {
  212. // returns a dup(2) - FD_CLOEXEC flag *not* set so the listening socket can be passed to child processes
  213. return wl.Listener.(filer).File()
  214. }
  215. type wrappedConn struct {
  216. net.Conn
  217. server *Server
  218. closed *int32
  219. deadline time.Time
  220. perWriteTimeout time.Duration
  221. perWritePerKbTimeout time.Duration
  222. }
  223. func (w *wrappedConn) Write(p []byte) (n int, err error) {
  224. if w.perWriteTimeout > 0 {
  225. minTimeout := time.Duration(len(p)/1024) * w.perWritePerKbTimeout
  226. minDeadline := time.Now().Add(minTimeout).Add(w.perWriteTimeout)
  227. w.deadline = w.deadline.Add(minTimeout)
  228. if minDeadline.After(w.deadline) {
  229. w.deadline = minDeadline
  230. }
  231. _ = w.Conn.SetWriteDeadline(w.deadline)
  232. }
  233. return w.Conn.Write(p)
  234. }
  235. func (w *wrappedConn) Close() error {
  236. if atomic.CompareAndSwapInt32(w.closed, 0, 1) {
  237. defer func() {
  238. if err := recover(); err != nil {
  239. select {
  240. case <-GetManager().IsHammer():
  241. // Likely deadlocked request released at hammertime
  242. log.Warn("Panic during connection close! %v. Likely there has been a deadlocked request which has been released by forced shutdown.", err)
  243. default:
  244. log.Error("Panic during connection close! %v", err)
  245. }
  246. }
  247. }()
  248. w.server.wg.Done()
  249. }
  250. return w.Conn.Close()
  251. }