@@ -1520,6 +1520,11 @@ def _close_kernel_socket(self):
1520
1520
raise
1521
1521
1522
1522
1523
+ # Unique identifier used to indicate the thread that handles unservicable
1524
+ # connections should shut down.
1525
+ _SHUT_DOWN_UNSERVICABLES_THREAD = object ()
1526
+
1527
+
1523
1528
class HTTPServer :
1524
1529
"""An HTTP server."""
1525
1530
@@ -1872,23 +1877,30 @@ def _serve_unservicable(self):
1872
1877
"""Serve connections we can't handle a 503."""
1873
1878
while self .ready :
1874
1879
conn = self ._unservicable_conns .get ()
1875
- if conn is None :
1880
+ if conn is _SHUT_DOWN_UNSERVICABLES_THREAD :
1876
1881
return
1877
1882
request = HTTPRequest (self , conn )
1878
1883
try :
1879
1884
request .simple_response ('503 Service Unavailable' )
1885
+ except (socket .error , errors .FatalSSLAlert ):
1886
+ # We're sending the 503 error to be polite, it it fails that's
1887
+ # fine.
1888
+ continue
1880
1889
except Exception as ex :
1881
1890
self .server .error_log (
1882
1891
repr (ex ),
1883
1892
level = logging .ERROR ,
1884
1893
traceback = True ,
1885
1894
)
1886
- conn .linger = True
1887
1895
conn .close ()
1888
1896
1889
1897
def serve (self ):
1890
1898
"""Serve requests, after invoking :func:`prepare()`."""
1899
+ # This thread will handle unservicable connections, as added to
1900
+ # self._unservicable_conns queue. It will run forever, until
1901
+ # self.stop() tells it to shut down.
1891
1902
threading .Thread (target = self ._serve_unservicable ).start ()
1903
+
1892
1904
while self .ready and not self .interrupt :
1893
1905
try :
1894
1906
self ._connections .run (self .expiration_interval )
@@ -2221,7 +2233,11 @@ def stop(self): # noqa: C901 # FIXME
2221
2233
return # already stopped
2222
2234
2223
2235
self .ready = False
2224
- self ._unservicable_conns .put (None )
2236
+
2237
+ # This tells the thread that handles unservicable connections to shut
2238
+ # down:
2239
+ self ._unservicable_conns .put (_SHUT_DOWN_UNSERVICABLES_THREAD )
2240
+
2225
2241
if self ._start_time is not None :
2226
2242
self ._run_time += time .time () - self ._start_time
2227
2243
self ._start_time = None
0 commit comments