Send a notification to systemd. state is a string; see the man page of sd_notify (http://www.freedesktop.org/software/systemd/man/sd_notify.html) for a description of the allowable values. If the unset_environment parameter is True, sd_notify() will unset the $NOTIFY_SOCKET environm
(state, logger, unset_environment=False)
| 46 | |
| 47 | |
| 48 | def sd_notify(state, logger, unset_environment=False): |
| 49 | """Send a notification to systemd. state is a string; see |
| 50 | the man page of sd_notify (http://www.freedesktop.org/software/systemd/man/sd_notify.html) |
| 51 | for a description of the allowable values. |
| 52 | |
| 53 | If the unset_environment parameter is True, sd_notify() will unset |
| 54 | the $NOTIFY_SOCKET environment variable before returning (regardless of |
| 55 | whether the function call itself succeeded or not). Further calls to |
| 56 | sd_notify() will then fail, but the variable is no longer inherited by |
| 57 | child processes. |
| 58 | """ |
| 59 | |
| 60 | addr = os.environ.get('NOTIFY_SOCKET') |
| 61 | if addr is None: |
| 62 | # not run in a service, just a noop |
| 63 | return |
| 64 | sock = None |
| 65 | try: |
| 66 | sock = socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM | socket.SOCK_CLOEXEC) |
| 67 | if addr[0] == '@': |
| 68 | addr = '\0' + addr[1:] |
| 69 | sock.connect(addr) |
| 70 | sock.sendall(state.encode('utf-8')) |
| 71 | except Exception: |
| 72 | logger.debug("Exception while invoking sd_notify()", exc_info=True) |
| 73 | finally: |
| 74 | if unset_environment: |
| 75 | os.environ.pop('NOTIFY_SOCKET') |
| 76 | if sock is not None: |
| 77 | sock.close() |