platforms.py 24 KB

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