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.

platforms.py 24KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813
  1. # -*- coding: utf-8 -*-
  2. """
  3. celery.platforms
  4. ~~~~~~~~~~~~~~~~
  5. Utilities dealing with platform specifics: signals, daemonization,
  6. users, groups, and so on.
  7. """
  8. from __future__ import absolute_import, print_function
  9. import atexit
  10. import errno
  11. import math
  12. import numbers
  13. import os
  14. import platform as _platform
  15. import signal as _signal
  16. import sys
  17. import warnings
  18. from collections import namedtuple
  19. from billiard import current_process
  20. # fileno used to be in this module
  21. from kombu.utils import maybe_fileno
  22. from kombu.utils.compat import get_errno
  23. from kombu.utils.encoding import safe_str
  24. from contextlib import contextmanager
  25. from .local import try_import
  26. from .five import items, range, reraise, string_t, zip_longest
  27. from .utils.functional import uniq
  28. _setproctitle = try_import('setproctitle')
  29. resource = try_import('resource')
  30. pwd = try_import('pwd')
  31. grp = try_import('grp')
  32. mputil = try_import('multiprocessing.util')
  33. __all__ = ['EX_OK', 'EX_FAILURE', 'EX_UNAVAILABLE', 'EX_USAGE', 'SYSTEM',
  34. 'IS_OSX', 'IS_WINDOWS', 'pyimplementation', 'LockFailed',
  35. 'get_fdmax', 'Pidfile', 'create_pidlock',
  36. 'close_open_fds', 'DaemonContext', 'detached', 'parse_uid',
  37. 'parse_gid', 'setgroups', 'initgroups', 'setgid', 'setuid',
  38. 'maybe_drop_privileges', 'signals', 'set_process_title',
  39. 'set_mp_process_title', 'get_errno_name', 'ignore_errno',
  40. 'fd_by_path']
  41. # exitcodes
  42. EX_OK = getattr(os, 'EX_OK', 0)
  43. EX_FAILURE = 1
  44. EX_UNAVAILABLE = getattr(os, 'EX_UNAVAILABLE', 69)
  45. EX_USAGE = getattr(os, 'EX_USAGE', 64)
  46. EX_CANTCREAT = getattr(os, 'EX_CANTCREAT', 73)
  47. SYSTEM = _platform.system()
  48. IS_OSX = SYSTEM == 'Darwin'
  49. IS_WINDOWS = SYSTEM == 'Windows'
  50. DAEMON_WORKDIR = '/'
  51. PIDFILE_FLAGS = os.O_CREAT | os.O_EXCL | os.O_WRONLY
  52. PIDFILE_MODE = ((os.R_OK | os.W_OK) << 6) | ((os.R_OK) << 3) | ((os.R_OK))
  53. PIDLOCKED = """ERROR: Pidfile ({0}) already exists.
  54. Seems we're already running? (pid: {1})"""
  55. _range = namedtuple('_range', ('start', 'stop'))
  56. C_FORCE_ROOT = os.environ.get('C_FORCE_ROOT', False)
  57. ROOT_DISALLOWED = """\
  58. Running a worker with superuser privileges when the
  59. worker accepts messages serialized with pickle is a very bad idea!
  60. If you really want to continue then you have to set the C_FORCE_ROOT
  61. environment variable (but please think about this before you do).
  62. User information: uid={uid} euid={euid} gid={gid} egid={egid}
  63. """
  64. ROOT_DISCOURAGED = """\
  65. You are running the worker with superuser privileges, which is
  66. absolutely not recommended!
  67. Please specify a different user using the -u option.
  68. User information: uid={uid} euid={euid} gid={gid} egid={egid}
  69. """
  70. def pyimplementation():
  71. """Return string identifying the current Python implementation."""
  72. if hasattr(_platform, 'python_implementation'):
  73. return _platform.python_implementation()
  74. elif sys.platform.startswith('java'):
  75. return 'Jython ' + sys.platform
  76. elif hasattr(sys, 'pypy_version_info'):
  77. v = '.'.join(str(p) for p in sys.pypy_version_info[:3])
  78. if sys.pypy_version_info[3:]:
  79. v += '-' + ''.join(str(p) for p in sys.pypy_version_info[3:])
  80. return 'PyPy ' + v
  81. else:
  82. return 'CPython'
  83. class LockFailed(Exception):
  84. """Raised if a pidlock can't be acquired."""
  85. def get_fdmax(default=None):
  86. """Return the maximum number of open file descriptors
  87. on this system.
  88. :keyword default: Value returned if there's no file
  89. descriptor limit.
  90. """
  91. try:
  92. return os.sysconf('SC_OPEN_MAX')
  93. except:
  94. pass
  95. if resource is None: # Windows
  96. return default
  97. fdmax = resource.getrlimit(resource.RLIMIT_NOFILE)[1]
  98. if fdmax == resource.RLIM_INFINITY:
  99. return default
  100. return fdmax
  101. class Pidfile(object):
  102. """Pidfile
  103. This is the type returned by :func:`create_pidlock`.
  104. TIP: Use the :func:`create_pidlock` function instead,
  105. which is more convenient and also removes stale pidfiles (when
  106. the process holding the lock is no longer running).
  107. """
  108. #: Path to the pid lock file.
  109. path = None
  110. def __init__(self, path):
  111. self.path = os.path.abspath(path)
  112. def acquire(self):
  113. """Acquire lock."""
  114. try:
  115. self.write_pid()
  116. except OSError as exc:
  117. reraise(LockFailed, LockFailed(str(exc)), sys.exc_info()[2])
  118. return self
  119. __enter__ = acquire
  120. def is_locked(self):
  121. """Return true if the pid lock exists."""
  122. return os.path.exists(self.path)
  123. def release(self, *args):
  124. """Release lock."""
  125. self.remove()
  126. __exit__ = release
  127. def read_pid(self):
  128. """Read and return the current pid."""
  129. with ignore_errno('ENOENT'):
  130. with open(self.path, 'r') as fh:
  131. line = fh.readline()
  132. if line.strip() == line: # must contain '\n'
  133. raise ValueError(
  134. 'Partial or invalid pidfile {0.path}'.format(self))
  135. try:
  136. return int(line.strip())
  137. except ValueError:
  138. raise ValueError(
  139. 'pidfile {0.path} contents invalid.'.format(self))
  140. def remove(self):
  141. """Remove the lock."""
  142. with ignore_errno(errno.ENOENT, errno.EACCES):
  143. os.unlink(self.path)
  144. def remove_if_stale(self):
  145. """Remove the lock if the process is not running.
  146. (does not respond to signals)."""
  147. try:
  148. pid = self.read_pid()
  149. except ValueError as exc:
  150. print('Broken pidfile found. Removing it.', file=sys.stderr)
  151. self.remove()
  152. return True
  153. if not pid:
  154. self.remove()
  155. return True
  156. try:
  157. os.kill(pid, 0)
  158. except os.error as exc:
  159. if exc.errno == errno.ESRCH:
  160. print('Stale pidfile exists. Removing it.', file=sys.stderr)
  161. self.remove()
  162. return True
  163. return False
  164. def write_pid(self):
  165. pid = os.getpid()
  166. content = '{0}\n'.format(pid)
  167. pidfile_fd = os.open(self.path, PIDFILE_FLAGS, PIDFILE_MODE)
  168. pidfile = os.fdopen(pidfile_fd, 'w')
  169. try:
  170. pidfile.write(content)
  171. # flush and sync so that the re-read below works.
  172. pidfile.flush()
  173. try:
  174. os.fsync(pidfile_fd)
  175. except AttributeError: # pragma: no cover
  176. pass
  177. finally:
  178. pidfile.close()
  179. rfh = open(self.path)
  180. try:
  181. if rfh.read() != content:
  182. raise LockFailed(
  183. "Inconsistency: Pidfile content doesn't match at re-read")
  184. finally:
  185. rfh.close()
  186. PIDFile = Pidfile # compat alias
  187. def create_pidlock(pidfile):
  188. """Create and verify pidfile.
  189. If the pidfile already exists the program exits with an error message,
  190. however if the process it refers to is not running anymore, the pidfile
  191. is deleted and the program continues.
  192. This function will automatically install an :mod:`atexit` handler
  193. to release the lock at exit, you can skip this by calling
  194. :func:`_create_pidlock` instead.
  195. :returns: :class:`Pidfile`.
  196. **Example**:
  197. .. code-block:: python
  198. pidlock = create_pidlock('/var/run/app.pid')
  199. """
  200. pidlock = _create_pidlock(pidfile)
  201. atexit.register(pidlock.release)
  202. return pidlock
  203. def _create_pidlock(pidfile):
  204. pidlock = Pidfile(pidfile)
  205. if pidlock.is_locked() and not pidlock.remove_if_stale():
  206. print(PIDLOCKED.format(pidfile, pidlock.read_pid()), file=sys.stderr)
  207. raise SystemExit(EX_CANTCREAT)
  208. pidlock.acquire()
  209. return pidlock
  210. def fd_by_path(paths):
  211. """Return a list of fds.
  212. This method returns list of fds corresponding to
  213. file paths passed in paths variable.
  214. :keyword paths: List of file paths go get fd for.
  215. :returns: :list:.
  216. **Example**:
  217. .. code-block:: python
  218. keep = fd_by_path(['/dev/urandom',
  219. '/my/precious/'])
  220. """
  221. stats = set()
  222. for path in paths:
  223. try:
  224. fd = os.open(path, os.O_RDONLY)
  225. except OSError:
  226. continue
  227. try:
  228. stats.add(os.fstat(fd)[1:3])
  229. finally:
  230. os.close(fd)
  231. def fd_in_stats(fd):
  232. try:
  233. return os.fstat(fd)[1:3] in stats
  234. except OSError:
  235. return False
  236. return [_fd for _fd in range(get_fdmax(2048)) if fd_in_stats(_fd)]
  237. if hasattr(os, 'closerange'):
  238. def close_open_fds(keep=None):
  239. # must make sure this is 0-inclusive (Issue #1882)
  240. keep = list(uniq(sorted(
  241. f for f in map(maybe_fileno, keep or []) if f is not None
  242. )))
  243. maxfd = get_fdmax(default=2048)
  244. kL, kH = iter([-1] + keep), iter(keep + [maxfd])
  245. for low, high in zip_longest(kL, kH):
  246. if low + 1 != high:
  247. os.closerange(low + 1, high)
  248. else:
  249. def close_open_fds(keep=None): # noqa
  250. keep = [maybe_fileno(f)
  251. for f in (keep or []) if maybe_fileno(f) is not None]
  252. for fd in reversed(range(get_fdmax(default=2048))):
  253. if fd not in keep:
  254. with ignore_errno(errno.EBADF):
  255. os.close(fd)
  256. class DaemonContext(object):
  257. _is_open = False
  258. def __init__(self, pidfile=None, workdir=None, umask=None,
  259. fake=False, after_chdir=None, after_forkers=True,
  260. **kwargs):
  261. if isinstance(umask, string_t):
  262. # octal or decimal, depending on initial zero.
  263. umask = int(umask, 8 if umask.startswith('0') else 10)
  264. self.workdir = workdir or DAEMON_WORKDIR
  265. self.umask = umask
  266. self.fake = fake
  267. self.after_chdir = after_chdir
  268. self.after_forkers = after_forkers
  269. self.stdfds = (sys.stdin, sys.stdout, sys.stderr)
  270. def redirect_to_null(self, fd):
  271. if fd is not None:
  272. dest = os.open(os.devnull, os.O_RDWR)
  273. os.dup2(dest, fd)
  274. def open(self):
  275. if not self._is_open:
  276. if not self.fake:
  277. self._detach()
  278. os.chdir(self.workdir)
  279. if self.umask is not None:
  280. os.umask(self.umask)
  281. if self.after_chdir:
  282. self.after_chdir()
  283. if not self.fake:
  284. # We need to keep /dev/urandom from closing because
  285. # shelve needs it, and Beat needs shelve to start.
  286. keep = list(self.stdfds) + fd_by_path(['/dev/urandom'])
  287. close_open_fds(keep)
  288. for fd in self.stdfds:
  289. self.redirect_to_null(maybe_fileno(fd))
  290. if self.after_forkers and mputil is not None:
  291. mputil._run_after_forkers()
  292. self._is_open = True
  293. __enter__ = open
  294. def close(self, *args):
  295. if self._is_open:
  296. self._is_open = False
  297. __exit__ = close
  298. def _detach(self):
  299. if os.fork() == 0: # first child
  300. os.setsid() # create new session
  301. if os.fork() > 0: # second child
  302. os._exit(0)
  303. else:
  304. os._exit(0)
  305. return self
  306. def detached(logfile=None, pidfile=None, uid=None, gid=None, umask=0,
  307. workdir=None, fake=False, **opts):
  308. """Detach the current process in the background (daemonize).
  309. :keyword logfile: Optional log file. The ability to write to this file
  310. will be verified before the process is detached.
  311. :keyword pidfile: Optional pidfile. The pidfile will not be created,
  312. as this is the responsibility of the child. But the process will
  313. exit if the pid lock exists and the pid written is still running.
  314. :keyword uid: Optional user id or user name to change
  315. effective privileges to.
  316. :keyword gid: Optional group id or group name to change effective
  317. privileges to.
  318. :keyword umask: Optional umask that will be effective in the child process.
  319. :keyword workdir: Optional new working directory.
  320. :keyword fake: Don't actually detach, intented for debugging purposes.
  321. :keyword \*\*opts: Ignored.
  322. **Example**:
  323. .. code-block:: python
  324. from celery.platforms import detached, create_pidlock
  325. with detached(logfile='/var/log/app.log', pidfile='/var/run/app.pid',
  326. uid='nobody'):
  327. # Now in detached child process with effective user set to nobody,
  328. # and we know that our logfile can be written to, and that
  329. # the pidfile is not locked.
  330. pidlock = create_pidlock('/var/run/app.pid')
  331. # Run the program
  332. program.run(logfile='/var/log/app.log')
  333. """
  334. if not resource:
  335. raise RuntimeError('This platform does not support detach.')
  336. workdir = os.getcwd() if workdir is None else workdir
  337. signals.reset('SIGCLD') # Make sure SIGCLD is using the default handler.
  338. maybe_drop_privileges(uid=uid, gid=gid)
  339. def after_chdir_do():
  340. # Since without stderr any errors will be silently suppressed,
  341. # we need to know that we have access to the logfile.
  342. logfile and open(logfile, 'a').close()
  343. # Doesn't actually create the pidfile, but makes sure it's not stale.
  344. if pidfile:
  345. _create_pidlock(pidfile).release()
  346. return DaemonContext(
  347. umask=umask, workdir=workdir, fake=fake, after_chdir=after_chdir_do,
  348. )
  349. def parse_uid(uid):
  350. """Parse user id.
  351. uid can be an integer (uid) or a string (user name), if a user name
  352. the uid is taken from the system user registry.
  353. """
  354. try:
  355. return int(uid)
  356. except ValueError:
  357. try:
  358. return pwd.getpwnam(uid).pw_uid
  359. except (AttributeError, KeyError):
  360. raise KeyError('User does not exist: {0}'.format(uid))
  361. def parse_gid(gid):
  362. """Parse group id.
  363. gid can be an integer (gid) or a string (group name), if a group name
  364. the gid is taken from the system group registry.
  365. """
  366. try:
  367. return int(gid)
  368. except ValueError:
  369. try:
  370. return grp.getgrnam(gid).gr_gid
  371. except (AttributeError, KeyError):
  372. raise KeyError('Group does not exist: {0}'.format(gid))
  373. def _setgroups_hack(groups):
  374. """:fun:`setgroups` may have a platform-dependent limit,
  375. and it is not always possible to know in advance what this limit
  376. is, so we use this ugly hack stolen from glibc."""
  377. groups = groups[:]
  378. while 1:
  379. try:
  380. return os.setgroups(groups)
  381. except ValueError: # error from Python's check.
  382. if len(groups) <= 1:
  383. raise
  384. groups[:] = groups[:-1]
  385. except OSError as exc: # error from the OS.
  386. if exc.errno != errno.EINVAL or len(groups) <= 1:
  387. raise
  388. groups[:] = groups[:-1]
  389. def setgroups(groups):
  390. """Set active groups from a list of group ids."""
  391. max_groups = None
  392. try:
  393. max_groups = os.sysconf('SC_NGROUPS_MAX')
  394. except Exception:
  395. pass
  396. try:
  397. return _setgroups_hack(groups[:max_groups])
  398. except OSError as exc:
  399. if exc.errno != errno.EPERM:
  400. raise
  401. if any(group not in groups for group in os.getgroups()):
  402. # we shouldn't be allowed to change to this group.
  403. raise
  404. def initgroups(uid, gid):
  405. """Compat version of :func:`os.initgroups` which was first
  406. added to Python 2.7."""
  407. if not pwd: # pragma: no cover
  408. return
  409. username = pwd.getpwuid(uid)[0]
  410. if hasattr(os, 'initgroups'): # Python 2.7+
  411. return os.initgroups(username, gid)
  412. groups = [gr.gr_gid for gr in grp.getgrall()
  413. if username in gr.gr_mem]
  414. setgroups(groups)
  415. def setgid(gid):
  416. """Version of :func:`os.setgid` supporting group names."""
  417. os.setgid(parse_gid(gid))
  418. def setuid(uid):
  419. """Version of :func:`os.setuid` supporting usernames."""
  420. os.setuid(parse_uid(uid))
  421. def maybe_drop_privileges(uid=None, gid=None):
  422. """Change process privileges to new user/group.
  423. If UID and GID is specified, the real user/group is changed.
  424. If only UID is specified, the real user is changed, and the group is
  425. changed to the users primary group.
  426. If only GID is specified, only the group is changed.
  427. """
  428. if sys.platform == 'win32':
  429. return
  430. if os.geteuid():
  431. # no point trying to setuid unless we're root.
  432. if not os.getuid():
  433. raise AssertionError('contact support')
  434. uid = uid and parse_uid(uid)
  435. gid = gid and parse_gid(gid)
  436. if uid:
  437. # If GID isn't defined, get the primary GID of the user.
  438. if not gid and pwd:
  439. gid = pwd.getpwuid(uid).pw_gid
  440. # Must set the GID before initgroups(), as setgid()
  441. # is known to zap the group list on some platforms.
  442. # setgid must happen before setuid (otherwise the setgid operation
  443. # may fail because of insufficient privileges and possibly stay
  444. # in a privileged group).
  445. setgid(gid)
  446. initgroups(uid, gid)
  447. # at last:
  448. setuid(uid)
  449. # ... and make sure privileges cannot be restored:
  450. try:
  451. setuid(0)
  452. except OSError as exc:
  453. if get_errno(exc) != errno.EPERM:
  454. raise
  455. pass # Good: cannot restore privileges.
  456. else:
  457. raise RuntimeError(
  458. 'non-root user able to restore privileges after setuid.')
  459. else:
  460. gid and setgid(gid)
  461. if uid and (not os.getuid()) and not (os.geteuid()):
  462. raise AssertionError('Still root uid after drop privileges!')
  463. if gid and (not os.getgid()) and not (os.getegid()):
  464. raise AssertionError('Still root gid after drop privileges!')
  465. class Signals(object):
  466. """Convenience interface to :mod:`signals`.
  467. If the requested signal is not supported on the current platform,
  468. the operation will be ignored.
  469. **Examples**:
  470. .. code-block:: python
  471. >>> from celery.platforms import signals
  472. >>> from proj.handlers import my_handler
  473. >>> signals['INT'] = my_handler
  474. >>> signals['INT']
  475. my_handler
  476. >>> signals.supported('INT')
  477. True
  478. >>> signals.signum('INT')
  479. 2
  480. >>> signals.ignore('USR1')
  481. >>> signals['USR1'] == signals.ignored
  482. True
  483. >>> signals.reset('USR1')
  484. >>> signals['USR1'] == signals.default
  485. True
  486. >>> from proj.handlers import exit_handler, hup_handler
  487. >>> signals.update(INT=exit_handler,
  488. ... TERM=exit_handler,
  489. ... HUP=hup_handler)
  490. """
  491. ignored = _signal.SIG_IGN
  492. default = _signal.SIG_DFL
  493. if hasattr(_signal, 'setitimer'):
  494. def arm_alarm(self, seconds):
  495. _signal.setitimer(_signal.ITIMER_REAL, seconds)
  496. else: # pragma: no cover
  497. try:
  498. from itimer import alarm as _itimer_alarm # noqa
  499. except ImportError:
  500. def arm_alarm(self, seconds): # noqa
  501. _signal.alarm(math.ceil(seconds))
  502. else: # pragma: no cover
  503. def arm_alarm(self, seconds): # noqa
  504. return _itimer_alarm(seconds) # noqa
  505. def reset_alarm(self):
  506. return _signal.alarm(0)
  507. def supported(self, signal_name):
  508. """Return true value if ``signal_name`` exists on this platform."""
  509. try:
  510. return self.signum(signal_name)
  511. except AttributeError:
  512. pass
  513. def signum(self, signal_name):
  514. """Get signal number from signal name."""
  515. if isinstance(signal_name, numbers.Integral):
  516. return signal_name
  517. if not isinstance(signal_name, string_t) \
  518. or not signal_name.isupper():
  519. raise TypeError('signal name must be uppercase string.')
  520. if not signal_name.startswith('SIG'):
  521. signal_name = 'SIG' + signal_name
  522. return getattr(_signal, signal_name)
  523. def reset(self, *signal_names):
  524. """Reset signals to the default signal handler.
  525. Does nothing if the platform doesn't support signals,
  526. or the specified signal in particular.
  527. """
  528. self.update((sig, self.default) for sig in signal_names)
  529. def ignore(self, *signal_names):
  530. """Ignore signal using :const:`SIG_IGN`.
  531. Does nothing if the platform doesn't support signals,
  532. or the specified signal in particular.
  533. """
  534. self.update((sig, self.ignored) for sig in signal_names)
  535. def __getitem__(self, signal_name):
  536. return _signal.getsignal(self.signum(signal_name))
  537. def __setitem__(self, signal_name, handler):
  538. """Install signal handler.
  539. Does nothing if the current platform doesn't support signals,
  540. or the specified signal in particular.
  541. """
  542. try:
  543. _signal.signal(self.signum(signal_name), handler)
  544. except (AttributeError, ValueError):
  545. pass
  546. def update(self, _d_=None, **sigmap):
  547. """Set signal handlers from a mapping."""
  548. for signal_name, handler in items(dict(_d_ or {}, **sigmap)):
  549. self[signal_name] = handler
  550. signals = Signals()
  551. get_signal = signals.signum # compat
  552. install_signal_handler = signals.__setitem__ # compat
  553. reset_signal = signals.reset # compat
  554. ignore_signal = signals.ignore # compat
  555. def strargv(argv):
  556. arg_start = 2 if 'manage' in argv[0] else 1
  557. if len(argv) > arg_start:
  558. return ' '.join(argv[arg_start:])
  559. return ''
  560. def set_process_title(progname, info=None):
  561. """Set the ps name for the currently running process.
  562. Only works if :mod:`setproctitle` is installed.
  563. """
  564. proctitle = '[{0}]'.format(progname)
  565. proctitle = '{0} {1}'.format(proctitle, info) if info else proctitle
  566. if _setproctitle:
  567. _setproctitle.setproctitle(safe_str(proctitle))
  568. return proctitle
  569. if os.environ.get('NOSETPS'): # pragma: no cover
  570. def set_mp_process_title(*a, **k):
  571. pass
  572. else:
  573. def set_mp_process_title(progname, info=None, hostname=None): # noqa
  574. """Set the ps name using the multiprocessing process name.
  575. Only works if :mod:`setproctitle` is installed.
  576. """
  577. if hostname:
  578. progname = '{0}: {1}'.format(progname, hostname)
  579. return set_process_title(
  580. '{0}:{1}'.format(progname, current_process().name), info=info)
  581. def get_errno_name(n):
  582. """Get errno for string, e.g. ``ENOENT``."""
  583. if isinstance(n, string_t):
  584. return getattr(errno, n)
  585. return n
  586. @contextmanager
  587. def ignore_errno(*errnos, **kwargs):
  588. """Context manager to ignore specific POSIX error codes.
  589. Takes a list of error codes to ignore, which can be either
  590. the name of the code, or the code integer itself::
  591. >>> with ignore_errno('ENOENT'):
  592. ... with open('foo', 'r') as fh:
  593. ... return fh.read()
  594. >>> with ignore_errno(errno.ENOENT, errno.EPERM):
  595. ... pass
  596. :keyword types: A tuple of exceptions to ignore (when the errno matches),
  597. defaults to :exc:`Exception`.
  598. """
  599. types = kwargs.get('types') or (Exception, )
  600. errnos = [get_errno_name(errno) for errno in errnos]
  601. try:
  602. yield
  603. except types as exc:
  604. if not hasattr(exc, 'errno'):
  605. raise
  606. if exc.errno not in errnos:
  607. raise
  608. def check_privileges(accept_content):
  609. uid = os.getuid() if hasattr(os, 'getuid') else 65535
  610. gid = os.getgid() if hasattr(os, 'getgid') else 65535
  611. euid = os.geteuid() if hasattr(os, 'geteuid') else 65535
  612. egid = os.getegid() if hasattr(os, 'getegid') else 65535
  613. if hasattr(os, 'fchown'):
  614. if not all(hasattr(os, attr)
  615. for attr in ['getuid', 'getgid', 'geteuid', 'getegid']):
  616. raise AssertionError('suspicious platform, contact support')
  617. if not uid or not gid or not euid or not egid:
  618. if ('pickle' in accept_content or
  619. 'application/x-python-serialize' in accept_content):
  620. if not C_FORCE_ROOT:
  621. try:
  622. print(ROOT_DISALLOWED.format(
  623. uid=uid, euid=euid, gid=gid, egid=egid,
  624. ), file=sys.stderr)
  625. finally:
  626. os._exit(1)
  627. warnings.warn(RuntimeWarning(ROOT_DISCOURAGED.format(
  628. uid=uid, euid=euid, gid=gid, egid=egid,
  629. )))