platforms.py 24 KB

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