1 # -*- test-case-name: twisted.python.test.test_systemd -*-
2 # Copyright (c) Twisted Matrix Laboratories.
3 # See LICENSE for details.
6 Integration with systemd.
8 Currently only the minimum APIs necessary for using systemd's socket activation
12 __all__ = ['ListenFDs']
17 class ListenFDs(object):
19 L{ListenFDs} provides access to file descriptors inherited from systemd.
21 Typically L{ListenFDs.fromEnvironment} should be used to construct a new
22 instance of L{ListenFDs}.
24 @cvar _START: File descriptors inherited from systemd are always
25 consecutively numbered, with a fixed lowest "starting" descriptor. This
26 gives the default starting descriptor. Since this must agree with the
27 value systemd is using, it typically should not be overridden.
30 @ivar _descriptors: A C{list} of C{int} giving the descriptors which were
35 def __init__(self, descriptors):
37 @param descriptors: The descriptors which will be returned from calls to
38 C{inheritedDescriptors}.
40 self._descriptors = descriptors
44 def fromEnvironment(cls, environ=None, start=None):
46 @param environ: A dictionary-like object to inspect to discover
47 inherited descriptors. By default, C{None}, indicating that the
48 real process environment should be inspected. The default is
49 suitable for typical usage.
51 @param start: An integer giving the lowest value of an inherited
52 descriptor systemd will give us. By default, C{None}, indicating
53 the known correct (that is, in agreement with systemd) value will be
54 used. The default is suitable for typical usage.
56 @return: A new instance of C{cls} which can be used to look up the
57 descriptors which have been inherited.
60 from os import environ
67 pid = int(environ['LISTEN_PID'])
68 except (KeyError, ValueError):
73 count = int(environ['LISTEN_FDS'])
74 except (KeyError, ValueError):
77 descriptors = range(start, start + count)
78 del environ['LISTEN_PID'], environ['LISTEN_FDS']
80 return cls(descriptors)
83 def inheritedDescriptors(self):
85 @return: The configured list of descriptors.
87 return list(self._descriptors)