Add func to salt.utils.systemd to tell if scopes are available

This commit is contained in:
Erik Johnson 2016-08-16 10:49:36 -05:00
parent bfe7107a87
commit 5b12f030c6

View file

@ -15,22 +15,34 @@ import salt.utils
log = logging.getLogger(__name__)
def booted(context):
def booted(context=None):
'''
Return True if the system was booted with systemd, False otherwise.
Pass in the loader context "__context__", this function will set the
systemd.sd_booted key to represent if systemd is running
'''
# We can cache this for as long as the minion runs.
if 'systemd.sd_booted' not in context:
try:
# This check does the same as sd_booted() from libsystemd-daemon:
# http://www.freedesktop.org/software/systemd/man/sd_booted.html
if os.stat('/run/systemd/system'):
context['systemd.sd_booted'] = True
except OSError:
context['systemd.sd_booted'] = False
return context['systemd.sd_booted']
contextkey = 'salt.utils.systemd.booted'
if isinstance(context, dict):
# Can't put this if block on the same line as the above if block,
# because it willl break the elif below.
if contextkey in context:
return context[contextkey]
elif context is not None:
raise SaltInvocationError('context must be a dictionary if passed')
try:
# This check does the same as sd_booted() from libsystemd-daemon:
# http://www.freedesktop.org/software/systemd/man/sd_booted.html
ret = bool(os.stat('/run/systemd/system'))
except OSError:
ret = False
try:
context[contextkey] = ret
except TypeError:
pass
return ret
def version(context=None):
@ -38,11 +50,14 @@ def version(context=None):
Attempts to run systemctl --version. Returns None if unable to determine
version.
'''
contextkey = 'salt.utils.systemd.version'
if isinstance(context, dict):
if 'systemd.version' in context:
return context['systemd.version']
# Can't put this if block on the same line as the above if block,
# because it willl break the elif below.
if contextkey in context:
return context[contextkey]
elif context is not None:
raise SaltInvocationError('context must be a dictionary or None')
raise SaltInvocationError('context must be a dictionary if passed')
stdout = subprocess.Popen(
['systemctl', '--version'],
close_fds=True,
@ -58,7 +73,20 @@ def version(context=None):
return None
else:
try:
context['systemd.version'] = ret
context[contextkey] = ret
except TypeError:
pass
return ret
def has_scope(context=None):
'''
Scopes were introduced in systemd 205, this function returns a boolean
which is true when the minion is systemd-booted and running systemd>=205.
'''
if not booted(context):
return False
_sd_version = version(context)
if _sd_version is None:
return False
return _sd_version >= 205