systemd.py 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. # -*- coding: utf-8 -
  2. #
  3. # This file is part of gunicorn released under the MIT license.
  4. # See the NOTICE for more information.
  5. import os
  6. SD_LISTEN_FDS_START = 3
  7. def listen_fds(unset_environment=True):
  8. """
  9. Get the number of sockets inherited from systemd socket activation.
  10. :param unset_environment: clear systemd environment variables unless False
  11. :type unset_environment: bool
  12. :return: the number of sockets to inherit from systemd socket activation
  13. :rtype: int
  14. Returns zero immediately if $LISTEN_PID is not set to the current pid.
  15. Otherwise, returns the number of systemd activation sockets specified by
  16. $LISTEN_FDS.
  17. When $LISTEN_PID matches the current pid, unsets the environment variables
  18. unless the ``unset_environment`` flag is ``False``.
  19. .. note::
  20. Unlike the sd_listen_fds C function, this implementation does not set
  21. the FD_CLOEXEC flag because the gunicorn arbiter never needs to do this.
  22. .. seealso::
  23. `<https://www.freedesktop.org/software/systemd/man/sd_listen_fds.html>`_
  24. """
  25. fds = int(os.environ.get('LISTEN_FDS', 0))
  26. listen_pid = int(os.environ.get('LISTEN_PID', 0))
  27. if listen_pid != os.getpid():
  28. return 0
  29. if unset_environment:
  30. os.environ.pop('LISTEN_PID', None)
  31. os.environ.pop('LISTEN_FDS', None)
  32. return fds