util.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547
  1. # -*- coding: utf-8 -
  2. #
  3. # This file is part of gunicorn released under the MIT license.
  4. # See the NOTICE for more information.
  5. from __future__ import print_function
  6. import email.utils
  7. import fcntl
  8. import io
  9. import os
  10. import pkg_resources
  11. import pwd
  12. import random
  13. import socket
  14. import sys
  15. import textwrap
  16. import time
  17. import traceback
  18. import inspect
  19. import errno
  20. import warnings
  21. import cgi
  22. import logging
  23. from gunicorn.errors import AppImportError
  24. from gunicorn.six import text_type
  25. from gunicorn.workers import SUPPORTED_WORKERS
  26. REDIRECT_TO = getattr(os, 'devnull', '/dev/null')
  27. # Server and Date aren't technically hop-by-hop
  28. # headers, but they are in the purview of the
  29. # origin server which the WSGI spec says we should
  30. # act like. So we drop them and add our own.
  31. #
  32. # In the future, concatenation server header values
  33. # might be better, but nothing else does it and
  34. # dropping them is easier.
  35. hop_headers = set("""
  36. connection keep-alive proxy-authenticate proxy-authorization
  37. te trailers transfer-encoding upgrade
  38. server date
  39. """.split())
  40. try:
  41. from setproctitle import setproctitle
  42. def _setproctitle(title):
  43. setproctitle("gunicorn: %s" % title)
  44. except ImportError:
  45. def _setproctitle(title):
  46. return
  47. try:
  48. from importlib import import_module
  49. except ImportError:
  50. def _resolve_name(name, package, level):
  51. """Return the absolute name of the module to be imported."""
  52. if not hasattr(package, 'rindex'):
  53. raise ValueError("'package' not set to a string")
  54. dot = len(package)
  55. for x in range(level, 1, -1):
  56. try:
  57. dot = package.rindex('.', 0, dot)
  58. except ValueError:
  59. msg = "attempted relative import beyond top-level package"
  60. raise ValueError(msg)
  61. return "%s.%s" % (package[:dot], name)
  62. def import_module(name, package=None):
  63. """Import a module.
  64. The 'package' argument is required when performing a relative import. It
  65. specifies the package to use as the anchor point from which to resolve the
  66. relative import to an absolute import.
  67. """
  68. if name.startswith('.'):
  69. if not package:
  70. raise TypeError("relative imports require the 'package' argument")
  71. level = 0
  72. for character in name:
  73. if character != '.':
  74. break
  75. level += 1
  76. name = _resolve_name(name[level:], package, level)
  77. __import__(name)
  78. return sys.modules[name]
  79. def load_class(uri, default="gunicorn.workers.sync.SyncWorker",
  80. section="gunicorn.workers"):
  81. if inspect.isclass(uri):
  82. return uri
  83. if uri.startswith("egg:"):
  84. # uses entry points
  85. entry_str = uri.split("egg:")[1]
  86. try:
  87. dist, name = entry_str.rsplit("#", 1)
  88. except ValueError:
  89. dist = entry_str
  90. name = default
  91. try:
  92. return pkg_resources.load_entry_point(dist, section, name)
  93. except:
  94. exc = traceback.format_exc()
  95. msg = "class uri %r invalid or not found: \n\n[%s]"
  96. raise RuntimeError(msg % (uri, exc))
  97. else:
  98. components = uri.split('.')
  99. if len(components) == 1:
  100. while True:
  101. if uri.startswith("#"):
  102. uri = uri[1:]
  103. if uri in SUPPORTED_WORKERS:
  104. components = SUPPORTED_WORKERS[uri].split(".")
  105. break
  106. try:
  107. return pkg_resources.load_entry_point("gunicorn",
  108. section, uri)
  109. except:
  110. exc = traceback.format_exc()
  111. msg = "class uri %r invalid or not found: \n\n[%s]"
  112. raise RuntimeError(msg % (uri, exc))
  113. klass = components.pop(-1)
  114. try:
  115. mod = import_module('.'.join(components))
  116. except:
  117. exc = traceback.format_exc()
  118. msg = "class uri %r invalid or not found: \n\n[%s]"
  119. raise RuntimeError(msg % (uri, exc))
  120. return getattr(mod, klass)
  121. def get_username(uid):
  122. """ get the username for a user id"""
  123. return pwd.getpwuid(uid).pw_name
  124. def set_owner_process(uid, gid, initgroups=False):
  125. """ set user and group of workers processes """
  126. if gid:
  127. if uid:
  128. try:
  129. username = get_username(uid)
  130. except KeyError:
  131. initgroups = False
  132. # versions of python < 2.6.2 don't manage unsigned int for
  133. # groups like on osx or fedora
  134. gid = abs(gid) & 0x7FFFFFFF
  135. if initgroups:
  136. os.initgroups(username, gid)
  137. else:
  138. os.setgid(gid)
  139. if uid:
  140. os.setuid(uid)
  141. def chown(path, uid, gid):
  142. gid = abs(gid) & 0x7FFFFFFF # see note above.
  143. os.chown(path, uid, gid)
  144. if sys.platform.startswith("win"):
  145. def _waitfor(func, pathname, waitall=False):
  146. # Peform the operation
  147. func(pathname)
  148. # Now setup the wait loop
  149. if waitall:
  150. dirname = pathname
  151. else:
  152. dirname, name = os.path.split(pathname)
  153. dirname = dirname or '.'
  154. # Check for `pathname` to be removed from the filesystem.
  155. # The exponential backoff of the timeout amounts to a total
  156. # of ~1 second after which the deletion is probably an error
  157. # anyway.
  158. # Testing on a i7@4.3GHz shows that usually only 1 iteration is
  159. # required when contention occurs.
  160. timeout = 0.001
  161. while timeout < 1.0:
  162. # Note we are only testing for the existance of the file(s) in
  163. # the contents of the directory regardless of any security or
  164. # access rights. If we have made it this far, we have sufficient
  165. # permissions to do that much using Python's equivalent of the
  166. # Windows API FindFirstFile.
  167. # Other Windows APIs can fail or give incorrect results when
  168. # dealing with files that are pending deletion.
  169. L = os.listdir(dirname)
  170. if not (L if waitall else name in L):
  171. return
  172. # Increase the timeout and try again
  173. time.sleep(timeout)
  174. timeout *= 2
  175. warnings.warn('tests may fail, delete still pending for ' + pathname,
  176. RuntimeWarning, stacklevel=4)
  177. def _unlink(filename):
  178. _waitfor(os.unlink, filename)
  179. else:
  180. _unlink = os.unlink
  181. def unlink(filename):
  182. try:
  183. _unlink(filename)
  184. except OSError as error:
  185. # The filename need not exist.
  186. if error.errno not in (errno.ENOENT, errno.ENOTDIR):
  187. raise
  188. def is_ipv6(addr):
  189. try:
  190. socket.inet_pton(socket.AF_INET6, addr)
  191. except socket.error: # not a valid address
  192. return False
  193. except ValueError: # ipv6 not supported on this platform
  194. return False
  195. return True
  196. def parse_address(netloc, default_port=8000):
  197. if netloc.startswith("unix://"):
  198. return netloc.split("unix://")[1]
  199. if netloc.startswith("unix:"):
  200. return netloc.split("unix:")[1]
  201. if netloc.startswith("tcp://"):
  202. netloc = netloc.split("tcp://")[1]
  203. # get host
  204. if '[' in netloc and ']' in netloc:
  205. host = netloc.split(']')[0][1:].lower()
  206. elif ':' in netloc:
  207. host = netloc.split(':')[0].lower()
  208. elif netloc == "":
  209. host = "0.0.0.0"
  210. else:
  211. host = netloc.lower()
  212. #get port
  213. netloc = netloc.split(']')[-1]
  214. if ":" in netloc:
  215. port = netloc.split(':', 1)[1]
  216. if not port.isdigit():
  217. raise RuntimeError("%r is not a valid port number." % port)
  218. port = int(port)
  219. else:
  220. port = default_port
  221. return (host, port)
  222. def close_on_exec(fd):
  223. flags = fcntl.fcntl(fd, fcntl.F_GETFD)
  224. flags |= fcntl.FD_CLOEXEC
  225. fcntl.fcntl(fd, fcntl.F_SETFD, flags)
  226. def set_non_blocking(fd):
  227. flags = fcntl.fcntl(fd, fcntl.F_GETFL) | os.O_NONBLOCK
  228. fcntl.fcntl(fd, fcntl.F_SETFL, flags)
  229. def close(sock):
  230. try:
  231. sock.close()
  232. except socket.error:
  233. pass
  234. try:
  235. from os import closerange
  236. except ImportError:
  237. def closerange(fd_low, fd_high):
  238. # Iterate through and close all file descriptors.
  239. for fd in range(fd_low, fd_high):
  240. try:
  241. os.close(fd)
  242. except OSError: # ERROR, fd wasn't open to begin with (ignored)
  243. pass
  244. def write_chunk(sock, data):
  245. if isinstance(data, text_type):
  246. data = data.encode('utf-8')
  247. chunk_size = "%X\r\n" % len(data)
  248. chunk = b"".join([chunk_size.encode('utf-8'), data, b"\r\n"])
  249. sock.sendall(chunk)
  250. def write(sock, data, chunked=False):
  251. if chunked:
  252. return write_chunk(sock, data)
  253. sock.sendall(data)
  254. def write_nonblock(sock, data, chunked=False):
  255. timeout = sock.gettimeout()
  256. if timeout != 0.0:
  257. try:
  258. sock.setblocking(0)
  259. return write(sock, data, chunked)
  260. finally:
  261. sock.setblocking(1)
  262. else:
  263. return write(sock, data, chunked)
  264. def write_error(sock, status_int, reason, mesg):
  265. html = textwrap.dedent("""\
  266. <html>
  267. <head>
  268. <title>%(reason)s</title>
  269. </head>
  270. <body>
  271. <h1><p>%(reason)s</p></h1>
  272. %(mesg)s
  273. </body>
  274. </html>
  275. """) % {"reason": reason, "mesg": cgi.escape(mesg)}
  276. http = textwrap.dedent("""\
  277. HTTP/1.1 %s %s\r
  278. Connection: close\r
  279. Content-Type: text/html\r
  280. Content-Length: %d\r
  281. \r
  282. %s""") % (str(status_int), reason, len(html), html)
  283. write_nonblock(sock, http.encode('latin1'))
  284. def import_app(module):
  285. parts = module.split(":", 1)
  286. if len(parts) == 1:
  287. module, obj = module, "application"
  288. else:
  289. module, obj = parts[0], parts[1]
  290. try:
  291. __import__(module)
  292. except ImportError:
  293. if module.endswith(".py") and os.path.exists(module):
  294. msg = "Failed to find application, did you mean '%s:%s'?"
  295. raise ImportError(msg % (module.rsplit(".", 1)[0], obj))
  296. else:
  297. raise
  298. mod = sys.modules[module]
  299. is_debug = logging.root.level == logging.DEBUG
  300. try:
  301. app = eval(obj, vars(mod))
  302. except NameError:
  303. if is_debug:
  304. traceback.print_exception(*sys.exc_info())
  305. raise AppImportError("Failed to find application: %r" % module)
  306. if app is None:
  307. raise AppImportError("Failed to find application object: %r" % obj)
  308. if not callable(app):
  309. raise AppImportError("Application object must be callable.")
  310. return app
  311. def getcwd():
  312. # get current path, try to use PWD env first
  313. try:
  314. a = os.stat(os.environ['PWD'])
  315. b = os.stat(os.getcwd())
  316. if a.st_ino == b.st_ino and a.st_dev == b.st_dev:
  317. cwd = os.environ['PWD']
  318. else:
  319. cwd = os.getcwd()
  320. except:
  321. cwd = os.getcwd()
  322. return cwd
  323. def http_date(timestamp=None):
  324. """Return the current date and time formatted for a message header."""
  325. if timestamp is None:
  326. timestamp = time.time()
  327. s = email.utils.formatdate(timestamp, localtime=False, usegmt=True)
  328. return s
  329. def is_hoppish(header):
  330. return header.lower().strip() in hop_headers
  331. def daemonize(enable_stdio_inheritance=False):
  332. """\
  333. Standard daemonization of a process.
  334. http://www.svbug.com/documentation/comp.unix.programmer-FAQ/faq_2.html#SEC16
  335. """
  336. if 'GUNICORN_FD' not in os.environ:
  337. if os.fork():
  338. os._exit(0)
  339. os.setsid()
  340. if os.fork():
  341. os._exit(0)
  342. os.umask(0o22)
  343. # In both the following any file descriptors above stdin
  344. # stdout and stderr are left untouched. The inheritence
  345. # option simply allows one to have output go to a file
  346. # specified by way of shell redirection when not wanting
  347. # to use --error-log option.
  348. if not enable_stdio_inheritance:
  349. # Remap all of stdin, stdout and stderr on to
  350. # /dev/null. The expectation is that users have
  351. # specified the --error-log option.
  352. closerange(0, 3)
  353. fd_null = os.open(REDIRECT_TO, os.O_RDWR)
  354. if fd_null != 0:
  355. os.dup2(fd_null, 0)
  356. os.dup2(fd_null, 1)
  357. os.dup2(fd_null, 2)
  358. else:
  359. fd_null = os.open(REDIRECT_TO, os.O_RDWR)
  360. # Always redirect stdin to /dev/null as we would
  361. # never expect to need to read interactive input.
  362. if fd_null != 0:
  363. os.close(0)
  364. os.dup2(fd_null, 0)
  365. # If stdout and stderr are still connected to
  366. # their original file descriptors we check to see
  367. # if they are associated with terminal devices.
  368. # When they are we map them to /dev/null so that
  369. # are still detached from any controlling terminal
  370. # properly. If not we preserve them as they are.
  371. #
  372. # If stdin and stdout were not hooked up to the
  373. # original file descriptors, then all bets are
  374. # off and all we can really do is leave them as
  375. # they were.
  376. #
  377. # This will allow 'gunicorn ... > output.log 2>&1'
  378. # to work with stdout/stderr going to the file
  379. # as expected.
  380. #
  381. # Note that if using --error-log option, the log
  382. # file specified through shell redirection will
  383. # only be used up until the log file specified
  384. # by the option takes over. As it replaces stdout
  385. # and stderr at the file descriptor level, then
  386. # anything using stdout or stderr, including having
  387. # cached a reference to them, will still work.
  388. def redirect(stream, fd_expect):
  389. try:
  390. fd = stream.fileno()
  391. if fd == fd_expect and stream.isatty():
  392. os.close(fd)
  393. os.dup2(fd_null, fd)
  394. except AttributeError:
  395. pass
  396. redirect(sys.stdout, 1)
  397. redirect(sys.stderr, 2)
  398. def seed():
  399. try:
  400. random.seed(os.urandom(64))
  401. except NotImplementedError:
  402. random.seed('%s.%s' % (time.time(), os.getpid()))
  403. def check_is_writeable(path):
  404. try:
  405. f = open(path, 'a')
  406. except IOError as e:
  407. raise RuntimeError("Error: '%s' isn't writable [%r]" % (path, e))
  408. f.close()
  409. def to_bytestring(value, encoding="utf8"):
  410. """Converts a string argument to a byte string"""
  411. if isinstance(value, bytes):
  412. return value
  413. if not isinstance(value, text_type):
  414. raise TypeError('%r is not a string' % value)
  415. return value.encode(encoding)
  416. def has_fileno(obj):
  417. if not hasattr(obj, "fileno"):
  418. return False
  419. # check BytesIO case and maybe others
  420. try:
  421. obj.fileno()
  422. except (AttributeError, IOError, io.UnsupportedOperation):
  423. return False
  424. return True
  425. def warn(msg):
  426. print("!!!", file=sys.stderr)
  427. lines = msg.splitlines()
  428. for i, line in enumerate(lines):
  429. if i == 0:
  430. line = "WARNING: %s" % line
  431. print("!!! %s" % line, file=sys.stderr)
  432. print("!!!\n", file=sys.stderr)
  433. sys.stderr.flush()
  434. def make_fail_app(msg):
  435. msg = to_bytestring(msg)
  436. def app(environ, start_response):
  437. start_response("500 Internal Server Error", [
  438. ("Content-Type", "text/plain"),
  439. ("Content-Length", str(len(msg)))
  440. ])
  441. return [msg]
  442. return app