platforms.py 23 KB

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