Development of an internal social media platform with personalised dashboards for students
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

util.py 15KB

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