httpserver.py 55 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415
  1. # (c) 2005 Ian Bicking and contributors; written for Paste (http://pythonpaste.org)
  2. # Licensed under the MIT license: http://www.opensource.org/licenses/mit-license.php
  3. # (c) 2005 Clark C. Evans
  4. # This module is part of the Python Paste Project and is released under
  5. # the MIT License: http://www.opensource.org/licenses/mit-license.php
  6. # This code was written with funding by http://prometheusresearch.com
  7. """
  8. WSGI HTTP Server
  9. This is a minimalistic WSGI server using Python's built-in BaseHTTPServer;
  10. if pyOpenSSL is installed, it also provides SSL capabilities.
  11. """
  12. # @@: add in protection against HTTP/1.0 clients who claim to
  13. # be 1.1 but do not send a Content-Length
  14. # @@: add support for chunked encoding, this is not a 1.1 server
  15. # till this is completed.
  16. from __future__ import print_function
  17. import atexit
  18. import traceback
  19. import socket, sys, threading
  20. import posixpath
  21. import six
  22. import time
  23. import os
  24. from itertools import count
  25. from six.moves import _thread
  26. from six.moves import queue
  27. from six.moves.BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
  28. from six.moves.socketserver import ThreadingMixIn
  29. from six.moves.urllib.parse import unquote, urlsplit
  30. from paste.util import converters
  31. import logging
  32. try:
  33. from paste.util import killthread
  34. except ImportError:
  35. # Not available, probably no ctypes
  36. killthread = None
  37. __all__ = ['WSGIHandlerMixin', 'WSGIServer', 'WSGIHandler', 'serve']
  38. __version__ = "0.5"
  39. class ContinueHook(object):
  40. """
  41. When a client request includes a 'Expect: 100-continue' header, then
  42. it is the responsibility of the server to send 100 Continue when it
  43. is ready for the content body. This allows authentication, access
  44. levels, and other exceptions to be detected *before* bandwith is
  45. spent on the request body.
  46. This is a rfile wrapper that implements this functionality by
  47. sending 100 Continue to the client immediately after the user
  48. requests the content via a read() operation on the rfile stream.
  49. After this response is sent, it becomes a pass-through object.
  50. """
  51. def __init__(self, rfile, write):
  52. self._ContinueFile_rfile = rfile
  53. self._ContinueFile_write = write
  54. for attr in ('close', 'closed', 'fileno', 'flush',
  55. 'mode', 'bufsize', 'softspace'):
  56. if hasattr(rfile, attr):
  57. setattr(self, attr, getattr(rfile, attr))
  58. for attr in ('read', 'readline', 'readlines'):
  59. if hasattr(rfile, attr):
  60. setattr(self, attr, getattr(self, '_ContinueFile_' + attr))
  61. def _ContinueFile_send(self):
  62. self._ContinueFile_write("HTTP/1.1 100 Continue\r\n\r\n")
  63. rfile = self._ContinueFile_rfile
  64. for attr in ('read', 'readline', 'readlines'):
  65. if hasattr(rfile, attr):
  66. setattr(self, attr, getattr(rfile, attr))
  67. def _ContinueFile_read(self, size=-1):
  68. self._ContinueFile_send()
  69. return self._ContinueFile_rfile.read(size)
  70. def _ContinueFile_readline(self, size=-1):
  71. self._ContinueFile_send()
  72. return self._ContinueFile_rfile.readline(size)
  73. def _ContinueFile_readlines(self, sizehint=0):
  74. self._ContinueFile_send()
  75. return self._ContinueFile_rfile.readlines(sizehint)
  76. class WSGIHandlerMixin:
  77. """
  78. WSGI mix-in for HTTPRequestHandler
  79. This class is a mix-in to provide WSGI functionality to any
  80. HTTPRequestHandler derivative (as provided in Python's BaseHTTPServer).
  81. This assumes a ``wsgi_application`` handler on ``self.server``.
  82. """
  83. lookup_addresses = True
  84. def log_request(self, *args, **kwargs):
  85. """ disable success request logging
  86. Logging transactions should not be part of a WSGI server,
  87. if you want logging; look at paste.translogger
  88. """
  89. pass
  90. def log_message(self, *args, **kwargs):
  91. """ disable error message logging
  92. Logging transactions should not be part of a WSGI server,
  93. if you want logging; look at paste.translogger
  94. """
  95. pass
  96. def version_string(self):
  97. """ behavior that BaseHTTPServer should have had """
  98. if not self.sys_version:
  99. return self.server_version
  100. else:
  101. return self.server_version + ' ' + self.sys_version
  102. def wsgi_write_chunk(self, chunk):
  103. """
  104. Write a chunk of the output stream; send headers if they
  105. have not already been sent.
  106. """
  107. if not self.wsgi_headers_sent and not self.wsgi_curr_headers:
  108. raise RuntimeError(
  109. "Content returned before start_response called")
  110. if not self.wsgi_headers_sent:
  111. self.wsgi_headers_sent = True
  112. (status, headers) = self.wsgi_curr_headers
  113. code, message = status.split(" ", 1)
  114. self.send_response(int(code), message)
  115. #
  116. # HTTP/1.1 compliance; either send Content-Length or
  117. # signal that the connection is being closed.
  118. #
  119. send_close = True
  120. for (k, v) in headers:
  121. lk = k.lower()
  122. if 'content-length' == lk:
  123. send_close = False
  124. if 'connection' == lk:
  125. if 'close' == v.lower():
  126. self.close_connection = 1
  127. send_close = False
  128. self.send_header(k, v)
  129. if send_close:
  130. self.close_connection = 1
  131. self.send_header('Connection', 'close')
  132. self.end_headers()
  133. self.wfile.write(chunk)
  134. def wsgi_start_response(self, status, response_headers, exc_info=None):
  135. if exc_info:
  136. try:
  137. if self.wsgi_headers_sent:
  138. six.reraise(exc_info[0], exc_info[1], exc_info[2])
  139. else:
  140. # In this case, we're going to assume that the
  141. # higher-level code is currently handling the
  142. # issue and returning a resonable response.
  143. # self.log_error(repr(exc_info))
  144. pass
  145. finally:
  146. exc_info = None
  147. elif self.wsgi_curr_headers:
  148. assert 0, "Attempt to set headers a second time w/o an exc_info"
  149. self.wsgi_curr_headers = (status, response_headers)
  150. return self.wsgi_write_chunk
  151. def wsgi_setup(self, environ=None):
  152. """
  153. Setup the member variables used by this WSGI mixin, including
  154. the ``environ`` and status member variables.
  155. After the basic environment is created; the optional ``environ``
  156. argument can be used to override any settings.
  157. """
  158. dummy_url = 'http://dummy%s' % (self.path,)
  159. (scheme, netloc, path, query, fragment) = urlsplit(dummy_url)
  160. path = unquote(path)
  161. endslash = path.endswith('/')
  162. path = posixpath.normpath(path)
  163. if endslash and path != '/':
  164. # Put the slash back...
  165. path += '/'
  166. (server_name, server_port) = self.server.server_address[:2]
  167. rfile = self.rfile
  168. # We can put in the protection to keep from over-reading the
  169. # file
  170. try:
  171. content_length = int(self.headers.get('Content-Length', '0'))
  172. except ValueError:
  173. content_length = 0
  174. if '100-continue' == self.headers.get('Expect','').lower():
  175. rfile = LimitedLengthFile(ContinueHook(rfile, self.wfile.write), content_length)
  176. else:
  177. if not hasattr(self.connection, 'get_context'):
  178. # @@: LimitedLengthFile is currently broken in connection
  179. # with SSL (sporatic errors that are diffcult to trace, but
  180. # ones that go away when you don't use LimitedLengthFile)
  181. rfile = LimitedLengthFile(rfile, content_length)
  182. remote_address = self.client_address[0]
  183. self.wsgi_environ = {
  184. 'wsgi.version': (1,0)
  185. ,'wsgi.url_scheme': 'http'
  186. ,'wsgi.input': rfile
  187. ,'wsgi.errors': sys.stderr
  188. ,'wsgi.multithread': True
  189. ,'wsgi.multiprocess': False
  190. ,'wsgi.run_once': False
  191. # CGI variables required by PEP-333
  192. ,'REQUEST_METHOD': self.command
  193. ,'SCRIPT_NAME': '' # application is root of server
  194. ,'PATH_INFO': path
  195. ,'QUERY_STRING': query
  196. ,'CONTENT_TYPE': self.headers.get('Content-Type', '')
  197. ,'CONTENT_LENGTH': self.headers.get('Content-Length', '0')
  198. ,'SERVER_NAME': server_name
  199. ,'SERVER_PORT': str(server_port)
  200. ,'SERVER_PROTOCOL': self.request_version
  201. # CGI not required by PEP-333
  202. ,'REMOTE_ADDR': remote_address
  203. }
  204. if scheme:
  205. self.wsgi_environ['paste.httpserver.proxy.scheme'] = scheme
  206. if netloc:
  207. self.wsgi_environ['paste.httpserver.proxy.host'] = netloc
  208. if self.lookup_addresses:
  209. # @@: make lookup_addreses actually work, at this point
  210. # it has been address_string() is overriden down in
  211. # file and hence is a noop
  212. if remote_address.startswith("192.168.") \
  213. or remote_address.startswith("10.") \
  214. or remote_address.startswith("172.16."):
  215. pass
  216. else:
  217. address_string = None # self.address_string()
  218. if address_string:
  219. self.wsgi_environ['REMOTE_HOST'] = address_string
  220. if hasattr(self.server, 'thread_pool'):
  221. # Now that we know what the request was for, we should
  222. # tell the thread pool what its worker is working on
  223. self.server.thread_pool.worker_tracker[_thread.get_ident()][1] = self.wsgi_environ
  224. self.wsgi_environ['paste.httpserver.thread_pool'] = self.server.thread_pool
  225. for k, v in self.headers.items():
  226. key = 'HTTP_' + k.replace("-","_").upper()
  227. if key in ('HTTP_CONTENT_TYPE','HTTP_CONTENT_LENGTH'):
  228. continue
  229. self.wsgi_environ[key] = ','.join(self.headers.get(k))
  230. if hasattr(self.connection,'get_context'):
  231. self.wsgi_environ['wsgi.url_scheme'] = 'https'
  232. # @@: extract other SSL parameters from pyOpenSSL at...
  233. # http://www.modssl.org/docs/2.8/ssl_reference.html#ToC25
  234. if environ:
  235. assert isinstance(environ, dict)
  236. self.wsgi_environ.update(environ)
  237. if 'on' == environ.get('HTTPS'):
  238. self.wsgi_environ['wsgi.url_scheme'] = 'https'
  239. self.wsgi_curr_headers = None
  240. self.wsgi_headers_sent = False
  241. def wsgi_connection_drop(self, exce, environ=None):
  242. """
  243. Override this if you're interested in socket exceptions, such
  244. as when the user clicks 'Cancel' during a file download.
  245. """
  246. pass
  247. def wsgi_execute(self, environ=None):
  248. """
  249. Invoke the server's ``wsgi_application``.
  250. """
  251. self.wsgi_setup(environ)
  252. try:
  253. result = self.server.wsgi_application(self.wsgi_environ,
  254. self.wsgi_start_response)
  255. try:
  256. for chunk in result:
  257. self.wsgi_write_chunk(chunk)
  258. if not self.wsgi_headers_sent:
  259. self.wsgi_write_chunk('')
  260. finally:
  261. if hasattr(result,'close'):
  262. result.close()
  263. result = None
  264. except socket.error as exce:
  265. self.wsgi_connection_drop(exce, environ)
  266. return
  267. except:
  268. if not self.wsgi_headers_sent:
  269. error_msg = "Internal Server Error\n"
  270. self.wsgi_curr_headers = (
  271. '500 Internal Server Error',
  272. [('Content-type', 'text/plain'),
  273. ('Content-length', str(len(error_msg)))])
  274. self.wsgi_write_chunk("Internal Server Error\n")
  275. raise
  276. #
  277. # SSL Functionality
  278. #
  279. # This implementation was motivated by Sebastien Martini's SSL example
  280. # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/442473
  281. #
  282. try:
  283. from OpenSSL import SSL, tsafe
  284. SocketErrors = (socket.error, SSL.ZeroReturnError, SSL.SysCallError)
  285. except ImportError:
  286. # Do not require pyOpenSSL to be installed, but disable SSL
  287. # functionality in that case.
  288. SSL = None
  289. SocketErrors = (socket.error,)
  290. class SecureHTTPServer(HTTPServer):
  291. def __init__(self, server_address, RequestHandlerClass,
  292. ssl_context=None, request_queue_size=None):
  293. assert not ssl_context, "pyOpenSSL not installed"
  294. HTTPServer.__init__(self, server_address, RequestHandlerClass)
  295. if request_queue_size:
  296. self.socket.listen(request_queue_size)
  297. else:
  298. class _ConnFixer(object):
  299. """ wraps a socket connection so it implements makefile """
  300. def __init__(self, conn):
  301. self.__conn = conn
  302. def makefile(self, mode, bufsize):
  303. return socket._fileobject(self.__conn, mode, bufsize)
  304. def __getattr__(self, attrib):
  305. return getattr(self.__conn, attrib)
  306. class SecureHTTPServer(HTTPServer):
  307. """
  308. Provides SSL server functionality on top of the BaseHTTPServer
  309. by overriding _private_ members of Python's standard
  310. distribution. The interface for this instance only changes by
  311. adding a an optional ssl_context attribute to the constructor:
  312. cntx = SSL.Context(SSL.SSLv23_METHOD)
  313. cntx.use_privatekey_file("host.pem")
  314. cntx.use_certificate_file("host.pem")
  315. """
  316. def __init__(self, server_address, RequestHandlerClass,
  317. ssl_context=None, request_queue_size=None):
  318. # This overrides the implementation of __init__ in python's
  319. # SocketServer.TCPServer (which BaseHTTPServer.HTTPServer
  320. # does not override, thankfully).
  321. HTTPServer.__init__(self, server_address, RequestHandlerClass)
  322. self.socket = socket.socket(self.address_family,
  323. self.socket_type)
  324. self.ssl_context = ssl_context
  325. if ssl_context:
  326. class TSafeConnection(tsafe.Connection):
  327. def settimeout(self, *args):
  328. self._lock.acquire()
  329. try:
  330. return self._ssl_conn.settimeout(*args)
  331. finally:
  332. self._lock.release()
  333. def gettimeout(self):
  334. self._lock.acquire()
  335. try:
  336. return self._ssl_conn.gettimeout()
  337. finally:
  338. self._lock.release()
  339. self.socket = TSafeConnection(ssl_context, self.socket)
  340. self.server_bind()
  341. if request_queue_size:
  342. self.socket.listen(request_queue_size)
  343. self.server_activate()
  344. def get_request(self):
  345. # The default SSL request object does not seem to have a
  346. # ``makefile(mode, bufsize)`` method as expected by
  347. # Socketserver.StreamRequestHandler.
  348. (conn, info) = self.socket.accept()
  349. if self.ssl_context:
  350. conn = _ConnFixer(conn)
  351. return (conn, info)
  352. def _auto_ssl_context():
  353. import OpenSSL, random
  354. pkey = OpenSSL.crypto.PKey()
  355. pkey.generate_key(OpenSSL.crypto.TYPE_RSA, 768)
  356. cert = OpenSSL.crypto.X509()
  357. cert.set_serial_number(random.randint(0, sys.maxint))
  358. cert.gmtime_adj_notBefore(0)
  359. cert.gmtime_adj_notAfter(60 * 60 * 24 * 365)
  360. cert.get_subject().CN = '*'
  361. cert.get_subject().O = 'Dummy Certificate'
  362. cert.get_issuer().CN = 'Untrusted Authority'
  363. cert.get_issuer().O = 'Self-Signed'
  364. cert.set_pubkey(pkey)
  365. cert.sign(pkey, 'md5')
  366. ctx = SSL.Context(SSL.SSLv23_METHOD)
  367. ctx.use_privatekey(pkey)
  368. ctx.use_certificate(cert)
  369. return ctx
  370. class WSGIHandler(WSGIHandlerMixin, BaseHTTPRequestHandler):
  371. """
  372. A WSGI handler that overrides POST, GET and HEAD to delegate
  373. requests to the server's ``wsgi_application``.
  374. """
  375. server_version = 'PasteWSGIServer/' + __version__
  376. def handle_one_request(self):
  377. """Handle a single HTTP request.
  378. You normally don't need to override this method; see the class
  379. __doc__ string for information on how to handle specific HTTP
  380. commands such as GET and POST.
  381. """
  382. self.raw_requestline = self.rfile.readline()
  383. if not self.raw_requestline:
  384. self.close_connection = 1
  385. return
  386. if not self.parse_request(): # An error code has been sent, just exit
  387. return
  388. self.wsgi_execute()
  389. def handle(self):
  390. # don't bother logging disconnects while handling a request
  391. try:
  392. BaseHTTPRequestHandler.handle(self)
  393. except SocketErrors as exce:
  394. self.wsgi_connection_drop(exce)
  395. def address_string(self):
  396. """Return the client address formatted for logging.
  397. This is overridden so that no hostname lookup is done.
  398. """
  399. return ''
  400. class LimitedLengthFile(object):
  401. def __init__(self, file, length):
  402. self.file = file
  403. self.length = length
  404. self._consumed = 0
  405. if hasattr(self.file, 'seek'):
  406. self.seek = self._seek
  407. def __repr__(self):
  408. base_repr = repr(self.file)
  409. return base_repr[:-1] + ' length=%s>' % self.length
  410. def read(self, length=None):
  411. left = self.length - self._consumed
  412. if length is None:
  413. length = left
  414. else:
  415. length = min(length, left)
  416. # next two lines are hnecessary only if read(0) blocks
  417. if not left:
  418. return ''
  419. data = self.file.read(length)
  420. self._consumed += len(data)
  421. return data
  422. def readline(self, *args):
  423. max_read = self.length - self._consumed
  424. if len(args):
  425. max_read = min(args[0], max_read)
  426. data = self.file.readline(max_read)
  427. self._consumed += len(data)
  428. return data
  429. def readlines(self, hint=None):
  430. data = self.file.readlines(hint)
  431. for chunk in data:
  432. self._consumed += len(chunk)
  433. return data
  434. def __iter__(self):
  435. return self
  436. def next(self):
  437. if self.length - self._consumed <= 0:
  438. raise StopIteration
  439. return self.readline()
  440. ## Optional methods ##
  441. def _seek(self, place):
  442. self.file.seek(place)
  443. self._consumed = place
  444. def tell(self):
  445. if hasattr(self.file, 'tell'):
  446. return self.file.tell()
  447. else:
  448. return self._consumed
  449. class ThreadPool(object):
  450. """
  451. Generic thread pool with a queue of callables to consume.
  452. Keeps a notion of the status of its worker threads:
  453. idle: worker thread with nothing to do
  454. busy: worker thread doing its job
  455. hung: worker thread that's been doing a job for too long
  456. dying: a hung thread that has been killed, but hasn't died quite
  457. yet.
  458. zombie: what was a worker thread that we've tried to kill but
  459. isn't dead yet.
  460. At any time you can call track_threads, to get a dictionary with
  461. these keys and lists of thread_ids that fall in that status. All
  462. keys will be present, even if they point to emty lists.
  463. hung threads are threads that have been busy more than
  464. hung_thread_limit seconds. Hung threads are killed when they live
  465. longer than kill_thread_limit seconds. A thread is then
  466. considered dying for dying_limit seconds, if it is still alive
  467. after that it is considered a zombie.
  468. When there are no idle workers and a request comes in, another
  469. worker *may* be spawned. If there are less than spawn_if_under
  470. threads in the busy state, another thread will be spawned. So if
  471. the limit is 5, and there are 4 hung threads and 6 busy threads,
  472. no thread will be spawned.
  473. When there are more than max_zombie_threads_before_die zombie
  474. threads, a SystemExit exception will be raised, stopping the
  475. server. Use 0 or None to never raise this exception. Zombie
  476. threads *should* get cleaned up, but killing threads is no
  477. necessarily reliable. This is turned off by default, since it is
  478. only a good idea if you've deployed the server with some process
  479. watching from above (something similar to daemontools or zdaemon).
  480. Each worker thread only processes ``max_requests`` tasks before it
  481. dies and replaces itself with a new worker thread.
  482. """
  483. SHUTDOWN = object()
  484. def __init__(
  485. self, nworkers, name="ThreadPool", daemon=False,
  486. max_requests=100, # threads are killed after this many requests
  487. hung_thread_limit=30, # when a thread is marked "hung"
  488. kill_thread_limit=1800, # when you kill that hung thread
  489. dying_limit=300, # seconds that a kill should take to go into effect (longer than this and the thread is a "zombie")
  490. spawn_if_under=5, # spawn if there's too many hung threads
  491. max_zombie_threads_before_die=0, # when to give up on the process
  492. hung_check_period=100, # every 100 requests check for hung workers
  493. logger=None, # Place to log messages to
  494. error_email=None, # Person(s) to notify if serious problem occurs
  495. ):
  496. """
  497. Create thread pool with `nworkers` worker threads.
  498. """
  499. self.nworkers = nworkers
  500. self.max_requests = max_requests
  501. self.name = name
  502. self.queue = queue.Queue()
  503. self.workers = []
  504. self.daemon = daemon
  505. if logger is None:
  506. logger = logging.getLogger('paste.httpserver.ThreadPool')
  507. if isinstance(logger, six.string_types):
  508. logger = logging.getLogger(logger)
  509. self.logger = logger
  510. self.error_email = error_email
  511. self._worker_count = count()
  512. assert (not kill_thread_limit
  513. or kill_thread_limit >= hung_thread_limit), (
  514. "kill_thread_limit (%s) should be higher than hung_thread_limit (%s)"
  515. % (kill_thread_limit, hung_thread_limit))
  516. if not killthread:
  517. kill_thread_limit = 0
  518. self.logger.info(
  519. "Cannot use kill_thread_limit as ctypes/killthread is not available")
  520. self.kill_thread_limit = kill_thread_limit
  521. self.dying_limit = dying_limit
  522. self.hung_thread_limit = hung_thread_limit
  523. assert spawn_if_under <= nworkers, (
  524. "spawn_if_under (%s) should be less than nworkers (%s)"
  525. % (spawn_if_under, nworkers))
  526. self.spawn_if_under = spawn_if_under
  527. self.max_zombie_threads_before_die = max_zombie_threads_before_die
  528. self.hung_check_period = hung_check_period
  529. self.requests_since_last_hung_check = 0
  530. # Used to keep track of what worker is doing what:
  531. self.worker_tracker = {}
  532. # Used to keep track of the workers not doing anything:
  533. self.idle_workers = []
  534. # Used to keep track of threads that have been killed, but maybe aren't dead yet:
  535. self.dying_threads = {}
  536. # This is used to track when we last had to add idle workers;
  537. # we shouldn't cull extra workers until some time has passed
  538. # (hung_thread_limit) since workers were added:
  539. self._last_added_new_idle_workers = 0
  540. if not daemon:
  541. atexit.register(self.shutdown)
  542. for i in range(self.nworkers):
  543. self.add_worker_thread(message='Initial worker pool')
  544. def add_task(self, task):
  545. """
  546. Add a task to the queue
  547. """
  548. self.logger.debug('Added task (%i tasks queued)', self.queue.qsize())
  549. if self.hung_check_period:
  550. self.requests_since_last_hung_check += 1
  551. if self.requests_since_last_hung_check > self.hung_check_period:
  552. self.requests_since_last_hung_check = 0
  553. self.kill_hung_threads()
  554. if not self.idle_workers and self.spawn_if_under:
  555. # spawn_if_under can come into effect...
  556. busy = 0
  557. now = time.time()
  558. self.logger.debug('No idle workers for task; checking if we need to make more workers')
  559. for worker in self.workers:
  560. if not hasattr(worker, 'thread_id'):
  561. # Not initialized
  562. continue
  563. time_started, info = self.worker_tracker.get(worker.thread_id,
  564. (None, None))
  565. if time_started is not None:
  566. if now - time_started < self.hung_thread_limit:
  567. busy += 1
  568. if busy < self.spawn_if_under:
  569. self.logger.info(
  570. 'No idle tasks, and only %s busy tasks; adding %s more '
  571. 'workers', busy, self.spawn_if_under-busy)
  572. self._last_added_new_idle_workers = time.time()
  573. for i in range(self.spawn_if_under - busy):
  574. self.add_worker_thread(message='Response to lack of idle workers')
  575. else:
  576. self.logger.debug(
  577. 'No extra workers needed (%s busy workers)',
  578. busy)
  579. if (len(self.workers) > self.nworkers
  580. and len(self.idle_workers) > 3
  581. and time.time()-self._last_added_new_idle_workers > self.hung_thread_limit):
  582. # We've spawned worers in the past, but they aren't needed
  583. # anymore; kill off some
  584. self.logger.info(
  585. 'Culling %s extra workers (%s idle workers present)',
  586. len(self.workers)-self.nworkers, len(self.idle_workers))
  587. self.logger.debug(
  588. 'Idle workers: %s', self.idle_workers)
  589. for i in range(len(self.workers) - self.nworkers):
  590. self.queue.put(self.SHUTDOWN)
  591. self.queue.put(task)
  592. def track_threads(self):
  593. """
  594. Return a dict summarizing the threads in the pool (as
  595. described in the ThreadPool docstring).
  596. """
  597. result = dict(idle=[], busy=[], hung=[], dying=[], zombie=[])
  598. now = time.time()
  599. for worker in self.workers:
  600. if not hasattr(worker, 'thread_id'):
  601. # The worker hasn't fully started up, we should just
  602. # ignore it
  603. continue
  604. time_started, info = self.worker_tracker.get(worker.thread_id,
  605. (None, None))
  606. if time_started is not None:
  607. if now - time_started > self.hung_thread_limit:
  608. result['hung'].append(worker)
  609. else:
  610. result['busy'].append(worker)
  611. else:
  612. result['idle'].append(worker)
  613. for thread_id, (time_killed, worker) in self.dying_threads.items():
  614. if not self.thread_exists(thread_id):
  615. # Cull dying threads that are actually dead and gone
  616. self.logger.info('Killed thread %s no longer around',
  617. thread_id)
  618. try:
  619. del self.dying_threads[thread_id]
  620. except KeyError:
  621. pass
  622. continue
  623. if now - time_killed > self.dying_limit:
  624. result['zombie'].append(worker)
  625. else:
  626. result['dying'].append(worker)
  627. return result
  628. def kill_worker(self, thread_id):
  629. """
  630. Removes the worker with the given thread_id from the pool, and
  631. replaces it with a new worker thread.
  632. This should only be done for mis-behaving workers.
  633. """
  634. if killthread is None:
  635. raise RuntimeError(
  636. "Cannot kill worker; killthread/ctypes not available")
  637. thread_obj = threading._active.get(thread_id)
  638. killthread.async_raise(thread_id, SystemExit)
  639. try:
  640. del self.worker_tracker[thread_id]
  641. except KeyError:
  642. pass
  643. self.logger.info('Killing thread %s', thread_id)
  644. if thread_obj in self.workers:
  645. self.workers.remove(thread_obj)
  646. self.dying_threads[thread_id] = (time.time(), thread_obj)
  647. self.add_worker_thread(message='Replacement for killed thread %s' % thread_id)
  648. def thread_exists(self, thread_id):
  649. """
  650. Returns true if a thread with this id is still running
  651. """
  652. return thread_id in threading._active
  653. def add_worker_thread(self, *args, **kwargs):
  654. index = six.next(self._worker_count)
  655. worker = threading.Thread(target=self.worker_thread_callback,
  656. args=args, kwargs=kwargs,
  657. name=("worker %d" % index))
  658. worker.setDaemon(self.daemon)
  659. worker.start()
  660. def kill_hung_threads(self):
  661. """
  662. Tries to kill any hung threads
  663. """
  664. if not self.kill_thread_limit:
  665. # No killing should occur
  666. return
  667. now = time.time()
  668. max_time = 0
  669. total_time = 0
  670. idle_workers = 0
  671. starting_workers = 0
  672. working_workers = 0
  673. killed_workers = 0
  674. for worker in self.workers:
  675. if not hasattr(worker, 'thread_id'):
  676. # Not setup yet
  677. starting_workers += 1
  678. continue
  679. time_started, info = self.worker_tracker.get(worker.thread_id,
  680. (None, None))
  681. if time_started is None:
  682. # Must be idle
  683. idle_workers += 1
  684. continue
  685. working_workers += 1
  686. max_time = max(max_time, now-time_started)
  687. total_time += now-time_started
  688. if now - time_started > self.kill_thread_limit:
  689. self.logger.warning(
  690. 'Thread %s hung (working on task for %i seconds)',
  691. worker.thread_id, now - time_started)
  692. try:
  693. import pprint
  694. info_desc = pprint.pformat(info)
  695. except:
  696. out = six.StringIO()
  697. traceback.print_exc(file=out)
  698. info_desc = 'Error:\n%s' % out.getvalue()
  699. self.notify_problem(
  700. "Killing worker thread (id=%(thread_id)s) because it has been \n"
  701. "working on task for %(time)s seconds (limit is %(limit)s)\n"
  702. "Info on task:\n"
  703. "%(info)s"
  704. % dict(thread_id=worker.thread_id,
  705. time=now - time_started,
  706. limit=self.kill_thread_limit,
  707. info=info_desc))
  708. self.kill_worker(worker.thread_id)
  709. killed_workers += 1
  710. if working_workers:
  711. ave_time = float(total_time) / working_workers
  712. ave_time = '%.2fsec' % ave_time
  713. else:
  714. ave_time = 'N/A'
  715. self.logger.info(
  716. "kill_hung_threads status: %s threads (%s working, %s idle, %s starting) "
  717. "ave time %s, max time %.2fsec, killed %s workers"
  718. % (idle_workers + starting_workers + working_workers,
  719. working_workers, idle_workers, starting_workers,
  720. ave_time, max_time, killed_workers))
  721. self.check_max_zombies()
  722. def check_max_zombies(self):
  723. """
  724. Check if we've reached max_zombie_threads_before_die; if so
  725. then kill the entire process.
  726. """
  727. if not self.max_zombie_threads_before_die:
  728. return
  729. found = []
  730. now = time.time()
  731. for thread_id, (time_killed, worker) in self.dying_threads.items():
  732. if not self.thread_exists(thread_id):
  733. # Cull dying threads that are actually dead and gone
  734. try:
  735. del self.dying_threads[thread_id]
  736. except KeyError:
  737. pass
  738. continue
  739. if now - time_killed > self.dying_limit:
  740. found.append(thread_id)
  741. if found:
  742. self.logger.info('Found %s zombie threads', found)
  743. if len(found) > self.max_zombie_threads_before_die:
  744. self.logger.fatal(
  745. 'Exiting process because %s zombie threads is more than %s limit',
  746. len(found), self.max_zombie_threads_before_die)
  747. self.notify_problem(
  748. "Exiting process because %(found)s zombie threads "
  749. "(more than limit of %(limit)s)\n"
  750. "Bad threads (ids):\n"
  751. " %(ids)s\n"
  752. % dict(found=len(found),
  753. limit=self.max_zombie_threads_before_die,
  754. ids="\n ".join(map(str, found))),
  755. subject="Process restart (too many zombie threads)")
  756. self.shutdown(10)
  757. print('Shutting down', threading.currentThread())
  758. raise ServerExit(3)
  759. def worker_thread_callback(self, message=None):
  760. """
  761. Worker thread should call this method to get and process queued
  762. callables.
  763. """
  764. thread_obj = threading.currentThread()
  765. thread_id = thread_obj.thread_id = _thread.get_ident()
  766. self.workers.append(thread_obj)
  767. self.idle_workers.append(thread_id)
  768. requests_processed = 0
  769. add_replacement_worker = False
  770. self.logger.debug('Started new worker %s: %s', thread_id, message)
  771. try:
  772. while True:
  773. if self.max_requests and self.max_requests < requests_processed:
  774. # Replace this thread then die
  775. self.logger.debug('Thread %s processed %i requests (limit %s); stopping thread'
  776. % (thread_id, requests_processed, self.max_requests))
  777. add_replacement_worker = True
  778. break
  779. runnable = self.queue.get()
  780. if runnable is ThreadPool.SHUTDOWN:
  781. self.logger.debug('Worker %s asked to SHUTDOWN', thread_id)
  782. break
  783. try:
  784. self.idle_workers.remove(thread_id)
  785. except ValueError:
  786. pass
  787. self.worker_tracker[thread_id] = [time.time(), None]
  788. requests_processed += 1
  789. try:
  790. try:
  791. runnable()
  792. except:
  793. # We are later going to call sys.exc_clear(),
  794. # removing all remnants of any exception, so
  795. # we should log it now. But ideally no
  796. # exception should reach this level
  797. print('Unexpected exception in worker %r' % runnable,
  798. file=sys.stderr)
  799. traceback.print_exc()
  800. if thread_id in self.dying_threads:
  801. # That last exception was intended to kill me
  802. break
  803. finally:
  804. try:
  805. del self.worker_tracker[thread_id]
  806. except KeyError:
  807. pass
  808. if six.PY2:
  809. sys.exc_clear()
  810. self.idle_workers.append(thread_id)
  811. finally:
  812. try:
  813. del self.worker_tracker[thread_id]
  814. except KeyError:
  815. pass
  816. try:
  817. self.idle_workers.remove(thread_id)
  818. except ValueError:
  819. pass
  820. try:
  821. self.workers.remove(thread_obj)
  822. except ValueError:
  823. pass
  824. try:
  825. del self.dying_threads[thread_id]
  826. except KeyError:
  827. pass
  828. if add_replacement_worker:
  829. self.add_worker_thread(message='Voluntary replacement for thread %s' % thread_id)
  830. def shutdown(self, force_quit_timeout=0):
  831. """
  832. Shutdown the queue (after finishing any pending requests).
  833. """
  834. self.logger.info('Shutting down threadpool')
  835. # Add a shutdown request for every worker
  836. for i in range(len(self.workers)):
  837. self.queue.put(ThreadPool.SHUTDOWN)
  838. # Wait for each thread to terminate
  839. hung_workers = []
  840. for worker in self.workers:
  841. worker.join(0.5)
  842. if worker.isAlive():
  843. hung_workers.append(worker)
  844. zombies = []
  845. for thread_id in self.dying_threads:
  846. if self.thread_exists(thread_id):
  847. zombies.append(thread_id)
  848. if hung_workers or zombies:
  849. self.logger.info("%s workers didn't stop properly, and %s zombies",
  850. len(hung_workers), len(zombies))
  851. if hung_workers:
  852. for worker in hung_workers:
  853. self.kill_worker(worker.thread_id)
  854. self.logger.info('Workers killed forcefully')
  855. if force_quit_timeout:
  856. timed_out = False
  857. need_force_quit = bool(zombies)
  858. for worker in self.workers:
  859. if not timed_out and worker.isAlive():
  860. timed_out = True
  861. worker.join(force_quit_timeout)
  862. if worker.isAlive():
  863. print("Worker %s won't die" % worker)
  864. need_force_quit = True
  865. if need_force_quit:
  866. import atexit
  867. # Remove the threading atexit callback
  868. for callback in list(atexit._exithandlers):
  869. func = getattr(callback[0], 'im_func', None)
  870. if not func:
  871. continue
  872. globs = getattr(func, 'func_globals', {})
  873. mod = globs.get('__name__')
  874. if mod == 'threading':
  875. atexit._exithandlers.remove(callback)
  876. atexit._run_exitfuncs()
  877. print('Forcefully exiting process')
  878. os._exit(3)
  879. else:
  880. self.logger.info('All workers eventually killed')
  881. else:
  882. self.logger.info('All workers stopped')
  883. def notify_problem(self, msg, subject=None, spawn_thread=True):
  884. """
  885. Called when there's a substantial problem. msg contains the
  886. body of the notification, subject the summary.
  887. If spawn_thread is true, then the email will be send in
  888. another thread (so this doesn't block).
  889. """
  890. if not self.error_email:
  891. return
  892. if spawn_thread:
  893. t = threading.Thread(
  894. target=self.notify_problem,
  895. args=(msg, subject, False))
  896. t.start()
  897. return
  898. from_address = 'errors@localhost'
  899. if not subject:
  900. subject = msg.strip().splitlines()[0]
  901. subject = subject[:50]
  902. subject = '[http threadpool] %s' % subject
  903. headers = [
  904. "To: %s" % self.error_email,
  905. "From: %s" % from_address,
  906. "Subject: %s" % subject,
  907. ]
  908. try:
  909. system = ' '.join(os.uname())
  910. except:
  911. system = '(unknown)'
  912. body = (
  913. "An error has occurred in the paste.httpserver.ThreadPool\n"
  914. "Error:\n"
  915. " %(msg)s\n"
  916. "Occurred at: %(time)s\n"
  917. "PID: %(pid)s\n"
  918. "System: %(system)s\n"
  919. "Server .py file: %(file)s\n"
  920. % dict(msg=msg,
  921. time=time.strftime("%c"),
  922. pid=os.getpid(),
  923. system=system,
  924. file=os.path.abspath(__file__),
  925. ))
  926. message = '\n'.join(headers) + "\n\n" + body
  927. import smtplib
  928. server = smtplib.SMTP('localhost')
  929. error_emails = [
  930. e.strip() for e in self.error_email.split(",")
  931. if e.strip()]
  932. server.sendmail(from_address, error_emails, message)
  933. server.quit()
  934. print('email sent to', error_emails, message)
  935. class ThreadPoolMixIn(object):
  936. """
  937. Mix-in class to process requests from a thread pool
  938. """
  939. def __init__(self, nworkers, daemon=False, **threadpool_options):
  940. # Create and start the workers
  941. self.running = True
  942. assert nworkers > 0, "ThreadPoolMixIn servers must have at least one worker"
  943. self.thread_pool = ThreadPool(
  944. nworkers,
  945. "ThreadPoolMixIn HTTP server on %s:%d"
  946. % (self.server_name, self.server_port),
  947. daemon,
  948. **threadpool_options)
  949. def process_request(self, request, client_address):
  950. """
  951. Queue the request to be processed by on of the thread pool threads
  952. """
  953. # This sets the socket to blocking mode (and no timeout) since it
  954. # may take the thread pool a little while to get back to it. (This
  955. # is the default but since we set a timeout on the parent socket so
  956. # that we can trap interrupts we need to restore this,.)
  957. request.setblocking(1)
  958. # Queue processing of the request
  959. self.thread_pool.add_task(
  960. lambda: self.process_request_in_thread(request, client_address))
  961. def handle_error(self, request, client_address):
  962. exc_class, exc, tb = sys.exc_info()
  963. if exc_class is ServerExit:
  964. # This is actually a request to stop the server
  965. raise
  966. return super(ThreadPoolMixIn, self).handle_error(request, client_address)
  967. def process_request_in_thread(self, request, client_address):
  968. """
  969. The worker thread should call back here to do the rest of the
  970. request processing. Error handling normaller done in 'handle_request'
  971. must be done here.
  972. """
  973. try:
  974. self.finish_request(request, client_address)
  975. self.close_request(request)
  976. except:
  977. self.handle_error(request, client_address)
  978. self.close_request(request)
  979. exc = sys.exc_info()[1]
  980. if isinstance(exc, (MemoryError, KeyboardInterrupt)):
  981. raise
  982. def serve_forever(self):
  983. """
  984. Overrides `serve_forever` to shut the threadpool down cleanly.
  985. """
  986. try:
  987. while self.running:
  988. try:
  989. self.handle_request()
  990. except socket.timeout:
  991. # Timeout is expected, gives interrupts a chance to
  992. # propogate, just keep handling
  993. pass
  994. finally:
  995. self.thread_pool.shutdown()
  996. def server_activate(self):
  997. """
  998. Overrides server_activate to set timeout on our listener socket.
  999. """
  1000. # We set the timeout here so that we can trap interrupts on windows
  1001. self.socket.settimeout(1)
  1002. def server_close(self):
  1003. """
  1004. Finish pending requests and shutdown the server.
  1005. """
  1006. self.running = False
  1007. self.socket.close()
  1008. self.thread_pool.shutdown(60)
  1009. class WSGIServerBase(SecureHTTPServer):
  1010. def __init__(self, wsgi_application, server_address,
  1011. RequestHandlerClass=None, ssl_context=None,
  1012. request_queue_size=None):
  1013. SecureHTTPServer.__init__(self, server_address,
  1014. RequestHandlerClass, ssl_context,
  1015. request_queue_size=request_queue_size)
  1016. self.wsgi_application = wsgi_application
  1017. self.wsgi_socket_timeout = None
  1018. def get_request(self):
  1019. # If there is a socket_timeout, set it on the accepted
  1020. (conn,info) = SecureHTTPServer.get_request(self)
  1021. if self.wsgi_socket_timeout:
  1022. conn.settimeout(self.wsgi_socket_timeout)
  1023. return (conn, info)
  1024. class WSGIServer(ThreadingMixIn, WSGIServerBase):
  1025. daemon_threads = False
  1026. class WSGIThreadPoolServer(ThreadPoolMixIn, WSGIServerBase):
  1027. def __init__(self, wsgi_application, server_address,
  1028. RequestHandlerClass=None, ssl_context=None,
  1029. nworkers=10, daemon_threads=False,
  1030. threadpool_options=None, request_queue_size=None):
  1031. WSGIServerBase.__init__(self, wsgi_application, server_address,
  1032. RequestHandlerClass, ssl_context,
  1033. request_queue_size=request_queue_size)
  1034. if threadpool_options is None:
  1035. threadpool_options = {}
  1036. ThreadPoolMixIn.__init__(self, nworkers, daemon_threads,
  1037. **threadpool_options)
  1038. class ServerExit(SystemExit):
  1039. """
  1040. Raised to tell the server to really exit (SystemExit is normally
  1041. caught)
  1042. """
  1043. def serve(application, host=None, port=None, handler=None, ssl_pem=None,
  1044. ssl_context=None, server_version=None, protocol_version=None,
  1045. start_loop=True, daemon_threads=None, socket_timeout=None,
  1046. use_threadpool=None, threadpool_workers=10,
  1047. threadpool_options=None, request_queue_size=5):
  1048. """
  1049. Serves your ``application`` over HTTP(S) via WSGI interface
  1050. ``host``
  1051. This is the ipaddress to bind to (or a hostname if your
  1052. nameserver is properly configured). This defaults to
  1053. 127.0.0.1, which is not a public interface.
  1054. ``port``
  1055. The port to run on, defaults to 8080 for HTTP, or 4443 for
  1056. HTTPS. This can be a string or an integer value.
  1057. ``handler``
  1058. This is the HTTP request handler to use, it defaults to
  1059. ``WSGIHandler`` in this module.
  1060. ``ssl_pem``
  1061. This an optional SSL certificate file (via OpenSSL). You can
  1062. supply ``*`` and a development-only certificate will be
  1063. created for you, or you can generate a self-signed test PEM
  1064. certificate file as follows::
  1065. $ openssl genrsa 1024 > host.key
  1066. $ chmod 400 host.key
  1067. $ openssl req -new -x509 -nodes -sha1 -days 365 \\
  1068. -key host.key > host.cert
  1069. $ cat host.cert host.key > host.pem
  1070. $ chmod 400 host.pem
  1071. ``ssl_context``
  1072. This an optional SSL context object for the server. A SSL
  1073. context will be automatically constructed for you if you supply
  1074. ``ssl_pem``. Supply this to use a context of your own
  1075. construction.
  1076. ``server_version``
  1077. The version of the server as reported in HTTP response line. This
  1078. defaults to something like "PasteWSGIServer/0.5". Many servers
  1079. hide their code-base identity with a name like 'Amnesiac/1.0'
  1080. ``protocol_version``
  1081. This sets the protocol used by the server, by default
  1082. ``HTTP/1.0``. There is some support for ``HTTP/1.1``, which
  1083. defaults to nicer keep-alive connections. This server supports
  1084. ``100 Continue``, but does not yet support HTTP/1.1 Chunked
  1085. Encoding. Hence, if you use HTTP/1.1, you're somewhat in error
  1086. since chunked coding is a mandatory requirement of a HTTP/1.1
  1087. server. If you specify HTTP/1.1, every response *must* have a
  1088. ``Content-Length`` and you must be careful not to read past the
  1089. end of the socket.
  1090. ``start_loop``
  1091. This specifies if the server loop (aka ``server.serve_forever()``)
  1092. should be called; it defaults to ``True``.
  1093. ``daemon_threads``
  1094. This flag specifies if when your webserver terminates all
  1095. in-progress client connections should be droppped. It defaults
  1096. to ``False``. You might want to set this to ``True`` if you
  1097. are using ``HTTP/1.1`` and don't set a ``socket_timeout``.
  1098. ``socket_timeout``
  1099. This specifies the maximum amount of time that a connection to a
  1100. given client will be kept open. At this time, it is a rude
  1101. disconnect, but at a later time it might follow the RFC a bit
  1102. more closely.
  1103. ``use_threadpool``
  1104. Server requests from a pool of worker threads (``threadpool_workers``)
  1105. rather than creating a new thread for each request. This can
  1106. substantially reduce latency since there is a high cost associated
  1107. with thread creation.
  1108. ``threadpool_workers``
  1109. Number of worker threads to create when ``use_threadpool`` is true. This
  1110. can be a string or an integer value.
  1111. ``threadpool_options``
  1112. A dictionary of options to be used when instantiating the
  1113. threadpool. See paste.httpserver.ThreadPool for specific
  1114. options (``threadpool_workers`` is a specific option that can
  1115. also go here).
  1116. ``request_queue_size``
  1117. The 'backlog' argument to socket.listen(); specifies the
  1118. maximum number of queued connections.
  1119. """
  1120. is_ssl = False
  1121. if ssl_pem or ssl_context:
  1122. assert SSL, "pyOpenSSL is not installed"
  1123. is_ssl = True
  1124. port = int(port or 4443)
  1125. if not ssl_context:
  1126. if ssl_pem == '*':
  1127. ssl_context = _auto_ssl_context()
  1128. else:
  1129. ssl_context = SSL.Context(SSL.SSLv23_METHOD)
  1130. ssl_context.use_privatekey_file(ssl_pem)
  1131. ssl_context.use_certificate_chain_file(ssl_pem)
  1132. host = host or '127.0.0.1'
  1133. if port is None:
  1134. if ':' in host:
  1135. host, port = host.split(':', 1)
  1136. else:
  1137. port = 8080
  1138. server_address = (host, int(port))
  1139. if not handler:
  1140. handler = WSGIHandler
  1141. if server_version:
  1142. handler.server_version = server_version
  1143. handler.sys_version = None
  1144. if protocol_version:
  1145. assert protocol_version in ('HTTP/0.9', 'HTTP/1.0', 'HTTP/1.1')
  1146. handler.protocol_version = protocol_version
  1147. if use_threadpool is None:
  1148. use_threadpool = True
  1149. if converters.asbool(use_threadpool):
  1150. server = WSGIThreadPoolServer(application, server_address, handler,
  1151. ssl_context, int(threadpool_workers),
  1152. daemon_threads,
  1153. threadpool_options=threadpool_options,
  1154. request_queue_size=request_queue_size)
  1155. else:
  1156. server = WSGIServer(application, server_address, handler, ssl_context,
  1157. request_queue_size=request_queue_size)
  1158. if daemon_threads:
  1159. server.daemon_threads = daemon_threads
  1160. if socket_timeout:
  1161. server.wsgi_socket_timeout = int(socket_timeout)
  1162. if converters.asbool(start_loop):
  1163. protocol = is_ssl and 'https' or 'http'
  1164. host, port = server.server_address[:2]
  1165. if host == '0.0.0.0':
  1166. print('serving on 0.0.0.0:%s view at %s://127.0.0.1:%s'
  1167. % (port, protocol, port))
  1168. else:
  1169. print("serving on %s://%s:%s" % (protocol, host, port))
  1170. try:
  1171. server.serve_forever()
  1172. except KeyboardInterrupt:
  1173. # allow CTRL+C to shutdown
  1174. pass
  1175. return server
  1176. # For paste.deploy server instantiation (egg:Paste#http)
  1177. # Note: this gets a separate function because it has to expect string
  1178. # arguments (though that's not much of an issue yet, ever?)
  1179. def server_runner(wsgi_app, global_conf, **kwargs):
  1180. from paste.deploy.converters import asbool
  1181. for name in ['port', 'socket_timeout', 'threadpool_workers',
  1182. 'threadpool_hung_thread_limit',
  1183. 'threadpool_kill_thread_limit',
  1184. 'threadpool_dying_limit', 'threadpool_spawn_if_under',
  1185. 'threadpool_max_zombie_threads_before_die',
  1186. 'threadpool_hung_check_period',
  1187. 'threadpool_max_requests', 'request_queue_size']:
  1188. if name in kwargs:
  1189. kwargs[name] = int(kwargs[name])
  1190. for name in ['use_threadpool', 'daemon_threads']:
  1191. if name in kwargs:
  1192. kwargs[name] = asbool(kwargs[name])
  1193. threadpool_options = {}
  1194. for name, value in kwargs.items():
  1195. if name.startswith('threadpool_') and name != 'threadpool_workers':
  1196. threadpool_options[name[len('threadpool_'):]] = value
  1197. del kwargs[name]
  1198. if ('error_email' not in threadpool_options
  1199. and 'error_email' in global_conf):
  1200. threadpool_options['error_email'] = global_conf['error_email']
  1201. kwargs['threadpool_options'] = threadpool_options
  1202. serve(wsgi_app, **kwargs)
  1203. server_runner.__doc__ = (serve.__doc__ or '') + """
  1204. You can also set these threadpool options:
  1205. ``threadpool_max_requests``:
  1206. The maximum number of requests a worker thread will process
  1207. before dying (and replacing itself with a new worker thread).
  1208. Default 100.
  1209. ``threadpool_hung_thread_limit``:
  1210. The number of seconds a thread can work on a task before it is
  1211. considered hung (stuck). Default 30 seconds.
  1212. ``threadpool_kill_thread_limit``:
  1213. The number of seconds a thread can work before you should kill it
  1214. (assuming it will never finish). Default 600 seconds (10 minutes).
  1215. ``threadpool_dying_limit``:
  1216. The length of time after killing a thread that it should actually
  1217. disappear. If it lives longer than this, it is considered a
  1218. "zombie". Note that even in easy situations killing a thread can
  1219. be very slow. Default 300 seconds (5 minutes).
  1220. ``threadpool_spawn_if_under``:
  1221. If there are no idle threads and a request comes in, and there are
  1222. less than this number of *busy* threads, then add workers to the
  1223. pool. Busy threads are threads that have taken less than
  1224. ``threadpool_hung_thread_limit`` seconds so far. So if you get
  1225. *lots* of requests but they complete in a reasonable amount of time,
  1226. the requests will simply queue up (adding more threads probably
  1227. wouldn't speed them up). But if you have lots of hung threads and
  1228. one more request comes in, this will add workers to handle it.
  1229. Default 5.
  1230. ``threadpool_max_zombie_threads_before_die``:
  1231. If there are more zombies than this, just kill the process. This is
  1232. only good if you have a monitor that will automatically restart
  1233. the server. This can clean up the mess. Default 0 (disabled).
  1234. `threadpool_hung_check_period``:
  1235. Every X requests, check for hung threads that need to be killed,
  1236. or for zombie threads that should cause a restart. Default 100
  1237. requests.
  1238. ``threadpool_logger``:
  1239. Logging messages will go the logger named here.
  1240. ``threadpool_error_email`` (or global ``error_email`` setting):
  1241. When threads are killed or the process restarted, this email
  1242. address will be contacted (using an SMTP server on localhost).
  1243. """
  1244. if __name__ == '__main__':
  1245. from paste.wsgilib import dump_environ
  1246. #serve(dump_environ, ssl_pem="test.pem")
  1247. serve(dump_environ, server_version="Wombles/1.0",
  1248. protocol_version="HTTP/1.1", port="8888")