platforms.py 23 KB

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