httpserver.py 54 KB

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