platforms.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768
  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.encoding import safe_str
  23. from contextlib import contextmanager
  24. from .local import try_import
  25. from .five import items, range, reraise, string_t, zip_longest
  26. from .utils.functional import uniq
  27. _setproctitle = try_import('setproctitle')
  28. resource = try_import('resource')
  29. pwd = try_import('pwd')
  30. grp = try_import('grp')
  31. mputil = try_import('multiprocessing.util')
  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, after_forkers=True,
  232. **kwargs):
  233. self.workdir = workdir or DAEMON_WORKDIR
  234. self.umask = DAEMON_UMASK if umask is None else umask
  235. self.fake = fake
  236. self.after_chdir = after_chdir
  237. self.after_forkers = after_forkers
  238. self.stdfds = (sys.stdin, sys.stdout, sys.stderr)
  239. def redirect_to_null(self, fd):
  240. if fd is not None:
  241. dest = os.open(os.devnull, os.O_RDWR)
  242. os.dup2(dest, fd)
  243. def open(self):
  244. if not self._is_open:
  245. if not self.fake:
  246. self._detach()
  247. os.chdir(self.workdir)
  248. os.umask(self.umask)
  249. if self.after_chdir:
  250. self.after_chdir()
  251. if not self.fake:
  252. close_open_fds(self.stdfds)
  253. for fd in self.stdfds:
  254. self.redirect_to_null(maybe_fileno(fd))
  255. if self.after_forkers and mputil is not None:
  256. mputil._run_after_forkers()
  257. self._is_open = True
  258. __enter__ = open
  259. def close(self, *args):
  260. if self._is_open:
  261. self._is_open = False
  262. __exit__ = close
  263. def _detach(self):
  264. if os.fork() == 0: # first child
  265. os.setsid() # create new session
  266. if os.fork() > 0: # second child
  267. os._exit(0)
  268. else:
  269. os._exit(0)
  270. return self
  271. def detached(logfile=None, pidfile=None, uid=None, gid=None, umask=0,
  272. workdir=None, fake=False, **opts):
  273. """Detach the current process in the background (daemonize).
  274. :keyword logfile: Optional log file. The ability to write to this file
  275. will be verified before the process is detached.
  276. :keyword pidfile: Optional pidfile. The pidfile will not be created,
  277. as this is the responsibility of the child. But the process will
  278. exit if the pid lock exists and the pid written is still running.
  279. :keyword uid: Optional user id or user name to change
  280. effective privileges to.
  281. :keyword gid: Optional group id or group name to change effective
  282. privileges to.
  283. :keyword umask: Optional umask that will be effective in the child process.
  284. :keyword workdir: Optional new working directory.
  285. :keyword fake: Don't actually detach, intented for debugging purposes.
  286. :keyword \*\*opts: Ignored.
  287. **Example**:
  288. .. code-block:: python
  289. from celery.platforms import detached, create_pidlock
  290. with detached(logfile='/var/log/app.log', pidfile='/var/run/app.pid',
  291. uid='nobody'):
  292. # Now in detached child process with effective user set to nobody,
  293. # and we know that our logfile can be written to, and that
  294. # the pidfile is not locked.
  295. pidlock = create_pidlock('/var/run/app.pid')
  296. # Run the program
  297. program.run(logfile='/var/log/app.log')
  298. """
  299. if not resource:
  300. raise RuntimeError('This platform does not support detach.')
  301. workdir = os.getcwd() if workdir is None else workdir
  302. signals.reset('SIGCLD') # Make sure SIGCLD is using the default handler.
  303. maybe_drop_privileges(uid=uid, gid=gid)
  304. def after_chdir_do():
  305. # Since without stderr any errors will be silently suppressed,
  306. # we need to know that we have access to the logfile.
  307. logfile and open(logfile, 'a').close()
  308. # Doesn't actually create the pidfile, but makes sure it's not stale.
  309. if pidfile:
  310. _create_pidlock(pidfile).release()
  311. return DaemonContext(
  312. umask=umask, workdir=workdir, fake=fake, after_chdir=after_chdir_do,
  313. )
  314. def parse_uid(uid):
  315. """Parse user id.
  316. uid can be an integer (uid) or a string (user name), if a user name
  317. the uid is taken from the system user registry.
  318. """
  319. try:
  320. return int(uid)
  321. except ValueError:
  322. try:
  323. return pwd.getpwnam(uid).pw_uid
  324. except (AttributeError, KeyError):
  325. raise KeyError('User does not exist: {0}'.format(uid))
  326. def parse_gid(gid):
  327. """Parse group id.
  328. gid can be an integer (gid) or a string (group name), if a group name
  329. the gid is taken from the system group registry.
  330. """
  331. try:
  332. return int(gid)
  333. except ValueError:
  334. try:
  335. return grp.getgrnam(gid).gr_gid
  336. except (AttributeError, KeyError):
  337. raise KeyError('Group does not exist: {0}'.format(gid))
  338. def _setgroups_hack(groups):
  339. """:fun:`setgroups` may have a platform-dependent limit,
  340. and it is not always possible to know in advance what this limit
  341. is, so we use this ugly hack stolen from glibc."""
  342. groups = groups[:]
  343. while 1:
  344. try:
  345. return os.setgroups(groups)
  346. except ValueError: # error from Python's check.
  347. if len(groups) <= 1:
  348. raise
  349. groups[:] = groups[:-1]
  350. except OSError as exc: # error from the OS.
  351. if exc.errno != errno.EINVAL or len(groups) <= 1:
  352. raise
  353. groups[:] = groups[:-1]
  354. def setgroups(groups):
  355. """Set active groups from a list of group ids."""
  356. max_groups = None
  357. try:
  358. max_groups = os.sysconf('SC_NGROUPS_MAX')
  359. except Exception:
  360. pass
  361. try:
  362. return _setgroups_hack(groups[:max_groups])
  363. except OSError as exc:
  364. if exc.errno != errno.EPERM:
  365. raise
  366. if any(group not in groups for group in os.getgroups()):
  367. # we shouldn't be allowed to change to this group.
  368. raise
  369. def initgroups(uid, gid):
  370. """Compat version of :func:`os.initgroups` which was first
  371. added to Python 2.7."""
  372. if not pwd: # pragma: no cover
  373. return
  374. username = pwd.getpwuid(uid)[0]
  375. if hasattr(os, 'initgroups'): # Python 2.7+
  376. return os.initgroups(username, gid)
  377. groups = [gr.gr_gid for gr in grp.getgrall()
  378. if username in gr.gr_mem]
  379. setgroups(groups)
  380. def setgid(gid):
  381. """Version of :func:`os.setgid` supporting group names."""
  382. os.setgid(parse_gid(gid))
  383. def setuid(uid):
  384. """Version of :func:`os.setuid` supporting usernames."""
  385. os.setuid(parse_uid(uid))
  386. def maybe_drop_privileges(uid=None, gid=None):
  387. """Change process privileges to new user/group.
  388. If UID and GID is specified, the real user/group is changed.
  389. If only UID is specified, the real user is changed, and the group is
  390. changed to the users primary group.
  391. If only GID is specified, only the group is changed.
  392. """
  393. if sys.platform == 'win32':
  394. return
  395. if os.geteuid():
  396. # no point trying to setuid unless we're root.
  397. if not os.getuid():
  398. raise AssertionError('contact support')
  399. uid = uid and parse_uid(uid)
  400. gid = gid and parse_gid(gid)
  401. if uid:
  402. # If GID isn't defined, get the primary GID of the user.
  403. if not gid and pwd:
  404. gid = pwd.getpwuid(uid).pw_gid
  405. # Must set the GID before initgroups(), as setgid()
  406. # is known to zap the group list on some platforms.
  407. # setgid must happen before setuid (otherwise the setgid operation
  408. # may fail because of insufficient privileges and possibly stay
  409. # in a privileged group).
  410. setgid(gid)
  411. initgroups(uid, gid)
  412. # at last:
  413. setuid(uid)
  414. # ... and make sure privileges cannot be restored:
  415. try:
  416. setuid(0)
  417. except OSError as exc:
  418. if exc.errno != errno.EPERM:
  419. raise
  420. pass # Good: cannot restore privileges.
  421. else:
  422. raise RuntimeError(
  423. 'non-root user able to restore privileges after setuid.')
  424. else:
  425. gid and setgid(gid)
  426. if uid and (not os.getuid()) and not (os.geteuid()):
  427. raise AssertionError('Still root uid after drop privileges!')
  428. if gid and (not os.getgid()) and not (os.getegid()):
  429. raise AssertionError('Still root gid after drop privileges!')
  430. class Signals(object):
  431. """Convenience interface to :mod:`signals`.
  432. If the requested signal is not supported on the current platform,
  433. the operation will be ignored.
  434. **Examples**:
  435. .. code-block:: python
  436. >>> from celery.platforms import signals
  437. >>> from proj.handlers import my_handler
  438. >>> signals['INT'] = my_handler
  439. >>> signals['INT']
  440. my_handler
  441. >>> signals.supported('INT')
  442. True
  443. >>> signals.signum('INT')
  444. 2
  445. >>> signals.ignore('USR1')
  446. >>> signals['USR1'] == signals.ignored
  447. True
  448. >>> signals.reset('USR1')
  449. >>> signals['USR1'] == signals.default
  450. True
  451. >>> from proj.handlers import exit_handler, hup_handler
  452. >>> signals.update(INT=exit_handler,
  453. ... TERM=exit_handler,
  454. ... HUP=hup_handler)
  455. """
  456. ignored = _signal.SIG_IGN
  457. default = _signal.SIG_DFL
  458. if hasattr(_signal, 'setitimer'):
  459. def arm_alarm(self, seconds):
  460. _signal.setitimer(_signal.ITIMER_REAL, seconds)
  461. else: # pragma: no cover
  462. try:
  463. from itimer import alarm as _itimer_alarm # noqa
  464. except ImportError:
  465. def arm_alarm(self, seconds): # noqa
  466. _signal.alarm(math.ceil(seconds))
  467. else: # pragma: no cover
  468. def arm_alarm(self, seconds): # noqa
  469. return _itimer_alarm(seconds) # noqa
  470. def reset_alarm(self):
  471. return _signal.alarm(0)
  472. def supported(self, signal_name):
  473. """Return true value if ``signal_name`` exists on this platform."""
  474. try:
  475. return self.signum(signal_name)
  476. except AttributeError:
  477. pass
  478. def signum(self, signal_name):
  479. """Get signal number from signal name."""
  480. if isinstance(signal_name, numbers.Integral):
  481. return signal_name
  482. if not isinstance(signal_name, string_t) \
  483. or not signal_name.isupper():
  484. raise TypeError('signal name must be uppercase string.')
  485. if not signal_name.startswith('SIG'):
  486. signal_name = 'SIG' + signal_name
  487. return getattr(_signal, signal_name)
  488. def reset(self, *signal_names):
  489. """Reset signals to the default signal handler.
  490. Does nothing if the platform doesn't support signals,
  491. or the specified signal in particular.
  492. """
  493. self.update((sig, self.default) for sig in signal_names)
  494. def ignore(self, *signal_names):
  495. """Ignore signal using :const:`SIG_IGN`.
  496. Does nothing if the platform doesn't support signals,
  497. or the specified signal in particular.
  498. """
  499. self.update((sig, self.ignored) for sig in signal_names)
  500. def __getitem__(self, signal_name):
  501. return _signal.getsignal(self.signum(signal_name))
  502. def __setitem__(self, signal_name, handler):
  503. """Install signal handler.
  504. Does nothing if the current platform doesn't support signals,
  505. or the specified signal in particular.
  506. """
  507. try:
  508. _signal.signal(self.signum(signal_name), handler)
  509. except (AttributeError, ValueError):
  510. pass
  511. def update(self, _d_=None, **sigmap):
  512. """Set signal handlers from a mapping."""
  513. for signal_name, handler in items(dict(_d_ or {}, **sigmap)):
  514. self[signal_name] = handler
  515. signals = Signals()
  516. get_signal = signals.signum # compat
  517. install_signal_handler = signals.__setitem__ # compat
  518. reset_signal = signals.reset # compat
  519. ignore_signal = signals.ignore # compat
  520. def strargv(argv):
  521. arg_start = 2 if 'manage' in argv[0] else 1
  522. if len(argv) > arg_start:
  523. return ' '.join(argv[arg_start:])
  524. return ''
  525. def set_process_title(progname, info=None):
  526. """Set the ps name for the currently running process.
  527. Only works if :mod:`setproctitle` is installed.
  528. """
  529. proctitle = '[{0}]'.format(progname)
  530. proctitle = '{0} {1}'.format(proctitle, info) if info else proctitle
  531. if _setproctitle:
  532. _setproctitle.setproctitle(safe_str(proctitle))
  533. return proctitle
  534. if os.environ.get('NOSETPS'): # pragma: no cover
  535. def set_mp_process_title(*a, **k):
  536. pass
  537. else:
  538. def set_mp_process_title(progname, info=None, hostname=None): # noqa
  539. """Set the ps name using the multiprocessing process name.
  540. Only works if :mod:`setproctitle` is installed.
  541. """
  542. if hostname:
  543. progname = '{0}: {1}'.format(progname, hostname)
  544. return set_process_title(
  545. '{0}:{1}'.format(progname, current_process().name), info=info)
  546. def get_errno_name(n):
  547. """Get errno for string, e.g. ``ENOENT``."""
  548. if isinstance(n, string_t):
  549. return getattr(errno, n)
  550. return n
  551. @contextmanager
  552. def ignore_errno(*errnos, **kwargs):
  553. """Context manager to ignore specific POSIX error codes.
  554. Takes a list of error codes to ignore, which can be either
  555. the name of the code, or the code integer itself::
  556. >>> with ignore_errno('ENOENT'):
  557. ... with open('foo', 'r') as fh:
  558. ... return fh.read()
  559. >>> with ignore_errno(errno.ENOENT, errno.EPERM):
  560. ... pass
  561. :keyword types: A tuple of exceptions to ignore (when the errno matches),
  562. defaults to :exc:`Exception`.
  563. """
  564. types = kwargs.get('types') or (Exception, )
  565. errnos = [get_errno_name(errno) for errno in errnos]
  566. try:
  567. yield
  568. except types as exc:
  569. if not hasattr(exc, 'errno'):
  570. raise
  571. if exc.errno not in errnos:
  572. raise
  573. def check_privileges(accept_content):
  574. uid = os.getuid() if hasattr(os, 'getuid') else 65535
  575. gid = os.getgid() if hasattr(os, 'getgid') else 65535
  576. euid = os.geteuid() if hasattr(os, 'geteuid') else 65535
  577. egid = os.getegid() if hasattr(os, 'getegid') else 65535
  578. if hasattr(os, 'fchown'):
  579. if not all(hasattr(os, attr)
  580. for attr in ['getuid', 'getgid', 'geteuid', 'getegid']):
  581. raise AssertionError('suspicious platform, contact support')
  582. if not uid or not gid or not euid or not egid:
  583. if ('pickle' in accept_content or
  584. 'application/x-python-serialize' in accept_content):
  585. if not C_FORCE_ROOT:
  586. try:
  587. print(ROOT_DISALLOWED.format(
  588. uid=uid, euid=euid, gid=gid, egid=egid,
  589. ), file=sys.stderr)
  590. finally:
  591. os._exit(1)
  592. warnings.warn(RuntimeWarning(ROOT_DISCOURAGED.format(
  593. uid=uid, euid=euid, gid=gid, egid=egid,
  594. )))